@vkontakte/videoplayer-core 2.0.131-dev.f14d8d97.0 → 2.0.131-dev.f80b28b8.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 (35) hide show
  1. package/es2015.cjs.js +10 -66
  2. package/es2015.esm.js +10 -66
  3. package/es2018.cjs.js +10 -66
  4. package/es2018.esm.js +9 -65
  5. package/es2024.cjs.js +9 -65
  6. package/es2024.esm.js +9 -65
  7. package/esnext.cjs.js +9 -65
  8. package/esnext.esm.js +9 -65
  9. package/evergreen.esm.js +8 -64
  10. package/package.json +2 -2
  11. package/types/player/Player.d.ts +2 -9
  12. package/types/player/types.d.ts +0 -15
  13. package/types/providers/ChromecastProvider/ChromecastInitializer/index.d.ts +1 -5
  14. package/types/providers/ChromecastProvider/index.d.ts +0 -2
  15. package/types/providers/DashLiveProvider/DashLiveProvider.d.ts +0 -1
  16. package/types/providers/DashLiveProvider/utils/FilesFetcher.d.ts +1 -2
  17. package/types/providers/DashLiveProvider/utils/LiveDashPlayer.d.ts +0 -1
  18. package/types/providers/DashLiveProvider/utils/ThroughputEstimator.d.ts +0 -4
  19. package/types/providers/DashProvider/baseDashProvider.d.ts +3 -4
  20. package/types/providers/DashProvider/lib/buffer.d.ts +3 -0
  21. package/types/providers/DashProvider/lib/fetcher.d.ts +4 -5
  22. package/types/providers/DashProvider/lib/player.d.ts +3 -8
  23. package/types/providers/DashProvider/lib/sourceBufferBufferedDiff.d.ts +19 -0
  24. package/types/providers/DashProvider/lib/types.d.ts +1 -5
  25. package/types/providers/DashProvider/lib/utils.d.ts +11 -0
  26. package/types/providers/ProviderContainer/index.d.ts +0 -4
  27. package/types/providers/ProviderContainer/utils/formatsSupport.d.ts +1 -4
  28. package/types/providers/WebRTCLiveProvider/WebRTCLiveProvider.d.ts +0 -1
  29. package/types/providers/types.d.ts +2 -7
  30. package/types/providers/utils/HTMLVideoElement/DroppedFramesManager.d.ts +1 -3
  31. package/types/utils/StatefulIterator/index.d.ts +1 -5
  32. package/types/utils/autoSelectTrack.d.ts +3 -4
  33. package/types/utils/qualityLimits.d.ts +3 -18
  34. package/types/utils/smoothedValue/baseSmoothedValue.d.ts +0 -3
  35. package/types/utils/tuningConfig.d.ts +2 -1
package/esnext.esm.js CHANGED
@@ -1,73 +1,17 @@
1
1
  /**
2
- * @vkontakte/videoplayer-core v2.0.131-dev.f14d8d97.0
3
- * Thu, 17 Apr 2025 15:45:13 GMT
2
+ * @vkontakte/videoplayer-core v2.0.131-dev.f80b28b8.0
3
+ * Fri, 18 Apr 2025 09:58:08 GMT
4
4
  * https://st.mycdn.me/static/vkontakte-videoplayer/2-0-131/doc/
5
5
  */
6
- var Uy=Object.create;var ac=Object.defineProperty;var Hy=Object.getOwnPropertyDescriptor;var jy=Object.getOwnPropertyNames;var Qy=Object.getPrototypeOf,Gy=Object.prototype.hasOwnProperty;var m=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports);var Wy=(r,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of jy(e))!Gy.call(r,a)&&a!==t&&ac(r,a,{get:()=>e[a],enumerable:!(i=Hy(e,a))||i.enumerable});return r};var R=(r,e,t)=>(t=r!=null?Uy(Qy(r)):{},Wy(e||!r||!r.__esModule?ac(t,"default",{value:r,enumerable:!0}):t,r));var Z=m(($n,nc)=>{"use strict";var Zi=function(r){return r&&r.Math===Math&&r};nc.exports=Zi(typeof globalThis=="object"&&globalThis)||Zi(typeof window=="object"&&window)||Zi(typeof self=="object"&&self)||Zi(typeof global=="object"&&global)||Zi(typeof $n=="object"&&$n)||function(){return this}()||Function("return this")()});var le=m((xD,oc)=>{"use strict";oc.exports=function(r){try{return!!r()}catch{return!0}}});var er=m((PD,uc)=>{"use strict";var Yy=le();uc.exports=!Yy(function(){var r=function(){}.bind();return typeof r!="function"||r.hasOwnProperty("prototype")})});var Mn=m((kD,pc)=>{"use strict";var zy=er(),dc=Function.prototype,lc=dc.apply,cc=dc.call;pc.exports=typeof Reflect=="object"&&Reflect.apply||(zy?cc.bind(lc):function(){return cc.apply(lc,arguments)})});var se=m((wD,fc)=>{"use strict";var hc=er(),mc=Function.prototype,Cn=mc.call,Ky=hc&&mc.bind.bind(Cn,Cn);fc.exports=hc?Ky:function(r){return function(){return Cn.apply(r,arguments)}}});var Ut=m((AD,gc)=>{"use strict";var bc=se(),Xy=bc({}.toString),Jy=bc("".slice);gc.exports=function(r){return Jy(Xy(r),8,-1)}});var Dn=m((LD,vc)=>{"use strict";var Zy=Ut(),eT=se();vc.exports=function(r){if(Zy(r)==="Function")return eT(r)}});var X=m((RD,Sc)=>{"use strict";var Vn=typeof document=="object"&&document.all;Sc.exports=typeof Vn>"u"&&Vn!==void 0?function(r){return typeof r=="function"||r===Vn}:function(r){return typeof r=="function"}});var Me=m(($D,yc)=>{"use strict";var tT=le();yc.exports=!tT(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var Ce=m((MD,Tc)=>{"use strict";var iT=er(),Qa=Function.prototype.call;Tc.exports=iT?Qa.bind(Qa):function(){return Qa.apply(Qa,arguments)}});var Bn=m(xc=>{"use strict";var Ic={}.propertyIsEnumerable,Ec=Object.getOwnPropertyDescriptor,rT=Ec&&!Ic.call({1:2},1);xc.f=rT?function(e){var t=Ec(this,e);return!!t&&t.enumerable}:Ic});var tr=m((DD,Pc)=>{"use strict";Pc.exports=function(r,e){return{enumerable:!(r&1),configurable:!(r&2),writable:!(r&4),value:e}}});var wc=m((VD,kc)=>{"use strict";var aT=se(),sT=le(),nT=Ut(),On=Object,oT=aT("".split);kc.exports=sT(function(){return!On("z").propertyIsEnumerable(0)})?function(r){return nT(r)==="String"?oT(r,""):On(r)}:On});var hi=m((BD,Ac)=>{"use strict";Ac.exports=function(r){return r==null}});var It=m((OD,Lc)=>{"use strict";var uT=hi(),lT=TypeError;Lc.exports=function(r){if(uT(r))throw new lT("Can't call method on "+r);return r}});var Ht=m((_D,Rc)=>{"use strict";var cT=wc(),dT=It();Rc.exports=function(r){return cT(dT(r))}});var De=m((ND,$c)=>{"use strict";var pT=X();$c.exports=function(r){return typeof r=="object"?r!==null:pT(r)}});var mi=m((FD,Mc)=>{"use strict";Mc.exports={}});var lt=m((qD,Dc)=>{"use strict";var _n=mi(),Nn=Z(),hT=X(),Cc=function(r){return hT(r)?r:void 0};Dc.exports=function(r,e){return arguments.length<2?Cc(_n[r])||Cc(Nn[r]):_n[r]&&_n[r][e]||Nn[r]&&Nn[r][e]}});var ir=m((UD,Vc)=>{"use strict";var mT=se();Vc.exports=mT({}.isPrototypeOf)});var jt=m((HD,_c)=>{"use strict";var fT=Z(),Bc=fT.navigator,Oc=Bc&&Bc.userAgent;_c.exports=Oc?String(Oc):""});var qn=m((jD,jc)=>{"use strict";var Hc=Z(),Fn=jt(),Nc=Hc.process,Fc=Hc.Deno,qc=Nc&&Nc.versions||Fc&&Fc.version,Uc=qc&&qc.v8,je,Ga;Uc&&(je=Uc.split("."),Ga=je[0]>0&&je[0]<4?1:+(je[0]+je[1]));!Ga&&Fn&&(je=Fn.match(/Edge\/(\d+)/),(!je||je[1]>=74)&&(je=Fn.match(/Chrome\/(\d+)/),je&&(Ga=+je[1])));jc.exports=Ga});var Un=m((QD,Gc)=>{"use strict";var Qc=qn(),bT=le(),gT=Z(),vT=gT.String;Gc.exports=!!Object.getOwnPropertySymbols&&!bT(function(){var r=Symbol("symbol detection");return!vT(r)||!(Object(r)instanceof Symbol)||!Symbol.sham&&Qc&&Qc<41})});var Hn=m((GD,Wc)=>{"use strict";var ST=Un();Wc.exports=ST&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var jn=m((WD,Yc)=>{"use strict";var yT=lt(),TT=X(),IT=ir(),ET=Hn(),xT=Object;Yc.exports=ET?function(r){return typeof r=="symbol"}:function(r){var e=yT("Symbol");return TT(e)&&IT(e.prototype,xT(r))}});var rr=m((YD,zc)=>{"use strict";var PT=String;zc.exports=function(r){try{return PT(r)}catch{return"Object"}}});var tt=m((zD,Kc)=>{"use strict";var kT=X(),wT=rr(),AT=TypeError;Kc.exports=function(r){if(kT(r))return r;throw new AT(wT(r)+" is not a function")}});var ar=m((KD,Xc)=>{"use strict";var LT=tt(),RT=hi();Xc.exports=function(r,e){var t=r[e];return RT(t)?void 0:LT(t)}});var Zc=m((XD,Jc)=>{"use strict";var Qn=Ce(),Gn=X(),Wn=De(),$T=TypeError;Jc.exports=function(r,e){var t,i;if(e==="string"&&Gn(t=r.toString)&&!Wn(i=Qn(t,r))||Gn(t=r.valueOf)&&!Wn(i=Qn(t,r))||e!=="string"&&Gn(t=r.toString)&&!Wn(i=Qn(t,r)))return i;throw new $T("Can't convert object to primitive value")}});var Qe=m((JD,ed)=>{"use strict";ed.exports=!0});var rd=m((ZD,id)=>{"use strict";var td=Z(),MT=Object.defineProperty;id.exports=function(r,e){try{MT(td,r,{value:e,configurable:!0,writable:!0})}catch{td[r]=e}return e}});var sr=m((e0,nd)=>{"use strict";var CT=Qe(),DT=Z(),VT=rd(),ad="__core-js_shared__",sd=nd.exports=DT[ad]||VT(ad,{});(sd.versions||(sd.versions=[])).push({version:"3.38.0",mode:CT?"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 Yn=m((t0,ud)=>{"use strict";var od=sr();ud.exports=function(r,e){return od[r]||(od[r]=e||{})}});var fi=m((i0,ld)=>{"use strict";var BT=It(),OT=Object;ld.exports=function(r){return OT(BT(r))}});var Ge=m((r0,cd)=>{"use strict";var _T=se(),NT=fi(),FT=_T({}.hasOwnProperty);cd.exports=Object.hasOwn||function(e,t){return FT(NT(e),t)}});var zn=m((a0,dd)=>{"use strict";var qT=se(),UT=0,HT=Math.random(),jT=qT(1 .toString);dd.exports=function(r){return"Symbol("+(r===void 0?"":r)+")_"+jT(++UT+HT,36)}});var ce=m((s0,hd)=>{"use strict";var QT=Z(),GT=Yn(),pd=Ge(),WT=zn(),YT=Un(),zT=Hn(),bi=QT.Symbol,Kn=GT("wks"),KT=zT?bi.for||bi:bi&&bi.withoutSetter||WT;hd.exports=function(r){return pd(Kn,r)||(Kn[r]=YT&&pd(bi,r)?bi[r]:KT("Symbol."+r)),Kn[r]}});var gd=m((n0,bd)=>{"use strict";var XT=Ce(),md=De(),fd=jn(),JT=ar(),ZT=Zc(),eI=ce(),tI=TypeError,iI=eI("toPrimitive");bd.exports=function(r,e){if(!md(r)||fd(r))return r;var t=JT(r,iI),i;if(t){if(e===void 0&&(e="default"),i=XT(t,r,e),!md(i)||fd(i))return i;throw new tI("Can't convert object to primitive value")}return e===void 0&&(e="number"),ZT(r,e)}});var Xn=m((o0,vd)=>{"use strict";var rI=gd(),aI=jn();vd.exports=function(r){var e=rI(r,"string");return aI(e)?e:e+""}});var Wa=m((u0,yd)=>{"use strict";var sI=Z(),Sd=De(),Jn=sI.document,nI=Sd(Jn)&&Sd(Jn.createElement);yd.exports=function(r){return nI?Jn.createElement(r):{}}});var Zn=m((l0,Td)=>{"use strict";var oI=Me(),uI=le(),lI=Wa();Td.exports=!oI&&!uI(function(){return Object.defineProperty(lI("div"),"a",{get:function(){return 7}}).a!==7})});var xd=m(Ed=>{"use strict";var cI=Me(),dI=Ce(),pI=Bn(),hI=tr(),mI=Ht(),fI=Xn(),bI=Ge(),gI=Zn(),Id=Object.getOwnPropertyDescriptor;Ed.f=cI?Id:function(e,t){if(e=mI(e),t=fI(t),gI)try{return Id(e,t)}catch{}if(bI(e,t))return hI(!dI(pI.f,e,t),e[t])}});var eo=m((d0,Pd)=>{"use strict";var vI=le(),SI=X(),yI=/#|\.prototype\./,nr=function(r,e){var t=II[TI(r)];return t===xI?!0:t===EI?!1:SI(e)?vI(e):!!e},TI=nr.normalize=function(r){return String(r).replace(yI,".").toLowerCase()},II=nr.data={},EI=nr.NATIVE="N",xI=nr.POLYFILL="P";Pd.exports=nr});var gi=m((p0,wd)=>{"use strict";var kd=Dn(),PI=tt(),kI=er(),wI=kd(kd.bind);wd.exports=function(r,e){return PI(r),e===void 0?r:kI?wI(r,e):function(){return r.apply(e,arguments)}}});var to=m((h0,Ad)=>{"use strict";var AI=Me(),LI=le();Ad.exports=AI&&LI(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var it=m((m0,Ld)=>{"use strict";var RI=De(),$I=String,MI=TypeError;Ld.exports=function(r){if(RI(r))return r;throw new MI($I(r)+" is not an object")}});var Qt=m($d=>{"use strict";var CI=Me(),DI=Zn(),VI=to(),Ya=it(),Rd=Xn(),BI=TypeError,io=Object.defineProperty,OI=Object.getOwnPropertyDescriptor,ro="enumerable",ao="configurable",so="writable";$d.f=CI?VI?function(e,t,i){if(Ya(e),t=Rd(t),Ya(i),typeof e=="function"&&t==="prototype"&&"value"in i&&so in i&&!i[so]){var a=OI(e,t);a&&a[so]&&(e[t]=i.value,i={configurable:ao in i?i[ao]:a[ao],enumerable:ro in i?i[ro]:a[ro],writable:!1})}return io(e,t,i)}:io:function(e,t,i){if(Ya(e),t=Rd(t),Ya(i),DI)try{return io(e,t,i)}catch{}if("get"in i||"set"in i)throw new BI("Accessors not supported");return"value"in i&&(e[t]=i.value),e}});var vi=m((b0,Md)=>{"use strict";var _I=Me(),NI=Qt(),FI=tr();Md.exports=_I?function(r,e,t){return NI.f(r,e,FI(1,t))}:function(r,e,t){return r[e]=t,r}});var te=m((g0,Dd)=>{"use strict";var or=Z(),qI=Mn(),UI=Dn(),HI=X(),jI=xd().f,QI=eo(),Si=mi(),GI=gi(),yi=vi(),Cd=Ge();sr();var WI=function(r){var e=function(t,i,a){if(this instanceof e){switch(arguments.length){case 0:return new r;case 1:return new r(t);case 2:return new r(t,i)}return new r(t,i,a)}return qI(r,this,arguments)};return e.prototype=r.prototype,e};Dd.exports=function(r,e){var t=r.target,i=r.global,a=r.stat,s=r.proto,n=i?or:a?or[t]:or[t]&&or[t].prototype,o=i?Si:Si[t]||yi(Si,t,{})[t],u=o.prototype,l,c,d,p,h,f,b,g,v;for(p in e)l=QI(i?p:t+(a?".":"#")+p,r.forced),c=!l&&n&&Cd(n,p),f=o[p],c&&(r.dontCallGetSet?(v=jI(n,p),b=v&&v.value):b=n[p]),h=c&&b?b:e[p],!(!l&&!s&&typeof f==typeof h)&&(r.bind&&c?g=GI(h,or):r.wrap&&c?g=WI(h):s&&HI(h)?g=UI(h):g=h,(r.sham||h&&h.sham||f&&f.sham)&&yi(g,"sham",!0),yi(o,p,g),s&&(d=t+"Prototype",Cd(Si,d)||yi(Si,d,{}),yi(Si[d],p,h),r.real&&u&&(l||!u[p])&&yi(u,p,h)))}});var Bd=m((v0,Vd)=>{"use strict";var YI=Math.ceil,zI=Math.floor;Vd.exports=Math.trunc||function(e){var t=+e;return(t>0?zI:YI)(t)}});var ur=m((S0,Od)=>{"use strict";var KI=Bd();Od.exports=function(r){var e=+r;return e!==e||e===0?0:KI(e)}});var Nd=m((y0,_d)=>{"use strict";var XI=ur(),JI=Math.max,ZI=Math.min;_d.exports=function(r,e){var t=XI(r);return t<0?JI(t+e,0):ZI(t,e)}});var no=m((T0,Fd)=>{"use strict";var eE=ur(),tE=Math.min;Fd.exports=function(r){var e=eE(r);return e>0?tE(e,9007199254740991):0}});var Ti=m((I0,qd)=>{"use strict";var iE=no();qd.exports=function(r){return iE(r.length)}});var oo=m((E0,Hd)=>{"use strict";var rE=Ht(),aE=Nd(),sE=Ti(),Ud=function(r){return function(e,t,i){var a=rE(e),s=sE(a);if(s===0)return!r&&-1;var n=aE(i,s),o;if(r&&t!==t){for(;s>n;)if(o=a[n++],o!==o)return!0}else for(;s>n;n++)if((r||n in a)&&a[n]===t)return r||n||0;return!r&&-1}};Hd.exports={includes:Ud(!0),indexOf:Ud(!1)}});var lr=m((x0,jd)=>{"use strict";jd.exports=function(){}});var Qd=m(()=>{"use strict";var nE=te(),oE=oo().includes,uE=le(),lE=lr(),cE=uE(function(){return!Array(1).includes()});nE({target:"Array",proto:!0,forced:cE},{includes:function(e){return oE(this,e,arguments.length>1?arguments[1]:void 0)}});lE("includes")});var Et=m((w0,Gd)=>{"use strict";var dE=lt();Gd.exports=dE});var Yd=m((A0,Wd)=>{"use strict";Qd();var pE=Et();Wd.exports=pE("Array","includes")});var Kd=m((L0,zd)=>{"use strict";var hE=Yd();zd.exports=hE});var Ie=m((R0,Xd)=>{"use strict";var mE=Kd();Xd.exports=mE});var Xa=m((U0,sp)=>{"use strict";var IE=Yn(),EE=zn(),ap=IE("keys");sp.exports=function(r){return ap[r]||(ap[r]=EE(r))}});var op=m((H0,np)=>{"use strict";var xE=le();np.exports=!xE(function(){function r(){}return r.prototype.constructor=null,Object.getPrototypeOf(new r)!==r.prototype})});var Ja=m((j0,lp)=>{"use strict";var PE=Ge(),kE=X(),wE=fi(),AE=Xa(),LE=op(),up=AE("IE_PROTO"),co=Object,RE=co.prototype;lp.exports=LE?co.getPrototypeOf:function(r){var e=wE(r);if(PE(e,up))return e[up];var t=e.constructor;return kE(t)&&e instanceof t?t.prototype:e instanceof co?RE:null}});var Za=m((Q0,cp)=>{"use strict";cp.exports={}});var hp=m((G0,pp)=>{"use strict";var $E=se(),po=Ge(),ME=Ht(),CE=oo().indexOf,DE=Za(),dp=$E([].push);pp.exports=function(r,e){var t=ME(r),i=0,a=[],s;for(s in t)!po(DE,s)&&po(t,s)&&dp(a,s);for(;e.length>i;)po(t,s=e[i++])&&(~CE(a,s)||dp(a,s));return a}});var ho=m((W0,mp)=>{"use strict";mp.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var mo=m((Y0,fp)=>{"use strict";var VE=hp(),BE=ho();fp.exports=Object.keys||function(e){return VE(e,BE)}});var fo=m((z0,yp)=>{"use strict";var gp=Me(),OE=le(),vp=se(),_E=Ja(),NE=mo(),FE=Ht(),qE=Bn().f,Sp=vp(qE),UE=vp([].push),HE=gp&&OE(function(){var r=Object.create(null);return r[2]=2,!Sp(r,2)}),bp=function(r){return function(e){for(var t=FE(e),i=NE(t),a=HE&&_E(t)===null,s=i.length,n=0,o=[],u;s>n;)u=i[n++],(!gp||(a?u in t:Sp(t,u)))&&UE(o,r?[u,t[u]]:t[u]);return o}};yp.exports={entries:bp(!0),values:bp(!1)}});var Tp=m(()=>{"use strict";var jE=te(),QE=fo().entries;jE({target:"Object",stat:!0},{entries:function(e){return QE(e)}})});var Ep=m((J0,Ip)=>{"use strict";Tp();var GE=mi();Ip.exports=GE.Object.entries});var Pp=m((Z0,xp)=>{"use strict";var WE=Ep();xp.exports=WE});var Ii=m((eV,kp)=>{"use strict";var YE=Pp();kp.exports=YE});var Gt=m((tV,wp)=>{"use strict";wp.exports={}});var Rp=m((iV,Lp)=>{"use strict";var zE=Z(),KE=X(),Ap=zE.WeakMap;Lp.exports=KE(Ap)&&/native code/.test(String(Ap))});var So=m((rV,Cp)=>{"use strict";var XE=Rp(),Mp=Z(),JE=De(),ZE=vi(),bo=Ge(),go=sr(),ex=Xa(),tx=Za(),$p="Object already initialized",vo=Mp.TypeError,ix=Mp.WeakMap,es,cr,ts,rx=function(r){return ts(r)?cr(r):es(r,{})},ax=function(r){return function(e){var t;if(!JE(e)||(t=cr(e)).type!==r)throw new vo("Incompatible receiver, "+r+" required");return t}};XE||go.state?(We=go.state||(go.state=new ix),We.get=We.get,We.has=We.has,We.set=We.set,es=function(r,e){if(We.has(r))throw new vo($p);return e.facade=r,We.set(r,e),e},cr=function(r){return We.get(r)||{}},ts=function(r){return We.has(r)}):(Wt=ex("state"),tx[Wt]=!0,es=function(r,e){if(bo(r,Wt))throw new vo($p);return e.facade=r,ZE(r,Wt,e),e},cr=function(r){return bo(r,Wt)?r[Wt]:{}},ts=function(r){return bo(r,Wt)});var We,Wt;Cp.exports={set:es,get:cr,has:ts,enforce:rx,getterFor:ax}});var Io=m((aV,Vp)=>{"use strict";var yo=Me(),sx=Ge(),Dp=Function.prototype,nx=yo&&Object.getOwnPropertyDescriptor,To=sx(Dp,"name"),ox=To&&function(){}.name==="something",ux=To&&(!yo||yo&&nx(Dp,"name").configurable);Vp.exports={EXISTS:To,PROPER:ox,CONFIGURABLE:ux}});var Op=m(Bp=>{"use strict";var lx=Me(),cx=to(),dx=Qt(),px=it(),hx=Ht(),mx=mo();Bp.f=lx&&!cx?Object.defineProperties:function(e,t){px(e);for(var i=hx(t),a=mx(t),s=a.length,n=0,o;s>n;)dx.f(e,o=a[n++],i[o]);return e}});var Eo=m((nV,_p)=>{"use strict";var fx=lt();_p.exports=fx("document","documentElement")});var wo=m((oV,Qp)=>{"use strict";var bx=it(),gx=Op(),Np=ho(),vx=Za(),Sx=Eo(),yx=Wa(),Tx=Xa(),Fp=">",qp="<",Po="prototype",ko="script",Hp=Tx("IE_PROTO"),xo=function(){},jp=function(r){return qp+ko+Fp+r+qp+"/"+ko+Fp},Up=function(r){r.write(jp("")),r.close();var e=r.parentWindow.Object;return r=null,e},Ix=function(){var r=yx("iframe"),e="java"+ko+":",t;return r.style.display="none",Sx.appendChild(r),r.src=String(e),t=r.contentWindow.document,t.open(),t.write(jp("document.F=Object")),t.close(),t.F},is,rs=function(){try{is=new ActiveXObject("htmlfile")}catch{}rs=typeof document<"u"?document.domain&&is?Up(is):Ix():Up(is);for(var r=Np.length;r--;)delete rs[Po][Np[r]];return rs()};vx[Hp]=!0;Qp.exports=Object.create||function(e,t){var i;return e!==null?(xo[Po]=bx(e),i=new xo,xo[Po]=null,i[Hp]=e):i=rs(),t===void 0?i:gx.f(i,t)}});var Ei=m((uV,Gp)=>{"use strict";var Ex=vi();Gp.exports=function(r,e,t,i){return i&&i.enumerable?r[e]=t:Ex(r,e,t),r}});var $o=m((lV,zp)=>{"use strict";var xx=le(),Px=X(),kx=De(),wx=wo(),Wp=Ja(),Ax=Ei(),Lx=ce(),Rx=Qe(),Ro=Lx("iterator"),Yp=!1,ct,Ao,Lo;[].keys&&(Lo=[].keys(),"next"in Lo?(Ao=Wp(Wp(Lo)),Ao!==Object.prototype&&(ct=Ao)):Yp=!0);var $x=!kx(ct)||xx(function(){var r={};return ct[Ro].call(r)!==r});$x?ct={}:Rx&&(ct=wx(ct));Px(ct[Ro])||Ax(ct,Ro,function(){return this});zp.exports={IteratorPrototype:ct,BUGGY_SAFARI_ITERATORS:Yp}});var as=m((cV,Xp)=>{"use strict";var Mx=ce(),Cx=Mx("toStringTag"),Kp={};Kp[Cx]="z";Xp.exports=String(Kp)==="[object z]"});var dr=m((dV,Jp)=>{"use strict";var Dx=as(),Vx=X(),ss=Ut(),Bx=ce(),Ox=Bx("toStringTag"),_x=Object,Nx=ss(function(){return arguments}())==="Arguments",Fx=function(r,e){try{return r[e]}catch{}};Jp.exports=Dx?ss:function(r){var e,t,i;return r===void 0?"Undefined":r===null?"Null":typeof(t=Fx(e=_x(r),Ox))=="string"?t:Nx?ss(e):(i=ss(e))==="Object"&&Vx(e.callee)?"Arguments":i}});var eh=m((pV,Zp)=>{"use strict";var qx=as(),Ux=dr();Zp.exports=qx?{}.toString:function(){return"[object "+Ux(this)+"]"}});var pr=m((hV,ih)=>{"use strict";var Hx=as(),jx=Qt().f,Qx=vi(),Gx=Ge(),Wx=eh(),Yx=ce(),th=Yx("toStringTag");ih.exports=function(r,e,t,i){var a=t?r:r&&r.prototype;a&&(Gx(a,th)||jx(a,th,{configurable:!0,value:e}),i&&!Hx&&Qx(a,"toString",Wx))}});var ah=m((mV,rh)=>{"use strict";var zx=$o().IteratorPrototype,Kx=wo(),Xx=tr(),Jx=pr(),Zx=Gt(),eP=function(){return this};rh.exports=function(r,e,t,i){var a=e+" Iterator";return r.prototype=Kx(zx,{next:Xx(+!i,t)}),Jx(r,a,!1,!0),Zx[a]=eP,r}});var nh=m((fV,sh)=>{"use strict";var tP=se(),iP=tt();sh.exports=function(r,e,t){try{return tP(iP(Object.getOwnPropertyDescriptor(r,e)[t]))}catch{}}});var uh=m((bV,oh)=>{"use strict";var rP=De();oh.exports=function(r){return rP(r)||r===null}});var ch=m((gV,lh)=>{"use strict";var aP=uh(),sP=String,nP=TypeError;lh.exports=function(r){if(aP(r))return r;throw new nP("Can't set "+sP(r)+" as a prototype")}});var Mo=m((vV,dh)=>{"use strict";var oP=nh(),uP=De(),lP=It(),cP=ch();dh.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var r=!1,e={},t;try{t=oP(Object.prototype,"__proto__","set"),t(e,[]),r=e instanceof Array}catch{}return function(a,s){return lP(a),cP(s),uP(a)&&(r?t(a,s):a.__proto__=s),a}}():void 0)});var Ih=m((SV,Th)=>{"use strict";var dP=te(),pP=Ce(),ns=Qe(),Sh=Io(),hP=X(),mP=ah(),ph=Ja(),hh=Mo(),fP=pr(),bP=vi(),Co=Ei(),gP=ce(),mh=Gt(),yh=$o(),vP=Sh.PROPER,SP=Sh.CONFIGURABLE,fh=yh.IteratorPrototype,os=yh.BUGGY_SAFARI_ITERATORS,hr=gP("iterator"),bh="keys",mr="values",gh="entries",vh=function(){return this};Th.exports=function(r,e,t,i,a,s,n){mP(t,e,i);var o=function(v){if(v===a&&p)return p;if(!os&&v&&v in c)return c[v];switch(v){case bh:return function(){return new t(this,v)};case mr:return function(){return new t(this,v)};case gh:return function(){return new t(this,v)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,c=r.prototype,d=c[hr]||c["@@iterator"]||a&&c[a],p=!os&&d||o(a),h=e==="Array"&&c.entries||d,f,b,g;if(h&&(f=ph(h.call(new r)),f!==Object.prototype&&f.next&&(!ns&&ph(f)!==fh&&(hh?hh(f,fh):hP(f[hr])||Co(f,hr,vh)),fP(f,u,!0,!0),ns&&(mh[u]=vh))),vP&&a===mr&&d&&d.name!==mr&&(!ns&&SP?bP(c,"name",mr):(l=!0,p=function(){return pP(d,this)})),a)if(b={values:o(mr),keys:s?p:o(bh),entries:o(gh)},n)for(g in b)(os||l||!(g in c))&&Co(c,g,b[g]);else dP({target:e,proto:!0,forced:os||l},b);return(!ns||n)&&c[hr]!==p&&Co(c,hr,p,{name:a}),mh[e]=p,b}});var xh=m((yV,Eh)=>{"use strict";Eh.exports=function(r,e){return{value:r,done:e}}});var Vo=m((TV,Lh)=>{"use strict";var yP=Ht(),Do=lr(),Ph=Gt(),wh=So(),TP=Qt().f,IP=Ih(),us=xh(),EP=Qe(),xP=Me(),Ah="Array Iterator",PP=wh.set,kP=wh.getterFor(Ah);Lh.exports=IP(Array,"Array",function(r,e){PP(this,{type:Ah,target:yP(r),index:0,kind:e})},function(){var r=kP(this),e=r.target,t=r.index++;if(!e||t>=e.length)return r.target=void 0,us(void 0,!0);switch(r.kind){case"keys":return us(t,!1);case"values":return us(e[t],!1)}return us([t,e[t]],!1)},"values");var kh=Ph.Arguments=Ph.Array;Do("keys");Do("values");Do("entries");if(!EP&&xP&&kh.name!=="values")try{TP(kh,"name",{value:"values"})}catch{}});var $h=m((IV,Rh)=>{"use strict";var wP=ce(),AP=Gt(),LP=wP("iterator"),RP=Array.prototype;Rh.exports=function(r){return r!==void 0&&(AP.Array===r||RP[LP]===r)}});var Bo=m((EV,Ch)=>{"use strict";var $P=dr(),Mh=ar(),MP=hi(),CP=Gt(),DP=ce(),VP=DP("iterator");Ch.exports=function(r){if(!MP(r))return Mh(r,VP)||Mh(r,"@@iterator")||CP[$P(r)]}});var Vh=m((xV,Dh)=>{"use strict";var BP=Ce(),OP=tt(),_P=it(),NP=rr(),FP=Bo(),qP=TypeError;Dh.exports=function(r,e){var t=arguments.length<2?FP(r):e;if(OP(t))return _P(BP(t,r));throw new qP(NP(r)+" is not iterable")}});var _h=m((PV,Oh)=>{"use strict";var UP=Ce(),Bh=it(),HP=ar();Oh.exports=function(r,e,t){var i,a;Bh(r);try{if(i=HP(r,"return"),!i){if(e==="throw")throw t;return t}i=UP(i,r)}catch(s){a=!0,i=s}if(e==="throw")throw t;if(a)throw i;return Bh(i),t}});var cs=m((kV,Uh)=>{"use strict";var jP=gi(),QP=Ce(),GP=it(),WP=rr(),YP=$h(),zP=Ti(),Nh=ir(),KP=Vh(),XP=Bo(),Fh=_h(),JP=TypeError,ls=function(r,e){this.stopped=r,this.result=e},qh=ls.prototype;Uh.exports=function(r,e,t){var i=t&&t.that,a=!!(t&&t.AS_ENTRIES),s=!!(t&&t.IS_RECORD),n=!!(t&&t.IS_ITERATOR),o=!!(t&&t.INTERRUPTED),u=jP(e,i),l,c,d,p,h,f,b,g=function(x){return l&&Fh(l,"normal",x),new ls(!0,x)},v=function(x){return a?(GP(x),o?u(x[0],x[1],g):u(x[0],x[1])):o?u(x,g):u(x)};if(s)l=r.iterator;else if(n)l=r;else{if(c=XP(r),!c)throw new JP(WP(r)+" is not iterable");if(YP(c)){for(d=0,p=zP(r);p>d;d++)if(h=v(r[d]),h&&Nh(qh,h))return h;return new ls(!1)}l=KP(r,c)}for(f=s?r.next:l.next;!(b=QP(f,l)).done;){try{h=v(b.value)}catch(x){Fh(l,"throw",x)}if(typeof h=="object"&&h&&Nh(qh,h))return h}return new ls(!1)}});var jh=m((wV,Hh)=>{"use strict";var ZP=Me(),ek=Qt(),tk=tr();Hh.exports=function(r,e,t){ZP?ek.f(r,e,tk(0,t)):r[e]=t}});var Qh=m(()=>{"use strict";var ik=te(),rk=cs(),ak=jh();ik({target:"Object",stat:!0},{fromEntries:function(e){var t={};return rk(e,function(i,a){ak(t,i,a)},{AS_ENTRIES:!0}),t}})});var Wh=m((RV,Gh)=>{"use strict";Vo();Qh();var sk=mi();Gh.exports=sk.Object.fromEntries});var zh=m(($V,Yh)=>{"use strict";Yh.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 Xh=m(()=>{"use strict";Vo();var nk=zh(),ok=Z(),uk=pr(),Kh=Gt();for(ds in nk)uk(ok[ds],ds),Kh[ds]=Kh.Array;var ds});var Zh=m((DV,Jh)=>{"use strict";var lk=Wh();Xh();Jh.exports=lk});var Oo=m((VV,em)=>{"use strict";var ck=Zh();em.exports=ck});var tm=m(()=>{"use strict"});var _o=m((_V,im)=>{"use strict";var fr=Z(),dk=jt(),pk=Ut(),ps=function(r){return dk.slice(0,r.length)===r};im.exports=function(){return ps("Bun/")?"BUN":ps("Cloudflare-Workers")?"CLOUDFLARE":ps("Deno/")?"DENO":ps("Node.js/")?"NODE":fr.Bun&&typeof Bun.version=="string"?"BUN":fr.Deno&&typeof Deno.version=="object"?"DENO":pk(fr.process)==="process"?"NODE":fr.window&&fr.document?"BROWSER":"REST"}()});var hs=m((NV,rm)=>{"use strict";var hk=_o();rm.exports=hk==="NODE"});var sm=m((FV,am)=>{"use strict";var mk=Qt();am.exports=function(r,e,t){return mk.f(r,e,t)}});var um=m((qV,om)=>{"use strict";var fk=lt(),bk=sm(),gk=ce(),vk=Me(),nm=gk("species");om.exports=function(r){var e=fk(r);vk&&e&&!e[nm]&&bk(e,nm,{configurable:!0,get:function(){return this}})}});var cm=m((UV,lm)=>{"use strict";var Sk=ir(),yk=TypeError;lm.exports=function(r,e){if(Sk(e,r))return r;throw new yk("Incorrect invocation")}});var Fo=m((HV,dm)=>{"use strict";var Tk=se(),Ik=X(),No=sr(),Ek=Tk(Function.toString);Ik(No.inspectSource)||(No.inspectSource=function(r){return Ek(r)});dm.exports=No.inspectSource});var Uo=m((jV,bm)=>{"use strict";var xk=se(),Pk=le(),pm=X(),kk=dr(),wk=lt(),Ak=Fo(),hm=function(){},mm=wk("Reflect","construct"),qo=/^\s*(?:class|function)\b/,Lk=xk(qo.exec),Rk=!qo.test(hm),br=function(e){if(!pm(e))return!1;try{return mm(hm,[],e),!0}catch{return!1}},fm=function(e){if(!pm(e))return!1;switch(kk(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return Rk||!!Lk(qo,Ak(e))}catch{return!0}};fm.sham=!0;bm.exports=!mm||Pk(function(){var r;return br(br.call)||!br(Object)||!br(function(){r=!0})||r})?fm:br});var vm=m((QV,gm)=>{"use strict";var $k=Uo(),Mk=rr(),Ck=TypeError;gm.exports=function(r){if($k(r))return r;throw new Ck(Mk(r)+" is not a constructor")}});var Ho=m((GV,ym)=>{"use strict";var Sm=it(),Dk=vm(),Vk=hi(),Bk=ce(),Ok=Bk("species");ym.exports=function(r,e){var t=Sm(r).constructor,i;return t===void 0||Vk(i=Sm(t)[Ok])?e:Dk(i)}});var Im=m((WV,Tm)=>{"use strict";var _k=se();Tm.exports=_k([].slice)});var xm=m((YV,Em)=>{"use strict";var Nk=TypeError;Em.exports=function(r,e){if(r<e)throw new Nk("Not enough arguments");return r}});var jo=m((zV,Pm)=>{"use strict";var Fk=jt();Pm.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(Fk)});var Zo=m((KV,Dm)=>{"use strict";var Ve=Z(),qk=Mn(),Uk=gi(),km=X(),Hk=Ge(),Cm=le(),wm=Eo(),jk=Im(),Am=Wa(),Qk=xm(),Gk=jo(),Wk=hs(),Ko=Ve.setImmediate,Xo=Ve.clearImmediate,Yk=Ve.process,Qo=Ve.Dispatch,zk=Ve.Function,Lm=Ve.MessageChannel,Kk=Ve.String,Go=0,gr={},Rm="onreadystatechange",vr,Yt,Wo,Yo;Cm(function(){vr=Ve.location});var Jo=function(r){if(Hk(gr,r)){var e=gr[r];delete gr[r],e()}},zo=function(r){return function(){Jo(r)}},$m=function(r){Jo(r.data)},Mm=function(r){Ve.postMessage(Kk(r),vr.protocol+"//"+vr.host)};(!Ko||!Xo)&&(Ko=function(e){Qk(arguments.length,1);var t=km(e)?e:zk(e),i=jk(arguments,1);return gr[++Go]=function(){qk(t,void 0,i)},Yt(Go),Go},Xo=function(e){delete gr[e]},Wk?Yt=function(r){Yk.nextTick(zo(r))}:Qo&&Qo.now?Yt=function(r){Qo.now(zo(r))}:Lm&&!Gk?(Wo=new Lm,Yo=Wo.port2,Wo.port1.onmessage=$m,Yt=Uk(Yo.postMessage,Yo)):Ve.addEventListener&&km(Ve.postMessage)&&!Ve.importScripts&&vr&&vr.protocol!=="file:"&&!Cm(Mm)?(Yt=Mm,Ve.addEventListener("message",$m,!1)):Rm in Am("script")?Yt=function(r){wm.appendChild(Am("script"))[Rm]=function(){wm.removeChild(this),Jo(r)}}:Yt=function(r){setTimeout(zo(r),0)});Dm.exports={set:Ko,clear:Xo}});var Om=m((XV,Bm)=>{"use strict";var Vm=Z(),Xk=Me(),Jk=Object.getOwnPropertyDescriptor;Bm.exports=function(r){if(!Xk)return Vm[r];var e=Jk(Vm,r);return e&&e.value}});var eu=m((JV,Nm)=>{"use strict";var _m=function(){this.head=null,this.tail=null};_m.prototype={add:function(r){var e={item:r,next:null},t=this.tail;t?t.next=e:this.head=e,this.tail=e},get:function(){var r=this.head;if(r){var e=this.head=r.next;return e===null&&(this.tail=null),r.item}}};Nm.exports=_m});var qm=m((ZV,Fm)=>{"use strict";var Zk=jt();Fm.exports=/ipad|iphone|ipod/i.test(Zk)&&typeof Pebble<"u"});var Hm=m((eB,Um)=>{"use strict";var ew=jt();Um.exports=/web0s(?!.*chrome)/i.test(ew)});var Km=m((tB,zm)=>{"use strict";var Pi=Z(),tw=Om(),jm=gi(),tu=Zo().set,iw=eu(),rw=jo(),aw=qm(),sw=Hm(),iu=hs(),Qm=Pi.MutationObserver||Pi.WebKitMutationObserver,Gm=Pi.document,Wm=Pi.process,ms=Pi.Promise,su=tw("queueMicrotask"),xi,ru,au,fs,Ym;su||(Sr=new iw,yr=function(){var r,e;for(iu&&(r=Wm.domain)&&r.exit();e=Sr.get();)try{e()}catch(t){throw Sr.head&&xi(),t}r&&r.enter()},!rw&&!iu&&!sw&&Qm&&Gm?(ru=!0,au=Gm.createTextNode(""),new Qm(yr).observe(au,{characterData:!0}),xi=function(){au.data=ru=!ru}):!aw&&ms&&ms.resolve?(fs=ms.resolve(void 0),fs.constructor=ms,Ym=jm(fs.then,fs),xi=function(){Ym(yr)}):iu?xi=function(){Wm.nextTick(yr)}:(tu=jm(tu,Pi),xi=function(){tu(yr)}),su=function(r){Sr.head||xi(),Sr.add(r)});var Sr,yr;zm.exports=su});var Jm=m((iB,Xm)=>{"use strict";Xm.exports=function(r,e){try{arguments.length===1?console.error(r):console.error(r,e)}catch{}}});var bs=m((rB,Zm)=>{"use strict";Zm.exports=function(r){try{return{error:!1,value:r()}}catch(e){return{error:!0,value:e}}}});var zt=m((aB,ef)=>{"use strict";var nw=Z();ef.exports=nw.Promise});var ki=m((sB,sf)=>{"use strict";var ow=Z(),Tr=zt(),uw=X(),lw=eo(),cw=Fo(),dw=ce(),tf=_o(),pw=Qe(),nu=qn(),rf=Tr&&Tr.prototype,hw=dw("species"),ou=!1,af=uw(ow.PromiseRejectionEvent),mw=lw("Promise",function(){var r=cw(Tr),e=r!==String(Tr);if(!e&&nu===66||pw&&!(rf.catch&&rf.finally))return!0;if(!nu||nu<51||!/native code/.test(r)){var t=new Tr(function(s){s(1)}),i=function(s){s(function(){},function(){})},a=t.constructor={};if(a[hw]=i,ou=t.then(function(){})instanceof i,!ou)return!0}return!e&&(tf==="BROWSER"||tf==="DENO")&&!af});sf.exports={CONSTRUCTOR:mw,REJECTION_EVENT:af,SUBCLASSING:ou}});var wi=m((nB,of)=>{"use strict";var nf=tt(),fw=TypeError,bw=function(r){var e,t;this.promise=new r(function(i,a){if(e!==void 0||t!==void 0)throw new fw("Bad Promise constructor");e=i,t=a}),this.resolve=nf(e),this.reject=nf(t)};of.exports.f=function(r){return new bw(r)}});var kf=m(()=>{"use strict";var gw=te(),vw=Qe(),ys=hs(),xt=Z(),$i=Ce(),uf=Ei(),lf=Mo(),Sw=pr(),yw=um(),Tw=tt(),Ss=X(),Iw=De(),Ew=cm(),xw=Ho(),mf=Zo().set,pu=Km(),Pw=Jm(),kw=bs(),ww=eu(),ff=So(),Ts=zt(),hu=ki(),bf=wi(),Is="Promise",gf=hu.CONSTRUCTOR,Aw=hu.REJECTION_EVENT,Lw=hu.SUBCLASSING,uu=ff.getterFor(Is),Rw=ff.set,Ai=Ts&&Ts.prototype,Kt=Ts,gs=Ai,vf=xt.TypeError,lu=xt.document,mu=xt.process,cu=bf.f,$w=cu,Mw=!!(lu&&lu.createEvent&&xt.dispatchEvent),Sf="unhandledrejection",Cw="rejectionhandled",cf=0,yf=1,Dw=2,fu=1,Tf=2,vs,df,Vw,pf,If=function(r){var e;return Iw(r)&&Ss(e=r.then)?e:!1},Ef=function(r,e){var t=e.value,i=e.state===yf,a=i?r.ok:r.fail,s=r.resolve,n=r.reject,o=r.domain,u,l,c;try{a?(i||(e.rejection===Tf&&Ow(e),e.rejection=fu),a===!0?u=t:(o&&o.enter(),u=a(t),o&&(o.exit(),c=!0)),u===r.promise?n(new vf("Promise-chain cycle")):(l=If(u))?$i(l,u,s,n):s(u)):n(t)}catch(d){o&&!c&&o.exit(),n(d)}},xf=function(r,e){r.notified||(r.notified=!0,pu(function(){for(var t=r.reactions,i;i=t.get();)Ef(i,r);r.notified=!1,e&&!r.rejection&&Bw(r)}))},Pf=function(r,e,t){var i,a;Mw?(i=lu.createEvent("Event"),i.promise=e,i.reason=t,i.initEvent(r,!1,!0),xt.dispatchEvent(i)):i={promise:e,reason:t},!Aw&&(a=xt["on"+r])?a(i):r===Sf&&Pw("Unhandled promise rejection",t)},Bw=function(r){$i(mf,xt,function(){var e=r.facade,t=r.value,i=hf(r),a;if(i&&(a=kw(function(){ys?mu.emit("unhandledRejection",t,e):Pf(Sf,e,t)}),r.rejection=ys||hf(r)?Tf:fu,a.error))throw a.value})},hf=function(r){return r.rejection!==fu&&!r.parent},Ow=function(r){$i(mf,xt,function(){var e=r.facade;ys?mu.emit("rejectionHandled",e):Pf(Cw,e,r.value)})},Li=function(r,e,t){return function(i){r(e,i,t)}},Ri=function(r,e,t){r.done||(r.done=!0,t&&(r=t),r.value=e,r.state=Dw,xf(r,!0))},du=function(r,e,t){if(!r.done){r.done=!0,t&&(r=t);try{if(r.facade===e)throw new vf("Promise can't be resolved itself");var i=If(e);i?pu(function(){var a={done:!1};try{$i(i,e,Li(du,a,r),Li(Ri,a,r))}catch(s){Ri(a,s,r)}}):(r.value=e,r.state=yf,xf(r,!1))}catch(a){Ri({done:!1},a,r)}}};if(gf&&(Kt=function(e){Ew(this,gs),Tw(e),$i(vs,this);var t=uu(this);try{e(Li(du,t),Li(Ri,t))}catch(i){Ri(t,i)}},gs=Kt.prototype,vs=function(e){Rw(this,{type:Is,done:!1,notified:!1,parent:!1,reactions:new ww,rejection:!1,state:cf,value:void 0})},vs.prototype=uf(gs,"then",function(e,t){var i=uu(this),a=cu(xw(this,Kt));return i.parent=!0,a.ok=Ss(e)?e:!0,a.fail=Ss(t)&&t,a.domain=ys?mu.domain:void 0,i.state===cf?i.reactions.add(a):pu(function(){Ef(a,i)}),a.promise}),df=function(){var r=new vs,e=uu(r);this.promise=r,this.resolve=Li(du,e),this.reject=Li(Ri,e)},bf.f=cu=function(r){return r===Kt||r===Vw?new df(r):$w(r)},!vw&&Ss(Ts)&&Ai!==Object.prototype)){pf=Ai.then,Lw||uf(Ai,"then",function(e,t){var i=this;return new Kt(function(a,s){$i(pf,i,a,s)}).then(e,t)},{unsafe:!0});try{delete Ai.constructor}catch{}lf&&lf(Ai,gs)}gw({global:!0,constructor:!0,wrap:!0,forced:gf},{Promise:Kt});Sw(Kt,Is,!1,!0);yw(Is)});var $f=m((lB,Rf)=>{"use strict";var _w=ce(),Af=_w("iterator"),Lf=!1;try{wf=0,bu={next:function(){return{done:!!wf++}},return:function(){Lf=!0}},bu[Af]=function(){return this},Array.from(bu,function(){throw 2})}catch{}var wf,bu;Rf.exports=function(r,e){try{if(!e&&!Lf)return!1}catch{return!1}var t=!1;try{var i={};i[Af]=function(){return{next:function(){return{done:t=!0}}}},r(i)}catch{}return t}});var gu=m((cB,Mf)=>{"use strict";var Nw=zt(),Fw=$f(),qw=ki().CONSTRUCTOR;Mf.exports=qw||!Fw(function(r){Nw.all(r).then(void 0,function(){})})});var Cf=m(()=>{"use strict";var Uw=te(),Hw=Ce(),jw=tt(),Qw=wi(),Gw=bs(),Ww=cs(),Yw=gu();Uw({target:"Promise",stat:!0,forced:Yw},{all:function(e){var t=this,i=Qw.f(t),a=i.resolve,s=i.reject,n=Gw(function(){var o=jw(t.resolve),u=[],l=0,c=1;Ww(e,function(d){var p=l++,h=!1;c++,Hw(o,t,d).then(function(f){h||(h=!0,u[p]=f,--c||a(u))},s)}),--c||a(u)});return n.error&&s(n.value),i.promise}})});var Vf=m(()=>{"use strict";var zw=te(),Kw=Qe(),Xw=ki().CONSTRUCTOR,Su=zt(),Jw=lt(),Zw=X(),eA=Ei(),Df=Su&&Su.prototype;zw({target:"Promise",proto:!0,forced:Xw,real:!0},{catch:function(r){return this.then(void 0,r)}});!Kw&&Zw(Su)&&(vu=Jw("Promise").prototype.catch,Df.catch!==vu&&eA(Df,"catch",vu,{unsafe:!0}));var vu});var Bf=m(()=>{"use strict";var tA=te(),iA=Ce(),rA=tt(),aA=wi(),sA=bs(),nA=cs(),oA=gu();tA({target:"Promise",stat:!0,forced:oA},{race:function(e){var t=this,i=aA.f(t),a=i.reject,s=sA(function(){var n=rA(t.resolve);nA(e,function(o){iA(n,t,o).then(i.resolve,a)})});return s.error&&a(s.value),i.promise}})});var Of=m(()=>{"use strict";var uA=te(),lA=wi(),cA=ki().CONSTRUCTOR;uA({target:"Promise",stat:!0,forced:cA},{reject:function(e){var t=lA.f(this),i=t.reject;return i(e),t.promise}})});var yu=m((SB,_f)=>{"use strict";var dA=it(),pA=De(),hA=wi();_f.exports=function(r,e){if(dA(r),pA(e)&&e.constructor===r)return e;var t=hA.f(r),i=t.resolve;return i(e),t.promise}});var qf=m(()=>{"use strict";var mA=te(),fA=lt(),Nf=Qe(),bA=zt(),Ff=ki().CONSTRUCTOR,gA=yu(),vA=fA("Promise"),SA=Nf&&!Ff;mA({target:"Promise",stat:!0,forced:Nf||Ff},{resolve:function(e){return gA(SA&&this===vA?bA:this,e)}})});var Uf=m(()=>{"use strict";kf();Cf();Vf();Bf();Of();qf()});var Gf=m(()=>{"use strict";var yA=te(),TA=Qe(),Es=zt(),IA=le(),jf=lt(),Qf=X(),EA=Ho(),Hf=yu(),xA=Ei(),Iu=Es&&Es.prototype,PA=!!Es&&IA(function(){Iu.finally.call({then:function(){}},function(){})});yA({target:"Promise",proto:!0,real:!0,forced:PA},{finally:function(r){var e=EA(this,jf("Promise")),t=Qf(r);return this.then(t?function(i){return Hf(e,r()).then(function(){return i})}:r,t?function(i){return Hf(e,r()).then(function(){throw i})}:r)}});!TA&&Qf(Es)&&(Tu=jf("Promise").prototype.finally,Iu.finally!==Tu&&xA(Iu,"finally",Tu,{unsafe:!0}));var Tu});var Yf=m((kB,Wf)=>{"use strict";tm();Uf();Gf();var kA=Et();Wf.exports=kA("Promise","finally")});var Kf=m((wB,zf)=>{"use strict";var wA=Yf();zf.exports=wA});var xs=m((AB,Xf)=>{"use strict";var AA=Kf();Xf.exports=AA});var cb=m(()=>{"use strict";var UA=te(),HA=fo().values;UA({target:"Object",stat:!0},{values:function(e){return HA(e)}})});var pb=m((pO,db)=>{"use strict";cb();var jA=mi();db.exports=jA.Object.values});var mb=m((hO,hb)=>{"use strict";var QA=pb();hb.exports=QA});var Ci=m((mO,fb)=>{"use strict";var GA=mb();fb.exports=GA});var Mb=m(()=>{"use strict";var bL=te(),gL=fi(),vL=Ti(),SL=ur(),yL=lr();bL({target:"Array",proto:!0},{at:function(e){var t=gL(this),i=vL(t),a=SL(e),s=a>=0?a:i+a;return s<0||s>=i?void 0:t[s]}});yL("at")});var Db=m((E_,Cb)=>{"use strict";Mb();var TL=Et();Cb.exports=TL("Array","at")});var Bb=m((x_,Vb)=>{"use strict";var IL=Db();Vb.exports=IL});var Lt=m((P_,Ob)=>{"use strict";var EL=Bb();Ob.exports=EL});var Yu=m((cF,vg)=>{"use strict";var nR=Ut();vg.exports=Array.isArray||function(e){return nR(e)==="Array"}});var yg=m((dF,Sg)=>{"use strict";var oR=TypeError,uR=9007199254740991;Sg.exports=function(r){if(r>uR)throw oR("Maximum allowed index exceeded");return r}});var Eg=m((pF,Ig)=>{"use strict";var lR=Yu(),cR=Ti(),dR=yg(),pR=gi(),Tg=function(r,e,t,i,a,s,n,o){for(var u=a,l=0,c=n?pR(n,o):!1,d,p;l<i;)l in t&&(d=c?c(t[l],l,e):t[l],s>0&&lR(d)?(p=cR(d),u=Tg(r,e,d,p,u,s-1)-1):(dR(u+1),r[u]=d),u++),l++;return u};Ig.exports=Tg});var wg=m((hF,kg)=>{"use strict";var xg=Yu(),hR=Uo(),mR=De(),fR=ce(),bR=fR("species"),Pg=Array;kg.exports=function(r){var e;return xg(r)&&(e=r.constructor,hR(e)&&(e===Pg||xg(e.prototype))?e=void 0:mR(e)&&(e=e[bR],e===null&&(e=void 0))),e===void 0?Pg:e}});var Lg=m((mF,Ag)=>{"use strict";var gR=wg();Ag.exports=function(r,e){return new(gR(r))(e===0?0:e)}});var Rg=m(()=>{"use strict";var vR=te(),SR=Eg(),yR=tt(),TR=fi(),IR=Ti(),ER=Lg();vR({target:"Array",proto:!0},{flatMap:function(e){var t=TR(this),i=IR(t),a;return yR(e),a=ER(t,0),a.length=SR(a,t,t,i,0,1,e,arguments.length>1?arguments[1]:void 0),a}})});var $g=m(()=>{"use strict";var xR=lr();xR("flatMap")});var Cg=m((SF,Mg)=>{"use strict";Rg();$g();var PR=Et();Mg.exports=PR("Array","flatMap")});var Vg=m((yF,Dg)=>{"use strict";var kR=Cg();Dg.exports=kR});var zu=m((TF,Bg)=>{"use strict";var wR=Vg();Bg.exports=wR});var _r=m((IF,Og)=>{"use strict";var AR=dr(),LR=String;Og.exports=function(r){if(AR(r)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return LR(r)}});var Ku=m((EF,_g)=>{"use strict";_g.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 qg=m((xF,Fg)=>{"use strict";var RR=se(),$R=It(),MR=_r(),Ju=Ku(),Ng=RR("".replace),CR=RegExp("^["+Ju+"]+"),DR=RegExp("(^|[^"+Ju+"])["+Ju+"]+$"),Xu=function(r){return function(e){var t=MR($R(e));return r&1&&(t=Ng(t,CR,"")),r&2&&(t=Ng(t,DR,"$1")),t}};Fg.exports={start:Xu(1),end:Xu(2),trim:Xu(3)}});var Qg=m((PF,jg)=>{"use strict";var VR=Io().PROPER,BR=le(),Ug=Ku(),Hg="\u200B\x85\u180E";jg.exports=function(r){return BR(function(){return!!Ug[r]()||Hg[r]()!==Hg||VR&&Ug[r].name!==r})}});var Zu=m((kF,Gg)=>{"use strict";var OR=qg().start,_R=Qg();Gg.exports=_R("trimStart")?function(){return OR(this)}:"".trimStart});var Yg=m(()=>{"use strict";var NR=te(),Wg=Zu();NR({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==Wg},{trimLeft:Wg})});var Kg=m(()=>{"use strict";Yg();var FR=te(),zg=Zu();FR({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==zg},{trimStart:zg})});var Jg=m(($F,Xg)=>{"use strict";Kg();var qR=Et();Xg.exports=qR("String","trimLeft")});var ev=m((MF,Zg)=>{"use strict";var UR=Jg();Zg.exports=UR});var iv=m((CF,tv)=>{"use strict";var HR=ev();tv.exports=HR});var vv=m(()=>{"use strict"});var Sv=m(()=>{"use strict"});var Tv=m((h1,yv)=>{"use strict";var p$=De(),h$=Ut(),m$=ce(),f$=m$("match");yv.exports=function(r){var e;return p$(r)&&((e=r[f$])!==void 0?!!e:h$(r)==="RegExp")}});var Ev=m((m1,Iv)=>{"use strict";var b$=it();Iv.exports=function(){var r=b$(this),e="";return r.hasIndices&&(e+="d"),r.global&&(e+="g"),r.ignoreCase&&(e+="i"),r.multiline&&(e+="m"),r.dotAll&&(e+="s"),r.unicode&&(e+="u"),r.unicodeSets&&(e+="v"),r.sticky&&(e+="y"),e}});var kv=m((f1,Pv)=>{"use strict";var g$=Ce(),v$=Ge(),S$=ir(),y$=Ev(),xv=RegExp.prototype;Pv.exports=function(r){var e=r.flags;return e===void 0&&!("flags"in xv)&&!v$(r,"flags")&&S$(xv,r)?g$(y$,r):e}});var Av=m((b1,wv)=>{"use strict";var ol=se(),T$=fi(),I$=Math.floor,sl=ol("".charAt),E$=ol("".replace),nl=ol("".slice),x$=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,P$=/\$([$&'`]|\d{1,2})/g;wv.exports=function(r,e,t,i,a,s){var n=t+r.length,o=i.length,u=P$;return a!==void 0&&(a=T$(a),u=x$),E$(s,u,function(l,c){var d;switch(sl(c,0)){case"$":return"$";case"&":return r;case"`":return nl(e,0,t);case"'":return nl(e,n);case"<":d=a[nl(c,1,-1)];break;default:var p=+c;if(p===0)return l;if(p>o){var h=I$(p/10);return h===0?l:h<=o?i[h-1]===void 0?sl(c,1):i[h-1]+sl(c,1):l}d=i[p-1]}return d===void 0?"":d})}});var $v=m(()=>{"use strict";var k$=te(),w$=Ce(),ll=se(),Lv=It(),A$=X(),L$=hi(),R$=Tv(),Ni=_r(),$$=ar(),M$=kv(),C$=Av(),D$=ce(),V$=Qe(),B$=D$("replace"),O$=TypeError,ul=ll("".indexOf),_$=ll("".replace),Rv=ll("".slice),N$=Math.max;k$({target:"String",proto:!0},{replaceAll:function(e,t){var i=Lv(this),a,s,n,o,u,l,c,d,p,h,f=0,b="";if(!L$(e)){if(a=R$(e),a&&(s=Ni(Lv(M$(e))),!~ul(s,"g")))throw new O$("`.replaceAll` does not allow non-global regexes");if(n=$$(e,B$),n)return w$(n,e,i,t);if(V$&&a)return _$(Ni(i),e,t)}for(o=Ni(i),u=Ni(e),l=A$(t),l||(t=Ni(t)),c=u.length,d=N$(1,c),p=ul(o,u);p!==-1;)h=l?Ni(t(u,p,o)):C$(u,o,p,[],void 0,t),b+=Rv(o,f,p)+h,f=p+c,p=p+d>o.length?-1:ul(o,u,p+d);return f<o.length&&(b+=Rv(o,f)),b}})});var Cv=m((S1,Mv)=>{"use strict";vv();Sv();$v();var F$=Et();Mv.exports=F$("String","replaceAll")});var Vv=m((y1,Dv)=>{"use strict";var q$=Cv();Dv.exports=q$});var Ov=m((T1,Bv)=>{"use strict";var U$=Vv();Bv.exports=U$});var Nv=m((I1,_v)=>{"use strict";var H$=ur(),j$=_r(),Q$=It(),G$=RangeError;_v.exports=function(e){var t=j$(Q$(this)),i="",a=H$(e);if(a<0||a===1/0)throw new G$("Wrong number of repetitions");for(;a>0;(a>>>=1)&&(t+=t))a&1&&(i+=t);return i}});var jv=m((E1,Hv)=>{"use strict";var Uv=se(),W$=no(),Fv=_r(),Y$=Nv(),z$=It(),K$=Uv(Y$),X$=Uv("".slice),J$=Math.ceil,qv=function(r){return function(e,t,i){var a=Fv(z$(e)),s=W$(t),n=a.length,o=i===void 0?" ":Fv(i),u,l;return s<=n||o===""?a:(u=s-n,l=K$(o,J$(u/o.length)),l.length>u&&(l=X$(l,0,u)),r?a+l:l+a)}};Hv.exports={start:qv(!1),end:qv(!0)}});var Gv=m((x1,Qv)=>{"use strict";var Z$=jt();Qv.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(Z$)});var Wv=m(()=>{"use strict";var eM=te(),tM=jv().start,iM=Gv();eM({target:"String",proto:!0,forced:iM},{padStart:function(e){return tM(this,e,arguments.length>1?arguments[1]:void 0)}})});var zv=m((w1,Yv)=>{"use strict";Wv();var rM=Et();Yv.exports=rM("String","padStart")});var Xv=m((A1,Kv)=>{"use strict";var aM=zv();Kv.exports=aM});var Zv=m((L1,Jv)=>{"use strict";var sM=Xv();Jv.exports=sM});var sc="2.0.131-dev.f14d8d97.0";var $e=(a=>(a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused",a))($e||{}),ut=(T=>(T.MPEG="MPEG",T.DASH="DASH",T.DASH_SEP="DASH_SEP",T.DASH_SEP_VK="DASH_SEP",T.DASH_WEBM="DASH_WEBM",T.DASH_WEBM_AV1="DASH_WEBM_AV1",T.DASH_STREAMS="DASH_STREAMS",T.DASH_WEBM_VK="DASH_WEBM",T.DASH_ONDEMAND="DASH_ONDEMAND",T.DASH_ONDEMAND_VK="DASH_ONDEMAND",T.DASH_LIVE="DASH_LIVE",T.DASH_LIVE_CMAF="DASH_LIVE_CMAF",T.DASH_LIVE_WEBM="DASH_LIVE_WEBM",T.HLS="HLS",T.HLS_ONDEMAND="HLS_ONDEMAND",T.HLS_JS="HLS",T.HLS_LIVE="HLS_LIVE",T.HLS_LIVE_CMAF="HLS_LIVE_CMAF",T.WEB_RTC_LIVE="WEB_RTC_LIVE",T))(ut||{});var Ha=(a=>(a.NOT_AVAILABLE="NOT_AVAILABLE",a.AVAILABLE="AVAILABLE",a.CONNECTING="CONNECTING",a.CONNECTED="CONNECTED",a))(Ha||{}),Ln=(i=>(i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic",i))(Ln||{});var Rn=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(Rn||{}),ja=(i=>(i.TRAFFIC_SAVING="traffic_saving",i.HIGH_QUALITY="high_quality",i.UNKNOWN="unknown",i))(ja||{});var Oy=R(Ie(),1);import{assertNever as rp,assertNonNullable as fE,isNonNullable as za,ValueSubject as uo,Subject as bE,Subscription as gE,merge as vE,observableFrom as SE,fromEvent as Zd,map as ep,tap as tp,filterChanged as yE,isNullable as lo,ErrorCategory as ip}from"@vkontakte/videoplayer-shared";var Jd=r=>new Promise((e,t)=>{let i=document.createElement("script");i.setAttribute("src",r),i.onload=()=>e(),i.onerror=a=>t(a),document.body.appendChild(i)});var Ka=class{constructor(e){this.connection$=new uo(void 0);this.castState$=new uo("NOT_AVAILABLE");this.errorEvent$=new bE;this.realCastState$=new uo("NOT_AVAILABLE");this.subscription=new gE;this.isDestroyed=!1;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");let t="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${t}`}),e.isDisabled||!t)return;let i=za(window.chrome?.cast),a=!!window.__onGCastApiAvailable;i?this.initializeCastApi():(window.__onGCastApiAvailable=s=>{delete window.__onGCastApiAvailable,s&&!this.isDestroyed&&this.initializeCastApi()},a||Jd("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:ip.NETWORK,message:"Script loading failed!"})))}connect(){cast.framework.CastContext.getInstance()?.requestSession()}disconnect(){cast.framework.CastContext.getInstance()?.getCurrentSession()?.endSession(!0)}stopMedia(){return new Promise((e,t)=>{cast.framework.CastContext.getInstance()?.getCurrentSession()?.getMediaSession()?.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){za(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();lo(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();lo(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(Zd(i,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(a=>{switch(a.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=i.getCurrentSession()?.getMediaSession()?.media?.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return rp(a.sessionState)}})).add(vE(Zd(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(tp(a=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(a)}`})}),ep(a=>a.castState)),SE([i.getCastState()])).pipe(yE(),ep(TE),tp(a=>{this.log({message:`realCastState$: ${a}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(a=>{let s=a==="CONNECTED",n=za(this.connection$.getValue());if(s&&!n){let o=i.getCurrentSession();fE(o);let u=o.getCastDevice(),l=o.getMediaSession()?.media?.contentId;(lo(l)||l===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:o,castDevice:u}))}else!s&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(a==="CONNECTED"?za(this.connection$.getValue())?"CONNECTED":"AVAILABLE":a)}))}initializeCastApi(){let e,t,i;try{e=cast.framework.CastContext.getInstance(),t=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,i=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch{return}try{e.setOptions({receiverApplicationId:this.params.receiverApplicationId??t,autoJoinPolicy:i}),this.initListeners()}catch(a){this.errorEvent$.next({id:"ChromecastInitializer",category:ip.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:a})}}},TE=r=>{switch(r){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 rp(r)}};var zl=R(Ie(),1),vy=R(Ii(),1),Sy=R(Oo(),1);var ob=R(xs(),1);import{assertNever as Jf}from"@vkontakte/videoplayer-shared";var de=(r,e=0,t=0)=>{switch(t){case 0:return r.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case 1:{if(e===0)return r;let i=new URL(r);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}case 2:{let i=new URL(r);return!i.searchParams.get("offset_p")&&e===0?r:(i.searchParams.set("offset_p",e.toFixed(0)),i.toString())}default:Jf(t)}return r},Ps=(r,e)=>{switch(e){case 0:return NaN;case 1:{let t=new URL(r);return Number(t.searchParams.get("playback_shift"))}case 2:{let t=new URL(r);return Number(t.searchParams.get("offset_p")??0)}default:Jf(e)}};var E=(r,e,t=!1)=>{let i=r.getTransition();(t||!i||i.to===e)&&r.setState(e)};import{isNonNullable as LA,Subject as ks,merge as Zf}from"@vkontakte/videoplayer-shared";var D=class{constructor(e){this.transitionStarted$=new ks;this.transitionEnded$=new ks;this.transitionUpdated$=new ks;this.forceChanged$=new ks;this.stateChangeStarted$=Zf(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=Zf(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||LA(t)&&t.to===e||(this.prevState=i,this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:i,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}getPrevState(){return this.prevState}};import{assertNever as RA}from"@vkontakte/videoplayer-shared";var eb=r=>{switch(r){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 RA(r)}};import{assertNever as Mi,assertNonNullable as Xt,debounce as tb,ErrorCategory as ib,fromEvent as Jt,isNonNullable as rb,map as ab,merge as sb,observableFrom as $A,Subject as MA,Subscription as Eu,timeout as CA,getHighestQuality as DA}from"@vkontakte/videoplayer-shared";var VA=5,BA=5,OA=500,nb=7e3,Ir=class{constructor(e){this.subscription=new Eu;this.loadMediaTimeoutSubscription=new Eu;this.videoState=new D("stopped");this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),a=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(a?.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:Mi(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:Mi(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:Mi(e)}break}default:Mi(i)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(eb(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 Eu;this.subscription.add(e),this.subscription.add(sb(this.videoState.stateChangeStarted$.pipe(ab(a=>`stateChangeStarted$ ${JSON.stringify(a)}`)),this.videoState.stateChangeEnded$.pipe(ab(a=>`stateChangeEnded$ ${JSON.stringify(a)}`))).subscribe(a=>this.log({message:`[videoState] ${a}`})));let t=(a,s)=>this.subscription.add(a.subscribe(s));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{let a=new MA;e.add(a.pipe(tb(OA)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add(Jt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(n=>{this.logRemoteEvent(n);let o=n.value;this.params.output.position$.next(o),(this.params.desiredState.seekState.getState().state==="applying"||Math.abs(o-s)>VA)&&a.next(o),s=o})),e.add(Jt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(Jt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),a=>{this.logRemoteEvent(a),a.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(Jt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),a=>{this.logRemoteEvent(a),a.value?this.handleRemotePause():this.handleRemotePlay()}),t(Jt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),a=>{this.logRemoteEvent(a);let{remotePlayer:s}=this.params.connection,n=a.value,o=this.params.output.isBuffering$.getValue(),u=n===chrome.cast.media.PlayerState.BUFFERING;switch(o!==u&&this.params.output.isBuffering$.next(u),n){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&s.duration-s.currentTime<BA&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),E(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:Mi(n)}}),t(Jt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),a=>{this.logRemoteEvent(a),this.handleRemoteVolumeChange({volume:a.value})}),t(Jt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),a=>{this.logRemoteEvent(a),this.handleRemoteVolumeChange({muted:a.value})});let i=sb(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,$A(["init"])).pipe(tb(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"),E(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),E(this.params.desiredState.playbackState,"playing"));let i=this.params.output.isLive$.getValue();this.params.output.duration$.next(i?0:t.duration),this.params.output.position$.next(i?0:t.currentTime),this.params.desiredState.seekState.setState({state:"none"})}}prepare(){let e=this.params.format;this.log({message:`[prepare] format: ${e}`});let t=this.createMediaInfo(e),i=this.createLoadRequest(t);this.loadMedia(i)}handleRemotePause(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="paused"||e==="playing")&&(this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="playing"||e==="paused")&&(this.videoState.setState("playing"),E(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.params.desiredState.playbackState.getTransition()?.to==="ready"&&E(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){let t=this.params.output.volume$.getValue(),i={volume:e.volume??t.volume,muted:e.muted??t.muted};(i.volume!==t.volume||i.muted!==i.muted)&&this.params.output.volume$.next(i)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:i}=this.params.connection;t.currentTime=e,i.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){let t=this.params.source,i,a,s;switch(e){case"MPEG":{let l=t[e];Xt(l);let c=DA(Object.keys(l));Xt(c);let d=l[c];Xt(d),i=d,a="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let l=t[e];Xt(l),i=l.url,a="application/x-mpegurl",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":{let l=t[e];Xt(l),i=l.url,a="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let l=t[e];Xt(l),i=l.url,a="application/dash+xml",s=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let l=t[e];Xt(l),i=de(l.url),a="application/x-mpegurl",s=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let l="Unsupported format for Chromecast",c=new Error(l);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:ib.VIDEO_PIPELINE,message:l,thrown:c}),c}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return Mi(e)}let n=new chrome.cast.media.MediaInfo(this.params.meta.videoId??i,a);n.contentUrl=i,n.streamType=s,n.metadata=new chrome.cast.media.GenericMediaMetadata;let{title:o,subtitle:u}=this.params.meta;return rb(o)&&(n.metadata.title=o),rb(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((a,s)=>{this.loadMediaTimeoutSubscription.add(CA(nb).subscribe(()=>s(`timeout(${nb})`)))});(0,ob.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()},a=>{let s=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${a}`;this.log({message:s}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:ib.VIDEO_PIPELINE,message:s,thrown:a})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var Gu=R(Ie(),1);import{clearVideoElement as lb}from"@vkontakte/videoplayer-shared";import{clearVideoElement as _A}from"@vkontakte/videoplayer-shared";var ub=r=>{try{r.pause(),r.playbackRate=0,_A(r),r.remove()}catch(e){console.error(e)}};import{fromEvent as NA,Subscription as FA}from"@vkontakte/videoplayer-shared";var xu=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)}},Pu=window.WeakMap?new WeakMap:new xu,ku=window.WeakMap?new WeakMap:new Map,qA=(r,e=20)=>{let t=0;return NA(r,"ratechange").subscribe(i=>{t++,t>=e&&(r.currentTime=r.currentTime,t=0)})},Ee=(r,{audioVideoSyncRate:e,disableYandexPiP:t})=>{let i=r.querySelector("video"),a=!!i;i?lb(i):(i=document.createElement("video"),r.appendChild(i)),Pu.set(i,a);let s=new FA;return s.add(qA(i,e)),ku.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},xe=r=>{ku.get(r)?.unsubscribe(),ku.delete(r);let t=Pu.get(r);Pu.delete(r),t?lb(r):ub(r)};var Au=R(Ci(),1);import{assertNonNullable as Er,isNonNullable as at,isNullable as zA,fromEvent as Di,merge as bb,observableFrom as gb,filterChanged as vb,map as xr,Subject as Sb,Subscription as KA,ValueSubject as XA,ErrorCategory as JA}from"@vkontakte/videoplayer-shared";import{isNonNullable as wu,isNullable as WA,Subscription as YA}from"@vkontakte/videoplayer-shared";var ws=(r,e,t,{equal:i=(n,o)=>n===o,changed$:a,onError:s}={})=>{let n=r.getState(),o=e(),u=WA(a),l=new YA;return a&&l.add(a.subscribe(c=>{let d=r.getState();i(c,d)&&r.setState(c)},s)),i(o,n)||(t(n),u&&r.setState(n)),l.add(r.stateChangeStarted$.subscribe(c=>{t(c.to),u&&r.setState(c.to)},s)),l},rt=(r,e,t)=>ws(e,()=>r.loop,i=>{wu(i)&&(r.loop=i)},{onError:t}),Pe=(r,e,t,i)=>ws(e,()=>({muted:r.muted,volume:r.volume}),a=>{wu(a)&&(r.muted=a.muted,r.volume=a.volume)},{equal:(a,s)=>a===s||a?.muted===s?.muted&&a?.volume===s?.volume,changed$:t,onError:i}),Ne=(r,e,t,i)=>ws(e,()=>r.playbackRate,a=>{wu(a)&&(r.playbackRate=a)},{changed$:t,onError:i}),Pt=ws;var ZA=r=>["__",r.language,r.label].join("|"),eL=(r,e)=>{if(r.id===e)return!0;let[t,i,a]=e.split("|");return r.language===i&&r.label===a},Lu=class r{constructor(e){this.available$=new Sb;this.current$=new XA(void 0);this.error$=new Sb;this.subscription=new KA;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 a=s=>{this.error$.next({id:"TextTracksManager",category:JA.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(Pt(t.internalTextTracks,()=>(0,Au.default)(this.internalTracks),s=>{at(s)&&this.setInternal(s)},{equal:(s,n)=>at(s)&&at(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(xr(s=>s.filter(({type:n})=>n==="internal"))),onError:a})),this.subscription.add(Pt(t.externalTextTracks,()=>(0,Au.default)(this.externalTracks),s=>{at(s)&&this.setExternal(s)},{equal:(s,n)=>at(s)&&at(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(xr(s=>s.filter(({type:n})=>n==="external"))),onError:a})),this.subscription.add(Pt(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:a})),this.subscription.add(Pt(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){Er(this.video);let{textTracks:e}=this.video;this.subscription.add(Di(e,"addtrack").subscribe(()=>{let i=this.current$.getValue();i&&this.select(i)})),this.subscription.add(bb(Di(e,"addtrack"),Di(e,"removetrack"),gb(["init"])).pipe(xr(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),vb((i,a)=>i.length===a.length&&i.every(({id:s},n)=>s===a[n].id))).subscribe(this.available$)),this.subscription.add(bb(Di(e,"change"),gb(["init"])).pipe(xr(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),xr(i=>i&&this.htmlTextTrackToITextTrack(i).id),vb()).subscribe(this.current$));let t=i=>this.applyCueSettings(i.target?.activeCues??null);this.subscription.add(Di(e,"addtrack").subscribe(i=>{i.track?.addEventListener("cuechange",t);let a=s=>{let n=s.target?.cues??null;n&&n.length&&(this.applyCueSettings(s.target?.cues??null),s.target?.removeEventListener("cuechange",a))};i.track?.addEventListener("cuechange",a)})),this.subscription.add(Di(e,"removetrack").subscribe(i=>{i.track?.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;let t=this.cueSettings.getState();for(let i of Array.from(e)){let a=i;at(t.align)&&(a.align=t.align),at(t.position)&&(a.position=t.position),at(t.size)&&(a.size=t.size),at(t.line)&&(a.line=t.line)}}htmlTextTracksAsArray(e=!1){Er(this.video);let t=[...this.video.textTracks];return e?t:t.filter(r.isHealthyTrack)}htmlTextTrackToITextTrack(e){let{language:t,label:i}=e,a=e.id?e.id:ZA(e),s=this.externalTracks.has(a),n=(s?this.externalTracks.get(a)?.isAuto:this.internalTracks.get(a)?.isAuto)??a.includes("auto");return s?{id:a,type:"external",isAuto:n,language:t,label:i,url:this.externalTracks.get(a)?.url}:{id:a,type:"internal",isAuto:n,language:t,label:i,url:this.internalTracks.get(a)?.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:a,isAuto:s})=>!this.internalTracks.has(i)&&!t.some(([,n])=>n.language===a&&n.isAuto===s)).forEach(i=>this.attach(i)),Array.from(this.internalTracks).filter(([i])=>!e.find(a=>a.id===i)).forEach(([,i])=>this.detach(i))}select(e){Er(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(zA(e)||!eL(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){Er(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){Er(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)}},Fe=Lu;var Zt=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 yb=r=>{let e=r;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e?.parentNode;return e??void 0},Ru=r=>{let e=yb(r);return!!(e&&e.fullscreenElement&&e.fullscreenElement===r)},Tb=r=>{let e=yb(r);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===r)};import{fromEvent as ke,map as kt,merge as Mu,filterChanged as lL,isNonNullable as Rb,Subject as cL,filter as kr,mapTo as Cu,combine as dL,once as pL,throttle as hL,ErrorCategory as mL,ValueSubject as $b,Subscription as fL}from"@vkontakte/videoplayer-shared";var tL=3,Ib=(r,e,t=tL)=>{let i=0,a=0;for(let s=0;s<r.length;s++){let n=r.start(s),o=r.end(s);if(n<=e&&e<=o){if(i=n,a=o,!t)return{from:i,to:a};for(let u=s-1;u>=0;u--)r.end(u)+t>=i&&(i=r.start(u));for(let u=s+1;u<r.length;u++)r.start(u)-t<=a&&(a=r.end(u))}}return{from:i,to:a}};var As=class{get current(){return this._current}get isYandex(){return this.current==="Yandex"}get isSafari(){return this.current==="Safari"}get isSamsungBrowser(){return this.current==="SamsungBrowser"}get safariVersion(){return this._safariVersion}detect(){let{userAgent:e}=navigator;try{let t=/yabrowser/i.test(e)?"Yandex":void 0,i=/samsungbrowser/i.test(e)?"SamsungBrowser":void 0,a=/chrome|crios/i.test(e)?"Chrome":void 0,s=/chromium/i.test(e)?"Chromium":void 0,n=/firefox|fxios/i.test(e)?"Firefox":void 0,o=/webkit|safari|khtml/i.test(e)?"Safari":void 0,u=/opr\//i.test(e)?"Opera":void 0,l=/edg/i.test(e)?"Edge":void 0;this._current=t||i||n||u||l||a||s||o||"Rest"}catch(t){console.error(t)}this.isSafari&&this.detectSafariVersion()}detectSafariVersion(){try{let{userAgent:e}=window.navigator,t=e.match(/Version\/(\d+)/);if(!t)return;let i=t[1],a=parseInt(i,10);if(isNaN(a))return;this._safariVersion=a}catch(e){console.error(e)}}};var Eb=R(Ie(),1);var Pr=()=>/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test(navigator.appVersion??navigator.userAgent)||navigator?.userAgentData?.mobile;var Ls=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,Eb.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=Pr()}catch(t){console.error(t)}this.detectDevice(e),this.detectHighEntropyValues(),this.isIOS&&this.detectIOSVersion()}async detectHighEntropyValues(){let{userAgentData:e}=navigator;if(e){let t=await e.getHighEntropyValues(["architecture","bitness","brands","mobile","platform","formFactor","model","platformVersion","wow64"]);this._highEntropyValues=t}}detectDevice(e){try{let t=/android/i.test(e)?"Android":void 0,i=/iphone/i.test(e)?"iPhone":void 0,a=/ipad/i.test(e)?"iPad":void 0,s=/ipod/i.test(e)?"iPod":void 0,n=/mac/i.test(e)?"Mac":void 0,o=/webOS|BlackBerry|IEMobile|Opera Mini/i.test(e)?"RestMobile":void 0;this._current=t||i||a||s||o||n||"Desktop"}catch(t){console.error(t)}}detectIOSVersion(){try{if(this._highEntropyValues.platformVersion){let s=this._highEntropyValues.platformVersion.split(".").slice(0,2).join("."),n=parseFloat(s);this._iosVersion=n;return}let{userAgent:e}=window.navigator,t=e.match(/OS (\d+(_\d+)?)/i);if(!t)return;let i=t[1].replace(/_/g,".");if(!i)return;let a=parseFloat(i);if(isNaN(a))return;this._iosVersion=a}catch(e){console.error(e)}}};var Rs=class{get isTouch(){return typeof this._maxTouchPoints=="number"?this._maxTouchPoints>1:"ontouchstart"in window}get maxTouchPoints(){return this._maxTouchPoints}get height(){return this._height}get width(){return this._width}get screenHeight(){return this._screenHeight}get screenWidth(){return this._screenWidth}get pixelRatio(){return this._pixelRatio}get isHDR(){return this._isHdr}get colorDepth(){return this._colorDepth}detect(){let{maxTouchPoints:e}=navigator;try{this._maxTouchPoints=e??0,this._isHdr=!!matchMedia("(dynamic-range: high)")?.matches,this._colorDepth=screen.colorDepth}catch(t){console.error(t)}try{this._pixelRatio=window.devicePixelRatio||1,this._height=screen.height,this._width=screen.width,this._height=screen.height,this._screenHeight=this._height*this._pixelRatio,this._screenWidth=this._width*this._pixelRatio}catch(t){console.error(t)}}};var Ye=()=>window.ManagedMediaSource||window.MediaSource,$s=()=>!!(window.ManagedMediaSource&&window.ManagedSourceBuffer?.prototype?.appendBuffer),xb=()=>!!(window.MediaSource&&window.SourceBuffer?.prototype?.appendBuffer),Pb=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var iL=document.createElement("video"),rL='video/mp4; codecs="avc1.42000a,mp4a.40.2"',aL='video/mp4; codecs="hev1.1.6.L93.B0"',kb='video/webm; codecs="vp09.00.10.08"',wb='video/webm; codecs="av01.0.00M.08"',sL='audio/mp4; codecs="mp4a.40.2"',nL='audio/webm; codecs="opus"',Ab,oL=async()=>{if(!window.navigator.mediaCapabilities)return;let r={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=await Promise.all([window.navigator.mediaCapabilities.decodingInfo({...r,video:{...r.video,contentType:wb}}),window.navigator.mediaCapabilities.decodingInfo({...r,video:{...r.video,contentType:kb}})]);Ab={DASH_WEBM_AV1:e,DASH_WEBM:t}};oL().catch(r=>{console.log(iL),console.error(r)});var Ms=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 Ab}get supportedCodecs(){return Object.keys(this._codecs).filter(e=>this._codecs[e])}get nativeHlsSupported(){return this._nativeHlsSupported}detect(){this._video=document.createElement("video");try{this._protocols={mms:$s(),mse:xb(),hls:!!(this._video.canPlayType?.("application/x-mpegurl")||this._video.canPlayType?.("vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},this._containers={mp4:!!this._video.canPlayType?.("video/mp4"),webm:!!this._video.canPlayType?.("video/webm"),cmaf:!0};let e=!!Ye()?.isTypeSupported?.(rL),t=!!Ye()?.isTypeSupported?.(aL),i=!!Ye()?.isTypeSupported?.(sL);this._codecs={h264:e,h265:t,vp9:!!Ye()?.isTypeSupported?.(kb),av1:!!Ye()?.isTypeSupported?.(wb),aac:i,opus:!!Ye()?.isTypeSupported?.(nL),mpeg:(e||t)&&i},this._nativeHlsSupported=this._protocols.hls&&this._containers.mp4}catch(e){console.error(e)}this.destroyVideoElement()}destroyVideoElement(){if(!this._video)return;if(this._video.pause(),this._video.currentTime=0,this._video.removeAttribute("src"),this._video.src="",this._video.load(),this._video.remove){this._video.remove(),this._video=null;return}this._video.parentNode&&this._video.parentNode.removeChild(this._video);let e=this._video.cloneNode(!1);this._video.parentNode?.replaceChild(e,this._video),this._video=null}};var Lb="audio/mpeg",Cs=class{supportMp3(){return this._codecs.mp3&&this._containers.mpeg}detect(){this._audio=document.createElement("audio");try{this._containers={mpeg:!!this._audio.canPlayType?.(Lb)},this._codecs={mp3:!!Ye()?.isTypeSupported?.(Lb)}}catch(e){console.error(e)}this.destroyAudioElement()}destroyAudioElement(){if(!this._audio)return;if(this._audio.pause(),this._audio.currentTime=0,this._audio.removeAttribute("src"),this._audio.src="",this._audio.load(),this._audio.remove){this._audio.remove(),this._audio=null;return}this._audio.parentNode&&this._audio.parentNode.removeChild(this._audio);let e=this._audio.cloneNode(!1);this._audio.parentNode?.replaceChild(e,this._audio),this._audio=null}};import{ValueSubject as uL}from"@vkontakte/videoplayer-shared";var $u=class{constructor(){this.isInited$=new uL(!1);this._displayChecker=new Rs,this._deviceChecker=new Ls(this._displayChecker),this._browserChecker=new As,this._videoChecker=new Ms(this._deviceChecker,this._browserChecker),this._audioChecker=new Cs,this.detect()}get display(){return this._displayChecker}get device(){return this._deviceChecker}get browser(){return this._browserChecker}get video(){return this._videoChecker}get audio(){return this._audioChecker}async detect(){this._displayChecker.detect(),this._deviceChecker.detect(),this._browserChecker.detect(),this._videoChecker.detect(),this._audioChecker.detect(),this.isInited$.next(!0)}},V=new $u;var we=r=>{let e=S=>ke(r,S).pipe(Cu(void 0)),t=new fL,i=()=>t.unsubscribe(),s=Mu(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(S=>ke(r,S))).pipe(kt(S=>S.type==="ended"?r.readyState<2:r.readyState<3),lL()),n=Mu(ke(r,"progress"),ke(r,"timeupdate")).pipe(kt(()=>Ib(r.buffered,r.currentTime))),o=V.browser.isSafari?dL({play:e("play").pipe(pL()),playing:e("playing")}).pipe(Cu(void 0)):e("playing"),u=ke(r,"volumechange").pipe(kt(()=>({muted:r.muted,volume:r.volume}))),l=ke(r,"ratechange").pipe(kt(()=>r.playbackRate)),c=ke(r,"error").pipe(kr(()=>!!(r.error||r.played.length)),kt(()=>{let S=r.error;return{id:S?`MediaError#${S.code}`:"HtmlVideoError",category:mL.VIDEO_PIPELINE,message:S?S.message:"Error event from HTML video element",thrown:r.error??void 0}})),d=ke(r,"timeupdate").pipe(kt(()=>r.currentTime)),p=new cL,h=.3,f;t.add(d.subscribe(S=>{r.loop&&Rb(f)&&Rb(S)&&f>=r.duration-h&&S<=h&&p.next(f),f=S}));let b=e("pause").pipe(kr(()=>!r.error&&f!==r.duration)),g=ke(r,"enterpictureinpicture"),v=ke(r,"leavepictureinpicture"),x=new $b(Tb(r));t.add(g.subscribe(()=>x.next(!0))),t.add(v.subscribe(()=>x.next(!1)));let T=new $b(Ru(r)),P=ke(r,"fullscreenchange");t.add(P.pipe(kt(()=>Ru(r))).subscribe(T));let I=.1,B=1e3,O=ke(r,"timeupdate").pipe(kr(S=>r.duration-r.currentTime<I)),F=Mu(O.pipe(kr(S=>!r.loop)),ke(r,"ended")).pipe(hL(B),Cu(void 0)),N=O.pipe(kr(S=>r.loop));return{playing$:o,pause$:b,canplay$:e("canplay"),ended$:F,looped$:p,loopExpected$:N,error$:c,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:d,durationChange$:ke(r,"durationchange").pipe(kt(()=>r.duration)),isBuffering$:s,currentBuffer$:n,volumeState$:u,playbackRateState$:l,inPiP$:x,inFullscreen$:T,enterPip$:g,leavePip$:v,destroy:i}};import{VideoQuality as wt}from"@vkontakte/videoplayer-shared";var At=r=>{switch(r){case"mobile":return wt.Q_144P;case"lowest":return wt.Q_240P;case"low":return wt.Q_360P;case"sd":case"medium":return wt.Q_480P;case"hd":case"high":return wt.Q_720P;case"fullhd":case"full":return wt.Q_1080P;case"quadhd":case"quad":return wt.Q_1440P;case"ultrahd":case"ultra":return wt.Q_2160P}};var Rt=R(Lt(),1),Wb=R(Ie(),1),Bs=R(Ii(),1);import{isNonNullable as ge,isNullable as Hb,now as Yb,isHigher as jb,isHigherOrEqual as Ou,isInvariantQuality as Qb,isLowerOrEqual as _u,videoSizeToQuality as kL,assertNotEmptyArray as zb,assertNonNullable as wL}from"@vkontakte/videoplayer-shared";var Du=!1,pt={},_b=r=>{Du=r},Nb=()=>{pt={}},Fb=r=>{r(pt)},wr=(r,e)=>{Du&&(pt.meta=pt.meta??{},pt.meta[r]=e)},be=class{constructor(e){this.name=e}next(e){if(!Du)return;pt.series=pt.series??{};let t=pt.series[this.name]??[];t.push([Date.now(),e]),pt.series[this.name]=t}};import{isHigher as xL,isHigherOrEqual as $_,isLower as qb,isLowerOrEqual as M_,isNonNullable as Ds,isNullable as PL,videoHeightToQuality as Vs}from"@vkontakte/videoplayer-shared";function Vu({limits:r,highQualityLimit:e,trafficSavingLimit:t}){return!r.max&&r.min===e?"high_quality":!r.min&&r.max===t?"traffic_saving":"unknown"}function Bu({limits:r,highQualityLimit:e,trafficSavingLimit:t}){return!!r&&Vu({limits:r,highQualityLimit:e,trafficSavingLimit:t})==="high_quality"}function Ar({limits:r,highestAvailableQuality:e,lowestAvailableQuality:t}){return PL(r)||Ds(r.min)&&Ds(r.max)&&qb(r.max,r.min)||Ds(r.min)&&e&&xL(r.min,e)||Ds(r.max)&&t&&qb(r.max,t)}function Ub({limits:r,highestAvailableHeight:e,lowestAvailableHeight:t}){return Ar({limits:{max:r?.max?Vs(r.max):void 0,min:r?.min?Vs(r.min):void 0},highestAvailableQuality:e?Vs(e):void 0,lowestAvailableQuality:t?Vs(t):void 0})}var AL=new be("best_bitrate"),Kb=(r,e,t)=>(e-t)*Math.pow(2,-10*r)+t;var Nu=r=>(e,t)=>r*(Number(e.bitrate)-Number(t.bitrate)),Lr=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=Yb()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},Xb='Assertion "ABR Tracks is empty array" failed',Os=(r,e,t,i)=>{let a=[...e].sort(Nu(1)),s=[...t].sort(Nu(1)),n=s.filter(u=>ge(u.bitrate)&&ge(r.bitrate)?r.bitrate/u.bitrate>i:!0),o=(0,Rt.default)(s,Math.round(s.length*a.indexOf(r)/(a.length+1)))??(0,Rt.default)(s,-1);return o&&(0,Wb.default)(n,o)?o:n.length?(0,Rt.default)(n,-1):(0,Rt.default)(s,0)},Gb=r=>"quality"in r,Jb=(r,e,t,i)=>{let a=ge(i?.last?.bitrate)&&ge(t?.bitrate)&&i.last.bitrate<t.bitrate?r.trackCooldownIncreaseQuality:r.trackCooldownDecreaseQuality,s=t&&i&&i.history[t.id]&&Yb()-i.history[t.id]<=a&&(!i.last||t.id!==i.last.id);if(t?.id&&i&&!s&&i.recordSelection(t),s&&i?.last){let n=i.last;i?.recordSwitch(n);let o=Gb(n)?"video":"audio",u=Gb(n)?n.quality:n.bitrate;return e({message:`
8
- [last ${o} selected] ${u}
9
- `}),n}return i?.recordSwitch(t),t},LL=(r,e)=>Math.log(e)/Math.log(r),RL=({tuning:r,container:e,limits:t,panelSize:i})=>{let a=r.containerSizeFactor;if(i)return{containerSizeLimit:i,containerSizeFactor:a};if(r.usePixelRatio&&V.display.pixelRatio){let s=V.display.pixelRatio;if(r.pixelRatioMultiplier)a*=r.pixelRatioMultiplier*(s-1)+1;else{let n=r.pixelRatioLogBase,[o=0,u=0,l=0]=r.pixelRatioLogCoefficients,c=LL(n,o*s+u)+l;Number.isFinite(c)&&(a*=c)}}return Bu({highQualityLimit:r.highQualityLimit,trafficSavingLimit:r.trafficSavingLimit,limits:t})&&(a*=2),{containerSizeLimit:r.limitByContainer&&e&&e.width>0&&e.height>0?{width:e.width*a,height:e.height*a}:void 0,containerSizeFactor:a}},$t=(r,{container:e,estimatedThroughput:t,tuning:i,limits:a,reserve:s=0,forwardBufferHealth:n,playbackRate:o,current:u,history:l,visible:c,droppedVideoMaxQualityLimit:d,stallsVideoMaxQualityLimit:p,stallsPredictedThroughput:h,abrLogger:f,panelSize:b})=>{zb(r,Xb);let{containerSizeFactor:g,containerSizeLimit:v}=RL({container:e,tuning:i,limits:a,panelSize:b}),x=i.considerPlaybackRate&&ge(o)?o:1,T=r.filter(A=>!Qb(A.quality)).sort((A,ie)=>jb(A.quality,ie.quality)?-1:1),P=(0,Rt.default)(T,-1)?.quality,I=(0,Rt.default)(T,0)?.quality,B=Ar({limits:a,lowestAvailableQuality:P,highestAvailableQuality:I}),O=x*Kb(n??.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),F={},S=T.filter(A=>{let ie=!0;if(v)if(A.size)ie=A.size.width<=v.width&&A.size.height<=v.height;else{let C=v&&kL(v);ie=C?_u(A.quality,C):!0}if(!ie)return F[A.quality]="FitsContainer",!1;let k=h||t,H=ge(k)&&isFinite(k)&&ge(A.bitrate)?k-s>=A.bitrate*O:!0,Y=Bu({highQualityLimit:i.highQualityLimit,trafficSavingLimit:i.trafficSavingLimit,limits:a})&&a?.min===A.quality;if(!H&&!Y)return F[A.quality]="FitsThroughput",!1;if(i.lazyQualitySwitch&&ge(i.minBufferToSwitchUp)&&u&&!Qb(u.quality)&&(n??0)<i.minBufferToSwitchUp&&jb(A.quality,u.quality))return F[A.quality]="Buffer",!1;if(!!d&&Ou(A.quality,d)&&!Y)return F[A.quality]="DroppedFramesLimit",!1;if(!!p&&Ou(A.quality,p)&&!Y)return F[A.quality]="StallsLimit",!1;let ye=B||(Hb(a?.max)||_u(A.quality,a.max))&&(Hb(a?.min)||Ou(A.quality,a.min)),j=ge(c)&&!c?_u(A.quality,i.backgroundVideoQualityLimit):!0;return!ye||!j?(F[A.quality]="FitsQualityLimits",!1):!0})[0];S&&S.bitrate&&AL.next(S.bitrate);let M=S??(0,Rt.default)(T,-1)??r[0],w=l?.last,W=Jb(i,f,M,l);return ge(l)&&W.quality!==w?.quality&&f({message:`
10
- [VIDEO TRACKS ABR]
11
- [available video tracks]
12
- ${r.map(A=>`{ id: ${A.id}, quality: ${A.quality}, bitrate: ${A.bitrate}, size: ${A.size?.width}:${A.size?.height} }`).join(`
13
- `)}
14
-
15
- [tuning]
16
- ${(0,Bs.default)(i??{}).map(([A,ie])=>`${A}: ${ie}`).join(`
17
- `)}
18
-
19
- [limit params]
20
- containerSizeFactor: ${g},
21
- containerSizeLimit: ${v?.width??0} x ${v?.height??0},
22
- estimatedThroughput: ${t},
23
- stallsPredictedThroughput: ${h},
24
- reserve: ${s},
25
- playbackRate: ${o},
26
- playbackRateFactor: ${x},
27
- forwardBufferHealth: ${n},
28
- bitrateFactor: ${O},
29
- minBufferToSwitchUp: ${i.minBufferToSwitchUp},
30
- droppedVideoMaxQualityLimit: ${d},
31
- stallsVideoMaxQualityLimit: ${p},
32
- limitsAreInvalid: ${B},
33
- maxQualityLimit: ${a?.max},
34
- minQualityLimit: ${a?.min},
35
-
36
- [limited video tracks]
37
- ${(0,Bs.default)(F).map(([A,ie])=>`${A}: ${ie}`).join(`
38
- `)||"All tracks are available"}
39
-
40
- [best video track] ${S?.quality}
41
- [selected video track] ${W?.quality}
42
- `}),W},Zb=(r,e,t,{estimatedThroughput:i,tuning:a,playbackRate:s,forwardBufferHealth:n,history:o,abrLogger:u,stallsPredictedThroughput:l})=>{zb(t,Xb);let c=a.considerPlaybackRate&&ge(s)?s:1,d=[...t].sort(Nu(-1)),p=r.bitrate;wL(p);let h=c*Kb(n??.5,a.bitrateAudioFactorAtEmptyBuffer,a.bitrateAudioFactorAtFullBuffer),f,b=Os(r,e,t,a.minVideoAudioRatio),g=l||i;ge(g)&&isFinite(g)&&(f=d.find(T=>ge(T.bitrate)&&ge(b?.bitrate)?g-p>=T.bitrate*h&&T.bitrate>=b.bitrate:!1)),f||(f=b);let v=o?.last,x=f&&Jb(a,u,f,o);return ge(o)&&x?.bitrate!==v?.bitrate&&u({message:`
43
- [AUDIO TRACKS ABR]
44
- [available audio tracks]
45
- ${t.map(T=>`{ id: ${T.id}, bitrate: ${T.bitrate} }`).join(`
46
- `)}
47
-
48
- [tuning]
49
- ${(0,Bs.default)(a??{}).map(([T,P])=>`${T}: ${P}`).join(`
50
- `)}
51
-
52
- [limit params]
53
- estimatedThroughput: ${i},
54
- stallsPredictedThroughput: ${l},
55
- reserve: ${p},
56
- playbackRate: ${s},
57
- playbackRateFactor: ${c},
58
- forwardBufferHealth: ${n},
59
- bitrateFactor: ${h},
60
- minBufferToSwitchUp: ${a.minBufferToSwitchUp},
61
-
62
- [selected audio track] ${x?.id}
63
- `}),x};var ne=r=>new URL(r).hostname;import{assertNever as cg,assertNonNullable as dg,combine as XL,debounce as JL,ErrorCategory as pg,filter as hg,filterChanged as ZL,isNonNullable as ju,map as Us,merge as mg,observableFrom as eR,once as tR,Subscription as iR,ValueSubject as Qu,videoQualityToHeight as fg,videoSizeToQuality as rR}from"@vkontakte/videoplayer-shared";var ng=R(Lt(),1);var tg=R(Ie(),1),eg=r=>{if(r instanceof DOMException&&(0,tg.default)(["Failed to load because no supported source was found.","The element has no supported sources."],r.message))throw r;return!(r instanceof DOMException&&(r.code===20||r.name==="AbortError"))},Ae=async(r,e)=>{let t=r.muted;try{await r.play()}catch(i){if(!eg(i))return!1;if(e&&e(),t)return console.warn(i),!1;r.muted=!0;try{await r.play()}catch(a){return eg(a)&&(r.muted=!1,console.warn(a)),!1}}return!0};import{isNonNullable as Ns,isNullable as CL,assertNonNullable as Mr}from"@vkontakte/videoplayer-shared";var rg=R(Ci(),1);import{isNonNullable as ig,assertNonNullable as _s,now as $L}from"@vkontakte/videoplayer-shared";function oe(){return $L()}function Fu(r){return oe()-r}function qu(r){let e=r.split("/"),t=e.slice(0,e.length-1).join("/"),i=/^([a-z]+:)?\/\//i,a=n=>i.test(n);return{resolve:(n,o,u=!1)=>{a(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 ag(r,e,t){let i=(...a)=>{t.apply(null,a),r.removeEventListener(e,i)};r.addEventListener(e,i)}function Vi(r,e,t,i){let a=window.XMLHttpRequest,s,n,o,u=!1,l=0,c,d,p=!1,h="arraybuffer",f=7e3,b=2e3,g=()=>{if(u)return;_s(c);let w=Fu(c),W;if(w<b){W=b-w,setTimeout(g,W);return}b*=2,b>f&&(b=f),n&&n.abort(),n=new a,B()},v=w=>(s=w,M),x=w=>(d=w,M),T=()=>(h="json",M),P=()=>{if(!u){if(--l>=0){g(),i&&i();return}u=!0,d&&d(),t&&t()}},I=w=>(p=w,M),B=()=>{c=oe(),n=new a,n.open("get",r);let w=0,W,A=0,ie=()=>(_s(c),Math.max(c,Math.max(W||0,A||0)));if(s&&n.addEventListener("progress",k=>{let H=oe();s.updateChunk&&k.loaded>w&&(s.updateChunk(ie(),k.loaded-w),w=k.loaded,W=H)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>P())),n.addEventListener("load",()=>{if(u)return;_s(n);let k=n.status;if(k>=200&&k<300){let{response:H,responseType:Y}=n,J=H?.byteLength;if(typeof J=="number"&&s){let re=J-w;re&&s.updateChunk&&s.updateChunk(ie(),re)}Y==="json"&&(!H||!(0,rg.default)(H).length)?P():(d&&d(),e(H))}else P()}),n.addEventListener("error",()=>{P()}),p){let k=()=>{_s(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(A=oe(),n.removeEventListener("readystatechange",k))};n.addEventListener("readystatechange",k)}return n.responseType=h,n.send(),M},M={withBitrateReporting:v,withParallel:I,withJSONResponse:T,withRetryCount:w=>(l=w,M),withRetryInterval:(w,W)=>(ig(w)&&(b=w),ig(W)&&(f=W),M),withTimeout:w=>(o=w,M),withFinally:x,send:B,abort:()=>{n&&(n.abort(),n=void 0),u=!0,d&&d()}};return M}var Rr=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,a=0;for(;this.intervals.length>0;){let s=this.intervals[0];if(s.end<=t)i+=s.end-s.start,a+=s.bytes,this.intervals.splice(0,1);else{if(s.start>=t)break;{let n=t-s.start,o=s.end-s.start;i+=n;let u=s.bytes*n/o;a+=u,s.start=t,s.bytes-=u}}}if(a>0&&i>0){let s=a*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(a)}/${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 sg=R(Ci(),1);var $r=class{constructor(e,t,i,a,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=a,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=oe(),a=u=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=u,e._errorCB?e._errorCB(u):(this.limitCompleteCount(),this.completeRequests[t]=e)},s=u=>{e._complete=1,e._responseData=u,e._downloadTime=oe()-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=Vi(t,s,()=>a("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=oe()}_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=oe();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,sg.default)(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,i,a){let s={};return s.send=()=>{let n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=i,n._retryCB=a,n._finallyCB=s._finallyCB,n._error||n._complete?(this._removeFromActive(e),setTimeout(()=>{n._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(n._responseData,n._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),i(n._errorMsg)),s._finallyCB&&s._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{let o=this.pendingQueue.indexOf(e);o!==-1&&this.pendingQueue.splice(o,1),this.logger(`Request not prefetched, starting new request, url=${e}${o===-1?"":"; removed pending"}`),this._sendRequest(s,e)}},s._cb=t,s._errorCB=i,s._retryCB=a,s.abort=function(){s.request&&s.request.abort()},s.withFinally=n=>(s._finallyCB=n,s),s}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}};import{Subject as DL}from"@vkontakte/videoplayer-shared";var Fs=1e4,Uu=3;var VL=6e4,BL=10,OL=1,_L=500,Cr=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 DL,this.chunkRateEstimator=new Rr(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=qu(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setAutoQualityLimits(e){this.autoQualityLimits=e}switchByName(e){let t;for(let i=0;i<this.manifest.length;++i)if(t=this.manifest[i],t.name===e){this._switchToQuality(t);return}}catchUp(){this.rep&&this.rep.stop(),this.currentManifestEntry&&(this.paused=!1,this._initPlayerWith(this.currentManifestEntry),this._notifyBuffering(!0))}stop(){this.params.videoElement.pause(),this.rep&&(this.rep.stop(),this.rep=null)}pause(){this.paused=!0,this.params.videoElement.pause(),this.videoPlayStarted=!1,this._notifyBuffering(!1)}play(){this.paused=!1;let e=this.lowLatency&&this._getBufferSizeSec()>this.sourceJitter+5;this.rep&&!e?(this.bufferStates=[],this.videoPlayStarted=!1,this.shouldPlay()?this._playVideoElement():this._notifyBuffering(!0)):this.catchUp()}startPlay(e,t){this.autoQuality=t,this._initPlayerWith(e)}destroy(){this.destroyed=!0,this.rep&&(this.rep.stop(),this.rep=null),this.manifestRequest&&this.manifestRequest.abort(),this.manifestRefetchTimer&&(clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=void 0)}reinit(e){this.manifestUrl=e,this.urlResolver=qu(e),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){let e=this.params.videoElement,t=0,i=e.buffered.length;return i!==0&&(t=e.buffered.end(i-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){let{videoElement:e,logger:t}=this.params;e.addEventListener("error",()=>{!!e.error&&!this.destroyed&&(t(`Video element error: ${e.error?.code}`),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,a;i!==0&&!this.waitingForFirstBufferAfterSrcChange&&(a=t.buffered.start(i-1),t.currentTime<a&&(e("Fixup stall"),t.currentTime=a))}_selectQuality(e){let{videoElement:t}=this.params,i,a,s,n=t&&1.62*(V.display.pixelRatio||1)*t.offsetHeight||520;for(let o=0;o<this.manifest.length;++o){s=this.manifest[o];let{max:u,min:l}=this.autoQualityLimits||{};!Ub({limits:this.autoQualityLimits,highestAvailableHeight:this.manifest[0].video.height,lowestAvailableHeight:(0,ng.default)(this.manifest,-1).video.height})&&(u&&s.video.height>u||l&&s.video.height<l)||(s.bitrate<e&&n>Math.min(s.video.height,s.video.width)?(!a||s.bitrate>a.bitrate)&&(a=s):(!i||i.bitrate>s.bitrate)&&(i=s))}return a||i}shouldPlay(){if(this.paused)return!1;let t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||Ns(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){let{logger:i,videoElement:a,playerCallback:s}=this.params;this.mediaSource=new window.MediaSource,i("setting video src"),a.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,a.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});let n=()=>{ag(a,"progress",()=>{a.buffered.length?(a.currentTime=a.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 $r(Uu,Fs,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:i,playerCallback:a}=this.params,s=!1,n=null,o=null,u=null,l=null,c=!1,d=()=>{let P=s&&(!c||c===this.rep);return P||t("Not running!"),P},p=(P,I,B)=>{u&&u.abort(),u=Vi(this.urlResolver.resolve(P,!1),I,B,()=>this._retryCallback()).withTimeout(Fs).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Uu).withFinally(()=>{u=null}).send()},h=(P,I,B)=>{Mr(this.filesFetcher),o?.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(P,!1),I,B,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},f=P=>{let I=i.playbackRate;i.playbackRate!==P&&(t(`Playback rate switch: ${I}=>${P}`),i.playbackRate=P)},b=P=>{this.lowLatency=P,t(`lowLatency changed to ${P}`),g()},g=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)f(1);else{let P=this._getBufferSizeSec();if(this.bufferStates.length<5){f(1);return}let B=oe()-1e4,O=0;for(let N=0;N<this.bufferStates.length;N++){let S=this.bufferStates[N];P=Math.min(P,S.buf),S.ts<B&&O++}this.bufferStates.splice(0,O),t(`update playback rate; minBuffer=${P} drop=${O} jitter=${this.sourceJitter}`);let F=P-OL;this.sourceJitter>=0?F-=this.sourceJitter/2:this.sourceJitter-=1,F>3?f(1.15):F>1?f(1.1):F>.3?f(1.05):f(1)}},v=P=>{let I,B=()=>I&&I.start?I.start.length:0,O=k=>I.start[k]/1e3,F=k=>I.dur[k]/1e3,N=k=>I.fragIndex+k,S=(k,H)=>({chunkIdx:N(k),startTS:O(k),dur:F(k),discontinuity:H}),M=()=>{let k=0;if(I&&I.dur){let H=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,Y=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,J=H;this.sourceJitter>1&&(J+=this.sourceJitter-1);let re=I.dur.length-1;for(;re>=0&&(J-=I.dur[re],!(J<=0));--re);k=Math.min(re,I.dur.length-1-Y),k=Math.max(k,0)}return S(k,!0)},w=k=>{let H=B();if(!(H<=0)){if(Ns(k)){for(let Y=0;Y<H;Y++)if(O(Y)>k)return S(Y)}return M()}},W=k=>{let H=B(),Y=k?k.chunkIdx+1:0,J=Y-I.fragIndex;if(!(H<=0)){if(!k||J<0||J-H>BL)return t(`Resync: offset=${J} bChunks=${H} chunk=`+JSON.stringify(k)),M();if(!(J>=H))return S(Y-I.fragIndex,!1)}},A=(k,H,Y)=>{l&&l.abort(),l=Vi(this.urlResolver.resolve(k,!0,this.lowLatency),H,Y,()=>this._retryCallback()).withTimeout(Fs).withRetryCount(Uu).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(k,H)=>{A(P,Y=>{if(!d())return;I=Y;let J=!!I.lowLatency;J!==this.lowLatency&&b(J);let re=0;for(let Se=0;Se<I.dur.length;++Se)re+=I.dur[Se];re>0&&(Mr(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(re/I.dur.length)),a({name:"index",zeroTime:I.zeroTime,shiftDuration:I.shiftDuration}),this.sourceJitter=I.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,I.jitter/1e3)):1,k(w(H))},()=>this._handleNetworkError())},nextChunk:W}},x=()=>{s=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),Mr(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:P=>{let{videoElement:I,logger:B}=this.params,O=v(e.jidxUrl),F,N,S,M,w=0,W,A,ie,k=()=>{W&&(clearTimeout(W),W=void 0);let C=Math.max(_L,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),Te=w+C,me=oe(),ae=Math.min(1e4,Te-me);w=me;let Oe=()=>{l||d()&&O.seek(()=>{d()&&(w=oe(),H(),k())})};ae>0?W=window.setTimeout(()=>{this.paused?k():Oe()},ae):Oe()},H=()=>{let C;for(;C=O.nextChunk(M);)M=C,ye(C);let Te=O.nextChunk(S);if(Te){if(S&&Te.discontinuity){B("Detected discontinuity; restarting playback"),this.paused?k():(x(),this._initPlayerWith(e));return}Se(Te)}else k()},Y=(C,Te)=>{if(!d()||!this.sourceBuffer)return;let me,ae,Oe,vt=Xe=>{window.setTimeout(()=>{d()&&Y(C,Te)},Xe)};if(this.sourceBuffer.updating)B("Source buffer is updating; delaying appendBuffer"),vt(100);else{let Xe=oe(),Re=I.currentTime;!this.paused&&I.buffered.length>1&&A===Re&&Xe-ie>500&&(B("Stall suspected; trying to fix"),this._fixupStall()),A!==Re&&(A=Re,ie=Xe);let St=this._getBufferSizeSec();if(St>30)B(`Buffered ${St} seconds; delaying appendBuffer`),vt(2e3);else try{this.sourceBuffer.appendBuffer(C),this.videoPlayStarted?(this.bufferStates.push({ts:Xe,buf:St}),g(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),Te&&Te()}catch(Je){if(Je.name==="QuotaExceededError")B("QuotaExceededError; delaying appendBuffer"),Oe=this.sourceBuffer.buffered.length,Oe!==0&&(me=this.sourceBuffer.buffered.start(0),ae=Re,ae-me>4&&this.sourceBuffer.remove(me,ae-3)),vt(1e3);else throw Je}}},J=()=>{N&&F&&(B([`Appending chunk, sz=${N.byteLength}:`,JSON.stringify(S)]),Y(N,function(){N=null,H()}))},re=C=>e.fragUrlTemplate.replace("%%id%%",C.chunkIdx),Se=C=>{d()&&h(re(C),(Te,me)=>{if(d()){if(me/=1e3,N=Te,S=C,n=C.startTS,me){let ae=Math.min(10,C.dur/me);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*ae:ae}J()}},()=>this._handleNetworkError())},ye=C=>{d()&&(Mr(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(re(C),!1)))},j=C=>{d()&&(e.cachedHeader=C,Y(C,()=>{F=!0,J()}))};s=!0,O.seek(C=>{if(d()){if(w=oe(),!C){k();return}M=C,!CL(P)||C.startTS>P?Se(C):(S=C,H())}},P),e.cachedHeader?j(e.cachedHeader):p(e.headerUrl,j,()=>this._handleNetworkError())},stop:x,getTimestampSec:()=>n},c}_switchToQuality(e){let{logger:t,playerCallback:i}=this.params,a;e.bitrate!==this.bitrate&&(this.rep&&(a=this.rep.getTimestampSec(),Ns(a)&&(a+=.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,Mr(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(a),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return Ns(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,i=d=>{if(!this.autoQuality)return;let p,h,f;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&d<this.bitrate&&(h=this._getBufferSizeSec(),f=d/this.bitrate,h>10&&f>.8||h>15&&f>.5||h>20&&f>.3)){e(`Not switching: buffer=${Math.floor(h)}; bitrate=${this.bitrate}; newRate=${Math.floor(d)}`);return}p=this._selectQuality(d),p?this._switchToQuality(p):e(`Could not find quality by bitrate ${d}`)},s={updateChunk:(p,h)=>{let f=oe();if(this.chunkRateEstimator.addInterval(p,f,h)){let g=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:h,duration:f-p,speed:g}),!0}},get:()=>{let p=this.chunkRateEstimator.getBitRate();return p?p*.85:0}},n=-1/0,o,u=!0,l=()=>{let d=s.get();if(d&&o&&this.autoQuality){if(u&&d>o&&Fu(n)<3e4)return;i(d)}u=this.autoQuality};return{updateChunk:(d,p)=>{let h=s.updateChunk(d,p);return h&&l(),h},notifySwitch:d=>{let p=oe();d<o&&(n=p),o=d}}}_fetchManifest(e,t,i){this.manifestRequest=Vi(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(Fs).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;Ae(e,()=>{this.soundProhibitedEvent$.next()}).then(t=>{t||(this.params.liveOffset.pause(),this.params.videoState.setState("paused"))})}_handleManifestUpdate(e){let{logger:t,playerCallback:i,videoElement:a}=this.params,s=n=>{let o=[];return n?.length?(n.forEach((u,l)=>{u.video&&a.canPlayType(u.codecs).replace(/no/,"")&&window.MediaSource?.isTypeSupported?.(u.codecs)&&(u.index=l,o.push(u))}),o.sort(function(u,l){return u.video&&l.video?l.video.height-u.video.height:l.bitrate-u.bitrate}),o):(i({name:"error",type:"empty_manifest"}),[])};this.manifest=s(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),i({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},VL))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var lg=R(Ii(),1);import{debounce as NL,filter as og,fromEvent as FL,interval as qL,isHigher as UL,isInvariantQuality as HL,isLower as jL,merge as QL,Subject as ug,Subscription as GL}from"@vkontakte/videoplayer-shared";var Hu=class{constructor(){this.onDroopedVideoFramesLimit$=new ug;this.subscription=new GL;this.playing=!1;this.tracks=[];this.forceChecker$=new ug;this.isForceCheckCounter=0;this.prevTotalVideoFrames=0;this.prevDroppedVideoFrames=0;this.limitCounts={};this.handleChangeVideoQuality=()=>{let e=this.tracks.find(({size:t})=>t?.height===this.video.videoHeight&&t?.width===this.video.videoWidth);e&&!HL(e.quality)&&this.onChangeQuality(e.quality)};this.checkDroppedFrames=()=>{let{totalVideoFrames:e,droppedVideoFrames:t}=this.video.getVideoPlaybackQuality(),i=e-this.prevTotalVideoFrames,a=t-this.prevDroppedVideoFrames,s=1-(i-a)/i;!isNaN(s)&&s>0&&this.log({message:`[dropped]. current dropped percent: ${s}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(s)&&s>=this.droppedFramesChecker.percentLimit&&UL(this.currentQuality,this.droppedFramesChecker.minQualityBanLimit)&&(this.limitCounts[this.currentQuality]=(this.limitCounts[this.currentQuality]??0)+1,this.maxQualityLimit=this.getMaxQualityLimit(this.currentQuality),this.currentTimer&&window.clearTimeout(this.currentTimer),this.currentTimer=window.setTimeout(()=>this.maxQualityLimit=this.getMaxQualityLimit(),this.droppedFramesChecker.qualityUpWaitingTime),this.onDroopedVideoFramesLimitTrigger()),this.savePrevFrameCounts(e,t)}}connect(e){this.log=e.logger.createComponentLog("DroppedFramesManager"),this.video=e.video,this.isAuto=e.isAuto,this.tracks=e.tracks,this.droppedFramesChecker=e.droppedFramesChecker,this.subscription.add(e.playing$.subscribe(()=>this.playing=!0)),this.subscription.add(e.pause$.subscribe(()=>this.playing=!1)),this.isEnabled&&this.subscribe()}destroy(){this.currentTimer&&window.clearTimeout(this.currentTimer),this.subscription.unsubscribe()}get droppedVideoMaxQualityLimit(){return this.maxQualityLimit}subscribe(){this.subscription.add(FL(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=qL(this.droppedFramesChecker.checkTime).pipe(og(()=>this.playing),og(()=>{let a=!!this.isForceCheckCounter;return a&&(this.isForceCheckCounter-=1),!a})),t=this.forceChecker$.pipe(NL(this.droppedFramesChecker.checkTime)),i=QL(e,t);this.subscription.add(i.subscribe(this.checkDroppedFrames))}onChangeQuality(e){this.currentQuality=e;let{totalVideoFrames:t,droppedVideoFrames:i}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,i),this.isForceCheckCounter=this.droppedFramesChecker.tickCountAfterQualityChange,this.forceChecker$.next()}onDroopedVideoFramesLimitTrigger(){this.isAuto.getState()&&(this.log({message:`[onDroopedVideoFramesLimit]. maxQualityLimit: ${this.maxQualityLimit}`}),this.onDroopedVideoFramesLimit$.next())}getMaxQualityLimit(e){let t=(0,lg.default)(this.limitCounts).filter(([,i])=>i>=this.droppedFramesChecker.countLimit).sort(([i],[a])=>jL(i,a)?-1:1)?.[0]?.[0];return e??t}get isEnabled(){return this.droppedFramesChecker.enabled&&this.isDroppedFramesCheckerSupport}get isDroppedFramesCheckerSupport(){return!!this.video&&typeof this.video.getVideoPlaybackQuality=="function"}savePrevFrameCounts(e,t){this.prevTotalVideoFrames=e,this.prevDroppedVideoFrames=t}},qs=Hu;import{map as WL,Observable as YL}from"@vkontakte/videoplayer-shared";import{fromEvent as zL}from"@vkontakte/videoplayer-shared";var Dr=()=>!!window.documentPictureInPicture?.window||!!document.pictureInPictureElement;var KL=(r,e)=>new YL(t=>{if(!window.IntersectionObserver)return;let i={root:null},a=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||Dr()))},{...i,...e});a.observe(r);let s=zL(document,"visibilitychange").pipe(WL(n=>!document.hidden||Dr())).subscribe(n=>t.next(n));return()=>{a.unobserve(r),s.unsubscribe()}}),qe=KL;var aR=["paused","playing","ready"],sR=["paused","playing","ready"],Vr=class{constructor(e){this.subscription=new iR;this.videoState=new D("stopped");this.representations$=new Qu([]);this.droppedFramesManager=new qs;this.maxSeekBackTime$=new Qu(1/0);this.zeroTime$=new Qu(void 0);this.liveOffset=new Zt;this._dashCb=e=>{switch(e.name){case"buffering":{let t=e.isBuffering;this.params.output.isBuffering$.next(t);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,category:pg.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{let t=e.manifest,i=[];for(let a of t){let s=a.name??a.index.toString(10),n=At(a.name)??rR(a.video),o=a.bitrate/1e3,u={...a.video};if(!n)continue;let l={id:s,quality:n,bitrate:o,size:u};i.push({track:l,representation:a})}this.representations$.next(i),this.params.output.availableVideoTracks$.next(i.map(({track:a})=>a)),this.videoState.getTransition()?.to==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let t=e.quality,i=this.representations$.getValue().find(({representation:a})=>a===t)?.track;this.params.output.hostname$.next(new URL(t.headerUrl,this.params.source.url).hostname),ju(i)&&this.params.output.currentVideoTrack$.next(i);break}case"bandwidth":{let{size:t,duration:i}=e;this.params.dependencies.throughputEstimator.addRawSpeed(t,i);break}case"index":{this.maxSeekBackTime$.next(e.shiftDuration||0),this.zeroTime$.next(e.zeroTime);break}}};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; seekState: ${JSON.stringify(s)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"));return}if(t)return;let n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if((0,Gu.default)(sR,e)&&(n||o)){this.prepare();return}if(a?.to!=="paused"&&s.state==="requested"&&(0,Gu.default)(aR,e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(de(this.params.source.url));return;case"manifest_ready":this.videoState.startTransitionTo("ready"),this.prepare();break;case"ready":if(i==="paused")this.videoState.setState("paused");else if(i==="playing"){this.videoState.startTransitionTo("playing");let u=a?.from;u&&u==="ready"&&this.dash.catchUp(),this.dash.play()}return;case"playing":i==="paused"&&(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.dash.pause());return;case"paused":if(i==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.dash.play(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let u=this.liveOffset.getTotalOffset();u>=this.maxSeekBackTime$.getValue()&&(u=0,this.liveOffset.resetTo(u)),this.liveOffset.resume(),this.params.output.position$.next(-u/1e3),this.dash.reinit(de(this.params.source.url,u))}return;default:return cg(e)}};this.textTracksManager=new Fe(e.source.url),this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=a=>{e.output.error$.next({id:"DashLiveProvider",category:pg.WTF,message:"DashLiveProvider internal logic error",thrown:a})};this.subscription.add(mg(this.videoState.stateChangeStarted$.pipe(Us(a=>({transition:a,type:"start"}))),this.videoState.stateChangeEnded$.pipe(Us(a=>({transition:a,type:"end"})))).subscribe(({transition:a,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(a)}`})})),this.video=Ee(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=we(this.video);this.subscription.add(()=>i.destroy()),this.subscription.add(this.representations$.pipe(Us(a=>a.map(({track:s})=>s)),hg(a=>!!a.length),tR()).subscribe(a=>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:a}))),this.subscription.add(i.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready")},t)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused")},t)).add(i.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.videoState.setState("playing")},t)).add(i.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(ZL(),Us(a=>-a/1e3)).subscribe(this.params.output.duration$)).add(XL({zeroTime:this.zeroTime$.pipe(hg(ju)),position:i.timeUpdate$}).subscribe(({zeroTime:a,position:s})=>this.params.output.liveTime$.next(a+s*1e3),t)).add(rt(this.video,this.params.desiredState.isLooped,t)).add(Pe(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(Ne(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(qe(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:a,min:s}})=>{this.dash.setAutoQualityLimits({max:a&&fg(a),min:s&&fg(s)}),this.params.output.autoVideoTrackLimits$.next({max:a,min:s})})).add(this.videoState.stateChangeEnded$.subscribe(a=>{switch(a.to){case"stopped":this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState("stopped");break;case"manifest_ready":case"ready":this.params.desiredState.playbackState.getTransition()?.to==="ready"&&this.params.desiredState.playbackState.setState("ready");break;case"paused":this.params.desiredState.playbackState.setState("paused");break;case"playing":this.params.desiredState.playbackState.setState("playing");break;default:return cg(a.to)}},t)).add(mg(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,eR(["init"])).pipe(JL(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),xe(this.video)}createLiveDashPlayer(){let e=new Cr({videoElement:this.video,videoState:this.videoState,liveOffset:this.liveOffset,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode,manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){let e=this.representations$.getValue(),t=this.params.desiredState.videoTrack.getTransition()?.to??this.params.desiredState.videoTrack.getState(),i=this.params.desiredState.autoVideoTrackSwitching.getTransition()?.to??this.params.desiredState.autoVideoTrackSwitching.getState(),a=!i&&ju(t)?t:$t(e.map(({track:l})=>l),{container:this.video.getBoundingClientRect(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),s=a?.id,n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.videoTrack.getState()?.id,u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(a&&(n||s!==o)&&this.setVideoTrack(a),u&&this.setAutoQuality(i),n||u||s!==o){let l=e.find(({track:c})=>c.id===s)?.representation;dg(l,"Representations missing"),this.dash.startPlay(l,i)}}setVideoTrack(e){let t=this.representations$.getValue().find(({track:i})=>i.id===e.id)?.representation;dg(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(),a=t==="paused"&&i==="paused",s=-e,n=s<=this.maxSeekBackTime$.getValue()?s:0;this.params.output.position$.next(e/1e3),this.dash.reinit(de(this.params.source.url,n)),a&&this.dash.pause(),this.liveOffset.resetTo(n,a)}};var bg=Vr;var qS=R(Ie(),1);var Bi=(r,e)=>{let t=0;for(let i=0;i<r.length;i++){let a=r.start(i)*1e3,s=r.end(i)*1e3;a<=e&&e<=s&&(t=s)}return Math.max(t-e,0)};import{assertNever as UM,assertNonNullable as HM,debounce as jM,ErrorCategory as _S,filter as Dl,filterChanged as Ea,fromEvent as QM,isNonNullable as NS,map as Vl,merge as dn,observableFrom as Bl,once as FS,Subscription as GM}from"@vkontakte/videoplayer-shared";var Hs=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 a=0,s=i.length;a<s;a++)if(i[a].callback===t){i.splice(a,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;let i=this.listeners[e.type].slice();for(let a=0,s=i.length;a<s;a++){let n=i[a];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}},Oi=class extends Hs{constructor(){super(),this.listeners||Hs.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)}},Br=class{constructor(){Object.defineProperty(this,"signal",{value:new Oi,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch{typeof document<"u"?document.createEvent?(t=document.createEvent("Event"),t.initEvent("abort",!1,!1)):(t=document.createEventObject(),t.type="abort"):t={type:"abort",bubbles:!1,cancelable:!1}}let i=e;if(i===void 0)if(typeof document>"u")i=new Error("This operation was aborted"),i.name="AbortError";else try{i=new DOMException("signal is aborted without reason")}catch{i=new Error("This operation was aborted"),i.name="AbortError"}this.signal.reason=i,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol<"u"&&Symbol.toStringTag&&(Br.prototype[Symbol.toStringTag]="AbortController",Oi.prototype[Symbol.toStringTag]="AbortSignal");function js(r){return r.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof r.Request=="function"&&!r.Request.prototype.hasOwnProperty("signal")||!r.AbortController}function Wu(r){typeof r=="function"&&(r={fetch:r});let{fetch:e,Request:t=e.Request,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:a=!1}=r;if(!js({fetch:e,Request:t,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:a}))return{fetch:e,Request:s};let s=t;(s&&!s.prototype.hasOwnProperty("signal")||a)&&(s=function(l,c){let d;c&&c.signal&&(d=c.signal,delete c.signal);let p=new t(l,c);return d&&Object.defineProperty(p,"signal",{writable:!1,enumerable:!1,configurable:!0,value:d}),p},s.prototype=t.prototype);let n=e;return{fetch:(u,l)=>{let c=s&&s.prototype.isPrototypeOf(u)?u.signal:l?l.signal:void 0;if(c){let d;try{d=new DOMException("Aborted","AbortError")}catch{d=new Error("Aborted"),d.name="AbortError"}if(c.aborted)return Promise.reject(d);let p=new Promise((h,f)=>{c.addEventListener("abort",()=>f(d),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([p,n(u,l)])}return n(u,l)},Request:s}}var Or=js({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),gg=Or?Wu({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,st=Or?gg.fetch:window.fetch,oF=Or?gg.Request:window.Request,pe=Or?Br:window.AbortController,uF=Or?Oi:window.AbortSignal;var MS=R(Ie(),1),Rl=R(zu(),1);var rv=R(iv(),1);import{ErrorCategory as Nr}from"@vkontakte/videoplayer-shared";var av=r=>{if(!r)return{id:"EmptyResponse",category:Nr.PARSER,message:"Empty response"};if(r.length<=2&&r.match(/^\d+$/))return{id:`UVError#${r}`,category:Nr.NETWORK,message:`UV Error ${r}`};let e=(0,rv.default)(r).substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:Nr.NETWORK,message:"Received unexpected HTML, possibly a ISP block"};if(e.startsWith("<?xml"))return new DOMParser().parseFromString(r,"text/xml").querySelector("parsererror")?{id:"InvalidXML",category:Nr.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:Nr.PARSER,message:"Response is valid XML, but parser failed"}};var Mt=(r,e,t=0)=>{for(let i=0;i<r.length;i++)if(r.start(i)*1e3-t<=e&&r.end(i)*1e3+t>e)return!0;return!1};import{abortable as wl,assertNonNullable as Hi,combine as ji,ErrorCategory as nt,filter as an,filterChanged as ya,flattenObject as Ta,fromEvent as bt,getTraceSubscriptionMethod as xM,interval as Al,isNonNullable as Ia,isNullable as RS,map as Qi,merge as si,now as Ll,Subject as sn,Subscription as $S,tap as PM,throttle as kM,ValueSubject as K}from"@vkontakte/videoplayer-shared";var Gs=R(Ie(),1),qi=R(Lt(),1),Ws=R(zu(),1);var jR=(r,e={})=>{let i=e.timeout||1,a=performance.now();return window.setTimeout(()=>{r({get didTimeout(){return e.timeout?!1:performance.now()-a-1>i},timeRemaining(){return Math.max(0,1+(performance.now()-a))}})},1)},QR=r=>window.clearTimeout(r),sv=r=>typeof r=="function"&&r?.toString().endsWith("{ [native code] }"),nv=!sv(window.requestIdleCallback)||!sv(window.cancelIdleCallback),el=nv?jR:window.requestIdleCallback,Fr=nv?QR:window.cancelIdleCallback;var fS=R(xs(),1);import{assertNever as GR,ErrorCategory as ov,Subject as uv}from"@vkontakte/videoplayer-shared";var WR=18,lv=!1;try{lv=V.browser.isSafari&&!!V.browser.safariVersion&&V.browser.safariVersion<=WR}catch(r){console.error(r)}var tl=class{constructor(e){this.bufferFull$=new uv;this.error$=new uv;this.queue=[];this.currentTask=null;this.destroyed=!1;this.abortRequested=!1;this.completeTask=()=>{try{if(this.currentTask){let e=this.currentTask.signal?.aborted;this.currentTask.callback(!e),this.currentTask=null}this.queue.length&&this.pull()}catch(e){this.error$.next({id:"BufferTaskQueueUnknown",category:ov.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:e})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(i=>{let a={operation:"append",data:e,signal:t,callback:i};this.queue.push(a),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(a=>{let s={operation:"remove",from:e,to:t,signal:i,callback:a};this.queue.unshift(s),this.pull()})}async abort(e){return new Promise(t=>{let i,a=s=>{this.abortRequested=!1,t(s)};lv&&e?i={operation:"safariAbort",init:e,callback:a}:i={operation:"abort",callback:a};for(let{callback:s}of this.queue)s(!1);this.abortRequested=!0,i&&(this.queue=[i]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){if((this.buffer.updating||this.currentTask||this.destroyed)&&!this.abortRequested)return;let e=this.queue.shift();if(!e)return;if(e.signal?.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(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:ov.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:GR(t)}}},cv=tl;var il=r=>{let e=0;for(let t=0;t<r.length;t++)e+=r.end(t)-r.start(t);return e*1e3};import{abortable as Dt,assertNonNullable as Le,ErrorCategory as ft,fromEvent as Sl,getExponentialDelay as yl,isNonNullable as Fi,isNullable as he,now as Qs,once as lM,Subject as cM,Subscription as dM,ValueSubject as ii}from"@vkontakte/videoplayer-shared";var q=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let i=this.readUint32();this.type=this.readString(4),this.size32=i<=e.buffer.byteLength-e.byteOffset?i:NaN;let a=this.size32?this.size32-8:void 0,s=e.byteOffset+this.cursor;this.size64=0,this.usertype=0,this.content=new DataView(e.buffer,s,a)}get id(){return this.type}get size(){return this.size32}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t="ascii"){let a=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,a}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 _i=class extends q{};var qr=class extends q{constructor(t,i){super(t,i);this.ondemandPrefix="ondemandlivejson";this.ondemandDataReceivedKey="t-in";this.ondemandDataPreparedKey="t-out";let a=this.content.byteOffset,s=a+this.content.byteLength,n=new TextDecoder("ascii").decode(this.content.buffer.slice(a,s)).split(this.ondemandPrefix)[1],o=JSON.parse(n);this.serverDataReceivedTimestamp=o[this.ondemandDataReceivedKey],this.serverDataPreparedTime=o[this.ondemandDataPreparedKey]}};var Ur=class extends q{constructor(e,t){super(e,t),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let i=this.size-this.cursor;for(;i;){let a=this.readString(4);this.compatibleBrands.push(a),i-=4}}};var Hr=class extends q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var z=class extends q{constructor(e,t){super(e,t);let i=this.readUint32();this.version=i>>>24,this.flags=i&16777215}};var jr=class extends z{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 Qr=class extends q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Gr=class extends q{constructor(e,t){super(e,t),this.data=this.content}};var ei=class extends z{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 a=this.readUint32(),s=a>>>31,n=a<<1>>>1,o=this.readUint32();a=this.readUint32();let u=a>>>28,l=a<<3>>>3;this.segments.push({referenceType:s,referencedSize:n,subsegmentDuration:o,SAPType:u,SAPDeltaTime:l})}}};var Wr=class extends q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Yr=class extends q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var zr=class extends z{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 Kr=class extends z{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var Xr=class extends z{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var Jr=class extends q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Zr=class extends z{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.trackId=this.readUint32(),this.cursor+=4,this.duration=this.readUint32(),this.cursor+=8,this.layer=this.readUint16(),this.alternateGroup=this.readUint16(),this.cursor+=2,this.cursor+=2,this.matrix=[[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()]],this.width=this.readUint32(),this.height=this.readUint32()}};var ea=class extends q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ta=class extends q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ia=class extends z{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var ra=class extends q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var aa=class extends z{constructor(e,t){super(e,t),this.trackId=this.readUint32(),this.flags&1&&(this.baseDataOffset=this.readUint64()),this.flags&2&&(this.sampleDescriptionIndex=this.readUint32()),this.flags&8&&(this.defaultSampleDuration=this.readUint32()),this.flags&16&&(this.defaultSampleSize=this.readUint32()),this.flags&32&&(this.defaultSampleFlags=this.readUint32())}};var sa=class extends z{constructor(t,i){super(t,i);this.baseMediaDecodeTime32=0;this.baseMediaDecodeTime64=BigInt(0);this.version===1?this.baseMediaDecodeTime64=this.readUint64():this.baseMediaDecodeTime32=this.readUint32()}get baseMediaDecodeTime(){return this.version===1?this.baseMediaDecodeTime64:this.baseMediaDecodeTime32}};var na=class extends z{constructor(t,i){super(t,i);this.sampleDuration=[];this.sampleSize=[];this.sampleFlags=[];this.sampleCompositionTimeOffset=[];this.optionalFields=0;this.sampleCount=this.readUint32(),this.flags&1&&(this.dataOffset=this.readUint32()),this.flags&4&&(this.firstSampleFlags=this.readUint32());for(let a=0;a<this.sampleCount;a++)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 oa=class extends q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ua=class extends z{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 la=class extends q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+78,this.content.byteLength-78))}};var zR={ftyp:Ur,moov:Hr,mvhd:jr,moof:Qr,mdat:Gr,sidx:ei,trak:Wr,mdia:Jr,mfhd:ia,tkhd:Zr,traf:ra,tfhd:aa,tfdt:sa,trun:na,minf:ea,sv3d:Yr,st3d:zr,prhd:Kr,proj:ta,equi:Xr,uuid:qr,stbl:oa,stsd:ua,avc1:la,unknown:_i},ht=class r{constructor(e={}){this.options={offset:0,...e}}parse(e){let t=[],i=this.options.offset;for(;i<e.byteLength;)try{let s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+i+4,4)),n=this.createBox(s,new DataView(e.buffer,e.byteOffset+i));if(!n.size)break;t.push(n),i+=n.size}catch{break}return t}createBox(e,t){let i=zR[e];return i?new i(t,new r):new _i(t,new r)}};var Ct=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{this.index[t.type]??=[],this.index[t.type].push(t),t.children.length>0&&this.indexBoxLevel(t.children)})}find(e){return this.index[e]&&this.index[e][0]?this.index[e][0]:null}findAll(e){return this.index[e]||[]}};var XR=new TextDecoder("ascii"),JR=r=>XR.decode(new DataView(r.buffer,r.byteOffset+4,4))==="ftyp",ZR=r=>{let e=new ei(r,new ht),t=e.earliestPresentationTime/e.timescale*1e3,i=r.byteOffset+r.byteLength+e.firstOffset;return e.segments.map(s=>{if(s.referenceType!==0)throw new Error("Unsupported multilevel sidx");let n=s.subsegmentDuration/e.timescale*1e3,o={status:"none",time:{from:t,to:t+n},byte:{from:i,to:i+s.referencedSize-1}};return t+=n,i+=s.referencedSize,o})},e$=(r,e)=>{let i=new ht().parse(r),a=new Ct(i),s=a.findAll("moof"),n=e?a.findAll("uuid"):a.findAll("mdat");if(!(n.length&&s.length))return null;let o=s[0],u=n[n.length-1],l=o.source.byteOffset,d=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(r.buffer,l,d)},t$=r=>{let t=new ht().parse(r),i=new Ct(t),a={},s=i.findAll("uuid");return s.length?s[s.length-1]:a},i$=r=>{let t=new ht().parse(r);return new Ct(t).find("sidx")?.timescale},r$=(r,e)=>{let i=new ht().parse(r),s=new Ct(i).findAll("traf"),n=s[s.length-1].children.find(d=>d.type==="tfhd"),o=s[s.length-1].children.find(d=>d.type==="tfdt"),u=s[s.length-1].children.find(d=>d.type==="trun"),l=0;return u.sampleDuration.length?l=u.sampleDuration.reduce((d,p)=>d+p,0):l=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+l)/e*1e3},a$=r=>{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 ht().parse(r),a=new Ct(i);if(a.find("sv3d")){e.is3dVideo=!0;let n=a.find("st3d");n&&(e.stereoMode=n.stereoMode);let o=a.find("prhd");o&&(e.projectionData.pose.yaw=o.poseYawDegrees,e.projectionData.pose.pitch=o.posePitchDegrees,e.projectionData.pose.roll=o.poseRollDegrees);let u=a.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},dv={validateData:JR,parseInit:a$,getIndexRange:()=>{},parseSegments:ZR,parseFeedableSegmentChunk:e$,getChunkEndTime:r$,getServerLatencyTimestamps:t$,getTimescaleFromIndex:i$};var da=R(Ie(),1);import{assertNonNullable as al,isNonNullable as fv,isNullable as n$}from"@vkontakte/videoplayer-shared";import{assertNever as s$}from"@vkontakte/videoplayer-shared";var pv={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"}},hv=r=>{let e=r.getUint8(0),t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);let i=ca(r,t),a=i in pv,s=a?pv[i].type:"binary",n=r.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(r.buffer,r.byteOffset+t+1,o-1),l=n&255>>o,c=ca(u),d=l*2**((o-1)*8)+c,p=t+o,h;return p+d>r.byteLength?h=new DataView(r.buffer,r.byteOffset+p):h=new DataView(r.buffer,r.byteOffset+p,d),{tag:a?i:"0x"+i.toString(16).toUpperCase(),type:s,tagHeaderSize:p,tagSize:p+d,value:h,valueSize:d}},ca=(r,e=r.byteLength)=>{switch(e){case 1:return r.getUint8(0);case 2:return r.getUint16(0);case 3:return r.getUint8(0)*2**16+r.getUint16(1);case 4:return r.getUint32(0);case 5:return r.getUint8(0)*2**32+r.getUint32(1);case 6:return r.getUint16(0)*2**32+r.getUint32(2);case 7:{let t=r.getUint8(0)*281474976710656+r.getUint16(1)*4294967296+r.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},ze=(r,e)=>{switch(e){case"int":return r.getInt8(0);case"uint":return ca(r);case"float":return r.byteLength===4?r.getFloat32(0):r.getFloat64(0);case"string":return new TextDecoder("ascii").decode(r);case"utf8":return new TextDecoder("utf-8").decode(r);case"date":return new Date(Date.UTC(2001,0)+r.getInt8(0)).getTime();case"master":return r;case"binary":return r;default:s$(e)}},ti=(r,e)=>{let t=0;for(;t<r.byteLength;){let i=new DataView(r.buffer,r.byteOffset+t),a=hv(i);if(!e(a))return;a.type==="master"&&ti(a.value,e),t=a.value.byteOffset-r.byteOffset+a.valueSize}},mv=r=>{if(r.getUint32(0)!==440786851)return!1;let e,t,i,a=hv(r);return ti(a.value,({tag:s,type:n,value:o})=>(s===17143?e=ze(o,n):s===17026?t=ze(o,n):s===17029&&(i=ze(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)};var bv=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],o$=[231,22612,22743,167,171,163,160,175],u$=r=>{let e,t,i,a,s=!1,n=!1,o=!1,u,l,c=!1,d=0;return ti(r,({tag:p,type:h,value:f,valueSize:b})=>{if(p===21419){let g=ze(f,h);l=ca(g)}else p!==21420&&(l=void 0);return p===408125543?(e=f.byteOffset,t=f.byteOffset+b):p===357149030?s=!0:p===290298740?n=!0:p===2807729?i=ze(f,h):p===17545?a=ze(f,h):p===21420&&l===475249515?u=ze(f,h):p===374648427?ti(f,({tag:g,type:v,value:x})=>g===30321?(c=ze(x,v)===1,!1):!0):s&&n&&(0,da.default)(bv,p)&&(o=!0),!o}),al(e,"Failed to parse webm Segment start"),al(t,"Failed to parse webm Segment end"),al(a,"Failed to parse webm Segment duration"),i=i??1e6,{segmentStart:Math.round(e/1e9*i*1e3),segmentEnd:Math.round(t/1e9*i*1e3),timeScale:i,segmentDuration:Math.round(a/1e9*i*1e3),cuesSeekPosition:u,is3dVideo:c,stereoMode:d,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},l$=r=>{if(n$(r.cuesSeekPosition))return;let e=r.segmentStart+r.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},c$=(r,e)=>{let t=!1,i=!1,a=o=>fv(o.time)&&fv(o.position),s=[],n;return ti(r,({tag:o,type:u,value:l})=>{switch(o){case 475249515:t=!0;break;case 187:n&&a(n)&&s.push(n),n={};break;case 179:n&&(n.time=ze(l,u));break;case 183:break;case 241:n&&(n.position=ze(l,u));break;default:t&&(0,da.default)(bv,o)&&(i=!0)}return!(t&&i)}),n&&a(n)&&s.push(n),s.map((o,u)=>{let{time:l,position:c}=o,d=s[u+1];return{status:"none",time:{from:l,to:d?d.time:e.segmentDuration},byte:{from:e.segmentStart+c,to:d?e.segmentStart+d.position-1:e.segmentEnd-1}}})},d$=r=>{let e=0,t=!1;try{ti(r,i=>i.tag===524531317?i.tagSize<=r.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):(0,da.default)(o$,i.tag)?(e+i.tagSize<=r.byteLength&&(e+=i.tagSize,t||=(0,da.default)([163,160,175],i.tag)),!0):!1)}catch{}return e>0&&e<=r.byteLength&&t?new DataView(r.buffer,r.byteOffset,e):null},gv={validateData:mv,parseInit:u$,getIndexRange:l$,parseSegments:c$,parseFeedableSegmentChunk:d$};var pa=r=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(r);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return gv;case"mp4":return dv}}throw new ReferenceError(`Unsupported mime type ${r}`)};var bl=R(Ov(),1),lS=R(Ii(),1),cS=R(Zv(),1),dS=R(Lt(),1),gl=R(Ci(),1);var eS=R(Ie(),1),cl=r=>{let e=r.split("."),[t,...i]=e;if(!t)return!1;switch(t){case"av01":{let[a,s,n]=i;return!!(n&&parseInt(n,10)>8)}case"vp09":{let[a,s,n]=i;return!!(a&&parseInt(a,10)>=2&&n&&parseInt(n,10)>8)}case"avc1":{let a=i[0];if(!a||a.length!==6)return!1;let[s,n]=a.toUpperCase(),o=s+n;return(0,eS.default)(["6E","7A","F4"],o)}}return!1};import{isNonNullable as uM,isNullable as oS}from"@vkontakte/videoplayer-shared";var tS=r=>{if(r.includes("/")){let e=r.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(r)};var iS=r=>{try{let e=nM(),t=r.match(e),{groups:i}=t??{};if(i){let a={};if(i.extensions){let o=i.extensions.toLowerCase().match(/(?:[0-9a-wy-z](?:-[a-z0-9]{2,8})+)/g);Array.from(o||[]).forEach(u=>{a[u[0]]=u.slice(2)})}let s=i.variants?.split(/-/).filter(o=>o!==""),n={extlang:i.extlang,langtag:i.langtag,language:i.language,privateuse:i.privateuse||i.privateuse2,region:i.region,script:i.script,extensions:a,variants:s};return Object.keys(n).forEach(o=>{let u=n[o];(typeof u>"u"||u==="")&&delete n[o]}),n}return null}catch{return null}};function nM(){let r="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",c=`^(?:(?<langtag>${`
6
+ var xy=Object.create;var Xl=Object.defineProperty;var Py=Object.getOwnPropertyDescriptor;var ky=Object.getOwnPropertyNames;var wy=Object.getPrototypeOf,Ay=Object.prototype.hasOwnProperty;var m=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports);var Ry=(r,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of ky(e))!Ay.call(r,a)&&a!==t&&Xl(r,a,{get:()=>e[a],enumerable:!(i=Py(e,a))||i.enumerable});return r};var D=(r,e,t)=>(t=r!=null?xy(wy(r)):{},Ry(e||!r||!r.__esModule?Xl(t,"default",{value:r,enumerable:!0}):t,r));var X=m((kn,Zl)=>{"use strict";var Wi=function(r){return r&&r.Math===Math&&r};Zl.exports=Wi(typeof globalThis=="object"&&globalThis)||Wi(typeof window=="object"&&window)||Wi(typeof self=="object"&&self)||Wi(typeof global=="object"&&global)||Wi(typeof kn=="object"&&kn)||function(){return this}()||Function("return this")()});var ne=m((o0,ec)=>{"use strict";ec.exports=function(r){try{return!!r()}catch{return!0}}});var Yi=m((u0,tc)=>{"use strict";var Ly=ne();tc.exports=!Ly(function(){var r=function(){}.bind();return typeof r!="function"||r.hasOwnProperty("prototype")})});var wn=m((l0,sc)=>{"use strict";var My=Yi(),ac=Function.prototype,ic=ac.apply,rc=ac.call;sc.exports=typeof Reflect=="object"&&Reflect.apply||(My?rc.bind(ic):function(){return rc.apply(ic,arguments)})});var ie=m((c0,uc)=>{"use strict";var nc=Yi(),oc=Function.prototype,An=oc.call,$y=nc&&oc.bind.bind(An,An);uc.exports=nc?$y:function(r){return function(){return An.apply(r,arguments)}}});var Bt=m((d0,cc)=>{"use strict";var lc=ie(),Dy=lc({}.toString),Cy=lc("".slice);cc.exports=function(r){return Cy(Dy(r),8,-1)}});var Rn=m((p0,dc)=>{"use strict";var Vy=Bt(),By=ie();dc.exports=function(r){if(Vy(r)==="Function")return By(r)}});var K=m((h0,pc)=>{"use strict";var Ln=typeof document=="object"&&document.all;pc.exports=typeof Ln>"u"&&Ln!==void 0?function(r){return typeof r=="function"||r===Ln}:function(r){return typeof r=="function"}});var Ee=m((m0,hc)=>{"use strict";var Oy=ne();hc.exports=!Oy(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var xe=m((f0,mc)=>{"use strict";var _y=Yi(),Na=Function.prototype.call;mc.exports=_y?Na.bind(Na):function(){return Na.apply(Na,arguments)}});var Mn=m(vc=>{"use strict";var fc={}.propertyIsEnumerable,bc=Object.getOwnPropertyDescriptor,Ny=bc&&!fc.call({1:2},1);vc.f=Ny?function(e){var t=bc(this,e);return!!t&&t.enumerable}:fc});var zi=m((v0,Sc)=>{"use strict";Sc.exports=function(r,e){return{enumerable:!(r&1),configurable:!(r&2),writable:!(r&4),value:e}}});var yc=m((S0,gc)=>{"use strict";var Fy=ie(),qy=ne(),Uy=Bt(),$n=Object,Hy=Fy("".split);gc.exports=qy(function(){return!$n("z").propertyIsEnumerable(0)})?function(r){return Uy(r)==="String"?Hy(r,""):$n(r)}:$n});var ci=m((g0,Tc)=>{"use strict";Tc.exports=function(r){return r==null}});var bt=m((y0,Ic)=>{"use strict";var jy=ci(),Gy=TypeError;Ic.exports=function(r){if(jy(r))throw new Gy("Can't call method on "+r);return r}});var Ot=m((T0,Ec)=>{"use strict";var Qy=yc(),Wy=bt();Ec.exports=function(r){return Qy(Wy(r))}});var Pe=m((I0,xc)=>{"use strict";var Yy=K();xc.exports=function(r){return typeof r=="object"?r!==null:Yy(r)}});var di=m((E0,Pc)=>{"use strict";Pc.exports={}});var lt=m((x0,wc)=>{"use strict";var Dn=di(),Cn=X(),zy=K(),kc=function(r){return zy(r)?r:void 0};wc.exports=function(r,e){return arguments.length<2?kc(Dn[r])||kc(Cn[r]):Dn[r]&&Dn[r][e]||Cn[r]&&Cn[r][e]}});var Ki=m((P0,Ac)=>{"use strict";var Ky=ie();Ac.exports=Ky({}.isPrototypeOf)});var _t=m((k0,Mc)=>{"use strict";var Xy=X(),Rc=Xy.navigator,Lc=Rc&&Rc.userAgent;Mc.exports=Lc?String(Lc):""});var Bn=m((w0,Oc)=>{"use strict";var Bc=X(),Vn=_t(),$c=Bc.process,Dc=Bc.Deno,Cc=$c&&$c.versions||Dc&&Dc.version,Vc=Cc&&Cc.v8,Fe,Fa;Vc&&(Fe=Vc.split("."),Fa=Fe[0]>0&&Fe[0]<4?1:+(Fe[0]+Fe[1]));!Fa&&Vn&&(Fe=Vn.match(/Edge\/(\d+)/),(!Fe||Fe[1]>=74)&&(Fe=Vn.match(/Chrome\/(\d+)/),Fe&&(Fa=+Fe[1])));Oc.exports=Fa});var On=m((A0,Nc)=>{"use strict";var _c=Bn(),Jy=ne(),Zy=X(),eT=Zy.String;Nc.exports=!!Object.getOwnPropertySymbols&&!Jy(function(){var r=Symbol("symbol detection");return!eT(r)||!(Object(r)instanceof Symbol)||!Symbol.sham&&_c&&_c<41})});var _n=m((R0,Fc)=>{"use strict";var tT=On();Fc.exports=tT&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var Nn=m((L0,qc)=>{"use strict";var iT=lt(),rT=K(),aT=Ki(),sT=_n(),nT=Object;qc.exports=sT?function(r){return typeof r=="symbol"}:function(r){var e=iT("Symbol");return rT(e)&&aT(e.prototype,nT(r))}});var Xi=m((M0,Uc)=>{"use strict";var oT=String;Uc.exports=function(r){try{return oT(r)}catch{return"Object"}}});var Je=m(($0,Hc)=>{"use strict";var uT=K(),lT=Xi(),cT=TypeError;Hc.exports=function(r){if(uT(r))return r;throw new cT(lT(r)+" is not a function")}});var Ji=m((D0,jc)=>{"use strict";var dT=Je(),pT=ci();jc.exports=function(r,e){var t=r[e];return pT(t)?void 0:dT(t)}});var Qc=m((C0,Gc)=>{"use strict";var Fn=xe(),qn=K(),Un=Pe(),hT=TypeError;Gc.exports=function(r,e){var t,i;if(e==="string"&&qn(t=r.toString)&&!Un(i=Fn(t,r))||qn(t=r.valueOf)&&!Un(i=Fn(t,r))||e!=="string"&&qn(t=r.toString)&&!Un(i=Fn(t,r)))return i;throw new hT("Can't convert object to primitive value")}});var qe=m((V0,Wc)=>{"use strict";Wc.exports=!0});var Kc=m((B0,zc)=>{"use strict";var Yc=X(),mT=Object.defineProperty;zc.exports=function(r,e){try{mT(Yc,r,{value:e,configurable:!0,writable:!0})}catch{Yc[r]=e}return e}});var Zi=m((O0,Zc)=>{"use strict";var fT=qe(),bT=X(),vT=Kc(),Xc="__core-js_shared__",Jc=Zc.exports=bT[Xc]||vT(Xc,{});(Jc.versions||(Jc.versions=[])).push({version:"3.38.0",mode:fT?"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 Hn=m((_0,td)=>{"use strict";var ed=Zi();td.exports=function(r,e){return ed[r]||(ed[r]=e||{})}});var pi=m((N0,id)=>{"use strict";var ST=bt(),gT=Object;id.exports=function(r){return gT(ST(r))}});var Ue=m((F0,rd)=>{"use strict";var yT=ie(),TT=pi(),IT=yT({}.hasOwnProperty);rd.exports=Object.hasOwn||function(e,t){return IT(TT(e),t)}});var jn=m((q0,ad)=>{"use strict";var ET=ie(),xT=0,PT=Math.random(),kT=ET(1 .toString);ad.exports=function(r){return"Symbol("+(r===void 0?"":r)+")_"+kT(++xT+PT,36)}});var oe=m((U0,nd)=>{"use strict";var wT=X(),AT=Hn(),sd=Ue(),RT=jn(),LT=On(),MT=_n(),hi=wT.Symbol,Gn=AT("wks"),$T=MT?hi.for||hi:hi&&hi.withoutSetter||RT;nd.exports=function(r){return sd(Gn,r)||(Gn[r]=LT&&sd(hi,r)?hi[r]:$T("Symbol."+r)),Gn[r]}});var cd=m((H0,ld)=>{"use strict";var DT=xe(),od=Pe(),ud=Nn(),CT=Ji(),VT=Qc(),BT=oe(),OT=TypeError,_T=BT("toPrimitive");ld.exports=function(r,e){if(!od(r)||ud(r))return r;var t=CT(r,_T),i;if(t){if(e===void 0&&(e="default"),i=DT(t,r,e),!od(i)||ud(i))return i;throw new OT("Can't convert object to primitive value")}return e===void 0&&(e="number"),VT(r,e)}});var Qn=m((j0,dd)=>{"use strict";var NT=cd(),FT=Nn();dd.exports=function(r){var e=NT(r,"string");return FT(e)?e:e+""}});var qa=m((G0,hd)=>{"use strict";var qT=X(),pd=Pe(),Wn=qT.document,UT=pd(Wn)&&pd(Wn.createElement);hd.exports=function(r){return UT?Wn.createElement(r):{}}});var Yn=m((Q0,md)=>{"use strict";var HT=Ee(),jT=ne(),GT=qa();md.exports=!HT&&!jT(function(){return Object.defineProperty(GT("div"),"a",{get:function(){return 7}}).a!==7})});var vd=m(bd=>{"use strict";var QT=Ee(),WT=xe(),YT=Mn(),zT=zi(),KT=Ot(),XT=Qn(),JT=Ue(),ZT=Yn(),fd=Object.getOwnPropertyDescriptor;bd.f=QT?fd:function(e,t){if(e=KT(e),t=XT(t),ZT)try{return fd(e,t)}catch{}if(JT(e,t))return zT(!WT(YT.f,e,t),e[t])}});var zn=m((Y0,Sd)=>{"use strict";var eI=ne(),tI=K(),iI=/#|\.prototype\./,er=function(r,e){var t=aI[rI(r)];return t===nI?!0:t===sI?!1:tI(e)?eI(e):!!e},rI=er.normalize=function(r){return String(r).replace(iI,".").toLowerCase()},aI=er.data={},sI=er.NATIVE="N",nI=er.POLYFILL="P";Sd.exports=er});var mi=m((z0,yd)=>{"use strict";var gd=Rn(),oI=Je(),uI=Yi(),lI=gd(gd.bind);yd.exports=function(r,e){return oI(r),e===void 0?r:uI?lI(r,e):function(){return r.apply(e,arguments)}}});var Kn=m((K0,Td)=>{"use strict";var cI=Ee(),dI=ne();Td.exports=cI&&dI(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var Ze=m((X0,Id)=>{"use strict";var pI=Pe(),hI=String,mI=TypeError;Id.exports=function(r){if(pI(r))return r;throw new mI(hI(r)+" is not an object")}});var Nt=m(xd=>{"use strict";var fI=Ee(),bI=Yn(),vI=Kn(),Ua=Ze(),Ed=Qn(),SI=TypeError,Xn=Object.defineProperty,gI=Object.getOwnPropertyDescriptor,Jn="enumerable",Zn="configurable",eo="writable";xd.f=fI?vI?function(e,t,i){if(Ua(e),t=Ed(t),Ua(i),typeof e=="function"&&t==="prototype"&&"value"in i&&eo in i&&!i[eo]){var a=gI(e,t);a&&a[eo]&&(e[t]=i.value,i={configurable:Zn in i?i[Zn]:a[Zn],enumerable:Jn in i?i[Jn]:a[Jn],writable:!1})}return Xn(e,t,i)}:Xn:function(e,t,i){if(Ua(e),t=Ed(t),Ua(i),bI)try{return Xn(e,t,i)}catch{}if("get"in i||"set"in i)throw new SI("Accessors not supported");return"value"in i&&(e[t]=i.value),e}});var fi=m((Z0,Pd)=>{"use strict";var yI=Ee(),TI=Nt(),II=zi();Pd.exports=yI?function(r,e,t){return TI.f(r,e,II(1,t))}:function(r,e,t){return r[e]=t,r}});var te=m((eC,wd)=>{"use strict";var tr=X(),EI=wn(),xI=Rn(),PI=K(),kI=vd().f,wI=zn(),bi=di(),AI=mi(),vi=fi(),kd=Ue();Zi();var RI=function(r){var e=function(t,i,a){if(this instanceof e){switch(arguments.length){case 0:return new r;case 1:return new r(t);case 2:return new r(t,i)}return new r(t,i,a)}return EI(r,this,arguments)};return e.prototype=r.prototype,e};wd.exports=function(r,e){var t=r.target,i=r.global,a=r.stat,s=r.proto,n=i?tr:a?tr[t]:tr[t]&&tr[t].prototype,o=i?bi:bi[t]||vi(bi,t,{})[t],u=o.prototype,l,d,c,p,h,f,b,S,v;for(p in e)l=wI(i?p:t+(a?".":"#")+p,r.forced),d=!l&&n&&kd(n,p),f=o[p],d&&(r.dontCallGetSet?(v=kI(n,p),b=v&&v.value):b=n[p]),h=d&&b?b:e[p],!(!l&&!s&&typeof f==typeof h)&&(r.bind&&d?S=AI(h,tr):r.wrap&&d?S=RI(h):s&&PI(h)?S=xI(h):S=h,(r.sham||h&&h.sham||f&&f.sham)&&vi(S,"sham",!0),vi(o,p,S),s&&(c=t+"Prototype",kd(bi,c)||vi(bi,c,{}),vi(bi[c],p,h),r.real&&u&&(l||!u[p])&&vi(u,p,h)))}});var Rd=m((tC,Ad)=>{"use strict";var LI=Math.ceil,MI=Math.floor;Ad.exports=Math.trunc||function(e){var t=+e;return(t>0?MI:LI)(t)}});var ir=m((iC,Ld)=>{"use strict";var $I=Rd();Ld.exports=function(r){var e=+r;return e!==e||e===0?0:$I(e)}});var $d=m((rC,Md)=>{"use strict";var DI=ir(),CI=Math.max,VI=Math.min;Md.exports=function(r,e){var t=DI(r);return t<0?CI(t+e,0):VI(t,e)}});var to=m((aC,Dd)=>{"use strict";var BI=ir(),OI=Math.min;Dd.exports=function(r){var e=BI(r);return e>0?OI(e,9007199254740991):0}});var Si=m((sC,Cd)=>{"use strict";var _I=to();Cd.exports=function(r){return _I(r.length)}});var io=m((nC,Bd)=>{"use strict";var NI=Ot(),FI=$d(),qI=Si(),Vd=function(r){return function(e,t,i){var a=NI(e),s=qI(a);if(s===0)return!r&&-1;var n=FI(i,s),o;if(r&&t!==t){for(;s>n;)if(o=a[n++],o!==o)return!0}else for(;s>n;n++)if((r||n in a)&&a[n]===t)return r||n||0;return!r&&-1}};Bd.exports={includes:Vd(!0),indexOf:Vd(!1)}});var rr=m((oC,Od)=>{"use strict";Od.exports=function(){}});var _d=m(()=>{"use strict";var UI=te(),HI=io().includes,jI=ne(),GI=rr(),QI=jI(function(){return!Array(1).includes()});UI({target:"Array",proto:!0,forced:QI},{includes:function(e){return HI(this,e,arguments.length>1?arguments[1]:void 0)}});GI("includes")});var vt=m((cC,Nd)=>{"use strict";var WI=lt();Nd.exports=WI});var qd=m((dC,Fd)=>{"use strict";_d();var YI=vt();Fd.exports=YI("Array","includes")});var Hd=m((pC,Ud)=>{"use strict";var zI=qd();Ud.exports=zI});var et=m((hC,jd)=>{"use strict";var KI=Hd();jd.exports=KI});var Ga=m((EC,Xd)=>{"use strict";var aE=Hn(),sE=jn(),Kd=aE("keys");Xd.exports=function(r){return Kd[r]||(Kd[r]=sE(r))}});var Zd=m((xC,Jd)=>{"use strict";var nE=ne();Jd.exports=!nE(function(){function r(){}return r.prototype.constructor=null,Object.getPrototypeOf(new r)!==r.prototype})});var Qa=m((PC,tp)=>{"use strict";var oE=Ue(),uE=K(),lE=pi(),cE=Ga(),dE=Zd(),ep=cE("IE_PROTO"),so=Object,pE=so.prototype;tp.exports=dE?so.getPrototypeOf:function(r){var e=lE(r);if(oE(e,ep))return e[ep];var t=e.constructor;return uE(t)&&e instanceof t?t.prototype:e instanceof so?pE:null}});var Wa=m((kC,ip)=>{"use strict";ip.exports={}});var sp=m((wC,ap)=>{"use strict";var hE=ie(),no=Ue(),mE=Ot(),fE=io().indexOf,bE=Wa(),rp=hE([].push);ap.exports=function(r,e){var t=mE(r),i=0,a=[],s;for(s in t)!no(bE,s)&&no(t,s)&&rp(a,s);for(;e.length>i;)no(t,s=e[i++])&&(~fE(a,s)||rp(a,s));return a}});var oo=m((AC,np)=>{"use strict";np.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var uo=m((RC,op)=>{"use strict";var vE=sp(),SE=oo();op.exports=Object.keys||function(e){return vE(e,SE)}});var lo=m((LC,pp)=>{"use strict";var lp=Ee(),gE=ne(),cp=ie(),yE=Qa(),TE=uo(),IE=Ot(),EE=Mn().f,dp=cp(EE),xE=cp([].push),PE=lp&&gE(function(){var r=Object.create(null);return r[2]=2,!dp(r,2)}),up=function(r){return function(e){for(var t=IE(e),i=TE(t),a=PE&&yE(t)===null,s=i.length,n=0,o=[],u;s>n;)u=i[n++],(!lp||(a?u in t:dp(t,u)))&&xE(o,r?[u,t[u]]:t[u]);return o}};pp.exports={entries:up(!0),values:up(!1)}});var hp=m(()=>{"use strict";var kE=te(),wE=lo().entries;kE({target:"Object",stat:!0},{entries:function(e){return wE(e)}})});var fp=m((DC,mp)=>{"use strict";hp();var AE=di();mp.exports=AE.Object.entries});var vp=m((CC,bp)=>{"use strict";var RE=fp();bp.exports=RE});var ar=m((VC,Sp)=>{"use strict";var LE=vp();Sp.exports=LE});var Ft=m((BC,gp)=>{"use strict";gp.exports={}});var Ip=m((OC,Tp)=>{"use strict";var ME=X(),$E=K(),yp=ME.WeakMap;Tp.exports=$E(yp)&&/native code/.test(String(yp))});var mo=m((_C,Pp)=>{"use strict";var DE=Ip(),xp=X(),CE=Pe(),VE=fi(),co=Ue(),po=Zi(),BE=Ga(),OE=Wa(),Ep="Object already initialized",ho=xp.TypeError,_E=xp.WeakMap,Ya,sr,za,NE=function(r){return za(r)?sr(r):Ya(r,{})},FE=function(r){return function(e){var t;if(!CE(e)||(t=sr(e)).type!==r)throw new ho("Incompatible receiver, "+r+" required");return t}};DE||po.state?(He=po.state||(po.state=new _E),He.get=He.get,He.has=He.has,He.set=He.set,Ya=function(r,e){if(He.has(r))throw new ho(Ep);return e.facade=r,He.set(r,e),e},sr=function(r){return He.get(r)||{}},za=function(r){return He.has(r)}):(qt=BE("state"),OE[qt]=!0,Ya=function(r,e){if(co(r,qt))throw new ho(Ep);return e.facade=r,VE(r,qt,e),e},sr=function(r){return co(r,qt)?r[qt]:{}},za=function(r){return co(r,qt)});var He,qt;Pp.exports={set:Ya,get:sr,has:za,enforce:NE,getterFor:FE}});var vo=m((NC,wp)=>{"use strict";var fo=Ee(),qE=Ue(),kp=Function.prototype,UE=fo&&Object.getOwnPropertyDescriptor,bo=qE(kp,"name"),HE=bo&&function(){}.name==="something",jE=bo&&(!fo||fo&&UE(kp,"name").configurable);wp.exports={EXISTS:bo,PROPER:HE,CONFIGURABLE:jE}});var Rp=m(Ap=>{"use strict";var GE=Ee(),QE=Kn(),WE=Nt(),YE=Ze(),zE=Ot(),KE=uo();Ap.f=GE&&!QE?Object.defineProperties:function(e,t){YE(e);for(var i=zE(t),a=KE(t),s=a.length,n=0,o;s>n;)WE.f(e,o=a[n++],i[o]);return e}});var So=m((qC,Lp)=>{"use strict";var XE=lt();Lp.exports=XE("document","documentElement")});var Io=m((UC,Op)=>{"use strict";var JE=Ze(),ZE=Rp(),Mp=oo(),ex=Wa(),tx=So(),ix=qa(),rx=Ga(),$p=">",Dp="<",yo="prototype",To="script",Vp=rx("IE_PROTO"),go=function(){},Bp=function(r){return Dp+To+$p+r+Dp+"/"+To+$p},Cp=function(r){r.write(Bp("")),r.close();var e=r.parentWindow.Object;return r=null,e},ax=function(){var r=ix("iframe"),e="java"+To+":",t;return r.style.display="none",tx.appendChild(r),r.src=String(e),t=r.contentWindow.document,t.open(),t.write(Bp("document.F=Object")),t.close(),t.F},Ka,Xa=function(){try{Ka=new ActiveXObject("htmlfile")}catch{}Xa=typeof document<"u"?document.domain&&Ka?Cp(Ka):ax():Cp(Ka);for(var r=Mp.length;r--;)delete Xa[yo][Mp[r]];return Xa()};ex[Vp]=!0;Op.exports=Object.create||function(e,t){var i;return e!==null?(go[yo]=JE(e),i=new go,go[yo]=null,i[Vp]=e):i=Xa(),t===void 0?i:ZE.f(i,t)}});var gi=m((HC,_p)=>{"use strict";var sx=fi();_p.exports=function(r,e,t,i){return i&&i.enumerable?r[e]=t:sx(r,e,t),r}});var ko=m((jC,qp)=>{"use strict";var nx=ne(),ox=K(),ux=Pe(),lx=Io(),Np=Qa(),cx=gi(),dx=oe(),px=qe(),Po=dx("iterator"),Fp=!1,ct,Eo,xo;[].keys&&(xo=[].keys(),"next"in xo?(Eo=Np(Np(xo)),Eo!==Object.prototype&&(ct=Eo)):Fp=!0);var hx=!ux(ct)||nx(function(){var r={};return ct[Po].call(r)!==r});hx?ct={}:px&&(ct=lx(ct));ox(ct[Po])||cx(ct,Po,function(){return this});qp.exports={IteratorPrototype:ct,BUGGY_SAFARI_ITERATORS:Fp}});var Ja=m((GC,Hp)=>{"use strict";var mx=oe(),fx=mx("toStringTag"),Up={};Up[fx]="z";Hp.exports=String(Up)==="[object z]"});var nr=m((QC,jp)=>{"use strict";var bx=Ja(),vx=K(),Za=Bt(),Sx=oe(),gx=Sx("toStringTag"),yx=Object,Tx=Za(function(){return arguments}())==="Arguments",Ix=function(r,e){try{return r[e]}catch{}};jp.exports=bx?Za:function(r){var e,t,i;return r===void 0?"Undefined":r===null?"Null":typeof(t=Ix(e=yx(r),gx))=="string"?t:Tx?Za(e):(i=Za(e))==="Object"&&vx(e.callee)?"Arguments":i}});var Qp=m((WC,Gp)=>{"use strict";var Ex=Ja(),xx=nr();Gp.exports=Ex?{}.toString:function(){return"[object "+xx(this)+"]"}});var or=m((YC,Yp)=>{"use strict";var Px=Ja(),kx=Nt().f,wx=fi(),Ax=Ue(),Rx=Qp(),Lx=oe(),Wp=Lx("toStringTag");Yp.exports=function(r,e,t,i){var a=t?r:r&&r.prototype;a&&(Ax(a,Wp)||kx(a,Wp,{configurable:!0,value:e}),i&&!Px&&wx(a,"toString",Rx))}});var Kp=m((zC,zp)=>{"use strict";var Mx=ko().IteratorPrototype,$x=Io(),Dx=zi(),Cx=or(),Vx=Ft(),Bx=function(){return this};zp.exports=function(r,e,t,i){var a=e+" Iterator";return r.prototype=$x(Mx,{next:Dx(+!i,t)}),Cx(r,a,!1,!0),Vx[a]=Bx,r}});var Jp=m((KC,Xp)=>{"use strict";var Ox=ie(),_x=Je();Xp.exports=function(r,e,t){try{return Ox(_x(Object.getOwnPropertyDescriptor(r,e)[t]))}catch{}}});var eh=m((XC,Zp)=>{"use strict";var Nx=Pe();Zp.exports=function(r){return Nx(r)||r===null}});var ih=m((JC,th)=>{"use strict";var Fx=eh(),qx=String,Ux=TypeError;th.exports=function(r){if(Fx(r))return r;throw new Ux("Can't set "+qx(r)+" as a prototype")}});var wo=m((ZC,rh)=>{"use strict";var Hx=Jp(),jx=Pe(),Gx=bt(),Qx=ih();rh.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var r=!1,e={},t;try{t=Hx(Object.prototype,"__proto__","set"),t(e,[]),r=e instanceof Array}catch{}return function(a,s){return Gx(a),Qx(s),jx(a)&&(r?t(a,s):a.__proto__=s),a}}():void 0)});var mh=m((eV,hh)=>{"use strict";var Wx=te(),Yx=xe(),es=qe(),dh=vo(),zx=K(),Kx=Kp(),ah=Qa(),sh=wo(),Xx=or(),Jx=fi(),Ao=gi(),Zx=oe(),nh=Ft(),ph=ko(),eP=dh.PROPER,tP=dh.CONFIGURABLE,oh=ph.IteratorPrototype,ts=ph.BUGGY_SAFARI_ITERATORS,ur=Zx("iterator"),uh="keys",lr="values",lh="entries",ch=function(){return this};hh.exports=function(r,e,t,i,a,s,n){Kx(t,e,i);var o=function(v){if(v===a&&p)return p;if(!ts&&v&&v in d)return d[v];switch(v){case uh:return function(){return new t(this,v)};case lr:return function(){return new t(this,v)};case lh:return function(){return new t(this,v)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,d=r.prototype,c=d[ur]||d["@@iterator"]||a&&d[a],p=!ts&&c||o(a),h=e==="Array"&&d.entries||c,f,b,S;if(h&&(f=ah(h.call(new r)),f!==Object.prototype&&f.next&&(!es&&ah(f)!==oh&&(sh?sh(f,oh):zx(f[ur])||Ao(f,ur,ch)),Xx(f,u,!0,!0),es&&(nh[u]=ch))),eP&&a===lr&&c&&c.name!==lr&&(!es&&tP?Jx(d,"name",lr):(l=!0,p=function(){return Yx(c,this)})),a)if(b={values:o(lr),keys:s?p:o(uh),entries:o(lh)},n)for(S in b)(ts||l||!(S in d))&&Ao(d,S,b[S]);else Wx({target:e,proto:!0,forced:ts||l},b);return(!es||n)&&d[ur]!==p&&Ao(d,ur,p,{name:a}),nh[e]=p,b}});var bh=m((tV,fh)=>{"use strict";fh.exports=function(r,e){return{value:r,done:e}}});var Lo=m((iV,Th)=>{"use strict";var iP=Ot(),Ro=rr(),vh=Ft(),gh=mo(),rP=Nt().f,aP=mh(),is=bh(),sP=qe(),nP=Ee(),yh="Array Iterator",oP=gh.set,uP=gh.getterFor(yh);Th.exports=aP(Array,"Array",function(r,e){oP(this,{type:yh,target:iP(r),index:0,kind:e})},function(){var r=uP(this),e=r.target,t=r.index++;if(!e||t>=e.length)return r.target=void 0,is(void 0,!0);switch(r.kind){case"keys":return is(t,!1);case"values":return is(e[t],!1)}return is([t,e[t]],!1)},"values");var Sh=vh.Arguments=vh.Array;Ro("keys");Ro("values");Ro("entries");if(!sP&&nP&&Sh.name!=="values")try{rP(Sh,"name",{value:"values"})}catch{}});var Eh=m((rV,Ih)=>{"use strict";var lP=oe(),cP=Ft(),dP=lP("iterator"),pP=Array.prototype;Ih.exports=function(r){return r!==void 0&&(cP.Array===r||pP[dP]===r)}});var Mo=m((aV,Ph)=>{"use strict";var hP=nr(),xh=Ji(),mP=ci(),fP=Ft(),bP=oe(),vP=bP("iterator");Ph.exports=function(r){if(!mP(r))return xh(r,vP)||xh(r,"@@iterator")||fP[hP(r)]}});var wh=m((sV,kh)=>{"use strict";var SP=xe(),gP=Je(),yP=Ze(),TP=Xi(),IP=Mo(),EP=TypeError;kh.exports=function(r,e){var t=arguments.length<2?IP(r):e;if(gP(t))return yP(SP(t,r));throw new EP(TP(r)+" is not iterable")}});var Lh=m((nV,Rh)=>{"use strict";var xP=xe(),Ah=Ze(),PP=Ji();Rh.exports=function(r,e,t){var i,a;Ah(r);try{if(i=PP(r,"return"),!i){if(e==="throw")throw t;return t}i=xP(i,r)}catch(s){a=!0,i=s}if(e==="throw")throw t;if(a)throw i;return Ah(i),t}});var as=m((oV,Ch)=>{"use strict";var kP=mi(),wP=xe(),AP=Ze(),RP=Xi(),LP=Eh(),MP=Si(),Mh=Ki(),$P=wh(),DP=Mo(),$h=Lh(),CP=TypeError,rs=function(r,e){this.stopped=r,this.result=e},Dh=rs.prototype;Ch.exports=function(r,e,t){var i=t&&t.that,a=!!(t&&t.AS_ENTRIES),s=!!(t&&t.IS_RECORD),n=!!(t&&t.IS_ITERATOR),o=!!(t&&t.INTERRUPTED),u=kP(e,i),l,d,c,p,h,f,b,S=function(P){return l&&$h(l,"normal",P),new rs(!0,P)},v=function(P){return a?(AP(P),o?u(P[0],P[1],S):u(P[0],P[1])):o?u(P,S):u(P)};if(s)l=r.iterator;else if(n)l=r;else{if(d=DP(r),!d)throw new CP(RP(r)+" is not iterable");if(LP(d)){for(c=0,p=MP(r);p>c;c++)if(h=v(r[c]),h&&Mh(Dh,h))return h;return new rs(!1)}l=$P(r,d)}for(f=s?r.next:l.next;!(b=wP(f,l)).done;){try{h=v(b.value)}catch(P){$h(l,"throw",P)}if(typeof h=="object"&&h&&Mh(Dh,h))return h}return new rs(!1)}});var Bh=m((uV,Vh)=>{"use strict";var VP=Ee(),BP=Nt(),OP=zi();Vh.exports=function(r,e,t){VP?BP.f(r,e,OP(0,t)):r[e]=t}});var Oh=m(()=>{"use strict";var _P=te(),NP=as(),FP=Bh();_P({target:"Object",stat:!0},{fromEntries:function(e){var t={};return NP(e,function(i,a){FP(t,i,a)},{AS_ENTRIES:!0}),t}})});var Nh=m((dV,_h)=>{"use strict";Lo();Oh();var qP=di();_h.exports=qP.Object.fromEntries});var qh=m((pV,Fh)=>{"use strict";Fh.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 Hh=m(()=>{"use strict";Lo();var UP=qh(),HP=X(),jP=or(),Uh=Ft();for(ss in UP)jP(HP[ss],ss),Uh[ss]=Uh.Array;var ss});var Gh=m((fV,jh)=>{"use strict";var GP=Nh();Hh();jh.exports=GP});var $o=m((bV,Qh)=>{"use strict";var QP=Gh();Qh.exports=QP});var Wh=m(()=>{"use strict"});var Do=m((gV,Yh)=>{"use strict";var cr=X(),WP=_t(),YP=Bt(),ns=function(r){return WP.slice(0,r.length)===r};Yh.exports=function(){return ns("Bun/")?"BUN":ns("Cloudflare-Workers")?"CLOUDFLARE":ns("Deno/")?"DENO":ns("Node.js/")?"NODE":cr.Bun&&typeof Bun.version=="string"?"BUN":cr.Deno&&typeof Deno.version=="object"?"DENO":YP(cr.process)==="process"?"NODE":cr.window&&cr.document?"BROWSER":"REST"}()});var os=m((yV,zh)=>{"use strict";var zP=Do();zh.exports=zP==="NODE"});var Xh=m((TV,Kh)=>{"use strict";var KP=Nt();Kh.exports=function(r,e,t){return KP.f(r,e,t)}});var em=m((IV,Zh)=>{"use strict";var XP=lt(),JP=Xh(),ZP=oe(),ek=Ee(),Jh=ZP("species");Zh.exports=function(r){var e=XP(r);ek&&e&&!e[Jh]&&JP(e,Jh,{configurable:!0,get:function(){return this}})}});var im=m((EV,tm)=>{"use strict";var tk=Ki(),ik=TypeError;tm.exports=function(r,e){if(tk(e,r))return r;throw new ik("Incorrect invocation")}});var Vo=m((xV,rm)=>{"use strict";var rk=ie(),ak=K(),Co=Zi(),sk=rk(Function.toString);ak(Co.inspectSource)||(Co.inspectSource=function(r){return sk(r)});rm.exports=Co.inspectSource});var Oo=m((PV,um)=>{"use strict";var nk=ie(),ok=ne(),am=K(),uk=nr(),lk=lt(),ck=Vo(),sm=function(){},nm=lk("Reflect","construct"),Bo=/^\s*(?:class|function)\b/,dk=nk(Bo.exec),pk=!Bo.test(sm),dr=function(e){if(!am(e))return!1;try{return nm(sm,[],e),!0}catch{return!1}},om=function(e){if(!am(e))return!1;switch(uk(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return pk||!!dk(Bo,ck(e))}catch{return!0}};om.sham=!0;um.exports=!nm||ok(function(){var r;return dr(dr.call)||!dr(Object)||!dr(function(){r=!0})||r})?om:dr});var cm=m((kV,lm)=>{"use strict";var hk=Oo(),mk=Xi(),fk=TypeError;lm.exports=function(r){if(hk(r))return r;throw new fk(mk(r)+" is not a constructor")}});var _o=m((wV,pm)=>{"use strict";var dm=Ze(),bk=cm(),vk=ci(),Sk=oe(),gk=Sk("species");pm.exports=function(r,e){var t=dm(r).constructor,i;return t===void 0||vk(i=dm(t)[gk])?e:bk(i)}});var mm=m((AV,hm)=>{"use strict";var yk=ie();hm.exports=yk([].slice)});var bm=m((RV,fm)=>{"use strict";var Tk=TypeError;fm.exports=function(r,e){if(r<e)throw new Tk("Not enough arguments");return r}});var No=m((LV,vm)=>{"use strict";var Ik=_t();vm.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(Ik)});var Yo=m((MV,km)=>{"use strict";var ke=X(),Ek=wn(),xk=mi(),Sm=K(),Pk=Ue(),Pm=ne(),gm=So(),kk=mm(),ym=qa(),wk=bm(),Ak=No(),Rk=os(),Go=ke.setImmediate,Qo=ke.clearImmediate,Lk=ke.process,Fo=ke.Dispatch,Mk=ke.Function,Tm=ke.MessageChannel,$k=ke.String,qo=0,pr={},Im="onreadystatechange",hr,Ut,Uo,Ho;Pm(function(){hr=ke.location});var Wo=function(r){if(Pk(pr,r)){var e=pr[r];delete pr[r],e()}},jo=function(r){return function(){Wo(r)}},Em=function(r){Wo(r.data)},xm=function(r){ke.postMessage($k(r),hr.protocol+"//"+hr.host)};(!Go||!Qo)&&(Go=function(e){wk(arguments.length,1);var t=Sm(e)?e:Mk(e),i=kk(arguments,1);return pr[++qo]=function(){Ek(t,void 0,i)},Ut(qo),qo},Qo=function(e){delete pr[e]},Rk?Ut=function(r){Lk.nextTick(jo(r))}:Fo&&Fo.now?Ut=function(r){Fo.now(jo(r))}:Tm&&!Ak?(Uo=new Tm,Ho=Uo.port2,Uo.port1.onmessage=Em,Ut=xk(Ho.postMessage,Ho)):ke.addEventListener&&Sm(ke.postMessage)&&!ke.importScripts&&hr&&hr.protocol!=="file:"&&!Pm(xm)?(Ut=xm,ke.addEventListener("message",Em,!1)):Im in ym("script")?Ut=function(r){gm.appendChild(ym("script"))[Im]=function(){gm.removeChild(this),Wo(r)}}:Ut=function(r){setTimeout(jo(r),0)});km.exports={set:Go,clear:Qo}});var Rm=m(($V,Am)=>{"use strict";var wm=X(),Dk=Ee(),Ck=Object.getOwnPropertyDescriptor;Am.exports=function(r){if(!Dk)return wm[r];var e=Ck(wm,r);return e&&e.value}});var zo=m((DV,Mm)=>{"use strict";var Lm=function(){this.head=null,this.tail=null};Lm.prototype={add:function(r){var e={item:r,next:null},t=this.tail;t?t.next=e:this.head=e,this.tail=e},get:function(){var r=this.head;if(r){var e=this.head=r.next;return e===null&&(this.tail=null),r.item}}};Mm.exports=Lm});var Dm=m((CV,$m)=>{"use strict";var Vk=_t();$m.exports=/ipad|iphone|ipod/i.test(Vk)&&typeof Pebble<"u"});var Vm=m((VV,Cm)=>{"use strict";var Bk=_t();Cm.exports=/web0s(?!.*chrome)/i.test(Bk)});var Um=m((BV,qm)=>{"use strict";var Ti=X(),Ok=Rm(),Bm=mi(),Ko=Yo().set,_k=zo(),Nk=No(),Fk=Dm(),qk=Vm(),Xo=os(),Om=Ti.MutationObserver||Ti.WebKitMutationObserver,_m=Ti.document,Nm=Ti.process,us=Ti.Promise,eu=Ok("queueMicrotask"),yi,Jo,Zo,ls,Fm;eu||(mr=new _k,fr=function(){var r,e;for(Xo&&(r=Nm.domain)&&r.exit();e=mr.get();)try{e()}catch(t){throw mr.head&&yi(),t}r&&r.enter()},!Nk&&!Xo&&!qk&&Om&&_m?(Jo=!0,Zo=_m.createTextNode(""),new Om(fr).observe(Zo,{characterData:!0}),yi=function(){Zo.data=Jo=!Jo}):!Fk&&us&&us.resolve?(ls=us.resolve(void 0),ls.constructor=us,Fm=Bm(ls.then,ls),yi=function(){Fm(fr)}):Xo?yi=function(){Nm.nextTick(fr)}:(Ko=Bm(Ko,Ti),yi=function(){Ko(fr)}),eu=function(r){mr.head||yi(),mr.add(r)});var mr,fr;qm.exports=eu});var jm=m((OV,Hm)=>{"use strict";Hm.exports=function(r,e){try{arguments.length===1?console.error(r):console.error(r,e)}catch{}}});var cs=m((_V,Gm)=>{"use strict";Gm.exports=function(r){try{return{error:!1,value:r()}}catch(e){return{error:!0,value:e}}}});var Ht=m((NV,Qm)=>{"use strict";var Uk=X();Qm.exports=Uk.Promise});var Ii=m((FV,Km)=>{"use strict";var Hk=X(),br=Ht(),jk=K(),Gk=zn(),Qk=Vo(),Wk=oe(),Wm=Do(),Yk=qe(),tu=Bn(),Ym=br&&br.prototype,zk=Wk("species"),iu=!1,zm=jk(Hk.PromiseRejectionEvent),Kk=Gk("Promise",function(){var r=Qk(br),e=r!==String(br);if(!e&&tu===66||Yk&&!(Ym.catch&&Ym.finally))return!0;if(!tu||tu<51||!/native code/.test(r)){var t=new br(function(s){s(1)}),i=function(s){s(function(){},function(){})},a=t.constructor={};if(a[zk]=i,iu=t.then(function(){})instanceof i,!iu)return!0}return!e&&(Wm==="BROWSER"||Wm==="DENO")&&!zm});Km.exports={CONSTRUCTOR:Kk,REJECTION_EVENT:zm,SUBCLASSING:iu}});var Ei=m((qV,Jm)=>{"use strict";var Xm=Je(),Xk=TypeError,Jk=function(r){var e,t;this.promise=new r(function(i,a){if(e!==void 0||t!==void 0)throw new Xk("Bad Promise constructor");e=i,t=a}),this.resolve=Xm(e),this.reject=Xm(t)};Jm.exports.f=function(r){return new Jk(r)}});var Sf=m(()=>{"use strict";var Zk=te(),ew=qe(),ms=os(),St=X(),wi=xe(),Zm=gi(),ef=wo(),tw=or(),iw=em(),rw=Je(),hs=K(),aw=Pe(),sw=im(),nw=_o(),nf=Yo().set,ou=Um(),ow=jm(),uw=cs(),lw=zo(),of=mo(),fs=Ht(),uu=Ii(),uf=Ei(),bs="Promise",lf=uu.CONSTRUCTOR,cw=uu.REJECTION_EVENT,dw=uu.SUBCLASSING,ru=of.getterFor(bs),pw=of.set,xi=fs&&fs.prototype,jt=fs,ds=xi,cf=St.TypeError,au=St.document,lu=St.process,su=uf.f,hw=su,mw=!!(au&&au.createEvent&&St.dispatchEvent),df="unhandledrejection",fw="rejectionhandled",tf=0,pf=1,bw=2,cu=1,hf=2,ps,rf,vw,af,mf=function(r){var e;return aw(r)&&hs(e=r.then)?e:!1},ff=function(r,e){var t=e.value,i=e.state===pf,a=i?r.ok:r.fail,s=r.resolve,n=r.reject,o=r.domain,u,l,d;try{a?(i||(e.rejection===hf&&gw(e),e.rejection=cu),a===!0?u=t:(o&&o.enter(),u=a(t),o&&(o.exit(),d=!0)),u===r.promise?n(new cf("Promise-chain cycle")):(l=mf(u))?wi(l,u,s,n):s(u)):n(t)}catch(c){o&&!d&&o.exit(),n(c)}},bf=function(r,e){r.notified||(r.notified=!0,ou(function(){for(var t=r.reactions,i;i=t.get();)ff(i,r);r.notified=!1,e&&!r.rejection&&Sw(r)}))},vf=function(r,e,t){var i,a;mw?(i=au.createEvent("Event"),i.promise=e,i.reason=t,i.initEvent(r,!1,!0),St.dispatchEvent(i)):i={promise:e,reason:t},!cw&&(a=St["on"+r])?a(i):r===df&&ow("Unhandled promise rejection",t)},Sw=function(r){wi(nf,St,function(){var e=r.facade,t=r.value,i=sf(r),a;if(i&&(a=uw(function(){ms?lu.emit("unhandledRejection",t,e):vf(df,e,t)}),r.rejection=ms||sf(r)?hf:cu,a.error))throw a.value})},sf=function(r){return r.rejection!==cu&&!r.parent},gw=function(r){wi(nf,St,function(){var e=r.facade;ms?lu.emit("rejectionHandled",e):vf(fw,e,r.value)})},Pi=function(r,e,t){return function(i){r(e,i,t)}},ki=function(r,e,t){r.done||(r.done=!0,t&&(r=t),r.value=e,r.state=bw,bf(r,!0))},nu=function(r,e,t){if(!r.done){r.done=!0,t&&(r=t);try{if(r.facade===e)throw new cf("Promise can't be resolved itself");var i=mf(e);i?ou(function(){var a={done:!1};try{wi(i,e,Pi(nu,a,r),Pi(ki,a,r))}catch(s){ki(a,s,r)}}):(r.value=e,r.state=pf,bf(r,!1))}catch(a){ki({done:!1},a,r)}}};if(lf&&(jt=function(e){sw(this,ds),rw(e),wi(ps,this);var t=ru(this);try{e(Pi(nu,t),Pi(ki,t))}catch(i){ki(t,i)}},ds=jt.prototype,ps=function(e){pw(this,{type:bs,done:!1,notified:!1,parent:!1,reactions:new lw,rejection:!1,state:tf,value:void 0})},ps.prototype=Zm(ds,"then",function(e,t){var i=ru(this),a=su(nw(this,jt));return i.parent=!0,a.ok=hs(e)?e:!0,a.fail=hs(t)&&t,a.domain=ms?lu.domain:void 0,i.state===tf?i.reactions.add(a):ou(function(){ff(a,i)}),a.promise}),rf=function(){var r=new ps,e=ru(r);this.promise=r,this.resolve=Pi(nu,e),this.reject=Pi(ki,e)},uf.f=su=function(r){return r===jt||r===vw?new rf(r):hw(r)},!ew&&hs(fs)&&xi!==Object.prototype)){af=xi.then,dw||Zm(xi,"then",function(e,t){var i=this;return new jt(function(a,s){wi(af,i,a,s)}).then(e,t)},{unsafe:!0});try{delete xi.constructor}catch{}ef&&ef(xi,ds)}Zk({global:!0,constructor:!0,wrap:!0,forced:lf},{Promise:jt});tw(jt,bs,!1,!0);iw(bs)});var Ef=m((jV,If)=>{"use strict";var yw=oe(),yf=yw("iterator"),Tf=!1;try{gf=0,du={next:function(){return{done:!!gf++}},return:function(){Tf=!0}},du[yf]=function(){return this},Array.from(du,function(){throw 2})}catch{}var gf,du;If.exports=function(r,e){try{if(!e&&!Tf)return!1}catch{return!1}var t=!1;try{var i={};i[yf]=function(){return{next:function(){return{done:t=!0}}}},r(i)}catch{}return t}});var pu=m((GV,xf)=>{"use strict";var Tw=Ht(),Iw=Ef(),Ew=Ii().CONSTRUCTOR;xf.exports=Ew||!Iw(function(r){Tw.all(r).then(void 0,function(){})})});var Pf=m(()=>{"use strict";var xw=te(),Pw=xe(),kw=Je(),ww=Ei(),Aw=cs(),Rw=as(),Lw=pu();xw({target:"Promise",stat:!0,forced:Lw},{all:function(e){var t=this,i=ww.f(t),a=i.resolve,s=i.reject,n=Aw(function(){var o=kw(t.resolve),u=[],l=0,d=1;Rw(e,function(c){var p=l++,h=!1;d++,Pw(o,t,c).then(function(f){h||(h=!0,u[p]=f,--d||a(u))},s)}),--d||a(u)});return n.error&&s(n.value),i.promise}})});var wf=m(()=>{"use strict";var Mw=te(),$w=qe(),Dw=Ii().CONSTRUCTOR,mu=Ht(),Cw=lt(),Vw=K(),Bw=gi(),kf=mu&&mu.prototype;Mw({target:"Promise",proto:!0,forced:Dw,real:!0},{catch:function(r){return this.then(void 0,r)}});!$w&&Vw(mu)&&(hu=Cw("Promise").prototype.catch,kf.catch!==hu&&Bw(kf,"catch",hu,{unsafe:!0}));var hu});var Af=m(()=>{"use strict";var Ow=te(),_w=xe(),Nw=Je(),Fw=Ei(),qw=cs(),Uw=as(),Hw=pu();Ow({target:"Promise",stat:!0,forced:Hw},{race:function(e){var t=this,i=Fw.f(t),a=i.reject,s=qw(function(){var n=Nw(t.resolve);Uw(e,function(o){_w(n,t,o).then(i.resolve,a)})});return s.error&&a(s.value),i.promise}})});var Rf=m(()=>{"use strict";var jw=te(),Gw=Ei(),Qw=Ii().CONSTRUCTOR;jw({target:"Promise",stat:!0,forced:Qw},{reject:function(e){var t=Gw.f(this),i=t.reject;return i(e),t.promise}})});var fu=m((eB,Lf)=>{"use strict";var Ww=Ze(),Yw=Pe(),zw=Ei();Lf.exports=function(r,e){if(Ww(r),Yw(e)&&e.constructor===r)return e;var t=zw.f(r),i=t.resolve;return i(e),t.promise}});var Df=m(()=>{"use strict";var Kw=te(),Xw=lt(),Mf=qe(),Jw=Ht(),$f=Ii().CONSTRUCTOR,Zw=fu(),eA=Xw("Promise"),tA=Mf&&!$f;Kw({target:"Promise",stat:!0,forced:Mf||$f},{resolve:function(e){return Zw(tA&&this===eA?Jw:this,e)}})});var Cf=m(()=>{"use strict";Sf();Pf();wf();Af();Rf();Df()});var _f=m(()=>{"use strict";var iA=te(),rA=qe(),vs=Ht(),aA=ne(),Bf=lt(),Of=K(),sA=_o(),Vf=fu(),nA=gi(),vu=vs&&vs.prototype,oA=!!vs&&aA(function(){vu.finally.call({then:function(){}},function(){})});iA({target:"Promise",proto:!0,real:!0,forced:oA},{finally:function(r){var e=sA(this,Bf("Promise")),t=Of(r);return this.then(t?function(i){return Vf(e,r()).then(function(){return i})}:r,t?function(i){return Vf(e,r()).then(function(){throw i})}:r)}});!rA&&Of(vs)&&(bu=Bf("Promise").prototype.finally,vu.finally!==bu&&nA(vu,"finally",bu,{unsafe:!0}));var bu});var Ff=m((oB,Nf)=>{"use strict";Wh();Cf();_f();var uA=vt();Nf.exports=uA("Promise","finally")});var Uf=m((uB,qf)=>{"use strict";var lA=Ff();qf.exports=lA});var Ss=m((lB,Hf)=>{"use strict";var cA=Uf();Hf.exports=cA});var eb=m(()=>{"use strict";var PA=te(),kA=lo().values;PA({target:"Object",stat:!0},{values:function(e){return kA(e)}})});var ib=m((QB,tb)=>{"use strict";eb();var wA=di();tb.exports=wA.Object.values});var ab=m((WB,rb)=>{"use strict";var AA=ib();rb.exports=AA});var Ri=m((YB,sb)=>{"use strict";var RA=ab();sb.exports=RA});var Ib=m(()=>{"use strict";var ZA=te(),eR=pi(),tR=Si(),iR=ir(),rR=rr();ZA({target:"Array",proto:!0},{at:function(e){var t=eR(this),i=tR(t),a=iR(e),s=a>=0?a:i+a;return s<0||s>=i?void 0:t[s]}});rR("at")});var xb=m((r_,Eb)=>{"use strict";Ib();var aR=vt();Eb.exports=aR("Array","at")});var kb=m((a_,Pb)=>{"use strict";var sR=xb();Pb.exports=sR});var Et=m((s_,wb)=>{"use strict";var nR=kb();wb.exports=nR});var Uu=m((ON,ov)=>{"use strict";var jR=Bt();ov.exports=Array.isArray||function(e){return jR(e)==="Array"}});var lv=m((_N,uv)=>{"use strict";var GR=TypeError,QR=9007199254740991;uv.exports=function(r){if(r>QR)throw GR("Maximum allowed index exceeded");return r}});var pv=m((NN,dv)=>{"use strict";var WR=Uu(),YR=Si(),zR=lv(),KR=mi(),cv=function(r,e,t,i,a,s,n,o){for(var u=a,l=0,d=n?KR(n,o):!1,c,p;l<i;)l in t&&(c=d?d(t[l],l,e):t[l],s>0&&WR(c)?(p=YR(c),u=cv(r,e,c,p,u,s-1)-1):(zR(u+1),r[u]=c),u++),l++;return u};dv.exports=cv});var bv=m((FN,fv)=>{"use strict";var hv=Uu(),XR=Oo(),JR=Pe(),ZR=oe(),eL=ZR("species"),mv=Array;fv.exports=function(r){var e;return hv(r)&&(e=r.constructor,XR(e)&&(e===mv||hv(e.prototype))?e=void 0:JR(e)&&(e=e[eL],e===null&&(e=void 0))),e===void 0?mv:e}});var Sv=m((qN,vv)=>{"use strict";var tL=bv();vv.exports=function(r,e){return new(tL(r))(e===0?0:e)}});var gv=m(()=>{"use strict";var iL=te(),rL=pv(),aL=Je(),sL=pi(),nL=Si(),oL=Sv();iL({target:"Array",proto:!0},{flatMap:function(e){var t=sL(this),i=nL(t),a;return aL(e),a=oL(t,0),a.length=rL(a,t,t,i,0,1,e,arguments.length>1?arguments[1]:void 0),a}})});var yv=m(()=>{"use strict";var uL=rr();uL("flatMap")});var Iv=m((QN,Tv)=>{"use strict";gv();yv();var lL=vt();Tv.exports=lL("Array","flatMap")});var xv=m((WN,Ev)=>{"use strict";var cL=Iv();Ev.exports=cL});var Hu=m((YN,Pv)=>{"use strict";var dL=xv();Pv.exports=dL});var $r=m((zN,kv)=>{"use strict";var pL=nr(),hL=String;kv.exports=function(r){if(pL(r)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return hL(r)}});var ju=m((KN,wv)=>{"use strict";wv.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 Lv=m((XN,Rv)=>{"use strict";var mL=ie(),fL=bt(),bL=$r(),Qu=ju(),Av=mL("".replace),vL=RegExp("^["+Qu+"]+"),SL=RegExp("(^|[^"+Qu+"])["+Qu+"]+$"),Gu=function(r){return function(e){var t=bL(fL(e));return r&1&&(t=Av(t,vL,"")),r&2&&(t=Av(t,SL,"$1")),t}};Rv.exports={start:Gu(1),end:Gu(2),trim:Gu(3)}});var Cv=m((JN,Dv)=>{"use strict";var gL=vo().PROPER,yL=ne(),Mv=ju(),$v="\u200B\x85\u180E";Dv.exports=function(r){return yL(function(){return!!Mv[r]()||$v[r]()!==$v||gL&&Mv[r].name!==r})}});var Wu=m((ZN,Vv)=>{"use strict";var TL=Lv().start,IL=Cv();Vv.exports=IL("trimStart")?function(){return TL(this)}:"".trimStart});var Ov=m(()=>{"use strict";var EL=te(),Bv=Wu();EL({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==Bv},{trimLeft:Bv})});var Nv=m(()=>{"use strict";Ov();var xL=te(),_v=Wu();xL({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==_v},{trimStart:_v})});var qv=m((aF,Fv)=>{"use strict";Nv();var PL=vt();Fv.exports=PL("String","trimLeft")});var Hv=m((sF,Uv)=>{"use strict";var kL=qv();Uv.exports=kL});var Gv=m((nF,jv)=>{"use strict";var wL=Hv();jv.exports=wL});var oS=m(()=>{"use strict"});var uS=m(()=>{"use strict"});var cS=m((FU,lS)=>{"use strict";var KL=Pe(),XL=Bt(),JL=oe(),ZL=JL("match");lS.exports=function(r){var e;return KL(r)&&((e=r[ZL])!==void 0?!!e:XL(r)==="RegExp")}});var pS=m((qU,dS)=>{"use strict";var eM=Ze();dS.exports=function(){var r=eM(this),e="";return r.hasIndices&&(e+="d"),r.global&&(e+="g"),r.ignoreCase&&(e+="i"),r.multiline&&(e+="m"),r.dotAll&&(e+="s"),r.unicode&&(e+="u"),r.unicodeSets&&(e+="v"),r.sticky&&(e+="y"),e}});var fS=m((UU,mS)=>{"use strict";var tM=xe(),iM=Ue(),rM=Ki(),aM=pS(),hS=RegExp.prototype;mS.exports=function(r){var e=r.flags;return e===void 0&&!("flags"in hS)&&!iM(r,"flags")&&rM(hS,r)?tM(aM,r):e}});var vS=m((HU,bS)=>{"use strict";var tl=ie(),sM=pi(),nM=Math.floor,Zu=tl("".charAt),oM=tl("".replace),el=tl("".slice),uM=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,lM=/\$([$&'`]|\d{1,2})/g;bS.exports=function(r,e,t,i,a,s){var n=t+r.length,o=i.length,u=lM;return a!==void 0&&(a=sM(a),u=uM),oM(s,u,function(l,d){var c;switch(Zu(d,0)){case"$":return"$";case"&":return r;case"`":return el(e,0,t);case"'":return el(e,n);case"<":c=a[el(d,1,-1)];break;default:var p=+d;if(p===0)return l;if(p>o){var h=nM(p/10);return h===0?l:h<=o?i[h-1]===void 0?Zu(d,1):i[h-1]+Zu(d,1):l}c=i[p-1]}return c===void 0?"":c})}});var yS=m(()=>{"use strict";var cM=te(),dM=xe(),rl=ie(),SS=bt(),pM=K(),hM=ci(),mM=cS(),Ci=$r(),fM=Ji(),bM=fS(),vM=vS(),SM=oe(),gM=qe(),yM=SM("replace"),TM=TypeError,il=rl("".indexOf),IM=rl("".replace),gS=rl("".slice),EM=Math.max;cM({target:"String",proto:!0},{replaceAll:function(e,t){var i=SS(this),a,s,n,o,u,l,d,c,p,h,f=0,b="";if(!hM(e)){if(a=mM(e),a&&(s=Ci(SS(bM(e))),!~il(s,"g")))throw new TM("`.replaceAll` does not allow non-global regexes");if(n=fM(e,yM),n)return dM(n,e,i,t);if(gM&&a)return IM(Ci(i),e,t)}for(o=Ci(i),u=Ci(e),l=pM(t),l||(t=Ci(t)),d=u.length,c=EM(1,d),p=il(o,u);p!==-1;)h=l?Ci(t(u,p,o)):vM(u,o,p,[],void 0,t),b+=gS(o,f,p)+h,f=p+d,p=p+c>o.length?-1:il(o,u,p+c);return f<o.length&&(b+=gS(o,f)),b}})});var IS=m((QU,TS)=>{"use strict";oS();uS();yS();var xM=vt();TS.exports=xM("String","replaceAll")});var xS=m((WU,ES)=>{"use strict";var PM=IS();ES.exports=PM});var kS=m((YU,PS)=>{"use strict";var kM=xS();PS.exports=kM});var AS=m((zU,wS)=>{"use strict";var wM=ir(),AM=$r(),RM=bt(),LM=RangeError;wS.exports=function(e){var t=AM(RM(this)),i="",a=wM(e);if(a<0||a===1/0)throw new LM("Wrong number of repetitions");for(;a>0;(a>>>=1)&&(t+=t))a&1&&(i+=t);return i}});var DS=m((KU,$S)=>{"use strict";var MS=ie(),MM=to(),RS=$r(),$M=AS(),DM=bt(),CM=MS($M),VM=MS("".slice),BM=Math.ceil,LS=function(r){return function(e,t,i){var a=RS(DM(e)),s=MM(t),n=a.length,o=i===void 0?" ":RS(i),u,l;return s<=n||o===""?a:(u=s-n,l=CM(o,BM(u/o.length)),l.length>u&&(l=VM(l,0,u)),r?a+l:l+a)}};$S.exports={start:LS(!1),end:LS(!0)}});var VS=m((XU,CS)=>{"use strict";var OM=_t();CS.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(OM)});var BS=m(()=>{"use strict";var _M=te(),NM=DS().start,FM=VS();_M({target:"String",proto:!0,forced:FM},{padStart:function(e){return NM(this,e,arguments.length>1?arguments[1]:void 0)}})});var _S=m((e1,OS)=>{"use strict";BS();var qM=vt();OS.exports=qM("String","padStart")});var FS=m((t1,NS)=>{"use strict";var UM=_S();NS.exports=UM});var US=m((i1,qS)=>{"use strict";var HM=FS();qS.exports=HM});var Jl="2.0.131-dev.f80b28b8.0";var Ie=(a=>(a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused",a))(Ie||{}),ut=(y=>(y.MPEG="MPEG",y.DASH="DASH",y.DASH_SEP="DASH_SEP",y.DASH_SEP_VK="DASH_SEP",y.DASH_WEBM="DASH_WEBM",y.DASH_WEBM_AV1="DASH_WEBM_AV1",y.DASH_STREAMS="DASH_STREAMS",y.DASH_WEBM_VK="DASH_WEBM",y.DASH_ONDEMAND="DASH_ONDEMAND",y.DASH_ONDEMAND_VK="DASH_ONDEMAND",y.DASH_LIVE="DASH_LIVE",y.DASH_LIVE_CMAF="DASH_LIVE_CMAF",y.DASH_LIVE_WEBM="DASH_LIVE_WEBM",y.HLS="HLS",y.HLS_ONDEMAND="HLS_ONDEMAND",y.HLS_JS="HLS",y.HLS_LIVE="HLS_LIVE",y.HLS_LIVE_CMAF="HLS_LIVE_CMAF",y.WEB_RTC_LIVE="WEB_RTC_LIVE",y))(ut||{});var Oa=(a=>(a.NOT_AVAILABLE="NOT_AVAILABLE",a.AVAILABLE="AVAILABLE",a.CONNECTING="CONNECTING",a.CONNECTED="CONNECTED",a))(Oa||{}),xn=(i=>(i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic",i))(xn||{});var Pn=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(Pn||{}),_a=(i=>(i.TRAFFIC_SAVING="traffic_saving",i.HIGH_QUALITY="high_quality",i.UNKNOWN="unknown",i))(_a||{});var gy=D(et(),1);import{assertNever as zd,assertNonNullable as XI,isNonNullable as Ha,ValueSubject as ro,Subject as JI,Subscription as ZI,merge as eE,observableFrom as tE,fromEvent as Qd,map as Wd,filterChanged as iE,isNullable as ao,ErrorCategory as Yd}from"@vkontakte/videoplayer-shared";var Gd=r=>new Promise((e,t)=>{let i=document.createElement("script");i.setAttribute("src",r),i.onload=()=>e(),i.onerror=a=>t(a),document.body.appendChild(i)});var ja=class{constructor(e){this.connection$=new ro(void 0);this.castState$=new ro("NOT_AVAILABLE");this.errorEvent$=new JI;this.realCastState$=new ro("NOT_AVAILABLE");this.subscription=new ZI;this.isDestroyed=!1;this.params=e;let t="chrome"in window;if(e.isDisabled||!t)return;let i=Ha(window.chrome?.cast),a=!!window.__onGCastApiAvailable;i?this.initializeCastApi():(window.__onGCastApiAvailable=s=>{delete window.__onGCastApiAvailable,s&&!this.isDestroyed&&this.initializeCastApi()},a||Gd("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:Yd.NETWORK,message:"Script loading failed!"})))}connect(){cast.framework.CastContext.getInstance()?.requestSession()}disconnect(){cast.framework.CastContext.getInstance()?.getCurrentSession()?.endSession(!0)}stopMedia(){return new Promise((e,t)=>{cast.framework.CastContext.getInstance()?.getCurrentSession()?.getMediaSession()?.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){Ha(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();ao(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();ao(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(Qd(i,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(a=>{switch(a.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=i.getCurrentSession()?.getMediaSession()?.media?.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return zd(a.sessionState)}})).add(eE(Qd(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(Wd(a=>a.castState)),tE([i.getCastState()])).pipe(iE(),Wd(rE)).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(a=>{let s=a==="CONNECTED",n=Ha(this.connection$.getValue());if(s&&!n){let o=i.getCurrentSession();XI(o);let u=o.getCastDevice(),l=o.getMediaSession()?.media?.contentId;(ao(l)||l===this.contentId)&&this.connection$.next({remotePlayer:e,remotePlayerController:t,session:o,castDevice:u})}else!s&&n&&this.connection$.next(void 0);this.castState$.next(a==="CONNECTED"?Ha(this.connection$.getValue())?"CONNECTED":"AVAILABLE":a)}))}initializeCastApi(){let e,t,i;try{e=cast.framework.CastContext.getInstance(),t=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,i=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch{return}try{e.setOptions({receiverApplicationId:this.params.receiverApplicationId??t,autoJoinPolicy:i}),this.initListeners()}catch(a){this.errorEvent$.next({id:"ChromecastInitializer",category:Yd.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:a})}}},rE=r=>{switch(r){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 zd(r)}};var Hl=D(et(),1),ty=D(ar(),1),iy=D($o(),1);var Xf=D(Ss(),1);import{assertNever as jf}from"@vkontakte/videoplayer-shared";var ue=(r,e=0,t=0)=>{switch(t){case 0:return r.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case 1:{if(e===0)return r;let i=new URL(r);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}case 2:{let i=new URL(r);return!i.searchParams.get("offset_p")&&e===0?r:(i.searchParams.set("offset_p",e.toFixed(0)),i.toString())}default:jf(t)}return r},gs=(r,e)=>{switch(e){case 0:return NaN;case 1:{let t=new URL(r);return Number(t.searchParams.get("playback_shift"))}case 2:{let t=new URL(r);return Number(t.searchParams.get("offset_p")??0)}default:jf(e)}};var x=(r,e,t=!1)=>{let i=r.getTransition();(t||!i||i.to===e)&&r.setState(e)};import{isNonNullable as dA,Subject as ys,merge as Gf}from"@vkontakte/videoplayer-shared";var A=class{constructor(e){this.transitionStarted$=new ys;this.transitionEnded$=new ys;this.transitionUpdated$=new ys;this.forceChanged$=new ys;this.stateChangeStarted$=Gf(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=Gf(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||dA(t)&&t.to===e||(this.prevState=i,this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:i,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}getPrevState(){return this.prevState}};import{assertNever as pA}from"@vkontakte/videoplayer-shared";var Qf=r=>{switch(r){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 pA(r)}};import{assertNever as Ai,assertNonNullable as Gt,debounce as Wf,ErrorCategory as Yf,fromEvent as Qt,isNonNullable as zf,merge as hA,observableFrom as mA,Subject as fA,Subscription as Su,timeout as bA,getHighestQuality as vA}from"@vkontakte/videoplayer-shared";var SA=5,gA=5,yA=500,Kf=7e3,vr=class{constructor(e){this.subscription=new Su;this.loadMediaTimeoutSubscription=new Su;this.videoState=new A("stopped");this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.stop());return}if(!t){if(a?.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:Ai(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:Ai(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:Ai(e)}break}default:Ai(i)}}};this.params=e,this.params.output.isLive$.next(Qf(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.subscription.unsubscribe()}subscribe(){this.subscription.add(this.loadMediaTimeoutSubscription);let e=new Su;this.subscription.add(e);let t=(a,s)=>this.subscription.add(a.subscribe(s));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{let a=new fA;e.add(a.pipe(Wf(yA)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add(Qt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(n=>{let o=n.value;this.params.output.position$.next(o),(this.params.desiredState.seekState.getState().state==="applying"||Math.abs(o-s)>SA)&&a.next(o),s=o})),e.add(Qt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.params.output.duration$.next(n.value)}))}t(Qt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),a=>{a.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(Qt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),a=>{a.value?this.handleRemotePause():this.handleRemotePlay()}),t(Qt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),a=>{let{remotePlayer:s}=this.params.connection,n=a.value,o=this.params.output.isBuffering$.getValue(),u=n===chrome.cast.media.PlayerState.BUFFERING;switch(o!==u&&this.params.output.isBuffering$.next(u),n){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&s.duration-s.currentTime<gA&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),x(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:Ai(n)}}),t(Qt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),a=>{this.handleRemoteVolumeChange({volume:a.value})}),t(Qt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),a=>{this.handleRemoteVolumeChange({muted:a.value})});let i=hA(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,mA(["init"])).pipe(Wf(0));t(i,this.syncPlayback)}restoreSession(e){let{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),x(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,t=this.createMediaInfo(e),i=this.createLoadRequest(t);this.loadMedia(i)}handleRemotePause(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="paused"||e==="playing")&&(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="playing"||e==="paused")&&(this.videoState.setState("playing"),x(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.params.desiredState.playbackState.getTransition()?.to==="ready"&&x(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){let t=this.params.output.volume$.getValue(),i={volume:e.volume??t.volume,muted:e.muted??t.muted};(i.volume!==t.volume||i.muted!==i.muted)&&this.params.output.volume$.next(i)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:i}=this.params.connection;t.currentTime=e,i.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){let t=this.params.source,i,a,s;switch(e){case"MPEG":{let l=t[e];Gt(l);let d=vA(Object.keys(l));Gt(d);let c=l[d];Gt(c),i=c,a="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let l=t[e];Gt(l),i=l.url,a="application/x-mpegurl",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":{let l=t[e];Gt(l),i=l.url,a="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let l=t[e];Gt(l),i=l.url,a="application/dash+xml",s=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let l=t[e];Gt(l),i=ue(l.url),a="application/x-mpegurl",s=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let l="Unsupported format for Chromecast",d=new Error(l);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:Yf.VIDEO_PIPELINE,message:l,thrown:d}),d}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return Ai(e)}let n=new chrome.cast.media.MediaInfo(this.params.meta.videoId??i,a);n.contentUrl=i,n.streamType=s,n.metadata=new chrome.cast.media.GenericMediaMetadata;let{title:o,subtitle:u}=this.params.meta;return zf(o)&&(n.metadata.title=o),zf(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((a,s)=>{this.loadMediaTimeoutSubscription.add(bA(Kf).subscribe(()=>s(`timeout(${Kf})`)))});(0,Xf.default)(Promise.race([t,i]).then(()=>{this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},a=>{let s=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${a}`;this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:Yf.VIDEO_PIPELINE,message:s,thrown:a})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}};var Fu=D(et(),1);import{clearVideoElement as Zf}from"@vkontakte/videoplayer-shared";import{clearVideoElement as TA}from"@vkontakte/videoplayer-shared";var Jf=r=>{try{r.pause(),r.playbackRate=0,TA(r),r.remove()}catch(e){console.error(e)}};import{fromEvent as IA,Subscription as EA}from"@vkontakte/videoplayer-shared";var gu=class{constructor(){this.attribute="data-pool-reused"}get(e){return e.hasAttribute(this.attribute)}set(e,t){e.toggleAttribute(this.attribute,t)}delete(e){e.removeAttribute(this.attribute)}},yu=window.WeakMap?new WeakMap:new gu,Tu=window.WeakMap?new WeakMap:new Map,xA=(r,e=20)=>{let t=0;return IA(r,"ratechange").subscribe(i=>{t++,t>=e&&(r.currentTime=r.currentTime,t=0)})},fe=(r,{audioVideoSyncRate:e,disableYandexPiP:t})=>{let i=r.querySelector("video"),a=!!i;i?Zf(i):(i=document.createElement("video"),r.appendChild(i)),yu.set(i,a);let s=new EA;return s.add(xA(i,e)),Tu.set(i,s),i.setAttribute("crossorigin","anonymous"),i.setAttribute("playsinline","playsinline"),t&&i.setAttribute("x-yandex-pip","false"),i.controls=!1,i.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),i},be=r=>{Tu.get(r)?.unsubscribe(),Tu.delete(r);let t=yu.get(r);yu.delete(r),t?Zf(r):Jf(r)};var Eu=D(Ri(),1);import{assertNonNullable as Sr,isNonNullable as it,isNullable as $A,fromEvent as Li,merge as nb,observableFrom as ob,filterChanged as ub,map as gr,Subject as lb,Subscription as DA,ValueSubject as CA,ErrorCategory as VA}from"@vkontakte/videoplayer-shared";import{isNonNullable as Iu,isNullable as LA,Subscription as MA}from"@vkontakte/videoplayer-shared";var Ts=(r,e,t,{equal:i=(n,o)=>n===o,changed$:a,onError:s}={})=>{let n=r.getState(),o=e(),u=LA(a),l=new MA;return a&&l.add(a.subscribe(d=>{let c=r.getState();i(d,c)&&r.setState(d)},s)),i(o,n)||(t(n),u&&r.setState(n)),l.add(r.stateChangeStarted$.subscribe(d=>{t(d.to),u&&r.setState(d.to)},s)),l},tt=(r,e,t)=>Ts(e,()=>r.loop,i=>{Iu(i)&&(r.loop=i)},{onError:t}),ve=(r,e,t,i)=>Ts(e,()=>({muted:r.muted,volume:r.volume}),a=>{Iu(a)&&(r.muted=a.muted,r.volume=a.volume)},{equal:(a,s)=>a===s||a?.muted===s?.muted&&a?.volume===s?.volume,changed$:t,onError:i}),De=(r,e,t,i)=>Ts(e,()=>r.playbackRate,a=>{Iu(a)&&(r.playbackRate=a)},{changed$:t,onError:i}),gt=Ts;var BA=r=>["__",r.language,r.label].join("|"),OA=(r,e)=>{if(r.id===e)return!0;let[t,i,a]=e.split("|");return r.language===i&&r.label===a},xu=class r{constructor(e){this.available$=new lb;this.current$=new CA(void 0);this.error$=new lb;this.subscription=new DA;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 a=s=>{this.error$.next({id:"TextTracksManager",category:VA.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(gt(t.internalTextTracks,()=>(0,Eu.default)(this.internalTracks),s=>{it(s)&&this.setInternal(s)},{equal:(s,n)=>it(s)&&it(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(gr(s=>s.filter(({type:n})=>n==="internal"))),onError:a})),this.subscription.add(gt(t.externalTextTracks,()=>(0,Eu.default)(this.externalTracks),s=>{it(s)&&this.setExternal(s)},{equal:(s,n)=>it(s)&&it(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(gr(s=>s.filter(({type:n})=>n==="external"))),onError:a})),this.subscription.add(gt(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:a})),this.subscription.add(gt(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){Sr(this.video);let{textTracks:e}=this.video;this.subscription.add(Li(e,"addtrack").subscribe(()=>{let i=this.current$.getValue();i&&this.select(i)})),this.subscription.add(nb(Li(e,"addtrack"),Li(e,"removetrack"),ob(["init"])).pipe(gr(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),ub((i,a)=>i.length===a.length&&i.every(({id:s},n)=>s===a[n].id))).subscribe(this.available$)),this.subscription.add(nb(Li(e,"change"),ob(["init"])).pipe(gr(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),gr(i=>i&&this.htmlTextTrackToITextTrack(i).id),ub()).subscribe(this.current$));let t=i=>this.applyCueSettings(i.target?.activeCues??null);this.subscription.add(Li(e,"addtrack").subscribe(i=>{i.track?.addEventListener("cuechange",t);let a=s=>{let n=s.target?.cues??null;n&&n.length&&(this.applyCueSettings(s.target?.cues??null),s.target?.removeEventListener("cuechange",a))};i.track?.addEventListener("cuechange",a)})),this.subscription.add(Li(e,"removetrack").subscribe(i=>{i.track?.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;let t=this.cueSettings.getState();for(let i of Array.from(e)){let a=i;it(t.align)&&(a.align=t.align),it(t.position)&&(a.position=t.position),it(t.size)&&(a.size=t.size),it(t.line)&&(a.line=t.line)}}htmlTextTracksAsArray(e=!1){Sr(this.video);let t=[...this.video.textTracks];return e?t:t.filter(r.isHealthyTrack)}htmlTextTrackToITextTrack(e){let{language:t,label:i}=e,a=e.id?e.id:BA(e),s=this.externalTracks.has(a),n=(s?this.externalTracks.get(a)?.isAuto:this.internalTracks.get(a)?.isAuto)??a.includes("auto");return s?{id:a,type:"external",isAuto:n,language:t,label:i,url:this.externalTracks.get(a)?.url}:{id:a,type:"internal",isAuto:n,language:t,label:i,url:this.internalTracks.get(a)?.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:a,isAuto:s})=>!this.internalTracks.has(i)&&!t.some(([,n])=>n.language===a&&n.isAuto===s)).forEach(i=>this.attach(i)),Array.from(this.internalTracks).filter(([i])=>!e.find(a=>a.id===i)).forEach(([,i])=>this.detach(i))}select(e){Sr(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))($A(e)||!OA(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){Sr(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){Sr(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)}},Ce=xu;var Wt=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 cb=r=>{let e=r;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e?.parentNode;return e??void 0},Pu=r=>{let e=cb(r);return!!(e&&e.fullscreenElement&&e.fullscreenElement===r)},db=r=>{let e=cb(r);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===r)};import{fromEvent as Se,map as yt,merge as wu,filterChanged as QA,isNonNullable as yb,Subject as WA,filter as Tr,mapTo as Au,combine as YA,once as zA,throttle as KA,ErrorCategory as XA,ValueSubject as Tb,Subscription as JA}from"@vkontakte/videoplayer-shared";var _A=3,pb=(r,e,t=_A)=>{let i=0,a=0;for(let s=0;s<r.length;s++){let n=r.start(s),o=r.end(s);if(n<=e&&e<=o){if(i=n,a=o,!t)return{from:i,to:a};for(let u=s-1;u>=0;u--)r.end(u)+t>=i&&(i=r.start(u));for(let u=s+1;u<r.length;u++)r.start(u)-t<=a&&(a=r.end(u))}}return{from:i,to:a}};var Is=class{get current(){return this._current}get isYandex(){return this.current==="Yandex"}get isSafari(){return this.current==="Safari"}get isSamsungBrowser(){return this.current==="SamsungBrowser"}get safariVersion(){return this._safariVersion}detect(){let{userAgent:e}=navigator;try{let t=/yabrowser/i.test(e)?"Yandex":void 0,i=/samsungbrowser/i.test(e)?"SamsungBrowser":void 0,a=/chrome|crios/i.test(e)?"Chrome":void 0,s=/chromium/i.test(e)?"Chromium":void 0,n=/firefox|fxios/i.test(e)?"Firefox":void 0,o=/webkit|safari|khtml/i.test(e)?"Safari":void 0,u=/opr\//i.test(e)?"Opera":void 0,l=/edg/i.test(e)?"Edge":void 0;this._current=t||i||n||u||l||a||s||o||"Rest"}catch(t){console.error(t)}this.isSafari&&this.detectSafariVersion()}detectSafariVersion(){try{let{userAgent:e}=window.navigator,t=e.match(/Version\/(\d+)/);if(!t)return;let i=t[1],a=parseInt(i,10);if(isNaN(a))return;this._safariVersion=a}catch(e){console.error(e)}}};var hb=D(et(),1);var yr=()=>/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test(navigator.appVersion??navigator.userAgent)||navigator?.userAgentData?.mobile;var Es=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,hb.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=yr()}catch(t){console.error(t)}this.detectDevice(e),this.detectHighEntropyValues(),this.isIOS&&this.detectIOSVersion()}async detectHighEntropyValues(){let{userAgentData:e}=navigator;if(e){let t=await e.getHighEntropyValues(["architecture","bitness","brands","mobile","platform","formFactor","model","platformVersion","wow64"]);this._highEntropyValues=t}}detectDevice(e){try{let t=/android/i.test(e)?"Android":void 0,i=/iphone/i.test(e)?"iPhone":void 0,a=/ipad/i.test(e)?"iPad":void 0,s=/ipod/i.test(e)?"iPod":void 0,n=/mac/i.test(e)?"Mac":void 0,o=/webOS|BlackBerry|IEMobile|Opera Mini/i.test(e)?"RestMobile":void 0;this._current=t||i||a||s||o||n||"Desktop"}catch(t){console.error(t)}}detectIOSVersion(){try{if(this._highEntropyValues.platformVersion){let s=this._highEntropyValues.platformVersion.split(".").slice(0,2).join("."),n=parseFloat(s);this._iosVersion=n;return}let{userAgent:e}=window.navigator,t=e.match(/OS (\d+(_\d+)?)/i);if(!t)return;let i=t[1].replace(/_/g,".");if(!i)return;let a=parseFloat(i);if(isNaN(a))return;this._iosVersion=a}catch(e){console.error(e)}}};var xs=class{get isTouch(){return typeof this._maxTouchPoints=="number"?this._maxTouchPoints>1:"ontouchstart"in window}get maxTouchPoints(){return this._maxTouchPoints}get height(){return this._height}get width(){return this._width}get screenHeight(){return this._screenHeight}get screenWidth(){return this._screenWidth}get pixelRatio(){return this._pixelRatio}get isHDR(){return this._isHdr}get colorDepth(){return this._colorDepth}detect(){let{maxTouchPoints:e}=navigator;try{this._maxTouchPoints=e??0,this._isHdr=!!matchMedia("(dynamic-range: high)")?.matches,this._colorDepth=screen.colorDepth}catch(t){console.error(t)}try{this._pixelRatio=window.devicePixelRatio||1,this._height=screen.height,this._width=screen.width,this._height=screen.height,this._screenHeight=this._height*this._pixelRatio,this._screenWidth=this._width*this._pixelRatio}catch(t){console.error(t)}}};var je=()=>window.ManagedMediaSource||window.MediaSource,Ps=()=>!!(window.ManagedMediaSource&&window.ManagedSourceBuffer?.prototype?.appendBuffer),mb=()=>!!(window.MediaSource&&window.SourceBuffer?.prototype?.appendBuffer),fb=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var NA=document.createElement("video"),FA='video/mp4; codecs="avc1.42000a,mp4a.40.2"',qA='video/mp4; codecs="hev1.1.6.L93.B0"',bb='video/webm; codecs="vp09.00.10.08"',vb='video/webm; codecs="av01.0.00M.08"',UA='audio/mp4; codecs="mp4a.40.2"',HA='audio/webm; codecs="opus"',Sb,jA=async()=>{if(!window.navigator.mediaCapabilities)return;let r={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=await Promise.all([window.navigator.mediaCapabilities.decodingInfo({...r,video:{...r.video,contentType:vb}}),window.navigator.mediaCapabilities.decodingInfo({...r,video:{...r.video,contentType:bb}})]);Sb={DASH_WEBM_AV1:e,DASH_WEBM:t}};jA().catch(r=>{console.log(NA),console.error(r)});var ks=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 Sb}get supportedCodecs(){return Object.keys(this._codecs).filter(e=>this._codecs[e])}get nativeHlsSupported(){return this._nativeHlsSupported}detect(){this._video=document.createElement("video");try{this._protocols={mms:Ps(),mse:mb(),hls:!!(this._video.canPlayType?.("application/x-mpegurl")||this._video.canPlayType?.("vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},this._containers={mp4:!!this._video.canPlayType?.("video/mp4"),webm:!!this._video.canPlayType?.("video/webm"),cmaf:!0};let e=!!je()?.isTypeSupported?.(FA),t=!!je()?.isTypeSupported?.(qA),i=!!je()?.isTypeSupported?.(UA);this._codecs={h264:e,h265:t,vp9:!!je()?.isTypeSupported?.(bb),av1:!!je()?.isTypeSupported?.(vb),aac:i,opus:!!je()?.isTypeSupported?.(HA),mpeg:(e||t)&&i},this._nativeHlsSupported=this._protocols.hls&&this._containers.mp4}catch(e){console.error(e)}this.destroyVideoElement()}destroyVideoElement(){if(!this._video)return;if(this._video.pause(),this._video.currentTime=0,this._video.removeAttribute("src"),this._video.src="",this._video.load(),this._video.remove){this._video.remove(),this._video=null;return}this._video.parentNode&&this._video.parentNode.removeChild(this._video);let e=this._video.cloneNode(!1);this._video.parentNode?.replaceChild(e,this._video),this._video=null}};var gb="audio/mpeg",ws=class{supportMp3(){return this._codecs.mp3&&this._containers.mpeg}detect(){this._audio=document.createElement("audio");try{this._containers={mpeg:!!this._audio.canPlayType?.(gb)},this._codecs={mp3:!!je()?.isTypeSupported?.(gb)}}catch(e){console.error(e)}this.destroyAudioElement()}destroyAudioElement(){if(!this._audio)return;if(this._audio.pause(),this._audio.currentTime=0,this._audio.removeAttribute("src"),this._audio.src="",this._audio.load(),this._audio.remove){this._audio.remove(),this._audio=null;return}this._audio.parentNode&&this._audio.parentNode.removeChild(this._audio);let e=this._audio.cloneNode(!1);this._audio.parentNode?.replaceChild(e,this._audio),this._audio=null}};import{ValueSubject as GA}from"@vkontakte/videoplayer-shared";var ku=class{constructor(){this.isInited$=new GA(!1);this._displayChecker=new xs,this._deviceChecker=new Es(this._displayChecker),this._browserChecker=new Is,this._videoChecker=new ks(this._deviceChecker,this._browserChecker),this._audioChecker=new ws,this.detect()}get display(){return this._displayChecker}get device(){return this._deviceChecker}get browser(){return this._browserChecker}get video(){return this._videoChecker}get audio(){return this._audioChecker}async detect(){this._displayChecker.detect(),this._deviceChecker.detect(),this._browserChecker.detect(),this._videoChecker.detect(),this._audioChecker.detect(),this.isInited$.next(!0)}},C=new ku;var ge=r=>{let e=g=>Se(r,g).pipe(Au(void 0)),t=new JA,i=()=>t.unsubscribe(),s=wu(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(g=>Se(r,g))).pipe(yt(g=>g.type==="ended"?r.readyState<2:r.readyState<3),QA()),n=wu(Se(r,"progress"),Se(r,"timeupdate")).pipe(yt(()=>pb(r.buffered,r.currentTime))),o=C.browser.isSafari?YA({play:e("play").pipe(zA()),playing:e("playing")}).pipe(Au(void 0)):e("playing"),u=Se(r,"volumechange").pipe(yt(()=>({muted:r.muted,volume:r.volume}))),l=Se(r,"ratechange").pipe(yt(()=>r.playbackRate)),d=Se(r,"error").pipe(Tr(()=>!!(r.error||r.played.length)),yt(()=>{let g=r.error;return{id:g?`MediaError#${g.code}`:"HtmlVideoError",category:XA.VIDEO_PIPELINE,message:g?g.message:"Error event from HTML video element",thrown:r.error??void 0}})),c=Se(r,"timeupdate").pipe(yt(()=>r.currentTime)),p=new WA,h=.3,f;t.add(c.subscribe(g=>{r.loop&&yb(f)&&yb(g)&&f>=r.duration-h&&g<=h&&p.next(f),f=g}));let b=e("pause").pipe(Tr(()=>!r.error&&f!==r.duration)),S=Se(r,"enterpictureinpicture"),v=Se(r,"leavepictureinpicture"),P=new Tb(db(r));t.add(S.subscribe(()=>P.next(!0))),t.add(v.subscribe(()=>P.next(!1)));let y=new Tb(Pu(r)),I=Se(r,"fullscreenchange");t.add(I.pipe(yt(()=>Pu(r))).subscribe(y));let k=.1,H=1e3,j=Se(r,"timeupdate").pipe(Tr(g=>r.duration-r.currentTime<k)),U=wu(j.pipe(Tr(g=>!r.loop)),Se(r,"ended")).pipe(KA(H),Au(void 0)),T=j.pipe(Tr(g=>r.loop));return{playing$:o,pause$:b,canplay$:e("canplay"),ended$:U,looped$:p,loopExpected$:T,error$:d,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:c,durationChange$:Se(r,"durationchange").pipe(yt(()=>r.duration)),isBuffering$:s,currentBuffer$:n,volumeState$:u,playbackRateState$:l,inPiP$:P,inFullscreen$:y,enterPip$:S,leavePip$:v,destroy:i}};import{VideoQuality as Tt}from"@vkontakte/videoplayer-shared";var It=r=>{switch(r){case"mobile":return Tt.Q_144P;case"lowest":return Tt.Q_240P;case"low":return Tt.Q_360P;case"sd":case"medium":return Tt.Q_480P;case"hd":case"high":return Tt.Q_720P;case"fullhd":case"full":return Tt.Q_1080P;case"quadhd":case"quad":return Tt.Q_1440P;case"ultrahd":case"ultra":return Tt.Q_2160P}};var xt=D(Et(),1),Bb=D(et(),1);import{isNonNullable as we,isNullable as Lb,now as Ob,isHigher as Mb,isHigherOrEqual as Mu,isInvariantQuality as $b,isLowerOrEqual as $u,videoSizeToQuality as lR,assertNotEmptyArray as _b,assertNonNullable as cR}from"@vkontakte/videoplayer-shared";import{isHigher as oR,isHigherOrEqual as c_,isLower as Ab,isLowerOrEqual as d_,isNonNullable as As,isNullable as uR,videoHeightToQuality as Rs}from"@vkontakte/videoplayer-shared";function Ru(r,e,t){return!r.max&&r.min===e?"high_quality":!r.min&&r.max===t?"traffic_saving":"unknown"}function Lu(r,e,t){return!!r&&Ru(r,e,t)==="high_quality"}function Ir(r,e,t){return uR(r)||As(r.min)&&As(r.max)&&Ab(r.max,r.min)||As(r.min)&&e&&oR(r.min,e)||As(r.max)&&t&&Ab(r.max,t)}function Rb({limits:r,highestAvailableHeight:e,lowestAvailableHeight:t}){return Ir({max:r?.max?Rs(r.max):void 0,min:r?.min?Rs(r.min):void 0},e?Rs(e):void 0,t?Rs(t):void 0)}var Nb=(r,e,t)=>(e-t)*Math.pow(2,-10*r)+t;var Du=r=>(e,t)=>r*(Number(e.bitrate)-Number(t.bitrate)),Er=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=Ob()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},Fb='Assertion "ABR Tracks is empty array" failed',Ls=new WeakMap,Db=new WeakMap,Cb=new WeakMap,Ms=(r,e,t,i)=>{let a=Ls.get(e);a||(a=[...e].sort(Du(1)),Ls.set(e,a));let s=Ls.get(t);s||(s=[...t].sort(Du(1)),Ls.set(t,s));let n=Cb.get(r);n||(n=s.filter(u=>we(u.bitrate)&&we(r.bitrate)?r.bitrate/u.bitrate>i:!0),Cb.set(r,n));let o=(0,xt.default)(s,Math.round(s.length*a.indexOf(r)/(a.length+1)))??(0,xt.default)(s,-1);return o&&(0,Bb.default)(n,o)?o:n.length?(0,xt.default)(n,-1):(0,xt.default)(s,0)},qb=(r,e,t)=>{let i=we(t?.last?.bitrate)&&we(e?.bitrate)&&t.last.bitrate<e.bitrate?r.trackCooldownIncreaseQuality:r.trackCooldownDecreaseQuality,a=e&&t&&t.history[e.id]&&Ob()-t.history[e.id]<=i&&(!t.last||e.id!==t.last.id);if(e?.id&&t&&!a&&t.recordSelection(e),a&&t?.last){let s=t.last;return t?.recordSwitch(s),s}return t?.recordSwitch(e),e},dR=(r,e)=>Math.log(e)/Math.log(r),pR=({tuning:r,container:e,limits:t,panelSize:i})=>{let a=r.containerSizeFactor;if(i)return{containerSizeLimit:i,containerSizeFactor:a};if(r.usePixelRatio&&C.display.pixelRatio){let s=C.display.pixelRatio;if(r.pixelRatioMultiplier)a*=r.pixelRatioMultiplier*(s-1)+1;else{let n=r.pixelRatioLogBase,[o=0,u=0,l=0]=r.pixelRatioLogCoefficients,d=dR(n,o*s+u)+l;Number.isFinite(d)&&(a*=d)}}return Lu(t,r.highQualityLimit,r.trafficSavingLimit)&&(a*=2),{containerSizeLimit:r.limitByContainer&&e&&e.width>0&&e.height>0?{width:e.width*a,height:e.height*a}:void 0,containerSizeFactor:a}},Vb=new WeakMap,Pt=(r,{container:e,estimatedThroughput:t,tuning:i,limits:a,reserve:s=0,forwardBufferHealth:n,playbackRate:o,current:u,history:l,visible:d,droppedVideoMaxQualityLimit:c,stallsVideoMaxQualityLimit:p,stallsPredictedThroughput:h,panelSize:f})=>{_b(r,Fb);let b=f??pR({container:e,tuning:i,limits:a,panelSize:f}).containerSizeLimit,S=i.considerPlaybackRate&&we(o)?o:1,v=Vb.get(r);v||(v=r.filter(T=>!$b(T.quality)).sort((T,g)=>Mb(T.quality,g.quality)?-1:1),Vb.set(r,v));let P=(0,xt.default)(v,-1)?.quality,y=(0,xt.default)(v,0)?.quality,I=Ir(a,y,P),k=S*Nb(n??.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),H=null;for(let T of v){let g=!0;if(b)if(T.size)g=T.size.width<=b.width&&T.size.height<=b.height;else{let Z=b&&lR(b);g=Z?$u(T.quality,Z):!0}if(!g)continue;let N=h||t,M=we(N)&&isFinite(N)&&we(T.bitrate)?N-s>=T.bitrate*k:!0,z=Lu(a,i.highQualityLimit,i.trafficSavingLimit)&&a?.min===T.quality;if(!M&&!z||i.lazyQualitySwitch&&we(i.minBufferToSwitchUp)&&u&&!$b(u.quality)&&(n??0)<i.minBufferToSwitchUp&&Mb(T.quality,u.quality)||!!c&&Mu(T.quality,c)&&!z||!!p&&Mu(T.quality,p)&&!z)continue;let F=I||(Lb(a?.max)||$u(T.quality,a.max))&&(Lb(a?.min)||Mu(T.quality,a.min)),J=we(d)&&!d?$u(T.quality,i.backgroundVideoQualityLimit):!0;!F||!J||H||(H=T)}let j=H??(0,xt.default)(v,-1)??r[0];return qb(i,j,l)},Ub=(r,e,t,{estimatedThroughput:i,tuning:a,playbackRate:s,forwardBufferHealth:n,history:o,stallsPredictedThroughput:u})=>{_b(t,Fb);let l=a.considerPlaybackRate&&we(s)?s:1,d=Db.get(t);d||(d=[...t].sort(Du(-1)),Db.set(t,d));let c=r.bitrate;cR(c);let p=l*Nb(n??.5,a.bitrateAudioFactorAtEmptyBuffer,a.bitrateAudioFactorAtFullBuffer),h,f=Ms(r,e,t,a.minVideoAudioRatio),b=u||i;return we(b)&&isFinite(b)&&(h=d.find(v=>we(v.bitrate)&&we(f?.bitrate)?b-c>=v.bitrate*p&&v.bitrate>=f.bitrate:!1)),h||(h=f),h&&qb(a,h,o)};var re=r=>new URL(r).hostname;import{assertNever as Zb,assertNonNullable as ev,combine as DR,debounce as CR,ErrorCategory as tv,filter as iv,filterChanged as VR,isNonNullable as _u,map as rv,merge as BR,observableFrom as OR,once as _R,Subscription as NR,ValueSubject as Nu,videoQualityToHeight as av,videoSizeToQuality as FR}from"@vkontakte/videoplayer-shared";var zb=D(Et(),1);var jb=D(et(),1),Hb=r=>{if(r instanceof DOMException&&(0,jb.default)(["Failed to load because no supported source was found.","The element has no supported sources."],r.message))throw r;return!(r instanceof DOMException&&(r.code===20||r.name==="AbortError"))},ye=async(r,e)=>{let t=r.muted;try{await r.play()}catch(i){if(!Hb(i))return!1;if(e&&e(),t)return console.warn(i),!1;r.muted=!0;try{await r.play()}catch(a){return Hb(a)&&(r.muted=!1,console.warn(a)),!1}}return!0};import{isNonNullable as Ds,isNullable as fR,assertNonNullable as kr}from"@vkontakte/videoplayer-shared";var Qb=D(Ri(),1);import{isNonNullable as Gb,assertNonNullable as $s,now as hR}from"@vkontakte/videoplayer-shared";function ae(){return hR()}function Cu(r){return ae()-r}function Vu(r){let e=r.split("/"),t=e.slice(0,e.length-1).join("/"),i=/^([a-z]+:)?\/\//i,a=n=>i.test(n);return{resolve:(n,o,u=!1)=>{a(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 Wb(r,e,t){let i=(...a)=>{t.apply(null,a),r.removeEventListener(e,i)};r.addEventListener(e,i)}function Mi(r,e,t,i){let a=window.XMLHttpRequest,s,n,o,u=!1,l=0,d,c,p=!1,h="arraybuffer",f=7e3,b=2e3,S=()=>{if(u)return;$s(d);let M=Cu(d),z;if(M<b){z=b-M,setTimeout(S,z);return}b*=2,b>f&&(b=f),n&&n.abort(),n=new a,H()},v=M=>(s=M,N),P=M=>(c=M,N),y=()=>(h="json",N),I=()=>{if(!u){if(--l>=0){S(),i&&i();return}u=!0,c&&c(),t&&t()}},k=M=>(p=M,N),H=()=>{d=ae(),n=new a,n.open("get",r);let M=0,z,me=0,$=()=>($s(d),Math.max(d,Math.max(z||0,me||0)));if(s&&n.addEventListener("progress",O=>{let F=ae();s.updateChunk&&O.loaded>M&&(s.updateChunk($(),O.loaded-M),M=O.loaded,z=F)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>I())),n.addEventListener("load",()=>{if(u)return;$s(n);let O=n.status;if(O>=200&&O<300){let{response:F,responseType:J}=n,Z=F?.byteLength;if(typeof Z=="number"&&s){let Ye=Z-M;Ye&&s.updateChunk&&s.updateChunk($(),Ye)}J==="json"&&(!F||!(0,Qb.default)(F).length)?I():(c&&c(),e(F))}else I()}),n.addEventListener("error",()=>{I()}),p){let O=()=>{$s(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(me=ae(),n.removeEventListener("readystatechange",O))};n.addEventListener("readystatechange",O)}return n.responseType=h,n.send(),N},N={withBitrateReporting:v,withParallel:k,withJSONResponse:y,withRetryCount:M=>(l=M,N),withRetryInterval:(M,z)=>(Gb(M)&&(b=M),Gb(z)&&(f=z),N),withTimeout:M=>(o=M,N),withFinally:P,send:H,abort:()=>{n&&(n.abort(),n=void 0),u=!0,c&&c()}};return N}var xr=class{constructor(){this.intervals=[];this.currentRate=0}_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,a=0;for(;this.intervals.length>0;){let s=this.intervals[0];if(s.end<=t)i+=s.end-s.start,a+=s.bytes,this.intervals.splice(0,1);else{if(s.start>=t)break;{let n=t-s.start,o=s.end-s.start;i+=n;let u=s.bytes*n/o;a+=u,s.start=t,s.bytes-=u}}}if(a>0&&i>0){let s=a*8/(i/1e3);return this._updateRate(s),!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._doMergeIntervals(this.intervals[1],this.intervals[0]),this.intervals.splice(0,1)),this._flushIntervals()}getBitRate(){return this.currentRate}};var Yb=D(Ri(),1);var Pr=class{constructor(e,t,i,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=a}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){let t=e[Math.floor(Math.random()*e.length)];delete this.completeRequests[t]}}_sendRequest(e,t){let i=ae(),a=u=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=u,e._errorCB?e._errorCB(u):(this.limitCompleteCount(),this.completeRequests[t]=e)},s=u=>{e._complete=1,e._responseData=u,e._downloadTime=ae()-i,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(u,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=Mi(t,s,()=>a("error"),o),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(n),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=ae()}_getParallelRequestCount(){return Math.min(this.MAX_PARALLEL_REQUESTS,this.averageSegmentDuration<3e3?3:2)}_getPrefetchDelay(){return Math.max(100,Math.min(5e3,this.averageSegmentDuration/3))}_canSendPending(){let e=this._getParallelRequestCount(),t=ae();if(Object.keys(this.activeRequests).length>=e)return!1;let i=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),i>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),i),!1):!0}_sendPending(){for(;this._canSendPending();){let e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){(0,Yb.default)(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,i,a){let s={};return s.send=()=>{let n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=i,n._retryCB=a,n._finallyCB=s._finallyCB,(n._error||n._complete)&&(this._removeFromActive(e),setTimeout(()=>{n._complete?t(n._responseData,n._downloadTime):i(n._errorMsg),s._finallyCB&&s._finallyCB()},0));else{let o=this.pendingQueue.indexOf(e);o!==-1&&this.pendingQueue.splice(o,1),this._sendRequest(s,e)}},s._cb=t,s._errorCB=i,s._retryCB=a,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.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}};import{Subject as bR}from"@vkontakte/videoplayer-shared";var Cs=1e4,Bu=3;var vR=6e4,SR=10,gR=1,yR=500,wr=class{constructor(e){this.paused=!1;this.autoQuality=!0;this.autoQualityLimits=void 0;this.buffering=!0;this.destroyed=!1;this.videoPlayStarted=!1;this.lowLatency=!1;this.bitrate=0;this.manifest=[];this.sourceBuffer=0;this.bufferStates=[];this.sourceJitter=-1;this.waitingForFirstBufferAfterSrcChange=!1;this.params=e,this.soundProhibitedEvent$=new bR,this.chunkRateEstimator=new xr,this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=Vu(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setAutoQualityLimits(e){this.autoQualityLimits=e}switchByName(e){let t;for(let i=0;i<this.manifest.length;++i)if(t=this.manifest[i],t.name===e){this._switchToQuality(t);return}}catchUp(){this.rep&&this.rep.stop(),this.currentManifestEntry&&(this.paused=!1,this._initPlayerWith(this.currentManifestEntry),this._notifyBuffering(!0))}stop(){this.params.videoElement.pause(),this.rep&&(this.rep.stop(),this.rep=null)}pause(){this.paused=!0,this.params.videoElement.pause(),this.videoPlayStarted=!1,this._notifyBuffering(!1)}play(){this.paused=!1;let e=this.lowLatency&&this._getBufferSizeSec()>this.sourceJitter+5;this.rep&&!e?(this.bufferStates=[],this.videoPlayStarted=!1,this.shouldPlay()?this._playVideoElement():this._notifyBuffering(!0)):this.catchUp()}startPlay(e,t){this.autoQuality=t,this._initPlayerWith(e)}destroy(){this.destroyed=!0,this.rep&&(this.rep.stop(),this.rep=null),this.manifestRequest&&this.manifestRequest.abort(),this.manifestRefetchTimer&&(clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=void 0)}reinit(e){this.manifestUrl=e,this.urlResolver=Vu(e),this.catchUp()}_handleNetworkError(){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.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){let{videoElement:e}=this.params;e.addEventListener("error",()=>{!!e.error&&!this.destroyed&&this.params.playerCallback({name:"error",type:"media"})}),e.addEventListener("timeupdate",()=>{let t=this._getBufferSizeSec();!this.paused&&t<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(t+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){let{videoElement:e}=this.params,t=e.buffered.length,i;t!==0&&!this.waitingForFirstBufferAfterSrcChange&&(i=e.buffered.start(t-1),e.currentTime<i&&(e.currentTime=i))}_selectQuality(e){let{videoElement:t}=this.params,i,a,s,n=t&&1.62*(C.display.pixelRatio||1)*t.offsetHeight||520;for(let o=0;o<this.manifest.length;++o){s=this.manifest[o];let{max:u,min:l}=this.autoQualityLimits||{};!Rb({limits:this.autoQualityLimits,highestAvailableHeight:this.manifest[0].video.height,lowestAvailableHeight:(0,zb.default)(this.manifest,-1).video.height})&&(u&&s.video.height>u||l&&s.video.height<l)||(s.bitrate<e&&n>Math.min(s.video.height,s.video.width)?(!a||s.bitrate>a.bitrate)&&(a=s):(!i||i.bitrate>s.bitrate)&&(i=s))}return a||i}shouldPlay(){if(this.paused)return!1;let t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||Ds(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){let{videoElement:i,playerCallback:a}=this.params;this.mediaSource=new window.MediaSource,i.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,i.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});let s=()=>{Wb(i,"progress",()=>{i.buffered.length?(i.currentTime=i.buffered.start(0),this.waitingForFirstBufferAfterSrcChange=!1,a({name:"playing"})):s()})};this.waitingForFirstBufferAfterSrcChange=!0,s()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new Pr(Bu,Cs,this.bitrateSwitcher,this.params.config.maxParallelRequests),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{videoElement:t,playerCallback:i}=this.params,a=!1,s=null,n=null,o=null,u=null,l=!1,d=()=>a&&(!l||l===this.rep),c=(y,I,k)=>{o&&o.abort(),o=Mi(this.urlResolver.resolve(y,!1),I,k,()=>this._retryCallback()).withTimeout(Cs).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Bu).withFinally(()=>{o=null}).send()},p=(y,I,k)=>{kr(this.filesFetcher),n?.abort(),n=this.filesFetcher.requestData(this.urlResolver.resolve(y,!1),I,k,()=>this._retryCallback()).withFinally(()=>{n=null}).send()},h=y=>{let I=t.playbackRate;t.playbackRate!==y&&(t.playbackRate=y)},f=y=>{this.lowLatency=y,b()},b=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)h(1);else{let y=this._getBufferSizeSec();if(this.bufferStates.length<5){h(1);return}let k=ae()-1e4,H=0;for(let U=0;U<this.bufferStates.length;U++){let T=this.bufferStates[U];y=Math.min(y,T.buf),T.ts<k&&H++}this.bufferStates.splice(0,H);let j=y-gR;this.sourceJitter>=0?j-=this.sourceJitter/2:this.sourceJitter-=1,j>3?h(1.15):j>1?h(1.1):j>.3?h(1.05):h(1)}},S=y=>{let I,k=()=>I&&I.start?I.start.length:0,H=$=>I.start[$]/1e3,j=$=>I.dur[$]/1e3,U=$=>I.fragIndex+$,T=($,O)=>({chunkIdx:U($),startTS:H($),dur:j($),discontinuity:O}),g=()=>{let $=0;if(I&&I.dur){let O=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,F=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,J=O;this.sourceJitter>1&&(J+=this.sourceJitter-1);let Z=I.dur.length-1;for(;Z>=0&&(J-=I.dur[Z],!(J<=0));--Z);$=Math.min(Z,I.dur.length-1-F),$=Math.max($,0)}return T($,!0)},N=$=>{let O=k();if(!(O<=0)){if(Ds($)){for(let F=0;F<O;F++)if(H(F)>$)return T(F)}return g()}},M=$=>{let O=k(),F=$?$.chunkIdx+1:0,J=F-I.fragIndex;if(!(O<=0)){if(!$||J<0||J-O>SR)return g();if(!(J>=O))return T(F-I.fragIndex,!1)}},z=($,O,F)=>{u&&u.abort(),u=Mi(this.urlResolver.resolve($,!0,this.lowLatency),O,F,()=>this._retryCallback()).withTimeout(Cs).withRetryCount(Bu).withFinally(()=>{u=null}).withJSONResponse().send()};return{seek:($,O)=>{z(y,F=>{if(!d())return;I=F;let J=!!I.lowLatency;J!==this.lowLatency&&f(J);let Z=0;for(let Ye=0;Ye<I.dur.length;++Ye)Z+=I.dur[Ye];Z>0&&(kr(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(Z/I.dur.length)),i({name:"index",zeroTime:I.zeroTime,shiftDuration:I.shiftDuration}),this.sourceJitter=I.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,I.jitter/1e3)):1,$(N(O))},()=>this._handleNetworkError())},nextChunk:M}},v=()=>{a=!1,n&&n.abort(),o&&o.abort(),u&&u.abort(),kr(this.filesFetcher),this.filesFetcher.abortAll()};return l={start:y=>{let{videoElement:I}=this.params,k=S(e.jidxUrl),H,j,U,T,g=0,N,M,z,me=()=>{N&&(clearTimeout(N),N=void 0);let L=Math.max(yR,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),w=g+L,ee=ae(),Le=Math.min(1e4,w-ee);g=ee;let ze=()=>{u||d()&&k.seek(()=>{d()&&(g=ae(),$(),me())})};Le>0?N=window.setTimeout(()=>{this.paused?me():ze()},Le):ze()},$=()=>{let L;for(;L=k.nextChunk(T);)T=L,Ye(L);let w=k.nextChunk(U);if(w){if(U&&w.discontinuity){this.paused?me():(v(),this._initPlayerWith(e));return}Z(w)}else me()},O=(L,w)=>{if(!d()||!this.sourceBuffer)return;let ee,Le,ze,Be=Me=>{window.setTimeout(()=>{d()&&O(L,w)},Me)};if(this.sourceBuffer.updating)Be(100);else{let Me=ae(),nt=I.currentTime;!this.paused&&I.buffered.length>1&&M===nt&&Me-z>500&&this._fixupStall(),M!==nt&&(M=nt,z=Me);let Mt=this._getBufferSizeSec();if(Mt>30)Be(2e3);else try{this.sourceBuffer.appendBuffer(L),this.videoPlayStarted?(this.bufferStates.push({ts:Me,buf:Mt}),b(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),w&&w()}catch(Oe){if(Oe.name==="QuotaExceededError")ze=this.sourceBuffer.buffered.length,ze!==0&&(ee=this.sourceBuffer.buffered.start(0),Le=nt,Le-ee>4&&this.sourceBuffer.remove(ee,Le-3)),Be(1e3);else throw Oe}}},F=()=>{j&&H&&O(j,function(){j=null,$()})},J=L=>e.fragUrlTemplate.replace("%%id%%",L.chunkIdx),Z=L=>{d()&&p(J(L),(w,ee)=>{if(d()){if(ee/=1e3,j=w,U=L,s=L.startTS,ee){let Le=Math.min(10,L.dur/ee);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*Le:Le}F()}},()=>this._handleNetworkError())},Ye=L=>{d()&&(kr(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(J(L),!1)))},st=L=>{d()&&(e.cachedHeader=L,O(L,()=>{H=!0,F()}))};a=!0,k.seek(L=>{if(d()){if(g=ae(),!L){me();return}T=L,!fR(y)||L.startTS>y?Z(L):(U=L,$())}},y),e.cachedHeader?st(e.cachedHeader):c(e.headerUrl,st,()=>this._handleNetworkError())},stop:v,getTimestampSec:()=>s},l}_switchToQuality(e){let{playerCallback:t}=this.params,i;e.bitrate!==this.bitrate&&(this.rep&&(i=this.rep.getTimestampSec(),Ds(i)&&(i+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),this.bitrate=e.bitrate,kr(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(i),t({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return Ds(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{playerCallback:e}=this.params,t=d=>{if(!this.autoQuality)return;let c,p,h;this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&d<this.bitrate&&(p=this._getBufferSizeSec(),h=d/this.bitrate,p>10&&h>.8||p>15&&h>.5||p>20&&h>.3)||(c=this._selectQuality(d),c&&this._switchToQuality(c))},a={updateChunk:(c,p)=>{let h=ae();if(this.chunkRateEstimator.addInterval(c,h,p)){let b=this.chunkRateEstimator.getBitRate();return e({name:"bandwidth",size:p,duration:h-c,speed:b}),!0}},get:()=>{let c=this.chunkRateEstimator.getBitRate();return c?c*.85:0}},s=-1/0,n,o=!0,u=()=>{let d=a.get();if(d&&n&&this.autoQuality){if(o&&d>n&&Cu(s)<3e4)return;t(d)}o=this.autoQuality};return{updateChunk:(d,c)=>{let p=a.updateChunk(d,c);return p&&u(),p},notifySwitch:d=>{let c=ae();d<n&&(s=c),n=d}}}_fetchManifest(e,t,i){this.manifestRequest=Mi(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(Cs).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;ye(e,()=>{this.soundProhibitedEvent$.next()}).then(t=>{t||(this.params.liveOffset.pause(),this.params.videoState.setState("paused"))})}_handleManifestUpdate(e){let{playerCallback:t,videoElement:i}=this.params,a=s=>{let n=[];return s?.length?(s.forEach((o,u)=>{o.video&&i.canPlayType(o.codecs).replace(/no/,"")&&window.MediaSource?.isTypeSupported?.(o.codecs)&&(o.index=u,n.push(o))}),n.sort(function(o,u){return o.video&&u.video?u.video.height-o.video.height:u.bitrate-o.bitrate}),n):(t({name:"error",type:"empty_manifest"}),[])};this.manifest=a(e),t({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))},vR))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var Jb=D(ar(),1);import{debounce as TR,filter as Kb,fromEvent as IR,interval as ER,isHigher as xR,isInvariantQuality as PR,isLower as kR,merge as wR,Subject as Xb,Subscription as AR}from"@vkontakte/videoplayer-shared";var Ou=class{constructor(){this.onDroopedVideoFramesLimit$=new Xb;this.subscription=new AR;this.playing=!1;this.tracks=[];this.forceChecker$=new Xb;this.isForceCheckCounter=0;this.prevTotalVideoFrames=0;this.prevDroppedVideoFrames=0;this.limitCounts={};this.handleChangeVideoQuality=()=>{let e=this.tracks.find(({size:t})=>t?.height===this.video.videoHeight&&t?.width===this.video.videoWidth);e&&!PR(e.quality)&&this.onChangeQuality(e.quality)};this.checkDroppedFrames=()=>{let{totalVideoFrames:e,droppedVideoFrames:t}=this.video.getVideoPlaybackQuality(),i=e-this.prevTotalVideoFrames,a=t-this.prevDroppedVideoFrames,s=1-(i-a)/i;!isNaN(s)&&s>=this.droppedFramesChecker.percentLimit&&xR(this.currentQuality,this.droppedFramesChecker.minQualityBanLimit)&&(this.limitCounts[this.currentQuality]=(this.limitCounts[this.currentQuality]??0)+1,this.maxQualityLimit=this.getMaxQualityLimit(this.currentQuality),this.currentTimer&&window.clearTimeout(this.currentTimer),this.currentTimer=window.setTimeout(()=>this.maxQualityLimit=this.getMaxQualityLimit(),this.droppedFramesChecker.qualityUpWaitingTime),this.onDroopedVideoFramesLimitTrigger()),this.savePrevFrameCounts(e,t)}}connect(e){this.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(IR(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=ER(this.droppedFramesChecker.checkTime).pipe(Kb(()=>this.playing),Kb(()=>{let a=!!this.isForceCheckCounter;return a&&(this.isForceCheckCounter-=1),!a})),t=this.forceChecker$.pipe(TR(this.droppedFramesChecker.checkTime)),i=wR(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.onDroopedVideoFramesLimit$.next()}getMaxQualityLimit(e){let t=(0,Jb.default)(this.limitCounts).filter(([,i])=>i>=this.droppedFramesChecker.countLimit).sort(([i],[a])=>kR(i,a)?-1:1)?.[0]?.[0];return e??t}get isEnabled(){return this.droppedFramesChecker.enabled&&this.isDroppedFramesCheckerSupport}get isDroppedFramesCheckerSupport(){return!!this.video&&typeof this.video.getVideoPlaybackQuality=="function"}savePrevFrameCounts(e,t){this.prevTotalVideoFrames=e,this.prevDroppedVideoFrames=t}},Vs=Ou;import{map as RR,Observable as LR}from"@vkontakte/videoplayer-shared";import{fromEvent as MR}from"@vkontakte/videoplayer-shared";var Ar=()=>!!window.documentPictureInPicture?.window||!!document.pictureInPictureElement;var $R=(r,e)=>new LR(t=>{if(!window.IntersectionObserver)return;let i={root:null},a=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||Ar()))},{...i,...e});a.observe(r);let s=MR(document,"visibilitychange").pipe(RR(n=>!document.hidden||Ar())).subscribe(n=>t.next(n));return()=>{a.unobserve(r),s.unsubscribe()}}),Ve=$R;var qR=["paused","playing","ready"],UR=["paused","playing","ready"],Rr=class{constructor(e){this.subscription=new NR;this.videoState=new A("stopped");this.representations$=new Nu([]);this.droppedFramesManager=new Vs;this.maxSeekBackTime$=new Nu(1/0);this.zeroTime$=new Nu(void 0);this.liveOffset=new Wt;this._dashCb=e=>{switch(e.name){case"buffering":{let t=e.isBuffering;this.params.output.isBuffering$.next(t);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,category:tv.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{let t=e.manifest,i=[];for(let a of t){let s=a.name??a.index.toString(10),n=It(a.name)??FR(a.video),o=a.bitrate/1e3,u={...a.video};if(!n)continue;let l={id:s,quality:n,bitrate:o,size:u};i.push({track:l,representation:a})}this.representations$.next(i),this.params.output.availableVideoTracks$.next(i.map(({track:a})=>a)),this.videoState.getTransition()?.to==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let t=e.quality,i=this.representations$.getValue().find(({representation:a})=>a===t)?.track;this.params.output.hostname$.next(new URL(t.headerUrl,this.params.source.url).hostname),_u(i)&&this.params.output.currentVideoTrack$.next(i);break}case"bandwidth":{let{size:t,duration:i}=e;this.params.dependencies.throughputEstimator.addRawSpeed(t,i);break}case"index":{this.maxSeekBackTime$.next(e.shiftDuration||0),this.zeroTime$.next(e.zeroTime);break}}};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(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,Fu.default)(UR,e)&&(n||o)){this.prepare();return}if(a?.to!=="paused"&&s.state==="requested"&&(0,Fu.default)(qR,e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(ue(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=a?.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(ue(this.params.source.url,u))}return;default:return Zb(e)}};this.textTracksManager=new Ce(e.source.url),this.params=e;let t=a=>{e.output.error$.next({id:"DashLiveProvider",category:tv.WTF,message:"DashLiveProvider internal logic error",thrown:a})};this.video=fe(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(re(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=ge(this.video);this.subscription.add(()=>i.destroy()),this.subscription.add(this.representations$.pipe(rv(a=>a.map(({track:s})=>s)),iv(a=>!!a.length),_R()).subscribe(a=>this.droppedFramesManager.connect({video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:a}))),this.subscription.add(i.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready")},t)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused")},t)).add(i.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.videoState.setState("playing")},t)).add(i.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(VR(),rv(a=>-a/1e3)).subscribe(this.params.output.duration$)).add(DR({zeroTime:this.zeroTime$.pipe(iv(_u)),position:i.timeUpdate$}).subscribe(({zeroTime:a,position:s})=>this.params.output.liveTime$.next(a+s*1e3),t)).add(tt(this.video,this.params.desiredState.isLooped,t)).add(ve(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(De(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(Ve(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:a,min:s}})=>{this.dash.setAutoQualityLimits({max:a&&av(a),min:s&&av(s)}),this.params.output.autoVideoTrackLimits$.next({max:a,min:s})})).add(this.videoState.stateChangeEnded$.subscribe(a=>{switch(a.to){case"stopped":this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState("stopped");break;case"manifest_ready":case"ready":this.params.desiredState.playbackState.getTransition()?.to==="ready"&&this.params.desiredState.playbackState.setState("ready");break;case"paused":this.params.desiredState.playbackState.setState("paused");break;case"playing":this.params.desiredState.playbackState.setState("playing");break;default:return Zb(a.to)}},t)).add(BR(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,OR(["init"])).pipe(CR(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),be(this.video)}createLiveDashPlayer(){let e=new wr({videoElement:this.video,videoState:this.videoState,liveOffset:this.liveOffset,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode,manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},playerCallback:this._dashCb});return e.pause(),e}prepare(){let e=this.representations$.getValue(),t=this.params.desiredState.videoTrack.getTransition()?.to??this.params.desiredState.videoTrack.getState(),i=this.params.desiredState.autoVideoTrackSwitching.getTransition()?.to??this.params.desiredState.autoVideoTrackSwitching.getState(),a=!i&&_u(t)?t:Pt(e.map(({track:l})=>l),{container:this.video.getBoundingClientRect(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit}),s=a?.id,n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.videoTrack.getState()?.id,u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(a&&(n||s!==o)&&this.setVideoTrack(a),u&&this.setAutoQuality(i),n||u||s!==o){let l=e.find(({track:d})=>d.id===s)?.representation;ev(l,"Representations missing"),this.dash.startPlay(l,i)}}setVideoTrack(e){let t=this.representations$.getValue().find(({track:i})=>i.id===e.id)?.representation;ev(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.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),a=t==="paused"&&i==="paused",s=-e,n=s<=this.maxSeekBackTime$.getValue()?s:0;this.params.output.position$.next(e/1e3),this.dash.reinit(ue(this.params.source.url,n)),a&&this.dash.pause(),this.liveOffset.resetTo(n,a)}};var sv=Rr;var Ge=(r,e)=>{let t=0;for(let i=0;i<r.length;i++){let a=r.start(i)*1e3,s=r.end(i)*1e3;a<=e&&e<=s&&(t=s)}return Math.max(t-e,0)};import{assertNever as k$,assertNonNullable as w$,debounce as A$,ErrorCategory as Pg,filter as Al,filterChanged as ma,fromEvent as R$,isNonNullable as kg,map as Rl,merge as nn,observableFrom as Ll,once as wg,Subscription as L$}from"@vkontakte/videoplayer-shared";var Bs=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 a=0,s=i.length;a<s;a++)if(i[a].callback===t){i.splice(a,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;let i=this.listeners[e.type].slice();for(let a=0,s=i.length;a<s;a++){let n=i[a];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}},$i=class extends Bs{constructor(){super(),this.listeners||Bs.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)}},Lr=class{constructor(){Object.defineProperty(this,"signal",{value:new $i,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch{typeof document<"u"?document.createEvent?(t=document.createEvent("Event"),t.initEvent("abort",!1,!1)):(t=document.createEventObject(),t.type="abort"):t={type:"abort",bubbles:!1,cancelable:!1}}let i=e;if(i===void 0)if(typeof document>"u")i=new Error("This operation was aborted"),i.name="AbortError";else try{i=new DOMException("signal is aborted without reason")}catch{i=new Error("This operation was aborted"),i.name="AbortError"}this.signal.reason=i,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol<"u"&&Symbol.toStringTag&&(Lr.prototype[Symbol.toStringTag]="AbortController",$i.prototype[Symbol.toStringTag]="AbortSignal");function Os(r){return r.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof r.Request=="function"&&!r.Request.prototype.hasOwnProperty("signal")||!r.AbortController}function qu(r){typeof r=="function"&&(r={fetch:r});let{fetch:e,Request:t=e.Request,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:a=!1}=r;if(!Os({fetch:e,Request:t,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:a}))return{fetch:e,Request:s};let s=t;(s&&!s.prototype.hasOwnProperty("signal")||a)&&(s=function(l,d){let c;d&&d.signal&&(c=d.signal,delete d.signal);let p=new t(l,d);return c&&Object.defineProperty(p,"signal",{writable:!1,enumerable:!1,configurable:!0,value:c}),p},s.prototype=t.prototype);let n=e;return{fetch:(u,l)=>{let d=s&&s.prototype.isPrototypeOf(u)?u.signal:l?l.signal:void 0;if(d){let c;try{c=new DOMException("Aborted","AbortError")}catch{c=new Error("Aborted"),c.name="AbortError"}if(d.aborted)return Promise.reject(c);let p=new Promise((h,f)=>{d.addEventListener("abort",()=>f(c),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([p,n(u,l)])}return n(u,l)},Request:s}}var HR=()=>"fetch"in window,Mr=HR()&&Os({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),nv=Mr?qu({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,rt=Mr?nv.fetch:window.fetch,CN=Mr?nv.Request:window.Request,le=Mr?Lr:window.AbortController,VN=Mr?$i:window.AbortSignal;var xl=D(Hu(),1);var Qv=D(Gv(),1);import{ErrorCategory as Dr}from"@vkontakte/videoplayer-shared";var Wv=r=>{if(!r)return{id:"EmptyResponse",category:Dr.PARSER,message:"Empty response"};if(r.length<=2&&r.match(/^\d+$/))return{id:`UVError#${r}`,category:Dr.NETWORK,message:`UV Error ${r}`};let e=(0,Qv.default)(r).substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:Dr.NETWORK,message:"Received unexpected HTML, possibly a ISP block"};if(e.startsWith("<?xml"))return new DOMParser().parseFromString(r,"text/xml").querySelector("parsererror")?{id:"InvalidXML",category:Dr.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:Dr.PARSER,message:"Response is valid XML, but parser failed"}};var kt=(r,e,t=0)=>{for(let i=0;i<r.length;i++)if(r.start(i)*1e3-t<=e&&r.end(i)*1e3+t>e)return!0;return!1};import{abortable as yl,assertNonNullable as Oi,combine as _i,ErrorCategory as at,filter as Xs,filterChanged as ha,fromEvent as Ae,interval as Js,isNonNullable as Ni,isNullable as gg,map as Fi,merge as ti,now as Tl,Subject as Zs,Subscription as Il,tap as El,throttle as yg,ValueSubject as W}from"@vkontakte/videoplayer-shared";var qs=D(et(),1),Bi=D(Et(),1),Us=D(Hu(),1);var AL=(r,e={})=>{let i=e.timeout||1,a=performance.now();return window.setTimeout(()=>{r({get didTimeout(){return e.timeout?!1:performance.now()-a-1>i},timeRemaining(){return Math.max(0,1+(performance.now()-a))}})},1)},RL=r=>window.clearTimeout(r),Yv=r=>typeof r=="function"&&r?.toString().endsWith("{ [native code] }"),zv=!Yv(window.requestIdleCallback)||!Yv(window.cancelIdleCallback),Yu=zv?AL:window.requestIdleCallback,Cr=zv?RL:window.cancelIdleCallback;var ng=D(Ss(),1);import{assertNever as LL,ErrorCategory as Kv,Subject as Xv}from"@vkontakte/videoplayer-shared";var ML=18,Jv=!1;try{Jv=C.browser.isSafari&&!!C.browser.safariVersion&&C.browser.safariVersion<=ML}catch(r){console.error(r)}var zu=class{constructor(e){this.bufferFull$=new Xv;this.error$=new Xv;this.queue=[];this.currentTask=null;this.destroyed=!1;this.abortRequested=!1;this.completeTask=()=>{try{if(this.currentTask){let e=this.currentTask.signal?.aborted;this.currentTask.callback(!e),this.currentTask=null}this.queue.length&&this.pull()}catch(e){this.error$.next({id:"BufferTaskQueueUnknown",category:Kv.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:e})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(i=>{let a={operation:"append",data:e,signal:t,callback:i};this.queue.push(a),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(a=>{let s={operation:"remove",from:e,to:t,signal:i,callback:a};this.queue.unshift(s),this.pull()})}async abort(e){return new Promise(t=>{let i,a=s=>{this.abortRequested=!1,t(s)};Jv&&e?i={operation:"safariAbort",init:e,callback:a}:i={operation:"abort",callback:a};for(let{callback:s}of this.queue)s(!1);this.abortRequested=!0,i&&(this.queue=[i]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){if((this.buffer.updating||this.currentTask||this.destroyed)&&!this.abortRequested)return;let e=this.queue.shift();if(!e)return;if(e.signal?.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(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:Kv.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:LL(t)}}},Zv=zu;var Ku=r=>{let e=0;for(let t=0;t<r.length;t++)e+=r.end(t)-r.start(t);return e*1e3};import{abortable as At,assertNonNullable as Te,ErrorCategory as Xt,fromEvent as sg,getExponentialDelay as hl,isNonNullable as Vi,isNullable as ce,now as Fs,once as XM,Subject as JM,Subscription as ZM,ValueSubject as Jt}from"@vkontakte/videoplayer-shared";var B=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 a=this.size32?this.size32-8:void 0,s=e.byteOffset+this.cursor;this.size64=0,this.usertype=0,this.content=new DataView(e.buffer,s,a)}get id(){return this.type}get size(){return this.size32}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t="ascii"){let a=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,a}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 Di=class extends B{};var Vr=class extends B{constructor(t,i){super(t,i);this.ondemandPrefix="ondemandlivejson";this.ondemandDataReceivedKey="t-in";this.ondemandDataPreparedKey="t-out";let a=this.content.byteOffset,s=a+this.content.byteLength,n=new TextDecoder("ascii").decode(this.content.buffer.slice(a,s)).split(this.ondemandPrefix)[1],o=JSON.parse(n);this.serverDataReceivedTimestamp=o[this.ondemandDataReceivedKey],this.serverDataPreparedTime=o[this.ondemandDataPreparedKey]}};var Br=class extends B{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 a=this.readString(4);this.compatibleBrands.push(a),i-=4}}};var Or=class extends B{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var G=class extends B{constructor(e,t){super(e,t);let i=this.readUint32();this.version=i>>>24,this.flags=i&16777215}};var _r=class extends G{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 Nr=class extends B{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Fr=class extends B{constructor(e,t){super(e,t),this.data=this.content}};var Yt=class extends G{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 a=this.readUint32(),s=a>>>31,n=a<<1>>>1,o=this.readUint32();a=this.readUint32();let u=a>>>28,l=a<<3>>>3;this.segments.push({referenceType:s,referencedSize:n,subsegmentDuration:o,SAPType:u,SAPDeltaTime:l})}}};var qr=class extends B{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ur=class extends B{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Hr=class extends G{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 jr=class extends G{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var Gr=class extends G{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var Qr=class extends B{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Wr=class extends G{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 Yr=class extends B{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var zr=class extends B{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Kr=class extends G{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var Xr=class extends B{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Jr=class extends G{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 Zr=class extends G{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 ea=class extends G{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 a=0;a<this.sampleCount;a++)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 ta=class extends B{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ia=class extends G{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 ra=class extends B{constructor(e,t){super(e,t),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+78,this.content.byteLength-78))}};var DL={ftyp:Br,moov:Or,mvhd:_r,moof:Nr,mdat:Fr,sidx:Yt,trak:qr,mdia:Qr,mfhd:Kr,tkhd:Wr,traf:Xr,tfhd:Jr,tfdt:Zr,trun:ea,minf:Yr,sv3d:Ur,st3d:Hr,prhd:jr,proj:zr,equi:Gr,uuid:Vr,stbl:ta,stsd:ia,avc1:ra,unknown:Di},pt=class r{constructor(e={}){this.options={offset:0,...e}}parse(e){let t=[],i=this.options.offset;for(;i<e.byteLength;)try{let s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+i+4,4)),n=this.createBox(s,new DataView(e.buffer,e.byteOffset+i));if(!n.size)break;t.push(n),i+=n.size}catch{break}return t}createBox(e,t){let i=DL[e];return i?new i(t,new r):new Di(t,new r)}};var wt=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{this.index[t.type]??=[],this.index[t.type].push(t),t.children.length>0&&this.indexBoxLevel(t.children)})}find(e){return this.index[e]&&this.index[e][0]?this.index[e][0]:null}findAll(e){return this.index[e]||[]}};var VL=new TextDecoder("ascii"),BL=r=>VL.decode(new DataView(r.buffer,r.byteOffset+4,4))==="ftyp",OL=r=>{let e=new Yt(r,new pt),t=e.earliestPresentationTime/e.timescale*1e3,i=r.byteOffset+r.byteLength+e.firstOffset;return e.segments.map(s=>{if(s.referenceType!==0)throw new Error("Unsupported multilevel sidx");let n=s.subsegmentDuration/e.timescale*1e3,o={status:"none",time:{from:t,to:t+n},byte:{from:i,to:i+s.referencedSize-1}};return t+=n,i+=s.referencedSize,o})},_L=(r,e)=>{let i=new pt().parse(r),a=new wt(i),s=a.findAll("moof"),n=e?a.findAll("uuid"):a.findAll("mdat");if(!(n.length&&s.length))return null;let o=s[0],u=n[n.length-1],l=o.source.byteOffset,c=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(r.buffer,l,c)},NL=r=>{let t=new pt().parse(r),i=new wt(t),a={},s=i.findAll("uuid");return s.length?s[s.length-1]:a},FL=r=>{let t=new pt().parse(r);return new wt(t).find("sidx")?.timescale},qL=(r,e)=>{let i=new pt().parse(r),s=new wt(i).findAll("traf"),n=s[s.length-1].children.find(c=>c.type==="tfhd"),o=s[s.length-1].children.find(c=>c.type==="tfdt"),u=s[s.length-1].children.find(c=>c.type==="trun"),l=0;return u.sampleDuration.length?l=u.sampleDuration.reduce((c,p)=>c+p,0):l=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+l)/e*1e3},UL=r=>{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 pt().parse(r),a=new wt(i);if(a.find("sv3d")){e.is3dVideo=!0;let n=a.find("st3d");n&&(e.stereoMode=n.stereoMode);let o=a.find("prhd");o&&(e.projectionData.pose.yaw=o.poseYawDegrees,e.projectionData.pose.pitch=o.posePitchDegrees,e.projectionData.pose.roll=o.poseRollDegrees);let u=a.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},eS={validateData:BL,parseInit:UL,getIndexRange:()=>{},parseSegments:OL,parseFeedableSegmentChunk:_L,getChunkEndTime:qL,getServerLatencyTimestamps:NL,getTimescaleFromIndex:FL};var sa=D(et(),1);import{assertNonNullable as Ju,isNonNullable as aS,isNullable as jL}from"@vkontakte/videoplayer-shared";import{assertNever as HL}from"@vkontakte/videoplayer-shared";var tS={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"}},iS=r=>{let e=r.getUint8(0),t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);let i=aa(r,t),a=i in tS,s=a?tS[i].type:"binary",n=r.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(r.buffer,r.byteOffset+t+1,o-1),l=n&255>>o,d=aa(u),c=l*2**((o-1)*8)+d,p=t+o,h;return p+c>r.byteLength?h=new DataView(r.buffer,r.byteOffset+p):h=new DataView(r.buffer,r.byteOffset+p,c),{tag:a?i:"0x"+i.toString(16).toUpperCase(),type:s,tagHeaderSize:p,tagSize:p+c,value:h,valueSize:c}},aa=(r,e=r.byteLength)=>{switch(e){case 1:return r.getUint8(0);case 2:return r.getUint16(0);case 3:return r.getUint8(0)*2**16+r.getUint16(1);case 4:return r.getUint32(0);case 5:return r.getUint8(0)*2**32+r.getUint32(1);case 6:return r.getUint16(0)*2**32+r.getUint32(2);case 7:{let t=r.getUint8(0)*281474976710656+r.getUint16(1)*4294967296+r.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},Qe=(r,e)=>{switch(e){case"int":return r.getInt8(0);case"uint":return aa(r);case"float":return r.byteLength===4?r.getFloat32(0):r.getFloat64(0);case"string":return new TextDecoder("ascii").decode(r);case"utf8":return new TextDecoder("utf-8").decode(r);case"date":return new Date(Date.UTC(2001,0)+r.getInt8(0)).getTime();case"master":return r;case"binary":return r;default:HL(e)}},zt=(r,e)=>{let t=0;for(;t<r.byteLength;){let i=new DataView(r.buffer,r.byteOffset+t),a=iS(i);if(!e(a))return;a.type==="master"&&zt(a.value,e),t=a.value.byteOffset-r.byteOffset+a.valueSize}},rS=r=>{if(r.getUint32(0)!==440786851)return!1;let e,t,i,a=iS(r);return zt(a.value,({tag:s,type:n,value:o})=>(s===17143?e=Qe(o,n):s===17026?t=Qe(o,n):s===17029&&(i=Qe(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)};var sS=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],GL=[231,22612,22743,167,171,163,160,175],QL=r=>{let e,t,i,a,s=!1,n=!1,o=!1,u,l,d=!1,c=0;return zt(r,({tag:p,type:h,value:f,valueSize:b})=>{if(p===21419){let S=Qe(f,h);l=aa(S)}else p!==21420&&(l=void 0);return p===408125543?(e=f.byteOffset,t=f.byteOffset+b):p===357149030?s=!0:p===290298740?n=!0:p===2807729?i=Qe(f,h):p===17545?a=Qe(f,h):p===21420&&l===475249515?u=Qe(f,h):p===374648427?zt(f,({tag:S,type:v,value:P})=>S===30321?(d=Qe(P,v)===1,!1):!0):s&&n&&(0,sa.default)(sS,p)&&(o=!0),!o}),Ju(e,"Failed to parse webm Segment start"),Ju(t,"Failed to parse webm Segment end"),Ju(a,"Failed to parse webm Segment duration"),i=i??1e6,{segmentStart:Math.round(e/1e9*i*1e3),segmentEnd:Math.round(t/1e9*i*1e3),timeScale:i,segmentDuration:Math.round(a/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}}}},WL=r=>{if(jL(r.cuesSeekPosition))return;let e=r.segmentStart+r.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},YL=(r,e)=>{let t=!1,i=!1,a=o=>aS(o.time)&&aS(o.position),s=[],n;return zt(r,({tag:o,type:u,value:l})=>{switch(o){case 475249515:t=!0;break;case 187:n&&a(n)&&s.push(n),n={};break;case 179:n&&(n.time=Qe(l,u));break;case 183:break;case 241:n&&(n.position=Qe(l,u));break;default:t&&(0,sa.default)(sS,o)&&(i=!0)}return!(t&&i)}),n&&a(n)&&s.push(n),s.map((o,u)=>{let{time:l,position:d}=o,c=s[u+1];return{status:"none",time:{from:l,to:c?c.time:e.segmentDuration},byte:{from:e.segmentStart+d,to:c?e.segmentStart+c.position-1:e.segmentEnd-1}}})},zL=r=>{let e=0,t=!1;try{zt(r,i=>i.tag===524531317?i.tagSize<=r.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):(0,sa.default)(GL,i.tag)?(e+i.tagSize<=r.byteLength&&(e+=i.tagSize,t||=(0,sa.default)([163,160,175],i.tag)),!0):!1)}catch{}return e>0&&e<=r.byteLength&&t?new DataView(r.buffer,r.byteOffset,e):null},nS={validateData:rS,parseInit:QL,getIndexRange:WL,parseSegments:YL,parseFeedableSegmentChunk:zL};var na=r=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(r);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return nS;case"mp4":return eS}}throw new ReferenceError(`Unsupported mime type ${r}`)};var cl=D(kS(),1),eg=D(ar(),1),tg=D(US(),1),ig=D(Et(),1),dl=D(Ri(),1);var HS=D(et(),1),al=r=>{let e=r.split("."),[t,...i]=e;if(!t)return!1;switch(t){case"av01":{let[a,s,n]=i;return!!(n&&parseInt(n,10)>8)}case"vp09":{let[a,s,n]=i;return!!(a&&parseInt(a,10)>=2&&n&&parseInt(n,10)>8)}case"avc1":{let a=i[0];if(!a||a.length!==6)return!1;let[s,n]=a.toUpperCase(),o=s+n;return(0,HS.default)(["6E","7A","F4"],o)}}return!1};import{isNonNullable as WM,isNullable as JS}from"@vkontakte/videoplayer-shared";var jS=r=>{if(r.includes("/")){let e=r.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(r)};var GS=r=>{try{let e=jM(),t=r.match(e),{groups:i}=t??{};if(i){let a={};if(i.extensions){let o=i.extensions.toLowerCase().match(/(?:[0-9a-wy-z](?:-[a-z0-9]{2,8})+)/g);Array.from(o||[]).forEach(u=>{a[u[0]]=u.slice(2)})}let s=i.variants?.split(/-/).filter(o=>o!==""),n={extlang:i.extlang,langtag:i.langtag,language:i.language,privateuse:i.privateuse||i.privateuse2,region:i.region,script:i.script,extensions:a,variants:s};return Object.keys(n).forEach(o=>{let u=n[o];(typeof u>"u"||u==="")&&delete n[o]}),n}return null}catch{return null}};function jM(){let r="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",d=`^(?:(?<langtag>${`
64
8
  (?<language>${`(?:[a-z]{2,3}(?:-${r})?|[a-z]{4}|[a-z]{5,8})`})
65
9
  (-(?<script>[a-z]{4}))?
66
10
  (-(?<region>(?:[a-z]{2}|[0-9]{3})))?
67
11
  (?<variants>(?:-(?:[a-z0-9]{5,8}|[0-9][a-z0-9]{3}))*)
68
12
  (?<extensions>(?:-[0-9a-wy-z](?:-[a-z0-9]{2,8})+)*)
69
13
  (?:-(?<privateuse>(?:${e})))?
70
- `})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(c,"i")}var pl=R(Lt(),1);import{videoSizeToQuality as oM}from"@vkontakte/videoplayer-shared";var rS=({id:r,width:e,height:t,bitrate:i,fps:a,quality:s,streamId:n})=>{let o=(s?At(s):void 0)??oM({width:e,height:t});return o&&{id:r,quality:o,bitrate:i,size:{width:e,height:t},fps:a,streamId:n}},aS=({id:r,bitrate:e})=>({id:r,bitrate:e}),sS=({language:r,label:e},{id:t,url:i,isAuto:a})=>({id:t,url:i,isAuto:a,type:"internal",language:r,label:e}),nS=({language:r,label:e,id:t,url:i,isAuto:a})=>({id:t,url:i,isAuto:a,type:"internal",language:r,label:e}),hl=({id:r,language:e,label:t,codecs:i,isDefault:a})=>({id:r,language:e,label:t,codec:(0,pl.default)(i.split("."),0),isDefault:a}),ml=({id:r,language:e,label:t,hdr:i,codecs:a})=>({id:r,language:e,hdr:i,label:t,codec:(0,pl.default)(a.split("."),0)}),fl=r=>"url"in r,ve=r=>r.type==="template",ha=r=>r instanceof DOMException&&(r.name==="AbortError"||r.code===20);var uS=r=>{if(!r?.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(r),a=i?.[1]==="-"?-1:1,s={days:e(i?.[5],a),hours:e(i?.[6],a),minutes:e(i?.[7],a),seconds:e(i?.[8],a)};return s.days*24*60*60*1e3+s.hours*60*60*1e3+s.minutes*60*1e3+s.seconds*1e3},mt=(r,e)=>{let t=r;t=(0,bl.default)(t,"$$","$");let i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[a,s]of(0,lS.default)(i)){let n=new RegExp(`\\$${a}(?:%0(\\d+)d)?\\$`,"g");t=(0,bl.default)(t,n,(o,u)=>oS(s)?o:oS(u)?s:(0,cS.default)(s,parseInt(u,10),"0"))}return t},pS=(r,e)=>{let i=new DOMParser().parseFromString(r,"application/xml"),a={video:[],audio:[],text:[]},s=i.children[0],n=Array.from(s.querySelectorAll("MPD > BaseURL").values()).map(N=>N.textContent?.trim()??""),o=(0,dS.default)(n,0)??"",u=s.getAttribute("type")==="dynamic",l=s.getAttribute("availabilityStartTime"),c=s.getAttribute("publishTime"),d=s.getElementsByTagName("vk:Attrs")[0],p=d?.getElementsByTagName("vk:XLatestSegmentPublishTime")[0].textContent,h=d?.getElementsByTagName("vk:XStreamIsLive")[0].textContent,f=d?.getElementsByTagName("vk:XStreamIsUnpublished")[0].textContent,b=d?.getElementsByTagName("vk:XPlaybackDuration")[0].textContent,g;u&&(g={availabilityStartTime:l?new Date(l).getTime():0,publishTime:c?new Date(c).getTime():0,latestSegmentPublishTime:p?new Date(p).getTime():0,streamIsAlive:h==="yes",streamIsUnpublished:f==="yes"});let v,x=s.getAttribute("mediaPresentationDuration"),T=[...s.getElementsByTagName("Period")],P=T.reduce((N,S)=>({...N,[S.id]:S.children}),{}),I=T.reduce((N,S)=>({...N,[S.id]:S.getAttribute("duration")}),{});x?v=uS(x):(0,gl.default)(I).filter(N=>N).length&&!u?v=(0,gl.default)(I).reduce((N,S)=>N+(uS(S)??0),0):b&&(v=parseInt(b,10));let B=0,O=s.getAttribute("profiles")?.split(",")??[];for(let N of T.map(S=>S.id))for(let S of P[N]){let M=S.getAttribute("id")??"id"+(B++).toString(10),w=S.getAttribute("mimeType")??"",W=S.getAttribute("codecs")??"",A=S.getAttribute("contentType")??w?.split("/")[0],ie=S.getAttribute("profiles")?.split(",")??[],k=iS(S.getAttribute("lang")??"")??{},H=S.querySelector("Label")?.textContent?.trim()??void 0,Y=S.querySelectorAll("Representation"),J=S.querySelector("SegmentTemplate"),re=S.querySelector("Role")?.getAttribute("value")??void 0,Se=A,ye={id:M,language:k.language,isDefault:re==="main",label:H,codecs:W,hdr:Se==="video"&&cl(W),mime:w,representations:[]};for(let j of Y){let C=j.getAttribute("lang")??void 0,Te=H??S.getAttribute("label")??j.getAttribute("label")??void 0,me=j.querySelector("BaseURL")?.textContent?.trim()??"",ae=new URL(me||o,e).toString(),Oe=j.getAttribute("mimeType")??w,vt=j.getAttribute("codecs")??W??"",Xe;if(A==="text"){let Re=j.getAttribute("id")||"",St=k.privateuse?.includes("x-auto")||Re.includes("_auto"),Je=j.querySelector("SegmentTemplate");if(Je){let zi={representationId:j.getAttribute("id")??void 0,bandwidth:j.getAttribute("bandwidth")??void 0},Va=parseInt(j.getAttribute("bandwidth")??"",10)/1e3,Ba=parseInt(Je.getAttribute("startNumber")??"",10)??1,oi=parseInt(Je.getAttribute("timescale")??"",10),wn=Je.querySelectorAll("SegmentTimeline S")??[],ui=Je.getAttribute("media");if(!ui)continue;let Oa=[],_a=0,Na="",li=0,Ki=Ba,fe=0;for(let Ue of wn){let Nt=parseInt(Ue.getAttribute("d")??"",10),_e=parseInt(Ue.getAttribute("r")??"",10)||0,yt=parseInt(Ue.getAttribute("t")??"",10);fe=Number.isFinite(yt)?yt:fe;let Ft=Nt/oi*1e3,ci=fe/oi*1e3;for(let Ze=0;Ze<_e+1;Ze++){let Tt=mt(ui,{...zi,segmentNumber:Ki.toString(10),segmentTime:(fe+Ze*Nt).toString(10)}),di=(ci??0)+Ze*Ft,Ji=di+Ft;Ki++,Oa.push({time:{from:di,to:Ji},url:Tt})}fe+=(_e+1)*Nt,_a+=(_e+1)*Ft}li=fe/oi*1e3,Na=mt(ui,{...zi,segmentNumber:Ki.toString(10),segmentTime:fe.toString(10)});let Xi={time:{from:li,to:1/0},url:Na},ot={type:"template",baseUrl:ae,segmentTemplateUrl:ui,initUrl:"",totalSegmentsDurationMs:_a,segments:Oa,nextSegmentBeyondManifest:Xi,timescale:oi};Xe={id:Re,kind:"text",segmentReference:ot,profiles:[],duration:v,bitrate:Va,mime:"",codecs:"",width:0,height:0,isAuto:St}}else Xe={id:Re,isAuto:St,kind:"text",url:ae}}else{let Re=j.getAttribute("contentType")??Oe?.split("/")[0]??A,St=S.getAttribute("profiles")?.split(",")??[],Je=parseInt(j.getAttribute("width")??"",10),zi=parseInt(j.getAttribute("height")??"",10),Va=parseInt(j.getAttribute("bandwidth")??"",10)/1e3,Ba=j.getAttribute("frameRate")??"",oi=j.getAttribute("quality")??void 0,wn=Ba?tS(Ba):void 0,ui=j.getAttribute("id")??"id"+(B++).toString(10),Oa=Re==="video"?`${zi}p`:Re==="audio"?`${Va}Kbps`:vt,_a=`${ui}@${Oa}`,Na=[...O,...ie,...St],li,Ki=j.querySelector("SegmentBase"),fe=j.querySelector("SegmentTemplate")??J;if(Ki){let ot=j.querySelector("SegmentBase Initialization")?.getAttribute("range")??"",[Ue,Nt]=ot.split("-").map(Tt=>parseInt(Tt,10)),_e={from:Ue,to:Nt},yt=j.querySelector("SegmentBase")?.getAttribute("indexRange"),[Ft,ci]=yt?yt.split("-").map(Tt=>parseInt(Tt,10)):[],Ze=yt?{from:Ft,to:ci}:void 0;li={type:"byteRange",url:ae,initRange:_e,indexRange:Ze}}else if(fe){let ot={representationId:j.getAttribute("id")??void 0,bandwidth:j.getAttribute("bandwidth")??void 0},Ue=parseInt(fe.getAttribute("timescale")??"",10),Nt=fe.getAttribute("initialization")??"",_e=fe.getAttribute("media"),yt=parseInt(fe.getAttribute("startNumber")??"",10)??1,Ft=mt(Nt,ot);if(!_e)throw new ReferenceError("No media attribute in SegmentTemplate");let ci=fe.querySelectorAll("SegmentTimeline S")??[],Ze=[],Tt=0,di="",Ji=0;if(ci.length){let Fa=yt,He=0;for(let pi of ci){let et=parseInt(pi.getAttribute("d")??"",10),qt=parseInt(pi.getAttribute("r")??"",10)||0,qa=parseInt(pi.getAttribute("t")??"",10);He=Number.isFinite(qa)?qa:He;let An=et/Ue*1e3,Ny=He/Ue*1e3;for(let Ua=0;Ua<qt+1;Ua++){let Fy=mt(_e,{...ot,segmentNumber:Fa.toString(10),segmentTime:(He+Ua*et).toString(10)}),rc=(Ny??0)+Ua*An,qy=rc+An;Fa++,Ze.push({time:{from:rc,to:qy},url:Fy})}He+=(qt+1)*et,Tt+=(qt+1)*An}Ji=He/Ue*1e3,di=mt(_e,{...ot,segmentNumber:Fa.toString(10),segmentTime:He.toString(10)})}else if(uM(v)){let He=parseInt(fe.getAttribute("duration")??"",10)/Ue*1e3,pi=Math.ceil(v/He),et=0;for(let qt=1;qt<pi;qt++){let qa=mt(_e,{...ot,segmentNumber:qt.toString(10),segmentTime:et.toString(10)});Ze.push({time:{from:et,to:et+He},url:qa}),et+=He}Ji=et,di=mt(_e,{...ot,segmentNumber:pi.toString(10),segmentTime:et.toString(10)})}let _y={time:{from:Ji,to:1/0},url:di};li={type:"template",baseUrl:ae,segmentTemplateUrl:_e,initUrl:Ft,totalSegmentsDurationMs:Tt,segments:Ze,nextSegmentBeyondManifest:_y,timescale:Ue}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Re||!Oe)continue;let Xi={video:"video",audio:"audio",text:"text"}[Re];if(!Xi)continue;Se||=Xi,Xe={id:_a,kind:Xi,segmentReference:li,profiles:Na,duration:v,bitrate:Va,mime:Oe,codecs:vt,width:Je,height:zi,fps:wn,quality:oi}}ye.language||=C,ye.label||=Te,ye.mime||=Oe,ye.codecs||=vt,ye.hdr||=Se==="video"&&cl(vt),ye.representations.push(Xe)}if(Se){let j=a[Se].find(C=>C.id===ye.id);if(j&&ye.representations.every(C=>ve(C.segmentReference)))for(let C of j.representations){let me=ye.representations.find(Oe=>Oe.id===C.id)?.segmentReference,ae=C.segmentReference;ae.segments.push(...me.segments),ae.nextSegmentBeyondManifest=me.nextSegmentBeyondManifest}else a[Se].push(ye)}}return{duration:v,streams:a,baseUrls:n,live:g}};var mS=R(Ie(),1);import{isNonNullable as hS}from"@vkontakte/videoplayer-shared";var ee=(r,e)=>hS(r)&&hS(e)&&r.readyState==="open"&&(0,mS.default)([...r.activeSourceBuffers],e);var ma=class{constructor(e,t,i,{fetcher:a,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new ii(0);this.currentLowLatencySegmentLength$=new ii(0);this.currentSegmentLength$=new ii(0);this.onLastSegment$=new ii(!1);this.fullyBuffered$=new ii(!1);this.playingRepresentation$=new ii(void 0);this.playingRepresentationInit$=new ii(void 0);this.error$=new cM;this.gaps=[];this.subscription=new dM;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new pe;this.switchAbortController=new pe;this.destroyAbortController=new pe;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=Dt(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);Le(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new cv(this.sourceBuffer),this.subscription.add(Sl(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:ft.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o??={id:"SegmentEjection",category:ft.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n},this.error$.next(o)})),this.subscription.add(Sl(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:ft.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o||!ee(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,il(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=this.getForwardBufferDuration(o),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,n*2,l<c).catch(d=>{this.handleAsyncError(d,"pruneBuffer")})})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);let i=this.initData.get(t.id),a=this.segments.get(t.id),s=this.parsedInitData.get(t.id);Le(i,"No init buffer for starting representation"),Le(a,"No segments for starting representation"),i instanceof ArrayBuffer&&(this.searchGaps(a,t),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s))}.bind(this));this.switchTo=Dt(this.destroyAbortController.signal,async function*(e,t=!1){if(!ee(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);Le(i,`No such representation ${e}`);let a=this.segments.get(e),s=this.initData.get(e);if(he(s)||he(a)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),a=this.segments.get(e),Le(a,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!ee(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();Fi(n)&&!this.isLive&&(this.bufferLimit=1/0,await this.pruneBuffer(n,1/0,!0)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}this.maintain()}}.bind(this));this.switchToOld=Dt(this.destroyAbortController.signal,async function*(e,t=!1){if(!ee(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);Le(i,`No such representation ${e}`);let a=this.segments.get(e),s=this.initData.get(e);if(he(s)||he(a)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),a=this.segments.get(e),Le(a,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!ee(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();Fi(n)&&(this.isLive||(this.bufferLimit=1/0,await this.pruneBuffer(n,1/0,!0)),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}}.bind(this));this.seekLive=Dt(this.destroyAbortController.signal,async function*(e){let t=(0,Ws.default)(e,u=>u.representations)??[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let u of this.representations.keys()){let l=t.find(p=>p.id===u);l&&this.representations.set(u,l);let c=this.representations.get(u);if(!c||!ve(c.segmentReference))return;let d=this.getActualLiveStartingSegments(c.segmentReference);this.segments.set(c.id,d)}let i=this.switchingToRepresentationId??this.downloadingRepresentationId,a=this.representations.get(i);Le(a);let s=this.segments.get(i);Le(s,"No segments for starting representation");let n=this.initData.get(i);if(Le(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer))return;let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(s,a),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));this.fetcher=a,this.tuning=s,this.compatibilityMode=u,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!l?.live,this.baseUrls=l?.baseUrls??[],this.initData=new Map(i.map(c=>[c.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(c=>[c.id,c])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchToWithPreviousAbort(e,t=!1){!ee(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new pe,Dt(this.switchAbortController.signal,async function*(i,a=!1){this.switchingToRepresentationId=i;let s=this.representations.get(i);Le(s,`No such representation ${i}`);let n=this.segments.get(i),o=this.initData.get(i);if(he(o)||he(n)?yield this.loadInit(s,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(i),Le(n,"No segments for starting representation"),o=this.initData.get(i),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer||!ee(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(o,this.downloadAbortController.signal),a)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=i,yield this.dropBuffer();else{let u=this.getCurrentPosition();Fi(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(){!he(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}async abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);return this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new pe,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(he(e)||he(this.downloadingRepresentationId)||he(this.playingRepresentationId)||he(this.sourceBuffer)||!ee(this.mediaSource,this.sourceBuffer)||Fi(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(Le(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;let a=i.find(c=>e>=c.time.from&&e<c.time.to);Fi(a)&&isFinite(a.time.from)&&isFinite(a.time.to)&&this.currentSegmentLength$.next(a?.time.to-a.time.from);let s=e,n=100;if(this.playingRepresentationId!==this.downloadingRepresentationId){let c=this.getForwardBufferDuration(e),d=a?a.time.to+n:-1/0;a&&a.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&c>=a.time.to-e+n&&(s=d)}if(isFinite(this.bufferLimit)&&il(this.sourceBuffer.buffered)>=this.bufferLimit){let c=this.getForwardBufferDuration(e),d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,c<d).catch(p=>{this.handleAsyncError(p,"pruneBuffer")});return}let u=[];if(!this.activeSegments.size&&(u=this.selectForwardBufferSegments(i,t.segmentReference.type,s),u.length)){let c="auto";if(this.tuning.dash.useFetchPriorityHints&&a)if((0,Gs.default)(u,a))c="high";else{let d=(0,qi.default)(u,0);d&&d.time.from-a.time.to>=this.forwardBufferTarget/2&&(c="low")}this.loadSegments(u,t,c).catch(d=>{this.handleAsyncError(d,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&a&&a.status==="fed"&&!u.length&&this.getForwardBufferDuration(e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let l=(0,qi.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,a=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+a}),i=s.time.to;Fi(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,a=[],s=0,n=t.length-1;do a.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()?[a[0]]:a}getLiveSegmentsToLoadState(e){let t=(0,Ws.default)(e?.streams[this.kind],a=>a.representations).find(a=>a.id===this.downloadingRepresentationId);if(!t)return;let i=this.segments.get(t.id);if(i?.length)return{from:i[0].time.from,to:i[i.length-1].time.to}}updateLive(e){let t=(0,Ws.default)(e?.streams[this.kind],i=>i.representations)??[];if(![...this.segments.values()].every(i=>!i.length))for(let i of t){if(!i||!ve(i.segmentReference))return;let a=i.segmentReference.segments.map(l=>({...l,status:"none",size:void 0})),s=100,n=this.segments.get(i.id)??[],o=(0,qi.default)(n,-1)?.time.to??0,u=a?.findIndex(l=>o>=l.time.from+s&&o<=l.time.to+s);if(u===-1){this.liveUpdateSegmentIndex=0;let l=this.getActualLiveStartingSegments(i.segmentReference);this.segments.set(i.id,l)}else{let l=a.slice(u+1);this.segments.set(i.id,[...n,...l])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;Le(e);let t=this.segments.get(e);if(t?.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}updateLowLatencyLiveIfNeeded(e){let t=0;for(let i of this.representations.values()){let a=i.segmentReference;if(!ve(a))return;let s=this.segments.get(i.id)??[],n=s.find(u=>Math.floor(u.time.from)===Math.floor(e.time.from));if(n&&!isFinite(n.time.to)&&(n.time.to=e.time.to,t=n.time.to-n.time.from),!!!s.find(u=>Math.floor(u.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let u=Math.round(e.time.to*a.timescale/1e3).toString(10),l=mt(a.segmentTemplateUrl,{segmentTime:u});s.push({status:"none",time:{from:e.time.to,to:1/0},url:l})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){let t=this.switchingToRepresentationId??this.downloadingRepresentationId??this.playingRepresentationId;if(!t)return;let i=this.segments.get(t);return i?i.find(s=>s.time.from<=e&&s.time.to>=e)?.time.from??void 0:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),this.sourceBufferTaskQueue?.destroy(),this.gapDetectionIdleCallback&&Fr&&Fr(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&Fr&&Fr(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(e){if(!(e instanceof DOMException&&e.name==="NotFoundError"))throw e}this.sourceBuffer=null,this.downloadAbortController.abort(),this.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,i){return this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){let i=e.findIndex(a=>t>=a.time.from&&t<a.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=i),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,i){let a=e.findIndex(({status:d,time:{from:p,to:h}},f)=>{let b=p<=i&&h>=i,g=p>i||b||f===0&&i===0,v=Math.min(this.forwardBufferTarget,this.bufferLimit),x=this.preloadOnly&&p<=i+v||h<=i+v;return(d==="none"||d==="partially_ejected"&&g&&x&&this.sourceBuffer&&ee(this.mediaSource,this.sourceBuffer)&&!(Mt(this.sourceBuffer.buffered,p)&&Mt(this.sourceBuffer.buffered,h)))&&g&&x});if(a===-1)return[];if(t!=="byteRange")return e.slice(a,a+1);let s=e,n=0,o=0,u=[],l=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,c=this.preloadOnly?this.forwardBufferTarget:0;for(let d=a;d<s.length&&(n<=l||o<=c);d++){let p=s[d];if(n+=p.byte.to+1-p.byte.from,o+=p.time.to+1-p.time.from,p.status==="none"||p.status==="partially_ejected")u.push(p);else break}return u}async loadSegments(e,t,i="auto"){ve(t.segmentReference)?await this.loadTemplateSegment(e[0],t,i):await this.loadByteRangeSegments(e,t,i)}async loadTemplateSegment(e,t,i="auto"){e.status="downloading";let a={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(a);let{range:s,url:n,signal:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await Dt(o,async function*(){let c=yl(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,c))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let c=await this.fetcher.fetch(n,{range:s,signal:o,onProgress:u,priority:i,isLowLatency:this.isActiveLowLatency()});if(this.lastDataObtainedTimestampMs=Qs(),!c)return;let d=new DataView(c),p=pa(t.mime);if(!isFinite(a.segment.time.to)){let b=t.segmentReference.timescale;a.segment.time.to=p.getChunkEndTime(d,b)}u&&a.feedingBytes&&l?await Promise.all(l):await this.sourceBufferTaskQueue.append(d,o);let{serverDataReceivedTimestamp:h,serverDataPreparedTime:f}=p.getServerLatencyTimestamps(d);h&&f&&this.currentLiveSegmentServerLatency$.next(f-h),a.segment.status="downloaded",this.onSegmentFullyAppended(a,t.id),this.failedDownloads=0}catch(c){this.abortActiveSegments([e]),ha(c)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}updateRepresentationsBaseUrlIfNeeded(){if(!this.tuning.dash.enableBaseUrlSupport||!this.baseUrls.length||this.failedDownloads<=this.tuning.dash.maxSegmentRetryCount)return;this.baseUrlsIndex=(this.baseUrlsIndex+1)%this.baseUrls.length;let e=this.baseUrls[this.baseUrlsIndex];for(let t of this.representations.values())ve(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}async loadByteRangeSegments(e,t,i="auto"){if(!e.length)return;for(let u of e)u.status="downloading",this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:a,url:s,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(await Dt(n,async function*(){let u=yl(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),Sl(window,"online").pipe(lM()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(s,{range:a,onProgress:o,signal:n,priority:i}),this.lastDataObtainedTimestampMs=Qs(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),ha(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(ve(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,a={from:(0,qi.default)(e,0).byte.from,to:(0,qi.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:i,range:a,signal:s,onProgress:async(o,u)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=Qs(),await this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:a?a.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:ft.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!ve(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 a=i.toString(),{signal:s}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,c)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=Qs();let d=this.onSomeTemplateDataLoaded({dataView:l,loaded:c,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(d)}catch(d){this.error$.next({id:"SegmentFeeding",category:ft.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}:void 0;return{url:a,signal:s,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,Gs.default)(e,t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:a,signal:s}){if(!this.activeSegments.size||!ee(this.mediaSource,this.sourceBuffer))return;let n=this.representations.get(t);if(n)for(let o of this.activeSegments){let{segment:u}=o;if(o.representationId===t){if(s.aborted){a();continue}if(o.loadedBytes=i,o.loadedBytes>o.feedingBytes){let l=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),c=pa(n.mime).parseFeedableSegmentChunk(l,this.isLive);c?.byteLength&&(u.status="partially_fed",o.feedingBytes+=c.byteLength,await this.sourceBufferTaskQueue.append(c),o.fedBytes+=c.byteLength)}}}}async onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:a,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size||!ee(this.mediaSource,this.sourceBuffer))return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){let{segment:l}=u;if(u.representationId!==t)continue;if(s.aborted){await n();continue}let c=l.byte.from-i,d=l.byte.to-i,p=d-c+1,h=c<a,f=d<=a;if(!h)continue;let b=pa(o.mime);if(l.status==="downloading"&&f){l.status="downloaded";let g=new DataView(e.buffer,e.byteOffset+c,p);await this.sourceBufferTaskQueue.append(g,s)&&!s.aborted?this.onSegmentFullyAppended(u,t):await n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(l.status==="downloading"||l.status==="partially_fed")&&(u.loadedBytes=Math.min(p,a-c),u.loadedBytes>u.feedingBytes)){let g=new DataView(e.buffer,e.byteOffset+c+u.feedingBytes,u.loadedBytes-u.feedingBytes),v=u.loadedBytes===p?g:b.parseFeedableSegmentChunk(g);v?.byteLength&&(l.status="partially_fed",u.feedingBytes+=v.byteLength,await this.sourceBufferTaskQueue.append(v,s)&&!s.aborted?(u.fedBytes+=v.byteLength,u.fedBytes===p&&this.onSegmentFullyAppended(u,t)):await n())}}}onSegmentFullyAppended(e,t){if(!(he(this.sourceBuffer)||!ee(this.mediaSource,this.sourceBuffer))){!this.isLive&&V.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(Mt(this.sourceBuffer.buffered,e.segment.time.from,100)&&Mt(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:ft.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",fl(e.segment)&&(e.segment.size=e.fedBytes);for(let i of this.representations.values())if(i.id!==t)for(let a of this.segments.get(i.id)??[])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[a,s]of this.initData.entries()){let n=s instanceof Promise;t||=n,s===null&&(e=a)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let i=this.representations.get(e);i&&(this.initLoadIdleCallback=el(()=>(0,fS.default)(this.loadInit(i,"low",!1),()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",i=!1){let a=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!i&&this.failedDownloads>0?Dt(this.destroyAbortController.signal,async function*(){let o=yl(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,pa(e.mime),a)).then(async o=>{if(!o)return;let{init:u,dataView:l,segments:c}=o,d=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,d);let p=c;this.isLive&&ve(e.segmentReference)&&(p=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,p),u&&this.parsedInitData.set(e.id,u)}).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:ft.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n}async dropBuffer(){for(let e of this.segments.values())for(let t of e)t.status="none";await this.pruneBuffer(0,1/0,!0)}async pruneBuffer(e,t,i=!1){if(!this.sourceBuffer||!ee(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||he(e))return!1;let a=[],s=0,n=u=>{u.sort((c,d)=>c.from-d.from);let l=[u[0]];for(let c=1;c<u.length;c++){let{from:d,to:p}=u[c],h=l[l.length-1];h.to>=d?h.to=Math.max(h.to,p):l.push(u[c])}return l},o=u=>{if(s>=t)return a;a.push({...u.time}),a=n(a);let l=fl(u)?u.size??0:u.byte.to-u.byte.from;s+=l};for(let u of this.segments.values())for(let l of u){let c=l.time.to<=e-this.tuning.dash.bufferPruningSafeZone,d=l.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(c||d)&&l.status==="fed"&&o(l)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let l=this.sourceBuffer.buffered.start(u)*1e3,c=this.sourceBuffer.buffered.end(u)*1e3,d=0;for(let p of this.segments.values())for(let h of p)(0,Gs.default)(["none","partially_ejected"],h.status)&&Math.round(h.time.from)<=Math.round(l)&&Math.round(h.time.to)>=Math.round(c)&&d++;if(d===this.segments.size){let p={time:{from:l,to:c},url:"",status:"none"};o(p)}}if(a.length&&i){let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let l of this.segments.values())for(let c of l)c.time.from>=e+u&&c.status==="fed"&&o(c)}return a.length?(await Promise.all(a.map(l=>this.sourceBufferTaskQueue.remove(l.from,l.to)))).reduce((l,c)=>l||c,!1):!1}async abortBuffer(){if(!this.sourceBuffer||!ee(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||!ee(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||!ee(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||he(e)?0:Bi(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!(!this.sourceBuffer||!ee(this.mediaSource,this.sourceBuffer))){if(this.tuning.useRefactoredSearchGap)for(let i=0;i<this.sourceBuffer.buffered.length;i++)this.gaps=this.gaps.filter(a=>this.sourceBuffer&&(Math.round(a.from)<Math.round(this.sourceBuffer.buffered.start(i)*1e3)||Math.round(a.to)>Math.round(this.sourceBuffer.buffered.end(i)*1e3)));for(let i of t){let a={representation:e,from:i.time.from,to:i.time.to};for(let s=0;s<this.sourceBuffer.buffered.length;s++){let n=this.sourceBuffer.buffered.start(s)*1e3,o=this.sourceBuffer.buffered.end(s)*1e3;if(!(o<=i.time.from||n>=i.time.to)){if(n<=i.time.from&&o>=i.time.to){a=void 0;break}o>i.time.from&&o<i.time.to&&(a.from=o),n<i.time.to&&n>i.time.from&&(a.to=n)}}a&&a.to-a.from>1&&!this.gaps.some(s=>a&&s.from===a.from&&s.to===a.to)&&this.gaps.push(a)}}}detectGapsWhenIdle(e,t){if(!(this.gapDetectionIdleCallback||!this.sourceBuffer||!ee(this.mediaSource,this.sourceBuffer))){if(!this.tuning.useRefactoredSearchGap)for(let i=0;i<this.sourceBuffer.buffered.length;i++)this.gaps=this.gaps.filter(a=>this.sourceBuffer&&(Math.round(a.from)<Math.round(this.sourceBuffer.buffered.start(i)*1e3)||Math.round(a.to)>Math.round(this.sourceBuffer.buffered.end(i)*1e3)));this.gapDetectionIdleCallback=el(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:ft.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if(he(this.sourceBuffer)||!ee(this.mediaSource,this.sourceBuffer)||he(this.playingRepresentationId))return;let e=[];for(let i=0;i<this.sourceBuffer.buffered.length;i++){let a=Math.floor(this.sourceBuffer.buffered.start(i)*1e3),s=Math.ceil(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:a,to:s})}let t=100;for(let i of this.segments.values())for(let a of i){let{status:s}=a;if(s!=="fed"&&s!=="partially_ejected")continue;let n=Math.floor(a.time.from),o=Math.ceil(a.time.to),u=e.some(c=>c.from-t<=n&&c.to+t>=o),l=e.filter(c=>n>=c.from&&n<c.to-t||o>c.from+t&&o<=c.to);u||(l.length===1?a.status="partially_ejected":this.gaps.some(c=>c.from===a.time.from||c.to===a.time.to)?a.status="partially_ejected":a.status="none")}}handleAsyncError(e,t){this.error$.next({id:t,category:ft.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}};var fa=r=>{let e=new URL(r);return e.searchParams.set("quic","1"),e.toString()};var bS=r=>{let e=r.get("X-Delivery-Type"),t=r.get("X-Reused"),i=e===null?"http1":e??void 0,a=t===null?void 0:{1:!0,0:!1}[t]??void 0;return{type:i,reused:a}};import{abortable as ba,assertNever as vS,fromEvent as SS,merge as pM,now as ga,Subscription as hM,Subject as yS,ValueSubject as Tl,flattenObject as Ui,ErrorCategory as va}from"@vkontakte/videoplayer-shared";var gS=r=>{let e=new URL(r);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var zs=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:a=!1,useEnableSubtitlesParam:s=!1}){this.lastConnectionType$=new Tl(void 0);this.lastConnectionReused$=new Tl(void 0);this.lastRequestFirstBytes$=new Tl(void 0);this.recoverableError$=new yS;this.error$=new yS;this.abortAllController=new pe;this.subscription=new hM;this.fetchManifest=ba(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=fa(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=gS(i));let a=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(Ys);return a?(t.log("success",Ui({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(a.headers),a.text()):(t.error("error",Ui({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=ba(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:a,priority:s="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1}={}){let l=e,c=new Headers,d=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{c.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let M=new URL(l,location.href);M.searchParams.append("bytes",`${i.from}-${i.to}`),l=M.toString();break}default:vS(t)}this.requestQuic&&(l=fa(l));let p=this.abortAllController.signal,h;if(n){let M=new pe;if(h=pM(SS(this.abortAllController.signal,"abort"),SS(n,"abort")).subscribe(()=>{try{M.abort()}catch(w){Ys(w)}}),this.subscription.add(h),this.abortAllController.signal.aborted||n.aborted)try{M.abort()}catch(w){Ys(w)}p=M.signal}let f=ga();d.log("startRequest",Ui({url:l,priority:s,rangeMethod:t,range:i,isLowLatency:u,requestStartedAt:f}));let b=yield this.doFetch(l,{priority:s,headers:c,signal:p}),g=ga();if(!b)return d.error("error",{message:"No response in request"}),d.end(),h?.unsubscribe(),null;if(this.throughputEstimator?.addRawRtt(g-f),!b.ok||!b.body){h?.unsubscribe();let M=`Fetch error ${b.status}: ${b.statusText}`;return d.error("error",{message:M}),d.end(),Promise.reject(new Error(`Fetch error ${b.status}: ${b.statusText}`))}if(this.onHeadersReceived(b.headers),!a&&!o){h?.unsubscribe();let M=ga(),w={requestStartedAt:f,requestEndedAt:M,duration:M-f};return d.log("endRequest",Ui(w)),d.end(),b.arrayBuffer()}let[v,x]=b.body.tee(),T=v.getReader();o&&this.throughputEstimator?.trackStream(x,u);let P=0,I=new Uint8Array(0),B=!1,O=M=>{h?.unsubscribe(),B=!0,Ys(M)},F=ba(p,async function*({done:M,value:w}){if(P===0&&this.lastRequestFirstBytes$.next(ga()-f),p.aborted){h?.unsubscribe();return}if(!M&&w){let W=new Uint8Array(I.length+w.length);W.set(I),W.set(w,I.length),I=W,P+=w.byteLength,a?.(new DataView(I.buffer),P),yield T?.read().then(F,O)}}.bind(this));yield T?.read().then(F,O),h?.unsubscribe();let N=ga(),S={failed:B,requestStartedAt:f,requestEndedAt:N,duration:N-f};return B?(d.error("endRequest",Ui(S)),d.end(),null):(d.log("endRequest",Ui(S)),d.end(),I.buffer)}.bind(this));this.fetchByteRangeRepresentation=ba(this.abortAllController.signal,async function*(e,t,i){if(e.type!=="byteRange")return null;let{from:a,to:s}=e.initRange,n=a,o=s,u=!1,l,c;e.indexRange&&(l=e.indexRange.from,c=e.indexRange.to,u=s+1===l,u&&(n=Math.min(l,a),o=Math.max(c,s))),n=Math.min(n,0);let d=yield this.fetch(e.url,{range:{from:n,to:o},priority:i,measureThroughput:!1});if(!d)return null;let p=new DataView(d,a-n,s-n+1);if(!t.validateData(p))throw new Error("Invalid media file");let h=t.parseInit(p),f=e.indexRange??t.getIndexRange(h);if(!f)throw new ReferenceError("No way to load representation index");let b;if(u)b=new DataView(d,f.from-n,f.to-f.from+1);else{let v=yield this.fetch(e.url,{range:f,priority:i,measureThroughput:!1});if(!v)return null;b=new DataView(v)}let g=t.parseSegments(b,h,f);return{init:h,dataView:new DataView(d),segments:g}}.bind(this));this.fetchTemplateRepresentation=ba(this.abortAllController.signal,async function*(e,t){if(e.type!=="template")return null;let i=new URL(e.initUrl,e.baseUrl).toString(),a=yield this.fetch(i,{priority:t,measureThroughput:!1});return a?{init:null,segments:e.segments.map(n=>({...n,status:"none",size:void 0})),dataView:new DataView(a)}:null}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=a,this.tracer=i.createComponentTracer("Fetcher"),this.useEnableSubtitlesParam=s}onHeadersReceived(e){let{type:t,reused:i}=bS(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,t,i="auto"){let{type:a}=e;switch(a){case"byteRange":return await this.fetchByteRangeRepresentation(e,t,i)??null;case"template":return await this.fetchTemplateRepresentation(e,i)??null;default:vS(a)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}async doFetch(e,t){let i=await st(e,t);if(i.ok)return i;let a=await i.text(),s=parseInt(a);if(!isNaN(s))switch(s){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:va.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:va.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:va.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:va.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${s})`,category:va.FATAL})}}},Ys=r=>{if(!ha(r))throw r};var ri=(r,e,t)=>t*e+(1-t)*r,Il=(r,e)=>r.reduce((t,i)=>t+i,0)/e,TS=(r,e,t,i)=>{let a=0,s=t,n=Il(r,e),o=e<i?e:i;for(let u=0;u<o;u++)r[s]>n?a++:a--,s=(r.length+s-1)%r.length;return Math.abs(a)===o};import{isNullable as mM,ValueSubject as IS}from"@vkontakte/videoplayer-shared";var Vt=class{constructor(e){this.prevReported=void 0;this.pastMeasures=[];this.takenMeasures=0;this.measuresCursor=0;this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new IS(e.initial),this.debounced$=new IS(e.initial);let t=e.label??"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new be(`raw_${t}`),this.smoothedSeries$=new be(`smoothed_${t}`),this.reportedSeries$=new be(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,i=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=(this.pastMeasures[o]-this.smoothed)**2,i++);this.takenMeasures=i,t/=i;let a=Math.sqrt(t),s=this.smoothed+this.params.deviationFactor*a,n=this.smoothed-this.params.deviationFactor*a;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)&&(mM(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 Ks=class extends Vt{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=ri(this.slow,e,this.params.emaAlphaSlow),this.fast=ri(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var Xs=class extends Vt{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=Il(this.pastMeasures,this.takenMeasures);this.emaSmoothed=ri(this.emaSmoothed,e,this.params.emaAlpha);let i=TS(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}};var Js=class extends Vt{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?ri(this.smoothed,t,this.params.emaAlpha):t}};var ai=class{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new Ks({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new Xs({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 Js({initial:e,label:"liveEdgeDelay",...t})}};var El=(r,e)=>{r&&r.playbackRate!==e&&(r.playbackRate=e)};import{isNullable as fM,ValueSubject as bM}from"@vkontakte/videoplayer-shared";var Sa=class r{constructor(e,t){this.currentRepresentation$=new bM(null);this.maxRepresentations=4;this.representationsCursor=0;this.representations=[];this.currentSegment=null;this.getCurrentPosition=t.getCurrentPosition,this.processStreams(e)}updateLive(e){this.processStreams(e?.streams.text)}seekLive(e){this.processStreams(e)}maintain(e=this.getCurrentPosition()){if(!fM(e))for(let t of this.representations)for(let i of t){let a=i.segmentReference,s=a.segments.length,n=a.segments[0].time.from,o=a.segments[s-1].time.to;if(e<n||e>o)continue;let u=a.segments.find(l=>l.time.from<=e&&l.time.to>=e);!u||this.currentSegment?.time.from===u.time.from&&this.currentSegment.time.to===u.time.to||(this.currentSegment=u,this.currentRepresentation$.next({...i,label:"Live Text",language:"ru",isAuto:!0,url:new URL(u.url,a.baseUrl).toString()}))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e??[]){let i=r.filterRepresentations(t.representations);if(i){this.representations[this.representationsCursor]=i,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!e?.some(t=>r.filterRepresentations(t.representations))}static filterRepresentations(e){return e?.filter(t=>t.kind==="text"&&"segmentReference"in t&&ve(t.segmentReference))}};var en=R(Lt(),1),xl=R(Ie(),1);import{assertNever as tn}from"@vkontakte/videoplayer-shared";var ES=(r,{useHlsJs:e,useManagedMediaSource:t,useOldMSEDetection:i})=>{let{containers:a,protocols:s,codecs:n,nativeHlsSupported:o}=V.video,u=(n.h264||n.h265)&&n.aac,l=s.mse&&(!i||!!window.MediaStreamTrack)||s.mms&&t;return r.filter(c=>{switch(c){case"DASH_SEP":return l&&a.mp4&&u;case"DASH_WEBM":return l&&a.webm&&n.vp9&&n.opus;case"DASH_WEBM_AV1":return l&&a.webm&&n.av1&&n.opus;case"DASH_STREAMS":return l&&(a.mp4&&u||a.webm&&(n.vp9||n.av1)&&(n.opus||n.aac));case"DASH_LIVE":return l&&a.mp4&&u;case"DASH_LIVE_CMAF":return l&&a.mp4&&u&&a.cmaf;case"DASH_ONDEMAND":return l&&a.mp4&&u;case"HLS":case"HLS_ONDEMAND":return o||e&&l&&a.mp4&&u;case"HLS_LIVE":case"HLS_LIVE_CMAF":return o;case"MPEG":return a.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return s.webrtc&&s.ws&&n.h264&&(a.mp4||a.webm);default:return tn(c)}})},Zs=r=>{let{webmDecodingInfo:e}=V.video,t="DASH_WEBM",i="DASH_WEBM_AV1";switch(r){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:tn(r)}return[t,i]},xS=({webmCodec:r,androidPreferredFormat:e,preferMultiStream:t})=>{let i=[...t?["DASH_STREAMS"]:[],...Zs(r),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],a=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(V.device.isAndroid)switch(e){case"mpeg":return["MPEG",...i,"HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...i,"MPEG"];case"dash":return[...i,"HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return[...a,"MPEG",...Zs(r),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...Zs(r),"MPEG",...a,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...Zs(r),...a,"HLS","HLS_ONDEMAND"];default:tn(e)}return V.video.nativeHlsSupported?[...i,"HLS","HLS_ONDEMAND","MPEG"]:[...i,"HLS","HLS_ONDEMAND","MPEG"]},PS=({androidPreferredFormat:r,preferCMAF:e,preferWebRTC:t})=>{let i=e?["DASH_LIVE_CMAF","DASH_LIVE"]:["DASH_LIVE","DASH_LIVE_CMAF"],a=e?["HLS_LIVE_CMAF","HLS_LIVE"]:["HLS_LIVE","HLS_LIVE_CMAF"],s=[...i,...a],n=[...a,...i],o,u=V.device.isMac&&V.browser.isSafari;if(V.device.isAndroid)switch(r){case"dash":case"dash_any_mpeg":case"dash_any_webm":case"dash_sep":{o=s;break}case"hls":case"mpeg":{o=n;break}default:tn(r)}else V.video.nativeHlsSupported&&!u?o=n:u?o=e?["DASH_LIVE_CMAF","HLS_LIVE_CMAF","HLS_LIVE","DASH_LIVE"]:["HLS_LIVE","DASH_LIVE","DASH_LIVE_CMAF","HLS_LIVE_CMAF"]:o=s;return t?["WEB_RTC_LIVE",...o]:[...o,"WEB_RTC_LIVE"]},Pl=r=>r?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],kS=r=>{if(r.size===0)return;if(r.size===1){let t=r.values().next();return(0,en.default)(t.value.split("."),0)}for(let t of r){let i=(0,en.default)(t.split("."),0);if(i==="opus"||i==="vp09"||i==="av01")return i}let e=r.values().next();return(0,en.default)(e.value.split("."),0)},wS=r=>{let e=r.map(i=>rn(i)),{codecs:t}=V.video;return SM().filter(i=>{if((0,xl.default)(e,i))switch(i){case"av1":return t.av1;case"vp9":return t.vp9;case"avc1":return t.h264;case"hev1":return t.h265;default:return!1}else return!1})},AS=r=>{let e=r.map(i=>rn(i)),{codecs:t}=V.video;return yM().filter(i=>{if((0,xl.default)(e,i))switch(i){case"opus":return t.opus;case"mp4a":return t.aac;default:return!1}})},rn=r=>r.split(".")[0].replace("0",""),SM=()=>["av1","vp9","avc1","hev1"],yM=()=>["opus","mp4a"];var wM=["timeupdate","progress","play","seeked","stalled","waiting"],AM=["timeupdate","progress","loadeddata","playing","seeked"];var nn=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new $S;this.representationSubscription=new $S;this.state$=new D("none");this.currentVideoRepresentation$=new K(void 0);this.currentVideoRepresentationInit$=new K(void 0);this.currentAudioRepresentation$=new K(void 0);this.currentVideoSegmentLength$=new K(0);this.currentAudioSegmentLength$=new K(0);this.error$=new sn;this.lastConnectionType$=new K(void 0);this.lastConnectionReused$=new K(void 0);this.lastRequestFirstBytes$=new K(void 0);this.currentLiveTextRepresentation$=new K(null);this.isLive$=new K(!1);this.isActiveLive$=new K(!1);this.isLowLatency$=new K(!1);this.liveDuration$=new K(0);this.liveSeekableDuration$=new K(0);this.liveAvailabilityStartTime$=new K(0);this.liveStreamStatus$=new K(void 0);this.bufferLength$=new K(0);this.liveLatency$=new K(void 0);this.liveLoadBufferLength$=new K(0);this.livePositionFromPlayer$=new K(0);this.currentStallDuration$=new K(0);this.videoLastDataObtainedTimestamp$=new K(0);this.fetcherRecoverableError$=new sn;this.fetcherError$=new sn;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new sn;this.gapWatchdogActive=!1;this.destroyController=new pe;this.initManifest=wl(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=de(t,i,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),this.manifest?.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:nt.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=wl(this.destroyController.signal,async function*(){this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(u=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:nt.NETWORK,message:"Failed to load manifest",thrown:u})});if(!e)return null;let t=null;try{t=pS(e??"",this.manifestUrlString)}catch(u){let l=av(e)??{id:"ManifestParsing",category:nt.PARSER,message:"Failed to parse MPD manifest",thrown:u};this.error$.next(l)}if(!t)return null;let i=(u,l,c)=>!!(this.element?.canPlayType?.(l)&&Ye()?.isTypeSupported?.(`${l}; codecs="${c}"`)||u==="text");if(t.live){this.isLive$.next(!!t.live);let{availabilityStartTime:u,latestSegmentPublishTime:l,streamIsUnpublished:c,streamIsAlive:d}=t.live,p=(t.duration??0)/1e3;this.liveSeekableDuration$.next(-1*p),this.liveDuration$.next((l-u)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let h="active";d||(h=c?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(h)}let a={text:t.streams.text,video:[],audio:[]},s,n;for(let u of["video","audio"]){let c=t.streams[u].filter(({mime:p,codecs:h})=>i(u,p,h));a[u]=c;let d;if(this.tuning.dash.codecsPrioritizeEnabled){let p=c.map(({codecs:h})=>h);u==="audio"&&(n=AS(p),d=n[0]),u==="video"&&(s=wS(p),this.forceVideoCodec&&(0,MS.default)(s,this.forceVideoCodec)?d=this.forceVideoCodec:d=s[0]),d&&(a[u]=c.filter(({codecs:h})=>rn(h)===d))}else{let p=new Set(c.map(({codecs:h})=>h));d=kS(p),d&&(a[u]=c.filter(({codecs:h})=>h.startsWith(d)))}if(u==="video"){let p=this.tuning.preferHDR,h=a.video.some(b=>b.hdr),f=a.video.some(b=>!b.hdr);V.display.isHDR&&p&&h?a.video=a.video.filter(b=>b.hdr):f&&(a.video=a.video.filter(b=>!b.hdr))}}let o={...t,streams:a};return this.tuning.dash.codecsPrioritizeEnabled&&(o.codecs={video:s,audio:n}),this.tracer.log("updateManifestEnd",Ta(o)),o}.bind(this));this.initRepresentations=wl(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initRepresentationsStart",Ta({initialVideo:e,initialAudio:t,sourceHls:i})),Hi(this.manifest),Hi(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let a=p=>{this.representationSubscription.add(bt(p,"error").pipe(an(h=>!!this.element?.played.length)).subscribe(h=>{this.error$.next({id:"VideoSource",category:nt.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=this.tuning.useManagedMediaSource?Pb():new MediaSource;let s=document.createElement("source");if(a(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&$s())if(i){let p=document.createElement("source");a(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 ma("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],Ia(t)){let p=this.manifest.streams.audio.reduce((h,f)=>[...h,...f.representations],[]);this.audioBufferManager=new ma("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}Sa.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new Sa(this.manifest.streams.text,n)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$));let u=()=>{this.stallWatchdogSubscription?.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add(si(...AM.map(p=>bt(this.element,p))).pipe(Qi(p=>this.element?Bi(this.element.buffered,this.element.currentTime*1e3):0),ya(),PM(p=>{p>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add(si(bt(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe(ya()).subscribe(h=>this.liveStreamEndTimestamp=Ll())),this.subscription.add(bt(this.element,"pause").subscribe(()=>{this.livePauseWatchdogSubscription=Al(1e3).subscribe(h=>{let f=Ps(this.manifestUrlString,2);this.manifestUrlString=de(this.manifestUrlString,f+1e3,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add(bt(this.element,"play").subscribe(h=>this.livePauseWatchdogSubscription?.unsubscribe())),this.representationSubscription.add(ji({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(Qi(({isActiveLive:h,isLowLatency:f})=>h&&f),ya()).subscribe(h=>{this.isManualDecreasePlaybackInLive()||El(this.element,1)})),this.representationSubscription.add(ji({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(an(({bufferLength:h,isActiveLive:f,isLowLatency:b})=>f&&b&&!!h)).subscribe(({bufferLength:h})=>this.liveBuffer.next(h))),this.representationSubscription.add(this.videoBufferManager.currentLowLatencySegmentLength$.subscribe(h=>{if(!this.isActiveLive$.getValue()&&!this.isLowLatency$.getValue()&&!h)return;let f=this.liveSeekableDuration$.getValue()-h/1e3;this.liveSeekableDuration$.next(Math.max(f,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+h/1e3)})),this.representationSubscription.add(ji({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(an(({isLive:h})=>h),ya((h,f)=>f.bufferLength<h.bufferLength),Qi(({rtt:h,bufferLength:f,segmentServerLatency:b})=>{let g=Ps(this.manifestUrlString,2);return(h/2+f+b+g)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(ji({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:h,isActiveLive:f,isLowLatency:b})=>{if(!b||!f)return;let g=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,v=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,x=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,T=h-g;if(this.isManualDecreasePlaybackInLive())return;let P=1;Math.abs(T)>v&&(P=1+Math.sign(T)*x),El(this.element,P)})),this.representationSubscription.add(this.bufferLength$.subscribe(h=>{let f=0;if(h){let b=(this.element?.currentTime??0)*1e3;f=Math.min(...this.bufferManagers.map(v=>v.getLiveSegmentsToLoadState(this.manifest)?.to??b))-b}this.liveLoadBufferLength$.getValue()!==f&&this.liveLoadBufferLength$.next(f)}));let p=0;this.representationSubscription.add(ji({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(kM(1e3)).subscribe(async({liveLoadBufferLength:h,bufferLength:f})=>{if(!this.element||this.isUpdatingLive)return;let b=this.element.playbackRate,g=Ps(this.manifestUrlString,2),v=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,x=Math.min(v,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*b),T=this.tuning.dashCmafLive.normalizedActualBufferOffset*b,P=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*b,I=isFinite(h)?h:f,B=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),O=v<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(O);let F="none";if(B?F="active_low_latency":this.isLowLatency$.getValue()&&O?(this.bufferManagers.forEach(N=>N.proceedLowLatencyLive()),F="active_low_latency"):g!==0&&I<x?F="live_forward_buffering":I<x+P&&(F="live_with_target_offset"),isFinite(h)&&(p=h>p?h:p),F==="live_forward_buffering"||F==="live_with_target_offset"){let N=p-(x+T),S=this.normolizeLiveOffset(Math.trunc(g+N/b)),M=Math.abs(S-g),w=0;!h||M<=this.tuning.dashCmafLive.offsetCalculationError?w=g:S>0&&M>this.tuning.dashCmafLive.offsetCalculationError&&(w=S),this.manifestUrlString=de(this.manifestUrlString,w,2)}(F==="live_with_target_offset"||F==="live_forward_buffering")&&(p=0,await this.updateLive())},h=>{this.error$.next({id:"updateLive",category:nt.VIDEO_PIPELINE,thrown:h,message:"Failed to update live with subscription"})}))}let l=si(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe(Qi(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),c=si(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe(Qi(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue()))),d=ji({allBuffersFull:l,someBufferEnded:c}).pipe(ya(),Qi(({allBuffersFull:p,someBufferEnded:h})=>p&&h),an(p=>p));if(this.representationSubscription.add(si(this.forceEnded$,d).subscribe(()=>{if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(p=>!p.updating))try{this.source?.endOfStream()}catch(p){this.error$.next({id:"EndOfStream",category:nt.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:p})}})),this.representationSubscription.add(si(...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,f)=>{p&&(this.timeoutSourceOpenId=setTimeout(()=>{if(this.source?.readyState==="open"){h();return}this.tuning.dash.rejectOnSourceOpenTimeout?f(new Error("Timeout reject when wait sourceopen event")):h()},this.tuning.dash.sourceOpenTimeout)),this.source?.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),h()},{once:!0})})}if(!this.isLive$.getValue()){let p=[this.manifest.duration??0,...(0,Rl.default)((0,Rl.default)([...this.manifest.streams.audio,...this.manifest.streams.video],h=>h.representations),h=>{let f=[];return h.duration&&f.push(h.duration),ve(h.segmentReference)&&h.segmentReference.totalSegmentsDurationMs&&f.push(h.segmentReference.totalSegmentsDurationMs),f})];this.source.duration=Math.max(...p)/1e3}this.audioBufferManager&&Ia(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")}.bind(this));this.tick=()=>{if(!this.element||!this.videoBufferManager||this.source?.readyState!=="open")return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),this.audioBufferManager?.maintain(e),this.liveTextManager?.maintain(e),(this.videoBufferManager.gaps.length||this.audioBufferManager?.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=Al(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:nt.WTF,message:"Error handling gaps",thrown:t})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.forceVideoCodec=e.forceVideoCodec,this.fetcher=new zs({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=ai.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator}),this.initTracerSubscription()}async seekLive(e){Hi(this.element);let t=this.liveStreamStatus$.getValue()!=="active"?Ll()-this.liveStreamEndTimestamp:0,i=this.normolizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=de(this.manifestUrlString,i,2),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await this.videoBufferManager?.seekLive(this.manifest.streams.video),await this.audioBufferManager?.seekLive(this.manifest.streams.audio),this.liveTextManager?.seekLive(this.manifest.streams.text))}initBuffer(){Hi(this.element),this.state$.setState("running"),this.subscription.add(si(...wM.map(e=>bt(this.element,e)),bt(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:nt.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(bt(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(bt(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&Mt(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{if(!this.element||this.source?.readyState!=="open")return;let t=this.currentStallDuration$.getValue();t+=50,this.currentStallDuration$.next(t);let i={timeInWaiting:t},a=Ll(),s=100,n=this.videoBufferManager?.lastDataObtainedTimestamp??0;this.videoLastDataObtainedTimestamp$.next(n);let o=this.audioBufferManager?.lastDataObtainedTimestamp??0,u=this.videoBufferManager?.getForwardBufferDuration()??0,l=this.audioBufferManager?.getForwardBufferDuration()??0,c=u<s&&a-n>this.tuning.dash.crashOnStallTWithoutDataTimeout,d=this.audioBufferManager&&l<s&&a-o>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((c||d)&&t>this.tuning.dash.crashOnStallTWithoutDataTimeout||t>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${t} ms`);if(this.isLive$.getValue()&&t%2e3===0){let p=this.normolizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(p).catch(h=>{this.error$.next({id:"stallIntervalCallback",category:nt.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:h})}),i.liveLastOffset=p}else{let p=this.element.currentTime*1e3;this.videoBufferManager?.maintain(p),this.audioBufferManager?.maintain(p),i.position=p}this.tracer.log("stallIntervalCallback",Ta(i))};this.stallWatchdogSubscription?.unsubscribe(),this.stallWatchdogSubscription=Al(50).subscribe(e,t=>{this.error$.next({id:"StallWatchdogCallback",category:nt.NETWORK,message:"Can't restore DASH after stall.",thrown:t})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,i=!1){let a={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return this.tuning.useNewSwitchTo?this.currentStallDuration$.getValue()>0?a?.switchToWithPreviousAbort(t,i):a?.switchTo(t,i):a?.switchToOld(t,i)}async seek(e,t){Hi(this.element),Hi(this.videoBufferManager);let i;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?i=e:i=Math.max(this.videoBufferManager.findSegmentStartTime(e)??e,this.audioBufferManager?.findSegmentStartTime(e)??e),this.warmUpMediaSourceIfNeeded(i),Mt(this.element.buffered,i)||await Promise.all([this.videoBufferManager.abort(),this.audioBufferManager?.abort()]),!(RS(this.element)||RS(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),this.audioBufferManager?.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",Ta({requestedPosition:e,forcePrecise:t,position:i})))}warmUpMediaSourceIfNeeded(e=this.element?.currentTime){Ia(this.element)&&Ia(this.source)&&Ia(e)&&this.source?.readyState==="ended"&&this.element.duration*1e3-e>this.tuning.dash.seekBiasInTheEnd&&this.bufferManagers.forEach(t=>t.warmUpMediaSource())}get isStreamEnded(){return this.source?.readyState==="ended"}stop(){this.tracer.log("stop"),this.element?.querySelectorAll("source").forEach(e=>{URL.revokeObjectURL(e.src),e.remove()}),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),this.videoBufferManager?.destroy(),this.videoBufferManager=null,this.audioBufferManager?.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){return this.manifest?.streams}getCodecs(){return this.manifest?.codecs}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),this.source?.readyState==="open"&&Array.from(this.source.sourceBuffers).every(e=>!e.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=xM(this.tracer.error.bind(this.tracer));this.subscription.add(this.error$.subscribe(e("error")))}isManualDecreasePlaybackInLive(){return!this.element||!this.isLive$.getValue()?!1:1-this.element.playbackRate>this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&(this.bufferManagers?.forEach(e=>e.updateLive(this.manifest)),this.liveTextManager?.updateLive(this.manifest)),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.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 a=this.element.currentTime*1e3,s=[],n=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let o of this.bufferManagers)for(let u of o.gaps)o.playingRepresentation$.getValue()===u.representation&&u.from-n<=a&&u.to+n>a&&(this.element.duration*1e3-u.to<this.tuning.endGapTolerance?s.push(1/0):s.push(u.to));if(s.length){let o=Math.max(...s)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,o===1/0?this.forceEnded$.next():(this.element.currentTime=o/1e3,i={...i,gapEnds:s,jumpTo:o,resultCurrentTime:this.element.currentTime},this.tracer.log("jumpGap",Ta(i)))}}};var on=class{constructor(e,t){this.fov=e,this.orientation=t}};var un=class{constructor(e,t){this.rotating=!1;this.fading=!1;this.lastTickTS=0;this.lastCameraTurnTS=0;this.fadeStartSpeed=null;this.fadeTime=0;this.camera=e,this.options=t,this.rotationSpeed={x:0,y:0,z:0},this.fadeCorrection=1/(this.options.speedFadeTime/1e3)**2}turnCamera(e=0,t=0,i=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+i)}pointCameraTo(e=0,t=0,i=0){t=this.limitCameraRotationY(t);let a=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:a,y:s,z:n},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,i){this.rotationSpeed.x=e??this.rotationSpeed.x,this.rotationSpeed.y=t??this.rotationSpeed.y,this.rotationSpeed.z=i??this.rotationSpeed.z}startRotation(){this.rotating=!0}stopRotation(e=!1){e?(this.setRotationSpeed(0,0,0),this.fadeStartSpeed=null):this.startFading(this.rotationSpeed.x,this.rotationSpeed.y,this.rotationSpeed.z),this.rotating=!1}onCameraRelease(){if(this.lastCameraTurn&&this.lastCameraTurnTS){let e=Date.now()-this.lastCameraTurnTS;if(e<this.options.speedFadeThreshold){let t=(1-e/this.options.speedFadeThreshold)*this.options.rotationSpeedCorrection;this.startFading(this.lastCameraTurn.x*t,this.lastCameraTurn.y*t,this.lastCameraTurn.z*t)}}}startFading(e,t,i){this.setRotationSpeed(e,t,i),this.fadeStartSpeed={...this.rotationSpeed},this.fading=!0}stopFading(){this.fadeStartSpeed=null,this.fading=!0,this.fadeTime=0}limitCameraRotationY(e){return Math.max(-this.options.maxYawAngle,Math.min(e,this.options.maxYawAngle))}tick(e){if(!this.lastTickTS){this.lastTickTS=e,this.lastCameraTurnTS=Date.now();return}let t=e-this.lastTickTS,i=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i);else if(this.fading&&this.fadeStartSpeed){let a=-this.fadeCorrection*(this.fadeTime/1e3)**2+1;this.setRotationSpeed(this.fadeStartSpeed.x*a,this.fadeStartSpeed.y*a,this.fadeStartSpeed.z*a),a>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 CS=`attribute vec2 a_vertex;
14
+ `})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(d,"i")}var nl=D(Et(),1);import{videoSizeToQuality as GM}from"@vkontakte/videoplayer-shared";var QS=({id:r,width:e,height:t,bitrate:i,fps:a,quality:s,streamId:n})=>{let o=(s?It(s):void 0)??GM({width:e,height:t});return o&&{id:r,quality:o,bitrate:i,size:{width:e,height:t},fps:a,streamId:n}},WS=({id:r,bitrate:e})=>({id:r,bitrate:e}),YS=({language:r,label:e},{id:t,url:i,isAuto:a})=>({id:t,url:i,isAuto:a,type:"internal",language:r,label:e}),zS=({language:r,label:e,id:t,url:i,isAuto:a})=>({id:t,url:i,isAuto:a,type:"internal",language:r,label:e}),ol=({id:r,language:e,label:t,codecs:i,isDefault:a})=>({id:r,language:e,label:t,codec:(0,nl.default)(i.split("."),0),isDefault:a}),ul=({id:r,language:e,label:t,hdr:i,codecs:a})=>({id:r,language:e,hdr:i,label:t,codec:(0,nl.default)(a.split("."),0)}),ll=r=>"url"in r,pe=r=>r.type==="template",oa=r=>r instanceof DOMException&&(r.name==="AbortError"||r.code===20);var KS=r=>{r.sort((t,i)=>t.from-i.from);let e=[r[0]];for(let t=1;t<r.length;t++){let{from:i,to:a}=r[t],s=e[e.length-1];s.to>=i?s.to=Math.max(s.to,a):e.push(r[t])}return e},Kt=(r,e)=>{for(let t of r)if(e(t))return t;return null},QM=(r,e)=>{let t=0;return()=>{let i=Date.now();i-t>=e&&(r(),t=i)}},XS=r=>{let e=!1,t=QM(()=>{e=!0},r);return()=>{try{return t(),e}finally{e=!1}}},_s=r=>{let e=[];for(let t=0;t<r.length;t++){let i=Math.floor(r.start(t)*1e3),a=Math.ceil(r.end(t)*1e3);e.push(i,a)}return e};var ZS=r=>{if(!r?.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(r),a=i?.[1]==="-"?-1:1,s={days:e(i?.[5],a),hours:e(i?.[6],a),minutes:e(i?.[7],a),seconds:e(i?.[8],a)};return s.days*24*60*60*1e3+s.hours*60*60*1e3+s.minutes*60*1e3+s.seconds*1e3},ht=(r,e)=>{let t=r;t=(0,cl.default)(t,"$$","$");let i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[a,s]of(0,eg.default)(i)){let n=new RegExp(`\\$${a}(?:%0(\\d+)d)?\\$`,"g");t=(0,cl.default)(t,n,(o,u)=>JS(s)?o:JS(u)?s:(0,tg.default)(s,parseInt(u,10),"0"))}return t},rg=(r,e)=>{let i=new DOMParser().parseFromString(r,"application/xml"),a={video:[],audio:[],text:[]},s=i.children[0],n=Array.from(s.querySelectorAll("MPD > BaseURL").values()).map(T=>T.textContent?.trim()??""),o=(0,ig.default)(n,0)??"",u=s.getAttribute("type")==="dynamic",l=s.getAttribute("availabilityStartTime"),d=s.getAttribute("publishTime"),c=s.getElementsByTagName("vk:Attrs")[0],p=c?.getElementsByTagName("vk:XLatestSegmentPublishTime")[0].textContent,h=c?.getElementsByTagName("vk:XStreamIsLive")[0].textContent,f=c?.getElementsByTagName("vk:XStreamIsUnpublished")[0].textContent,b=c?.getElementsByTagName("vk:XPlaybackDuration")[0].textContent,S;u&&(S={availabilityStartTime:l?new Date(l).getTime():0,publishTime:d?new Date(d).getTime():0,latestSegmentPublishTime:p?new Date(p).getTime():0,streamIsAlive:h==="yes",streamIsUnpublished:f==="yes"});let v,P=s.getAttribute("mediaPresentationDuration"),y=[...s.getElementsByTagName("Period")],I=y.reduce((T,g)=>({...T,[g.id]:g.children}),{}),k=y.reduce((T,g)=>({...T,[g.id]:g.getAttribute("duration")}),{});P?v=ZS(P):(0,dl.default)(k).filter(T=>T).length&&!u?v=(0,dl.default)(k).reduce((T,g)=>T+(ZS(g)??0),0):b&&(v=parseInt(b,10));let H=0,j=s.getAttribute("profiles")?.split(",")??[];for(let T of y.map(g=>g.id))for(let g of I[T]){let N=g.getAttribute("id")??"id"+(H++).toString(10),M=g.getAttribute("mimeType")??"",z=g.getAttribute("codecs")??"",me=g.getAttribute("contentType")??M?.split("/")[0],$=g.getAttribute("profiles")?.split(",")??[],O=GS(g.getAttribute("lang")??"")??{},F=g.querySelector("Label")?.textContent?.trim()??void 0,J=g.querySelectorAll("Representation"),Z=g.querySelector("SegmentTemplate"),Ye=g.querySelector("Role")?.getAttribute("value")??void 0,st=me,L={id:N,language:O.language,isDefault:Ye==="main",label:F,codecs:z,hdr:st==="video"&&al(z),mime:M,representations:[]};for(let w of J){let ee=w.getAttribute("lang")??void 0,Le=F??g.getAttribute("label")??w.getAttribute("label")??void 0,ze=w.querySelector("BaseURL")?.textContent?.trim()??"",Be=new URL(ze||o,e).toString(),Me=w.getAttribute("mimeType")??M,nt=w.getAttribute("codecs")??z??"",Mt;if(me==="text"){let Oe=w.getAttribute("id")||"",Aa=O.privateuse?.includes("x-auto")||Oe.includes("_auto"),$t=w.querySelector("SegmentTemplate");if($t){let Hi={representationId:w.getAttribute("id")??void 0,bandwidth:w.getAttribute("bandwidth")??void 0},Ra=parseInt(w.getAttribute("bandwidth")??"",10)/1e3,La=parseInt($t.getAttribute("startNumber")??"",10)??1,ai=parseInt($t.getAttribute("timescale")??"",10),In=$t.querySelectorAll("SegmentTimeline S")??[],si=$t.getAttribute("media");if(!si)continue;let Ma=[],$a=0,Da="",ni=0,ji=La,de=0;for(let _e of In){let Dt=parseInt(_e.getAttribute("d")??"",10),$e=parseInt(_e.getAttribute("r")??"",10)||0,mt=parseInt(_e.getAttribute("t")??"",10);de=Number.isFinite(mt)?mt:de;let Ct=Dt/ai*1e3,oi=de/ai*1e3;for(let Ke=0;Ke<$e+1;Ke++){let ft=ht(si,{...Hi,segmentNumber:ji.toString(10),segmentTime:(de+Ke*Dt).toString(10)}),ui=(oi??0)+Ke*Ct,Qi=ui+Ct;ji++,Ma.push({time:{from:ui,to:Qi},url:ft})}de+=($e+1)*Dt,$a+=($e+1)*Ct}ni=de/ai*1e3,Da=ht(si,{...Hi,segmentNumber:ji.toString(10),segmentTime:de.toString(10)});let Gi={time:{from:ni,to:1/0},url:Da},ot={type:"template",baseUrl:Be,segmentTemplateUrl:si,initUrl:"",totalSegmentsDurationMs:$a,segments:Ma,nextSegmentBeyondManifest:Gi,timescale:ai};Mt={id:Oe,kind:"text",segmentReference:ot,profiles:[],duration:v,bitrate:Ra,mime:"",codecs:"",width:0,height:0,isAuto:Aa}}else Mt={id:Oe,isAuto:Aa,kind:"text",url:Be}}else{let Oe=w.getAttribute("contentType")??Me?.split("/")[0]??me,Aa=g.getAttribute("profiles")?.split(",")??[],$t=parseInt(w.getAttribute("width")??"",10),Hi=parseInt(w.getAttribute("height")??"",10),Ra=parseInt(w.getAttribute("bandwidth")??"",10)/1e3,La=w.getAttribute("frameRate")??"",ai=w.getAttribute("quality")??void 0,In=La?jS(La):void 0,si=w.getAttribute("id")??"id"+(H++).toString(10),Ma=Oe==="video"?`${Hi}p`:Oe==="audio"?`${Ra}Kbps`:nt,$a=`${si}@${Ma}`,Da=[...j,...$,...Aa],ni,ji=w.querySelector("SegmentBase"),de=w.querySelector("SegmentTemplate")??Z;if(ji){let ot=w.querySelector("SegmentBase Initialization")?.getAttribute("range")??"",[_e,Dt]=ot.split("-").map(ft=>parseInt(ft,10)),$e={from:_e,to:Dt},mt=w.querySelector("SegmentBase")?.getAttribute("indexRange"),[Ct,oi]=mt?mt.split("-").map(ft=>parseInt(ft,10)):[],Ke=mt?{from:Ct,to:oi}:void 0;ni={type:"byteRange",url:Be,initRange:$e,indexRange:Ke}}else if(de){let ot={representationId:w.getAttribute("id")??void 0,bandwidth:w.getAttribute("bandwidth")??void 0},_e=parseInt(de.getAttribute("timescale")??"",10),Dt=de.getAttribute("initialization")??"",$e=de.getAttribute("media"),mt=parseInt(de.getAttribute("startNumber")??"",10)??1,Ct=ht(Dt,ot);if(!$e)throw new ReferenceError("No media attribute in SegmentTemplate");let oi=de.querySelectorAll("SegmentTimeline S")??[],Ke=[],ft=0,ui="",Qi=0;if(oi.length){let Ca=mt,Ne=0;for(let li of oi){let Xe=parseInt(li.getAttribute("d")??"",10),Vt=parseInt(li.getAttribute("r")??"",10)||0,Va=parseInt(li.getAttribute("t")??"",10);Ne=Number.isFinite(Va)?Va:Ne;let En=Xe/_e*1e3,Ty=Ne/_e*1e3;for(let Ba=0;Ba<Vt+1;Ba++){let Iy=ht($e,{...ot,segmentNumber:Ca.toString(10),segmentTime:(Ne+Ba*Xe).toString(10)}),Kl=(Ty??0)+Ba*En,Ey=Kl+En;Ca++,Ke.push({time:{from:Kl,to:Ey},url:Iy})}Ne+=(Vt+1)*Xe,ft+=(Vt+1)*En}Qi=Ne/_e*1e3,ui=ht($e,{...ot,segmentNumber:Ca.toString(10),segmentTime:Ne.toString(10)})}else if(WM(v)){let Ne=parseInt(de.getAttribute("duration")??"",10)/_e*1e3,li=Math.ceil(v/Ne),Xe=0;for(let Vt=1;Vt<li;Vt++){let Va=ht($e,{...ot,segmentNumber:Vt.toString(10),segmentTime:Xe.toString(10)});Ke.push({time:{from:Xe,to:Xe+Ne},url:Va}),Xe+=Ne}Qi=Xe,ui=ht($e,{...ot,segmentNumber:li.toString(10),segmentTime:Xe.toString(10)})}let yy={time:{from:Qi,to:1/0},url:ui};ni={type:"template",baseUrl:Be,segmentTemplateUrl:$e,initUrl:Ct,totalSegmentsDurationMs:ft,segments:Ke,nextSegmentBeyondManifest:yy,timescale:_e}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Oe||!Me)continue;let Gi={video:"video",audio:"audio",text:"text"}[Oe];if(!Gi)continue;st||=Gi,Mt={id:$a,kind:Gi,segmentReference:ni,profiles:Da,duration:v,bitrate:Ra,mime:Me,codecs:nt,width:$t,height:Hi,fps:In,quality:ai}}L.language||=ee,L.label||=Le,L.mime||=Me,L.codecs||=nt,L.hdr||=st==="video"&&al(nt),L.representations.push(Mt)}if(st){let w=a[st].find(ee=>ee.id===L.id);if(w&&L.representations.every(ee=>pe(ee.segmentReference)))for(let ee of w.representations){let ze=L.representations.find(Me=>Me.id===ee.id)?.segmentReference,Be=ee.segmentReference;Be.segments.push(...ze.segments),Be.nextSegmentBeyondManifest=ze.nextSegmentBeyondManifest}else a[st].push(L)}}return{duration:v,streams:a,baseUrls:n,live:S}};import{isNonNullable as ag}from"@vkontakte/videoplayer-shared";var Q=(r,e)=>ag(r)&&ag(e)&&r.readyState==="open"&&YM(r,e);function YM(r,e){for(let t=0;t<r.activeSourceBuffers.length;++t)if(r.activeSourceBuffers[t]===e)return!0;return!1}import{fromEvent as zM,Subscription as KM}from"@vkontakte/videoplayer-shared";var Ns=class{constructor(e,t){this.lastUpdateTs=0;this.lastCallTs=0;this.prevRanges=[];this.subscription=new KM;this.mediaSource=e,this.sourceBuffer=t,this.subscription.add(zM(this.sourceBuffer,"updateend").subscribe(()=>this.updateend()))}updateend(){if(!Q(this.mediaSource,this.sourceBuffer))return;let{prevRanges:e}=this,t=_s(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 a=e[i],s=e[i+1],n=t[i],o=t[i+1];if(n>a||o<s)return!0}return!1}wasUpdated(){let{lastCallTs:e,lastUpdateTs:t}=this;return this.lastCallTs=Date.now(),e<=t}destroy(){this.subscription.unsubscribe()}};var ua=class{constructor(e,t,i,{fetcher:a,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new Jt(0);this.currentLowLatencySegmentLength$=new Jt(0);this.currentSegmentLength$=new Jt(0);this.onLastSegment$=new Jt(!1);this.fullyBuffered$=new Jt(!1);this.playingRepresentation$=new Jt(void 0);this.playingRepresentationInit$=new Jt(void 0);this.error$=new JM;this.gaps=[];this.subscription=new ZM;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new le;this.switchAbortController=new le;this.destroyAbortController=new le;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=At(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);Te(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new Zv(this.sourceBuffer),this.sourceBufferBufferedDiff=new Ns(this.mediaSource,this.sourceBuffer),this.subscription.add(sg(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:Xt.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o||!Q(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,Ku(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=Ge(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),a=this.segments.get(t.id),s=this.parsedInitData.get(t.id);Te(i,"No init buffer for starting representation"),Te(a,"No segments for starting representation"),i instanceof ArrayBuffer&&(this.searchGaps(a,t),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s))}.bind(this));this.switchTo=At(this.destroyAbortController.signal,async function*(e,t=!1){if(!Q(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);Te(i,`No such representation ${e}`);let a=this.segments.get(e),s=this.initData.get(e);if(ce(s)||ce(a)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),a=this.segments.get(e),Te(a,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!Q(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();Vi(n)&&!this.isLive&&(this.bufferLimit=1/0,await this.pruneBuffer(n,1/0,!0)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}this.maintain()}}.bind(this));this.switchToOld=At(this.destroyAbortController.signal,async function*(e,t=!1){if(!Q(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);Te(i,`No such representation ${e}`);let a=this.segments.get(e),s=this.initData.get(e);if(ce(s)||ce(a)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),a=this.segments.get(e),Te(a,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!Q(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();Vi(n)&&(this.isLive||(this.bufferLimit=1/0,await this.pruneBuffer(n,1/0,!0)),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}}.bind(this));this.seekLive=At(this.destroyAbortController.signal,async function*(e){let t=(0,Us.default)(e,u=>u.representations)??[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let u of this.representations.keys()){let l=t.find(p=>p.id===u);l&&this.representations.set(u,l);let d=this.representations.get(u);if(!d||!pe(d.segmentReference))return;let c=this.getActualLiveStartingSegments(d.segmentReference);this.segments.set(d.id,c)}let i=this.switchingToRepresentationId??this.downloadingRepresentationId,a=this.representations.get(i);Te(a);let s=this.segments.get(i);Te(s,"No segments for starting representation");let n=this.initData.get(i);if(Te(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer))return;let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(s,a),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));this.fetcher=a,this.tuning=s,this.compatibilityMode=u,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!l?.live,this.baseUrls=l?.baseUrls??[],this.initData=new Map(i.map(d=>[d.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(d=>[d.id,d])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchToWithPreviousAbort(e,t=!1){!Q(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new le,At(this.switchAbortController.signal,async function*(i,a=!1){this.switchingToRepresentationId=i;let s=this.representations.get(i);Te(s,`No such representation ${i}`);let n=this.segments.get(i),o=this.initData.get(i);if(ce(o)||ce(n)?yield this.loadInit(s,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(i),Te(n,"No segments for starting representation"),o=this.initData.get(i),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer||!Q(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(o,this.downloadAbortController.signal),a)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=i,yield this.dropBuffer();else{let u=this.getCurrentPosition();Vi(u)&&!this.isLive&&(this.bufferLimit=this.forwardBufferTarget,yield this.pruneBuffer(u,1/0,!0)),this.downloadingRepresentationId=i,this.switchingToRepresentationId=void 0}this.maintain()}}.bind(this))(e,t))}warmUpMediaSource(){!ce(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}async abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);return this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new le,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(ce(e)||ce(this.downloadingRepresentationId)||ce(this.playingRepresentationId)||ce(this.sourceBuffer)||!Q(this.mediaSource,this.sourceBuffer)||Vi(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(Te(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;let a=i.find(d=>e>=d.time.from&&e<d.time.to);Vi(a)&&isFinite(a.time.from)&&isFinite(a.time.to)&&this.currentSegmentLength$.next(a?.time.to-a.time.from);let s=e,n=100;if(this.playingRepresentationId!==this.downloadingRepresentationId){let d=Ge(this.sourceBuffer.buffered,e),c=a?a.time.to+n:-1/0;a&&a.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&d>=a.time.to-e+n&&(s=c)}if(isFinite(this.bufferLimit)&&Ku(this.sourceBuffer.buffered)>=this.bufferLimit){let d=Ge(this.sourceBuffer.buffered,e),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,d<c).catch(p=>{this.handleAsyncError(p,"pruneBuffer")});return}let u=null;if(!this.activeSegments.size&&(u=this.selectForwardBufferSegments(i,t.segmentReference.type,s),u?.length)){let d="auto";if(this.tuning.dash.useFetchPriorityHints&&a)if((0,qs.default)(u,a))d="high";else{let c=(0,Bi.default)(u,0);c&&c.time.from-a.time.to>=this.forwardBufferTarget/2&&(d="low")}this.loadSegments(u,t,d).catch(c=>{this.handleAsyncError(c,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&a&&a.status==="fed"&&!u?.length&&Ge(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let l=(0,Bi.default)(i,-1);!this.isLive&&l&&(this.fullyBuffered$.next(l.time.to-e-Ge(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,a=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+a,persistent:!0}),i=s.time.to;Vi(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,a=[],s=0,n=t.length-1;do a.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()?[a[0]]:a}getLiveSegmentsToLoadState(e){let t=(0,Us.default)(e?.streams[this.kind],a=>a.representations).find(a=>a.id===this.downloadingRepresentationId);if(!t)return;let i=this.segments.get(t.id);if(i?.length)return{from:i[0].time.from,to:i[i.length-1].time.to}}updateLive(e){let t=(0,Us.default)(e?.streams[this.kind],i=>i.representations)??[];if(![...this.segments.values()].every(i=>!i.length))for(let i of t){if(!i||!pe(i.segmentReference))return;let a=i.segmentReference.segments.map(l=>({...l,status:"none",size:void 0})),s=100,n=this.segments.get(i.id)??[],o=(0,Bi.default)(n,-1)?.time.to??0,u=a?.findIndex(l=>o>=l.time.from+s&&o<=l.time.to+s);if(u===-1){this.liveUpdateSegmentIndex=0;let l=this.getActualLiveStartingSegments(i.segmentReference);this.segments.set(i.id,l)}else{let l=a.slice(u+1);this.segments.set(i.id,[...n,...l])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;Te(e);let t=this.segments.get(e);if(t?.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}updateLowLatencyLiveIfNeeded(e){let t=0;for(let i of this.representations.values()){let a=i.segmentReference;if(!pe(a))return;let s=this.segments.get(i.id);if(!s)continue;let n=s.find(u=>Math.floor(u.time.from)===Math.floor(e.time.from));if(n&&!isFinite(n.time.to)&&(n.time.to=e.time.to,t=n.time.to-n.time.from),!!!s.find(u=>Math.floor(u.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let u=Math.round(e.time.to*a.timescale/1e3).toString(10),l=ht(a.segmentTemplateUrl,{segmentTime:u});s.push({status:"none",time:{from:e.time.to,to:1/0},url:l})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){let t=this.switchingToRepresentationId??this.downloadingRepresentationId??this.playingRepresentationId;if(!t)return;let i=this.segments.get(t);return i?i.find(s=>s.time.from<=e&&s.time.to>=e)?.time.from??void 0:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),this.sourceBufferTaskQueue?.destroy(),this.sourceBufferBufferedDiff?.destroy(),this.gapDetectionIdleCallback&&Cr&&Cr(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&Cr&&Cr(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(e){if(!(e instanceof DOMException&&e.name==="NotFoundError"))throw e}this.sourceBuffer=null,this.downloadAbortController.abort(),this.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,i){return this.checkEjectedSegments(),this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){if(this.playingRepresentationId!==this.downloadingRepresentationId){let i=e.findIndex(a=>t>=a.time.from&&t<a.time.to);this.liveUpdateSegmentIndex=i}return this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):null}selectForwardBufferSegmentsRecord(e,t,i){let a=e.findIndex(({status:c,time:{from:p,to:h}},f)=>{let b=p<=i&&h>=i,S=p>i||b||f===0&&i===0,v=Math.min(this.forwardBufferTarget,this.bufferLimit),P=this.preloadOnly&&p<=i+v||h<=i+v;return(c==="none"||c==="partially_ejected"&&S&&P&&this.sourceBuffer&&Q(this.mediaSource,this.sourceBuffer)&&!(kt(this.sourceBuffer.buffered,p)&&kt(this.sourceBuffer.buffered,h)))&&S&&P});if(a===-1)return null;if(t!=="byteRange")return e.slice(a,a+1);let s=e,n=0,o=0,u=[],l=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,d=this.preloadOnly?this.forwardBufferTarget:0;for(let c=a;c<s.length&&(n<=l||o<=d);c++){let p=s[c];if(n+=p.byte.to+1-p.byte.from,o+=p.time.to+1-p.time.from,p.status==="none"||p.status==="partially_ejected")u.push(p);else break}return u}async loadSegments(e,t,i="auto"){pe(t.segmentReference)?await this.loadTemplateSegment(e[0],t,i):await this.loadByteRangeSegments(e,t,i)}async loadTemplateSegment(e,t,i="auto"){e.status="downloading";let a={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(a);let{range:s,url:n,signal:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await At(o,async function*(){let d=hl(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,d))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let d=await this.fetcher.fetch(n,{range:s,signal:o,onProgress:u,priority:i,isLowLatency:this.isActiveLowLatency()});if(this.lastDataObtainedTimestampMs=Fs(),!d)return;let c=new DataView(d),p=na(t.mime);if(!isFinite(a.segment.time.to)){let b=t.segmentReference.timescale;a.segment.time.to=p.getChunkEndTime(c,b)}u&&a.feedingBytes&&l?await Promise.all(l):await this.sourceBufferTaskQueue.append(c,o);let{serverDataReceivedTimestamp:h,serverDataPreparedTime:f}=p.getServerLatencyTimestamps(c);h&&f&&this.currentLiveSegmentServerLatency$.next(f-h),a.segment.status="downloaded",this.onSegmentFullyAppended(a,t.id),this.failedDownloads=0}catch(d){this.abortActiveSegments([e]),oa(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())pe(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}async loadByteRangeSegments(e,t,i="auto"){if(!e.length)return;for(let u of e)u.status="downloading",this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:a,url:s,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(await At(n,async function*(){let u=hl(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),sg(window,"online").pipe(XM()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(s,{range:a,onProgress:o,signal:n,priority:i}),this.lastDataObtainedTimestampMs=Fs(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),oa(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(pe(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,a={from:(0,Bi.default)(e,0).byte.from,to:(0,Bi.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:i,range:a,signal:s,onProgress:async(o,u)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=Fs(),await this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:a?a.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:Xt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!pe(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 a=i.toString(),{signal:s}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,d)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=Fs();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:Xt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}}:void 0;return{url:a,signal:s,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,qs.default)(e,t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:a,signal:s}){if(!this.activeSegments.size||!Q(this.mediaSource,this.sourceBuffer))return;let n=this.representations.get(t);if(n)for(let o of this.activeSegments){let{segment:u}=o;if(o.representationId===t){if(s.aborted){a();continue}if(o.loadedBytes=i,o.loadedBytes>o.feedingBytes){let l=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),d=na(n.mime).parseFeedableSegmentChunk(l,this.isLive);d?.byteLength&&(u.status="partially_fed",o.feedingBytes+=d.byteLength,await this.sourceBufferTaskQueue.append(d),o.fedBytes+=d.byteLength)}}}}async onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:a,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size||!Q(this.mediaSource,this.sourceBuffer))return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){if(u.representationId!==t)continue;if(s.aborted){await n();continue}let{segment:l}=u,d=l.byte.from-i,c=l.byte.to-i,p=c-d+1,h=d<a,f=c<=a;if(h){if(l.status==="downloading"&&f){l.status="downloaded";let b=new DataView(e.buffer,e.byteOffset+d,p);await this.sourceBufferTaskQueue.append(b,s)&&!s.aborted?this.onSegmentFullyAppended(u,t):await n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(l.status==="downloading"||l.status==="partially_fed")&&(u.loadedBytes=Math.min(p,a-d),u.loadedBytes>u.feedingBytes)){let b=new DataView(e.buffer,e.byteOffset+d+u.feedingBytes,u.loadedBytes-u.feedingBytes),S=u.loadedBytes===p?b:na(o.mime).parseFeedableSegmentChunk(b);S?.byteLength&&(l.status="partially_fed",u.feedingBytes+=S.byteLength,await this.sourceBufferTaskQueue.append(S,s)&&!s.aborted?(u.fedBytes+=S.byteLength,u.fedBytes===p&&this.onSegmentFullyAppended(u,t)):await n())}}}}onSegmentFullyAppended(e,t){if(!(ce(this.sourceBuffer)||!Q(this.mediaSource,this.sourceBuffer))){!this.isLive&&C.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(kt(this.sourceBuffer.buffered,e.segment.time.from,100)&&kt(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:Xt.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",ll(e.segment)&&(e.segment.size=e.fedBytes);for(let i of this.representations.values()){if(i.id===t)continue;let a=this.segments.get(i.id);if(a)for(let s of a)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[a,s]of this.initData.entries()){let n=s instanceof Promise;t||=n,s===null&&(e=a)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let i=this.representations.get(e);i&&(this.initLoadIdleCallback=Yu(()=>(0,ng.default)(this.loadInit(i,"low",!1),()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",i=!1){let a=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!i&&this.failedDownloads>0?At(this.destroyAbortController.signal,async function*(){let o=hl(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,na(e.mime),a)).then(o=>{if(!o)return;let{init:u,dataView:l,segments:d}=o,c=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,c);let p=d;this.isLive&&pe(e.segmentReference)&&(p=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,p),u&&this.parsedInitData.set(e.id,u)}).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:Xt.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n}async dropBuffer(){for(let e of this.segments.values())for(let t of e)t.status="none";await this.pruneBuffer(0,1/0,!0)}async pruneBuffer(e,t,i=!1){if(!this.sourceBuffer||!Q(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||ce(e))return!1;this.checkEjectedSegments();let a=[],s=0,n=o=>{if(s>=t)return;a.push({...o.time});let u=ll(o)?o.size??0:o.byte.to-o.byte.from;s+=u};for(let o of this.segments.values())for(let u of o){let l=u.time.to<=e-this.tuning.dash.bufferPruningSafeZone,d=u.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(l||d)&&u.status==="fed"&&n(u)}for(let o=0;o<this.sourceBuffer.buffered.length;o++){let u=this.sourceBuffer.buffered.start(o)*1e3,l=this.sourceBuffer.buffered.end(o)*1e3,d=0;for(let c of this.segments.values())for(let p of c)(0,qs.default)(["none","partially_ejected"],p.status)&&Math.round(p.time.from)<=Math.round(u)&&Math.round(p.time.to)>=Math.round(l)&&d++;if(d===this.segments.size){let c={time:{from:u,to:l},url:"",status:"none"};n(c)}}if(a.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 a.length?(a=KS(a),(await Promise.all(a.map(u=>this.sourceBufferTaskQueue.remove(u.from,u.to)))).reduce((u,l)=>u||l,!1)):!1}async abortBuffer(){if(!this.sourceBuffer||!Q(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||!Q(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||!Q(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||!Q(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||ce(e)?0:Ge(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!this.sourceBuffer||!Q(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),o=Math.round(s.to);for(let u=0;u<i.length;u++)if(n>=Math.round(i.start(u)*1e3)&&o<=Math.round(i.end(u)*1e3))return!1;return!0}));let a={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,o=i.end(s)*1e3;if(!(o<=t.time.from||n>=t.time.to)){if(n<=t.time.from&&o>=t.time.to){a=void 0;break}o>t.time.from&&o<t.time.to&&(a.from=o),n<t.time.to&&n>t.time.from&&(a.to=n)}}a&&a.to-a.from>1&&!this.gaps.some(s=>a&&s.from===a.from&&s.to===a.to)&&this.gaps.push(a)}detectGapsWhenIdle(e,t){if(!(this.gapDetectionIdleCallback||!this.sourceBuffer||!Q(this.mediaSource,this.sourceBuffer))){if(!this.tuning.useRefactoredSearchGap)for(let i=0;i<this.sourceBuffer.buffered.length;i++)this.gaps=this.gaps.filter(a=>a.persistent||this.sourceBuffer&&(Math.round(a.from)<Math.round(this.sourceBuffer.buffered.start(i)*1e3)||Math.round(a.to)>Math.round(this.sourceBuffer.buffered.end(i)*1e3)));this.gapDetectionIdleCallback=Yu(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:Xt.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if(ce(this.sourceBuffer)||!Q(this.mediaSource,this.sourceBuffer)||ce(this.playingRepresentationId)||this.sourceBufferBufferedDiff&&!this.sourceBufferBufferedDiff.wasUpdated())return;let e=_s(this.sourceBuffer.buffered),t=100;for(let i of this.segments.values())for(let a of i){let{status:s}=a;if(s!=="fed"&&s!=="partially_ejected")continue;let n=Math.floor(a.time.from),o=Math.ceil(a.time.to),u=!1,l=0;for(let d=0;d<e.length;d+=2){let c=e[d],p=e[d+1];u||(u=c-t<=n&&p+t>=o),(n>=c&&n<p-t||o>c+t&&o<=p)&&(l+=1)}u||(l===1?a.status="partially_ejected":this.gaps.some(d=>d.from===a.time.from||d.to===a.time.to)?a.status="partially_ejected":a.status="none")}}handleAsyncError(e,t){this.error$.next({id:t,category:Xt.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}};var la=r=>{let e=new URL(r);return e.searchParams.set("quic","1"),e.toString()};var og=r=>{let e=r.get("X-Delivery-Type"),t=r.get("X-Reused"),i=e===null?"http1":e??void 0,a=t===null?void 0:{1:!0,0:!1}[t]??void 0;return{type:i,reused:a}};import{abortable as ca,assertNever as lg,fromEvent as cg,merge as e$,now as ml,Subject as dg,ValueSubject as fl,ErrorCategory as da,SubscriptionRemovable as t$}from"@vkontakte/videoplayer-shared";var ug=r=>{let e=new URL(r);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var js=class{constructor({throughputEstimator:e,requestQuic:t,compatibilityMode:i=!1,useEnableSubtitlesParam:a=!1}){this.lastConnectionType$=new fl(void 0);this.lastConnectionReused$=new fl(void 0);this.lastRequestFirstBytes$=new fl(void 0);this.recoverableError$=new dg;this.error$=new dg;this.abortAllController=new le;this.subscription=new t$;this.fetchManifest=ca(this.abortAllController.signal,async function*(e){let t=e;this.requestQuic&&(t=la(t)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(t=ug(t));let i=yield this.doFetch(t,{signal:this.abortAllController.signal}).catch(Hs);return i?(this.onHeadersReceived(i.headers),i.text()):null}.bind(this));this.fetch=ca(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:a,priority:s="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1}={}){let l=e,d=new Headers;if(i)switch(t){case 0:{d.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let T=new URL(l,location.href);T.searchParams.append("bytes",`${i.from}-${i.to}`),l=T.toString();break}default:lg(t)}this.requestQuic&&(l=la(l));let c=this.abortAllController.signal,p;if(n){let T=new le;if(p=e$(cg(this.abortAllController.signal,"abort"),cg(n,"abort")).subscribe(()=>{try{T.abort()}catch(g){Hs(g)}}),this.abortAllController.signal.aborted||n.aborted)try{T.abort()}catch(g){Hs(g)}c=T.signal}let h=ml(),f=yield this.doFetch(l,{priority:s,headers:d,signal:c}),b=ml();if(!f)return this.unsubscribeAbortSubscription(p),null;if(this.throughputEstimator?.addRawRtt(b-h),!f.ok||!f.body)return this.unsubscribeAbortSubscription(p),Promise.reject(new Error(`Fetch error ${f.status}: ${f.statusText}`));if(this.onHeadersReceived(f.headers),!a&&!o)return this.unsubscribeAbortSubscription(p),f.arrayBuffer();let S=f.body;if(o){let T;[S,T]=f.body.tee(),this.throughputEstimator?.trackStream(T,u)}let v=S.getReader(),P,y=parseInt(f.headers.get("content-length")??"",10);Number.isFinite(y)&&(P=y),!P&&i&&(P=i.to-i.from+1);let I=0,k=P?new Uint8Array(P):new Uint8Array(0),H=!1,j=T=>{this.unsubscribeAbortSubscription(p),H=!0,Hs(T)},U=ca(c,async function*({done:T,value:g}){if(I===0&&this.lastRequestFirstBytes$.next(ml()-h),c.aborted){this.unsubscribeAbortSubscription(p);return}if(!T&&g){if(P)k.set(g,I),I+=g.byteLength;else{let N=new Uint8Array(k.length+g.length);N.set(k),N.set(g,k.length),k=N,I+=g.byteLength}a?.(new DataView(k.buffer),I),yield v?.read().then(U,j)}}.bind(this));return yield v?.read().then(U,j),this.unsubscribeAbortSubscription(p),H?null:k.buffer}.bind(this));this.fetchByteRangeRepresentation=ca(this.abortAllController.signal,async function*(e,t,i){if(e.type!=="byteRange")return null;let{from:a,to:s}=e.initRange,n=a,o=s,u=!1,l,d;e.indexRange&&(l=e.indexRange.from,d=e.indexRange.to,u=s+1===l,u&&(n=Math.min(l,a),o=Math.max(d,s))),n=Math.min(n,0);let c=yield this.fetch(e.url,{range:{from:n,to:o},priority:i,measureThroughput:!1});if(!c)return null;let p=new DataView(c,a-n,s-n+1);if(!t.validateData(p))throw new Error("Invalid media file");let h=t.parseInit(p),f=e.indexRange??t.getIndexRange(h);if(!f)throw new ReferenceError("No way to load representation index");let b;if(u)b=new DataView(c,f.from-n,f.to-f.from+1);else{let v=yield this.fetch(e.url,{range:f,priority:i,measureThroughput:!1});if(!v)return null;b=new DataView(v)}let S=t.parseSegments(b,h,f);return{init:h,dataView:new DataView(c),segments:S}}.bind(this));this.fetchTemplateRepresentation=ca(this.abortAllController.signal,async function*(e,t){if(e.type!=="template")return null;let i=new URL(e.initUrl,e.baseUrl).toString(),a=yield this.fetch(i,{priority:t,measureThroughput:!1});return a?{init:null,segments:e.segments.map(n=>({...n,status:"none",size:void 0})),dataView:new DataView(a)}:null}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=i,this.useEnableSubtitlesParam=a}onHeadersReceived(e){let{type:t,reused:i}=og(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,t,i="auto"){let{type:a}=e;switch(a){case"byteRange":return await this.fetchByteRangeRepresentation(e,t,i)??null;case"template":return await this.fetchTemplateRepresentation(e,i)??null;default:lg(a)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}async doFetch(e,t){let i=await rt(e,t);if(i.ok)return i;let a=await i.text(),s=parseInt(a);if(!isNaN(s))switch(s){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:da.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:da.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:da.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:da.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${s})`,category:da.FATAL})}}unsubscribeAbortSubscription(e){e&&(e.unsubscribe(),this.subscription.remove(e))}},Hs=r=>{if(!oa(r))throw r};var Zt=(r,e,t)=>t*e+(1-t)*r,bl=(r,e)=>r.reduce((t,i)=>t+i,0)/e,pg=(r,e,t,i)=>{let a=0,s=t,n=bl(r,e),o=e<i?e:i;for(let u=0;u<o;u++)r[s]>n?a++:a--,s=(r.length+s-1)%r.length;return Math.abs(a)===o};import{isNullable as i$,ValueSubject as hg}from"@vkontakte/videoplayer-shared";var Rt=class{constructor(e){this.prevReported=void 0;this.pastMeasures=[];this.takenMeasures=0;this.measuresCursor=0;this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new hg(e.initial),this.debounced$=new hg(e.initial)}next(e){let t=0,i=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=(this.pastMeasures[o]-this.smoothed)**2,i++);this.takenMeasures=i,t/=i;let a=Math.sqrt(t),s=this.smoothed+this.params.deviationFactor*a,n=this.smoothed-this.params.deviationFactor*a;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),!(this.smoothed>s||this.smoothed<n)&&(i$(this.prevReported)||Math.abs(this.smoothed-this.prevReported)/this.prevReported>=this.params.changeThreshold)&&(this.prevReported=this.smoothed,this.debounced$.next(this.smoothed))}};var Gs=class extends Rt{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=Zt(this.slow,e,this.params.emaAlphaSlow),this.fast=Zt(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var Qs=class extends Rt{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=bl(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Zt(this.emaSmoothed,e,this.params.emaAlpha);let i=pg(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}};var Ws=class extends Rt{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?Zt(this.smoothed,t,this.params.emaAlpha):t}};var ei=class{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new Gs({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new Qs({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 Ws({initial:e,label:"liveEdgeDelay",...t})}};var vl=(r,e)=>{r&&r.playbackRate!==e&&(r.playbackRate=e)};import{isNullable as r$,ValueSubject as a$}from"@vkontakte/videoplayer-shared";var pa=class r{constructor(e,t){this.currentRepresentation$=new a$(null);this.maxRepresentations=4;this.representationsCursor=0;this.representations=[];this.currentSegment=null;this.getCurrentPosition=t.getCurrentPosition,this.processStreams(e)}updateLive(e){this.processStreams(e?.streams.text)}seekLive(e){this.processStreams(e)}maintain(e=this.getCurrentPosition()){if(!r$(e))for(let t of this.representations)for(let i of t){let a=i.segmentReference,s=a.segments.length,n=a.segments[0].time.from,o=a.segments[s-1].time.to;if(e<n||e>o)continue;let u=a.segments.find(l=>l.time.from<=e&&l.time.to>=e);!u||this.currentSegment?.time.from===u.time.from&&this.currentSegment.time.to===u.time.to||(this.currentSegment=u,this.currentRepresentation$.next({...i,label:"Live Text",language:"ru",isAuto:!0,url:new URL(u.url,a.baseUrl).toString()}))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e??[]){let i=r.filterRepresentations(t.representations);if(i){this.representations[this.representationsCursor]=i,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!e?.some(t=>r.filterRepresentations(t.representations))}static filterRepresentations(e){return e?.filter(t=>t.kind==="text"&&"segmentReference"in t&&pe(t.segmentReference))}};var zs=D(Et(),1);import{assertNever as Ks}from"@vkontakte/videoplayer-shared";var mg=(r,{useHlsJs:e,useManagedMediaSource:t,useOldMSEDetection:i})=>{let{containers:a,protocols:s,codecs:n,nativeHlsSupported:o}=C.video,u=(n.h264||n.h265)&&n.aac,l=s.mse&&(!i||!!window.MediaStreamTrack)||s.mms&&t;return r.filter(d=>{switch(d){case"DASH_SEP":return l&&a.mp4&&u;case"DASH_WEBM":return l&&a.webm&&n.vp9&&n.opus;case"DASH_WEBM_AV1":return l&&a.webm&&n.av1&&n.opus;case"DASH_STREAMS":return l&&(a.mp4&&u||a.webm&&(n.vp9||n.av1)&&(n.opus||n.aac));case"DASH_LIVE":return l&&a.mp4&&u;case"DASH_LIVE_CMAF":return l&&a.mp4&&u&&a.cmaf;case"DASH_ONDEMAND":return l&&a.mp4&&u;case"HLS":case"HLS_ONDEMAND":return o||e&&l&&a.mp4&&u;case"HLS_LIVE":case"HLS_LIVE_CMAF":return o;case"MPEG":return a.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return s.webrtc&&s.ws&&n.h264&&(a.mp4||a.webm);default:return Ks(d)}})},Ys=r=>{let{webmDecodingInfo:e}=C.video,t="DASH_WEBM",i="DASH_WEBM_AV1";switch(r){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:Ks(r)}return[t,i]},fg=({webmCodec:r,androidPreferredFormat:e,preferMultiStream:t})=>{let i=[...t?["DASH_STREAMS"]:[],...Ys(r),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],a=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(C.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[...a,"MPEG",...Ys(r),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...Ys(r),"MPEG",...a,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...Ys(r),...a,"HLS","HLS_ONDEMAND"];default:Ks(e)}return C.video.nativeHlsSupported?[...i,"HLS","HLS_ONDEMAND","MPEG"]:[...i,"HLS","HLS_ONDEMAND","MPEG"]},bg=({androidPreferredFormat:r,preferCMAF:e,preferWebRTC:t})=>{let i=e?["DASH_LIVE_CMAF","DASH_LIVE"]:["DASH_LIVE","DASH_LIVE_CMAF"],a=e?["HLS_LIVE_CMAF","HLS_LIVE"]:["HLS_LIVE","HLS_LIVE_CMAF"],s=[...i,...a],n=[...a,...i],o,u=C.device.isMac&&C.browser.isSafari;if(C.device.isAndroid)switch(r){case"dash":case"dash_any_mpeg":case"dash_any_webm":case"dash_sep":{o=s;break}case"hls":case"mpeg":{o=n;break}default:Ks(r)}else C.video.nativeHlsSupported&&!u?o=n:u?o=e?["DASH_LIVE_CMAF","HLS_LIVE_CMAF","HLS_LIVE","DASH_LIVE"]:["HLS_LIVE","DASH_LIVE","DASH_LIVE_CMAF","HLS_LIVE_CMAF"]:o=s;return t?["WEB_RTC_LIVE",...o]:[...o,"WEB_RTC_LIVE"]},Sl=r=>r?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],vg=r=>{if(r.size===0)return;if(r.size===1){let t=r.values().next();return(0,zs.default)(t.value.split("."),0)}for(let t of r){let i=(0,zs.default)(t.split("."),0);if(i==="opus"||i==="vp09"||i==="av01")return i}let e=r.values().next();return(0,zs.default)(e.value.split("."),0)};var c$=["timeupdate","progress","play","seeked","stalled","waiting"],d$=["timeupdate","progress","loadeddata","playing","seeked"];var en=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new Il;this.representationSubscription=new Il;this.state$=new A("none");this.currentVideoRepresentation$=new W(void 0);this.currentVideoRepresentationInit$=new W(void 0);this.currentAudioRepresentation$=new W(void 0);this.currentVideoSegmentLength$=new W(0);this.currentAudioSegmentLength$=new W(0);this.error$=new Zs;this.lastConnectionType$=new W(void 0);this.lastConnectionReused$=new W(void 0);this.lastRequestFirstBytes$=new W(void 0);this.currentLiveTextRepresentation$=new W(null);this.isLive$=new W(!1);this.isActiveLive$=new W(!1);this.isLowLatency$=new W(!1);this.liveDuration$=new W(0);this.liveSeekableDuration$=new W(0);this.liveAvailabilityStartTime$=new W(0);this.liveStreamStatus$=new W(void 0);this.bufferLength$=new W(0);this.liveLatency$=new W(void 0);this.liveLoadBufferLength$=new W(0);this.livePositionFromPlayer$=new W(0);this.currentStallDuration$=new W(0);this.videoLastDataObtainedTimestamp$=new W(0);this.fetcherRecoverableError$=new Zs;this.fetcherError$=new Zs;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new Zs;this.gapWatchdogActive=!1;this.destroyController=new le;this.initedPruneBufferCallback=!1;this.initManifest=yl(this.destroyController.signal,async function*(e,t,i){this.element=e,this.manifestUrlString=ue(t,i,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),this.manifest?.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:at.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=yl(this.destroyController.signal,async function*(){let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(n=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:at.NETWORK,message:"Failed to load manifest",thrown:n})});if(!e)return null;let t=null;try{t=rg(e??"",this.manifestUrlString)}catch(n){let o=Wv(e)??{id:"ManifestParsing",category:at.PARSER,message:"Failed to parse MPD manifest",thrown:n};this.error$.next(o)}if(!t)return null;let i=(n,o,u)=>!!(this.element?.canPlayType?.(o)&&je()?.isTypeSupported?.(`${o}; codecs="${u}"`)||n==="text");if(t.live){this.isLive$.next(!!t.live);let{availabilityStartTime:n,latestSegmentPublishTime:o,streamIsUnpublished:u,streamIsAlive:l}=t.live,d=(t.duration??0)/1e3;this.liveSeekableDuration$.next(-1*d),this.liveDuration$.next((o-n)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let c="active";l||(c=u?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(c)}let a={text:t.streams.text,video:[],audio:[]};for(let n of["video","audio"]){let u=t.streams[n].filter(({mime:c,codecs:p})=>i(n,c,p)),l=new Set(u.map(({codecs:c})=>c)),d=vg(l);if(d&&(a[n]=u.filter(({codecs:c})=>c.startsWith(d))),n==="video"){let c=this.tuning.preferHDR,p=a.video.some(f=>f.hdr),h=a.video.some(f=>!f.hdr);C.display.isHDR&&c&&p?a.video=a.video.filter(f=>f.hdr):h&&(a.video=a.video.filter(f=>!f.hdr))}}return{...t,streams:a}}.bind(this));this.initRepresentations=yl(this.destroyController.signal,async function*(e,t,i){Oi(this.manifest),Oi(this.element),this.representationSubscription.unsubscribe(),this.representationSubscription=new Il,this.state$.startTransitionTo("representations_ready");let a=p=>{this.representationSubscription.add(Ae(p,"error").pipe(Xs(h=>!!this.element?.played.length)).subscribe(h=>{this.error$.next({id:"VideoSource",category:at.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=this.tuning.useManagedMediaSource?fb():new MediaSource;let s=document.createElement("source");if(a(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&Ps())if(i){let p=document.createElement("source");a(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 ua("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],Ni(t)){let p=this.manifest.streams.audio.reduce((h,f)=>[...h,...f.representations],[]);this.audioBufferManager=new ua("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}pa.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new pa(this.manifest.streams.text,n)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$));let u=()=>{this.stallWatchdogSubscription?.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add(ti(...d$.map(p=>Ae(this.element,p))).pipe(Fi(p=>this.element?Ge(this.element.buffered,this.element.currentTime*1e3):0),ha(),El(p=>{p>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add(ti(Ae(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe(ha()).subscribe(h=>this.liveStreamEndTimestamp=Tl())),this.subscription.add(Ae(this.element,"pause").subscribe(()=>{this.livePauseWatchdogSubscription=Js(1e3).subscribe(h=>{let f=gs(this.manifestUrlString,2);this.manifestUrlString=ue(this.manifestUrlString,f+1e3,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add(Ae(this.element,"play").subscribe(h=>this.livePauseWatchdogSubscription?.unsubscribe())),this.representationSubscription.add(_i({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(Fi(({isActiveLive:h,isLowLatency:f})=>h&&f),ha()).subscribe(h=>{this.isManualDecreasePlaybackInLive()||vl(this.element,1)})),this.representationSubscription.add(_i({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(Xs(({bufferLength:h,isActiveLive:f,isLowLatency:b})=>f&&b&&!!h)).subscribe(({bufferLength:h})=>this.liveBuffer.next(h))),this.representationSubscription.add(this.videoBufferManager.currentLowLatencySegmentLength$.subscribe(h=>{if(!this.isActiveLive$.getValue()&&!this.isLowLatency$.getValue()&&!h)return;let f=this.liveSeekableDuration$.getValue()-h/1e3;this.liveSeekableDuration$.next(Math.max(f,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+h/1e3)})),this.representationSubscription.add(_i({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(Xs(({isLive:h})=>h),ha((h,f)=>f.bufferLength<h.bufferLength),Fi(({rtt:h,bufferLength:f,segmentServerLatency:b})=>{let S=gs(this.manifestUrlString,2);return(h/2+f+b+S)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(_i({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:h,isActiveLive:f,isLowLatency:b})=>{if(!b||!f)return;let S=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,v=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,P=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,y=h-S;if(this.isManualDecreasePlaybackInLive())return;let I=1;Math.abs(y)>v&&(I=1+Math.sign(y)*P),vl(this.element,I)})),this.representationSubscription.add(this.bufferLength$.subscribe(h=>{let f=0;if(h){let b=(this.element?.currentTime??0)*1e3;f=Math.min(...this.bufferManagers.map(v=>v.getLiveSegmentsToLoadState(this.manifest)?.to??b))-b}this.liveLoadBufferLength$.getValue()!==f&&this.liveLoadBufferLength$.next(f)}));let p=0;this.representationSubscription.add(_i({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(yg(1e3)).subscribe(async({liveLoadBufferLength:h,bufferLength:f})=>{if(!this.element||this.isUpdatingLive)return;let b=this.element.playbackRate,S=gs(this.manifestUrlString,2),v=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,P=Math.min(v,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*b),y=this.tuning.dashCmafLive.normalizedActualBufferOffset*b,I=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*b,k=isFinite(h)?h:f,H=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),j=v<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(j);let U="none";if(H?U="active_low_latency":this.isLowLatency$.getValue()&&j?(this.bufferManagers.forEach(T=>T.proceedLowLatencyLive()),U="active_low_latency"):S!==0&&k<P?U="live_forward_buffering":k<P+I&&(U="live_with_target_offset"),isFinite(h)&&(p=h>p?h:p),U==="live_forward_buffering"||U==="live_with_target_offset"){let T=p-(P+y),g=this.normolizeLiveOffset(Math.trunc(S+T/b)),N=Math.abs(g-S),M=0;!h||N<=this.tuning.dashCmafLive.offsetCalculationError?M=S:g>0&&N>this.tuning.dashCmafLive.offsetCalculationError&&(M=g),this.manifestUrlString=ue(this.manifestUrlString,M,2)}(U==="live_with_target_offset"||U==="live_forward_buffering")&&(p=0,await this.updateLive())},h=>{this.error$.next({id:"updateLive",category:at.VIDEO_PIPELINE,thrown:h,message:"Failed to update live with subscription"})}))}let l=ti(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe(Fi(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),d=ti(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe(Fi(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue()))),c=_i({allBuffersFull:l,someBufferEnded:d}).pipe(ha(),Fi(({allBuffersFull:p,someBufferEnded:h})=>p&&h),Xs(p=>p));if(this.representationSubscription.add(Ae(this.source,"sourceopen").subscribe(p=>console.log("sourceopen"))).add(Ae(this.source,"sourceclose").subscribe(p=>console.log("sourceclose"))).add(Ae(this.source,"sourceended").subscribe(p=>console.log("sourceended"))),this.representationSubscription.add(ti(this.forceEnded$.pipe(El(p=>console.log("forceEnded$"))),c.pipe(El(p=>console.log("streamEnded$")))).subscribe(()=>{if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(p=>!p.updating))try{console.log("endOfStream"),this.source?.endOfStream()}catch(p){this.error$.next({id:"EndOfStream",category:at.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:p})}})),this.representationSubscription.add(ti(...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,f)=>{p&&(this.timeoutSourceOpenId=setTimeout(()=>{if(this.source?.readyState==="open"){h();return}this.tuning.dash.rejectOnSourceOpenTimeout?f(new Error("Timeout reject when wait sourceopen event")):h()},this.tuning.dash.sourceOpenTimeout)),this.source?.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),h()},{once:!0})})}if(!this.isLive$.getValue()){let p=[this.manifest.duration??0,...(0,xl.default)((0,xl.default)([...this.manifest.streams.audio,...this.manifest.streams.video],h=>h.representations),h=>{let f=[];return h.duration&&f.push(h.duration),pe(h.segmentReference)&&h.segmentReference.totalSegmentsDurationMs&&f.push(h.segmentReference.totalSegmentsDurationMs),f})];this.source.duration=Math.max(...p)/1e3}this.audioBufferManager&&Ni(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready")}.bind(this));this.tick=()=>{if(!this.element||!this.videoBufferManager||this.source?.readyState!=="open")return;let e=this.element.currentTime*1e3;console.log("tick maintain"),this.videoBufferManager.maintain(e),this.audioBufferManager?.maintain(e),this.liveTextManager?.maintain(e),(this.videoBufferManager.gaps.length||this.audioBufferManager?.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=Js(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:at.WTF,message:"Error handling gaps",thrown:t})}),this.subscription.add(this.gapWatchdogSubscription)),typeof this.tuning.dash.pruneBufferInterval=="number"&&!this.initedPruneBufferCallback&&(this.initedPruneBufferCallback=!0,this.subscription.add(Js(this.tuning.dash.pruneBufferInterval).subscribe(()=>{if(Ni(this.element)){let t=this.element.currentTime*1e3;this.bufferManagers.forEach(i=>{i.pruneBuffer(t,1/0)})}})))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new js({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.subscription.add(this.fetcher.recoverableError$.subscribe(this.fetcherRecoverableError$)),this.subscription.add(this.fetcher.error$.subscribe(this.fetcherError$)),this.liveBuffer=ei.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator})}async seekLive(e){Oi(this.element);let t=this.liveStreamStatus$.getValue()!=="active"?Tl()-this.liveStreamEndTimestamp:0,i=this.normolizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=ue(this.manifestUrlString,i,2),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await this.videoBufferManager?.seekLive(this.manifest.streams.video),await this.audioBufferManager?.seekLive(this.manifest.streams.audio),this.liveTextManager?.seekLive(this.manifest.streams.text))}initBuffer(){Oi(this.element),this.state$.setState("running"),this.subscription.add(ti(...c$.filter(e=>e!=="timeupdate").map(e=>Ae(this.element,e)),Ae(window,"online"),Ae(this.element,"timeupdate").pipe(yg(300))).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:at.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(Ae(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(Ae(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===HTMLMediaElement.HAVE_CURRENT_DATA&&!this.element.seeking&&kt(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{if(!this.element||this.source?.readyState!=="open")return;let t=this.currentStallDuration$.getValue();t+=50,this.currentStallDuration$.next(t);let i={timeInWaiting:t},a=Tl(),s=100,n=this.videoBufferManager?.lastDataObtainedTimestamp??0;this.videoLastDataObtainedTimestamp$.next(n);let o=this.audioBufferManager?.lastDataObtainedTimestamp??0,u=this.videoBufferManager?.getForwardBufferDuration()??0,l=this.audioBufferManager?.getForwardBufferDuration()??0,d=u<s&&a-n>this.tuning.dash.crashOnStallTWithoutDataTimeout,c=this.audioBufferManager&&l<s&&a-o>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((d||c)&&t>this.tuning.dash.crashOnStallTWithoutDataTimeout||t>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${t} ms`);if(this.isLive$.getValue()&&t%2e3===0){let p=this.normolizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(p).catch(h=>{this.error$.next({id:"stallIntervalCallback",category:at.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:h})}),i.liveLastOffset=p}else{let p=this.element.currentTime*1e3;console.log("stall maintain"),this.videoBufferManager?.maintain(p),this.audioBufferManager?.maintain(p),i.position=p}};this.stallWatchdogSubscription?.unsubscribe(),this.stallWatchdogSubscription=Js(50).subscribe(e,t=>{this.error$.next({id:"StallWatchdogCallback",category:at.NETWORK,message:"Can't restore DASH after stall.",thrown:t})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,i=!1){let a={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return this.tuning.useNewSwitchTo?this.currentStallDuration$.getValue()>0?a?.switchToWithPreviousAbort(t,i):a?.switchTo(t,i):a?.switchToOld(t,i)}async seek(e,t){Oi(this.element),Oi(this.videoBufferManager);let i;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?i=e:i=Math.max(this.videoBufferManager.findSegmentStartTime(e)??e,this.audioBufferManager?.findSegmentStartTime(e)??e),this.warmUpMediaSourceIfNeeded(i),kt(this.element.buffered,i)||await Promise.all([this.videoBufferManager.abort(),this.audioBufferManager?.abort()]),!(gg(this.element)||gg(this.videoBufferManager))&&(console.log("seek maintain"),this.videoBufferManager.maintain(i),this.audioBufferManager?.maintain(i),this.element.currentTime=i/1e3)}warmUpMediaSourceIfNeeded(e=this.element?.currentTime){Ni(this.element)&&Ni(this.source)&&Ni(e)&&this.source?.readyState==="ended"&&this.element.duration*1e3-e>this.tuning.dash.seekBiasInTheEnd&&(console.log("warmUpMediaSourceIfNeeded"),this.bufferManagers.forEach(t=>t.warmUpMediaSource()))}get isStreamEnded(){return this.source?.readyState==="ended"}stop(){this.element?.querySelectorAll("source").forEach(e=>{URL.revokeObjectURL(e.src),e.remove()}),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),this.videoBufferManager?.destroy(),this.videoBufferManager=null,this.audioBufferManager?.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){return this.manifest?.streams}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),this.source?.readyState==="open"&&Array.from(this.source.sourceBuffers).every(e=>!e.updating)&&this.source.endOfStream(),this.source=null}isManualDecreasePlaybackInLive(){return!this.element||!this.isLive$.getValue()?!1:1-this.element.playbackRate>this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&(this.bufferManagers?.forEach(e=>e.updateLive(this.manifest)),this.liveTextManager?.updateLive(this.manifest)),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getBufferedTo();if(e===null)return;let t=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue();this.isJumpGapAfterSeekLive&&!t&&this.element.currentTime>e&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let i=this.element.currentTime*1e3,a=null,s=this.element.readyState===HTMLMediaElement.HAVE_METADATA?this.tuning.endGapTolerance:0;for(let n of this.bufferManagers)for(let o of n.gaps)(o.persistent||n.playingRepresentation$.getValue()===o.representation)&&o.from-s<=i&&o.to+s>i&&(this.element.duration*1e3-o.to<this.tuning.endGapTolerance?a=1/0:(a===null||o.to>a)&&(a=o.to));if(a!==null){let n=a+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,n===1/0?this.forceEnded$.next():(console.log("JUMP TO "+n/1e3),this.element.currentTime=n/1e3)}}};var tn=class{constructor(e,t){this.fov=e,this.orientation=t}};var rn=class{constructor(e,t){this.rotating=!1;this.fading=!1;this.lastTickTS=0;this.lastCameraTurnTS=0;this.fadeStartSpeed=null;this.fadeTime=0;this.camera=e,this.options=t,this.rotationSpeed={x:0,y:0,z:0},this.fadeCorrection=1/(this.options.speedFadeTime/1e3)**2}turnCamera(e=0,t=0,i=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+i)}pointCameraTo(e=0,t=0,i=0){t=this.limitCameraRotationY(t);let a=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:a,y:s,z:n},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,i){this.rotationSpeed.x=e??this.rotationSpeed.x,this.rotationSpeed.y=t??this.rotationSpeed.y,this.rotationSpeed.z=i??this.rotationSpeed.z}startRotation(){this.rotating=!0}stopRotation(e=!1){e?(this.setRotationSpeed(0,0,0),this.fadeStartSpeed=null):this.startFading(this.rotationSpeed.x,this.rotationSpeed.y,this.rotationSpeed.z),this.rotating=!1}onCameraRelease(){if(this.lastCameraTurn&&this.lastCameraTurnTS){let e=Date.now()-this.lastCameraTurnTS;if(e<this.options.speedFadeThreshold){let t=(1-e/this.options.speedFadeThreshold)*this.options.rotationSpeedCorrection;this.startFading(this.lastCameraTurn.x*t,this.lastCameraTurn.y*t,this.lastCameraTurn.z*t)}}}startFading(e,t,i){this.setRotationSpeed(e,t,i),this.fadeStartSpeed={...this.rotationSpeed},this.fading=!0}stopFading(){this.fadeStartSpeed=null,this.fading=!0,this.fadeTime=0}limitCameraRotationY(e){return Math.max(-this.options.maxYawAngle,Math.min(e,this.options.maxYawAngle))}tick(e){if(!this.lastTickTS){this.lastTickTS=e,this.lastCameraTurnTS=Date.now();return}let t=e-this.lastTickTS,i=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i);else if(this.fading&&this.fadeStartSpeed){let a=-this.fadeCorrection*(this.fadeTime/1e3)**2+1;this.setRotationSpeed(this.fadeStartSpeed.x*a,this.fadeStartSpeed.y*a,this.fadeStartSpeed.z*a),a>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 Tg=`attribute vec2 a_vertex;
71
15
  attribute vec2 a_texel;
72
16
 
73
17
  varying vec2 v_texel;
@@ -78,7 +22,7 @@ void main(void) {
78
22
  // save texel vector to pass to fragment shader
79
23
  v_texel = a_texel;
80
24
  }
81
- `;var DS=`#ifdef GL_ES
25
+ `;var Ig=`#ifdef GL_ES
82
26
  precision highp float;
83
27
  precision highp int;
84
28
  #else
@@ -121,6 +65,6 @@ void main(void) {
121
65
  // sample using new coordinates
122
66
  gl_FragColor = texture2D(u_texture, tc);
123
67
  }
124
- `;var ln=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 a=this.canvas.getContext("webgl");if(!a)throw new Error("Could not initialize WebGL context");this.gl=a,this.container.appendChild(this.canvas),this.camera=new on(this.params.fov,this.params.orientation),this.cameraRotationManager=new un(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"),a=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(a,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(CS,this.gl.VERTEX_SHADER),i=this.createShader(DS,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,a=this.frameHeight/(this.frameWidth/this.viewportWidth);return a>this.viewportHeight?t=this.viewportHeight/a:i=a/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,a=this.camera.fov.y/180/2,s=e-i,n=t-a,o=e+i,u=t-a,l=e+i,c=t+a,d=e-i,p=t+a;return[s,n,o,u,l,c,d,p]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){let e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}};import{isNullable as $M,now as VS,Subscription as MM,filter as CM,combine as BS,debounce as DM,ValueSubject as $l,isNonNullable as VM}from"@vkontakte/videoplayer-shared";var Ml=class{constructor(){this.isSeeked$=new $l(!1);this.isBuffering$=new $l(!1);this.currentStallsCount=0;this.maxQualityLimit=void 0;this.lastUniqueVideoTrackSelectedTimestamp=0;this.predictedThroughputWithoutData=0;this.subscription=new MM;this.severeStallOccurred$=new $l(!1)}connect(e){this.currentStallDuration$=e.currentStallDuration$,this.videoLastDataObtainedTimestamp$=e.videoLastDataObtainedTimestamp$,this.throughput$=e.throughput$,this.rtt$=e.rtt$,this.qualityLimitsOnStall=e.qualityLimitsOnStall,this.subscription.add(e.isSeeked$.subscribe(this.isSeeked$)),this.subscription.add(e.isBuffering$.subscribe(this.isBuffering$)),this.subscription.add(e.looped$.subscribe(t=>this.currentStallsCount=0)),this.subscription.add(BS({isBuffering:this.isBuffering$,isSeeked:this.isSeeked$}).pipe(DM(this.qualityLimitsOnStall.stallDurationToBeCount),CM(({isBuffering:t,isSeeked:i})=>t&&!i)).subscribe(t=>{this.currentStallsCount++})),this.subscription.add(BS({currentStallDuration:this.currentStallDuration$}).subscribe(({currentStallDuration:t})=>{let{stallDurationNoDataBeforeQualityDecrease:i,stallCountBeforeQualityDecrease:a,resetQualityRestrictionTimeout:s,ignoreStallsOnSeek:n}=this.qualityLimitsOnStall;if($M(this.lastUniqueVideoTrackSelected)||n&&this.isSeeked$.getValue())return;let o=this.rtt$.getValue(),u=this.throughput$.getValue(),l=this.videoLastDataObtainedTimestamp$.getValue(),c=VS(),d=a&&this.currentStallsCount>=a,p=i&&c-this.lastUniqueVideoTrackSelectedTimestamp>=i+o&&c-l>=i+o&&t>=i;(d||p)&&(this.severeStallOccurred$.next(!0),window.clearTimeout(this.qualityRestrictionTimer),this.maxQualityLimit=this.lastUniqueVideoTrackSelected.quality,VM(this.lastUniqueVideoTrackSelected.bitrate)&&u>this.lastUniqueVideoTrackSelected.bitrate&&(this.predictedThroughputWithoutData=this.lastUniqueVideoTrackSelected.bitrate)),t||(this.severeStallOccurred$.next(!1),window.clearTimeout(this.qualityRestrictionTimer),this.qualityRestrictionTimer=window.setTimeout(()=>{this.maxQualityLimit=void 0,this.predictedThroughputWithoutData=0},s))}))}get videoMaxQualityLimit(){return this.maxQualityLimit}get predictedThroughput(){return this.predictedThroughputWithoutData}set lastVideoTrackSelected(e){this.lastUniqueVideoTrackSelected?.id!==e.id&&(this.lastUniqueVideoTrackSelected=e,this.lastUniqueVideoTrackSelectedTimestamp=VS(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe()}},OS=Ml;import{combine as BM,map as OM,observeElementSize as _M,Subscription as NM,ValueSubject as Cl,noop as FM}from"@vkontakte/videoplayer-shared";var cn=class{constructor(){this.subscription=new NM;this.pipSize$=new Cl(void 0);this.videoSize$=new Cl(void 0);this.elementSize$=new Cl(void 0);this.pictureInPictureWindowRemoveEventListener=FM}connect({observableVideo:e,video:t}){let i=a=>{let s=a.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add(_M(t).subscribe(this.videoSize$)).add(e.enterPip$.subscribe(({pictureInPictureWindow:a})=>{this.pipSize$.next({width:a.width,height:a.height}),a.addEventListener("resize",i),this.pictureInPictureWindowRemoveEventListener=()=>{a.removeEventListener("resize",i)}})).add(e.leavePip$.subscribe(()=>{this.pictureInPictureWindowRemoveEventListener()})).add(BM({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(OM(({videoSize:a,inPip:s,pipSize:n})=>s?n:a)).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 ni=class{constructor(e){this.subscription=new GM;this.videoState=new D("stopped");this.droppedFramesManager=new qs;this.stallsManager=new OS;this.elementSizeManager=new cn;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Lr;this.audioTrackSwitchHistory=new Lr;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(a.state==="requested"&&i?.to!=="paused"&&e!=="stopped"&&t!=="stopped"&&this.seek(a.position,a.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"),E(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"),E(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="ready"&&E(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):t==="playing"&&this.video.paused?this.playIfAllowed():i?.to==="playing"&&E(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&E(this.params.desiredState.playbackState,"paused");return;default:return UM(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new ln(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:e.projectionData?.pose.yaw||0,y:e.projectionData?.pose.pitch||0,z:e.projectionData?.pose.roll||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSizeManager.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.textTracksManager=new Fe(e.source.url),this.params=e,this.video=Ee(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 nn({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer,forceVideoCodec:this.params.forceVideoCodec}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params,i=we(this.video);this.subscription.add(()=>i.destroy());let a=this.constructor.name,s=o=>{e.error$.next({id:a,category:_S.WTF,message:`${a} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:i,genericErrorListener:s,connect:(o,u)=>this.subscription.add(o.subscribe(u,s))}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:a,connect:s}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(Dl(l=>!!l.length),FS()).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(Vl(l=>l.to.state!=="none"),Ea());this.stallsManager.connect({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$.pipe(Ea()),videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,qualityLimitsOnStall:this.params.tuning.dash.qualityLimitsOnStall,isBuffering$:i.isBuffering$,looped$:i.looped$}),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(this.player.error$,e.error$),s(this.player.fetcherRecoverableError$,e.fetcherRecoverableError$),s(this.player.fetcherError$,e.fetcherError$),s(this.player.lastConnectionType$,e.httpConnectionType$),s(this.player.lastConnectionReused$,e.httpConnectionReused$),s(this.player.isLive$,e.isLive$),s(this.player.lastRequestFirstBytes$.pipe(Dl(NS),FS()),e.firstBytesEvent$),s(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),s(this.videoState.stateChangeEnded$.pipe(Vl(l=>l.to)),this.params.output.playbackState$),this.subscription.add(i.loopExpected$.subscribe(l=>{t.seekState.setState({state:"requested",position:0,forcePrecise:!1})})),this.subscription.add(i.looped$.subscribe(()=>this.player.warmUpMediaSourceIfNeeded(),a)),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,a)),this.subscription.add(rt(this.video,t.isLooped,a)),this.subscription.add(Pe(this.video,t.volume,i.volumeState$,a)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,a)),this.subscription.add(Ne(this.video,t.playbackRate,i.playbackRateState$,a)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),s(qe(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),E(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},a)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),E(t.playbackState,"paused")},a)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},a)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:l})=>{if(l==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let c=this.player.getStreams(),d=this.player.getCodecs();if(HM(c,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let h=[];for(let f of c.audio){h.push(hl(f));let b=[];for(let g of f.representations){let v=aS(g);b.push(v),this.audioTracksMap.set(v,{stream:f,representation:g})}this.audioStreamsMap.set(f,b)}this.params.output.availableAudioStreams$.next(h)}let p=[];for(let h of c.video){p.push(ml(h));let f=[];for(let b of h.representations){let g=rS({...b,streamId:h.id});g&&(f.push(g),this.videoTracksMap.set(g,{stream:h,representation:b}))}this.videoStreamsMap.set(h,f)}this.params.output.availableVideoStreams$.next(p);for(let h of c.text)for(let f of h.representations){let b=sS(h,f);this.textTracksMap.set(b,{stream:h,representation:f})}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),d?.video&&this.params.output.availableVideoCodecs$.next(d.video),d?.audio&&this.params.output.availableAudioCodecs$.next(d.audio),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else l==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},a)),this.subscription.add(dn(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$,QM(this.video,"progress")).pipe(Dl(()=>this.videoTracksMap.size>0)).subscribe(async()=>{let l=this.player.state$.getState(),c=this.player.state$.getTransition();if(!(0,qS.default)(["manifest_ready","running"],l)||c)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let d=this.selectVideoAudioRepresentations();if(!d)return;let[p,h]=d,f=[...this.videoTracksMap.keys()].find(g=>this.videoTracksMap.get(g)?.representation.id===p.id);NS(f)&&(this.stallsManager.lastVideoTrackSelected=f);let b=this.params.desiredState.autoVideoTrackLimits.getTransition();if(b&&this.params.output.autoVideoTrackLimits$.next(b.to),l==="manifest_ready")await this.player.initRepresentations(p.id,h?.id,this.params.sourceHls);else if(await this.player.switchRepresentation("video",p.id),h){let g=!!t.audioStream.getTransition();await this.player.switchRepresentation("audio",h.id,g)}},a)),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(Ea()).subscribe(l=>{let c=[...this.videoTracksMap.entries()].find(([,{representation:f}])=>f.id===l);if(!c){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[d,{stream:p}]=c,h=this.params.desiredState.videoStream.getTransition();h&&h.to&&h.to.id===p.id&&this.params.desiredState.videoStream.setState(h.to),e.currentVideoTrack$.next(d),e.currentVideoStream$.next(ml(p))},a)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(Ea()).subscribe(l=>{let c=[...this.audioTracksMap.entries()].find(([,{representation:f}])=>f.id===l);if(!c){e.currentAudioStream$.next(void 0);return}let[d,{stream:p}]=c,h=this.params.desiredState.audioStream.getTransition();h&&h.to&&h.to.id===p.id&&this.params.desiredState.audioStream.setState(h.to),e.currentAudioStream$.next(hl(p))},a)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(l=>{if(l?.is3dVideo&&this.params.tuning.spherical?.enabled)try{this.init3DScene(l),e.is3DVideo$.next(!0)}catch(c){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${c}`})}else this.destroy3DScene(),this.params.tuning.spherical?.enabled&&e.is3DVideo$.next(!1)},a)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,a)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,a)),this.textTracksManager.connect(this.video,t,e);let o=t.playbackState.stateChangeStarted$.pipe(Vl(({to:l})=>l==="ready"),Ea());this.subscription.add(dn(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,Bl(["init"])).subscribe(()=>{let l=t.autoVideoTrackSwitching.getState(),d=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:l?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(d)})),this.subscription.add(dn(o,this.player.state$.stateChangeEnded$,Bl(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let u=dn(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Bl(["init"])).pipe(jM(0));this.subscription.add(u.subscribe(this.syncPlayback,a))}selectVideoAudioRepresentations(){if(this.player.isStreamEnded)return;let{desiredState:e,output:t}=this.params,i=e.autoVideoTrackSwitching.getState(),a=e.videoTrack.getState()?.id,n=[...this.videoTracksMap.keys()].find(({id:O})=>O===a),o=t.currentVideoTrack$.getValue(),u=e.videoStream.getState()??(n&&this.videoTracksMap.get(n)?.stream)??this.videoStreamsMap.size===1?this.videoStreamsMap.keys().next().value:void 0;if(!u)return;let l=[...this.videoStreamsMap.keys()].find(({id:O})=>O===u.id),c=l&&this.videoStreamsMap.get(l);if(!c)return;let d=Bi(this.video.buffered,this.video.currentTime*1e3),p;this.player.isActiveLive$.getValue()?p=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?p=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:p=i?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let h=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,f=Math.min(d/Math.min(p,h||1/0),1),b=e.audioStream.getState()??(this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0),g=[...this.audioStreamsMap.keys()].find(({id:O})=>O===b?.id)??this.audioStreamsMap.keys().next().value,v=0;if(g){if(n&&!i){let O=Os(n,c,this.audioStreamsMap.get(g)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);v=Math.max(v,O?.bitrate??-1/0)}if(o){let O=Os(o,c,this.audioStreamsMap.get(g)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);v=Math.max(v,O?.bitrate??-1/0)}}let x=$t(c,{container:this.elementSizeManager.getValue(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:v,forwardBufferHealth:f,current:o,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,stallsVideoMaxQualityLimit:this.stallsManager.videoMaxQualityLimit,stallsPredictedThroughput:this.stallsManager.predictedThroughput,abrLogger:this.params.dependencies.abrLogger}),T=i?x??n:n??x,P=g&&Zb(T,c,this.audioStreamsMap.get(g)??[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:f,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),I=this.videoTracksMap.get(T)?.representation,B=P&&this.audioTracksMap.get(P)?.representation;if(I&&B)return[I,B];if(I&&!B&&this.audioTracksMap.size===0)return[I,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Ae(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:_S.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),xe(this.video),this.tracer.end()}};var xa=class extends ni{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};import{combine as Ol,merge as US,filter as HS,filterChanged as WM,isNullable as _l,map as jS,ValueSubject as Nl,isNonNullable as YM}from"@vkontakte/videoplayer-shared";var Pa=class extends ni{constructor(e){super(e),this.textTracksManager.destroy()}subscribe(){super.subscribe();let e=-1,{output:t,observableVideo:i,desiredState:a,connect:s}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),s(i.timeUpdate$,t.liveBufferTime$),s(this.player.liveSeekableDuration$,t.duration$),s(this.player.liveLatency$,t.liveLatency$);let n=new Nl(1);s(i.playbackRateState$,n),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(a.isLowLatency.stateChangeEnded$.pipe(jS(o=>o.to)).subscribe(this.player.isLowLatency$)).add(Ol({liveBufferTime:t.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(jS(({liveBufferTime:o,liveAvailabilityStartTime:u})=>o&&u?o+u:void 0)).subscribe(t.liveTime$)).add(this.player.liveStreamStatus$.pipe(HS(o=>YM(o))).subscribe(o=>t.isLiveEnded$.next(o!=="active"&&t.position$.getValue()===0))).add(Ol({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:US(i.playbackRateState$,new Nl(1))}).pipe(HS(({liveStreamStatus:o,liveDuration:u})=>o==="active"&&!!u)).subscribe(({liveDuration:o,playbackRate:u})=>{let l=t.liveBufferTime$.getValue(),c=t.position$.getValue(),{playbackCatchupSpeedup:d}=this.params.tuning.dashCmafLive.lowLatency;c||u<1-d||this.video.paused||_l(l)||(e=o-l)})).add(Ol({time:t.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:US(i.playbackRateState$,new Nl(1))}).pipe(WM((o,u)=>this.player.liveStreamStatus$.getValue()==="active"?o.liveDuration===u.liveDuration:o.time===u.time)).subscribe(({time:o,liveDuration:u,playbackRate:l})=>{let c=t.position$.getValue(),{playbackCatchupSpeedup:d}=this.params.tuning.dashCmafLive.lowLatency;if(!c&&!this.video.paused&&l>=1-d||_l(o)||_l(u))return;let p=-1*(u-o-e);t.position$.next(Math.min(p,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(o=>{if(o){let u=nS(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 GS=R(xs(),1);import{assertNever as ka,assertNonNullable as QS,debounce as zM,ErrorCategory as pn,filter as KM,isNonNullable as XM,isNullable as JM,map as hn,merge as ZM,Observable as eC,observableFrom as tC,Subscription as iC,videoSizeToQuality as rC}from"@vkontakte/videoplayer-shared";var Ke={};var Gi=(r,e)=>new eC(t=>{let i=(a,s)=>t.next(s);return r.on(e,i),()=>r.off(e,i)}),wa=class{constructor(e){this.subscription=new iC;this.videoState=new D("initializing");this.trackLevels=new Map;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(e!=="initializing")switch(i?.to!=="paused"&&a.state==="requested"&&this.seek(a.position),t){case"stopped":switch(e){case"stopped":break;case"ready":case"playing":case"paused":this.stop();break;default:ka(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:ka(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:ka(e)}break;case"paused":switch(e){case"paused":break;case"stopped":this.prepare();break;case"ready":this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused");break;case"playing":this.pause();break;default:ka(e)}break;default:ka(t)}};this.textTracksManager=new Fe(e.source.url),this.video=Ee(e.container,e.tuning),this.params=e,this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(ne(this.params.source.url)),this.loadHlsJs()}destroy(){this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),this.hls?.detachMedia(),this.hls?.destroy(),this.params.output.element$.next(void 0),xe(this.video)}loadHlsJs(){let e=!1,t=a=>{e||this.params.output.error$.next({id:a==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:pn.NETWORK,message:"Failed to load Hls.js",thrown:a}),e=!0},i=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);(0,GS.default)(import("hls.js").then(a=>{e||(Ke.Hls=a.default,Ke.Events=a.default.Events,this.init())},t),()=>{window.clearTimeout(i),e=!0})}init(){QS(Ke.Hls,"hls.js not loaded"),this.hls=new Ke.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){QS(Ke.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,i=l=>{t.error$.next({id:"HlsJsProvider",category:pn.WTF,message:"HlsJsProvider internal logic error",thrown:l})},a=we(this.video);this.subscription.add(()=>a.destroy());let s=(l,c)=>this.subscription.add(l.subscribe(c,i));s(a.timeUpdate$,t.position$),s(a.durationChange$,t.duration$),s(a.ended$,t.endedEvent$),s(a.looped$,t.loopedEvent$),s(a.error$,t.error$),s(a.isBuffering$,t.isBuffering$),s(a.currentBuffer$,t.currentBuffer$),s(a.loadStart$,t.firstBytesEvent$),s(a.loadedMetadata$,t.loadedMetadataEvent$),s(a.playing$,t.firstFrameEvent$),s(a.canplay$,t.canplay$),s(a.seeked$,t.seekedEvent$),s(a.inPiP$,t.inPiP$),s(a.inFullscreen$,t.inFullscreen$),this.subscription.add(rt(this.video,e.isLooped,i)),this.subscription.add(Pe(this.video,e.volume,a.volumeState$,i)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Ne(this.video,e.playbackRate,a.playbackRateState$,i)),s(qe(this.video),t.elementVisible$),s(this.videoState.stateChangeEnded$.pipe(hn(l=>l.to)),this.params.output.playbackState$),this.subscription.add(Gi(this.hls,Ke.Events.ERROR).subscribe(l=>{l.fatal&&t.error$.next({id:["HlsJsFatal",l.type,l.details].join("_"),category:pn.WTF,message:`HlsJs fatal ${l.type} ${l.details}, ${l.err?.message} ${l.reason}`,thrown:l.error})})),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),E(e.playbackState,"playing")},i)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),E(e.playbackState,"paused")},i)).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),s(Gi(this.hls,Ke.Events.MANIFEST_PARSED).pipe(hn(({levels:l})=>l.reduce((c,d)=>{let p=d.name||d.height.toString(10),{width:h,height:f}=d,b=At(d.attrs.QUALITY??"")??rC({width:h,height:f});if(!b)return c;let g=d.attrs["FRAME-RATE"]?parseFloat(d.attrs["FRAME-RATE"]):void 0,v={id:p.toString(),quality:b,bitrate:d.bitrate/1e3,size:{width:h,height:f},fps:g};return this.trackLevels.set(p,{track:v,level:d}),c.push(v),c},[]))),t.availableVideoTracks$),s(Gi(this.hls,Ke.Events.MANIFEST_PARSED),l=>{if(l.subtitleTracks.length>0){let c=[];for(let d of l.subtitleTracks){let p=d.name,h=d.attrs.URI||"",f=d.lang;c.push({id:p,url:h,language:f,type:"internal"})}e.internalTextTracks.startTransitionTo(c)}}),s(Gi(this.hls,Ke.Events.LEVEL_LOADING).pipe(hn(({url:l})=>ne(l))),t.hostname$),s(Gi(this.hls,Ke.Events.FRAG_CHANGED),l=>{let{video:c,audio:d}=l.frag.elementaryStreams;t.currentVideoSegmentLength$.next(((c?.endPTS??0)-(c?.startPTS??0))*1e3),t.currentAudioSegmentLength$.next(((d?.endPTS??0)-(d?.startPTS??0))*1e3)}),this.subscription.add(Pt(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,l=>{this.hls.nextLevel=l?-1:this.hls.currentLevel,this.hls.loadLevel=l?-1:this.hls.loadLevel},{onError:i}));let n=l=>Array.from(this.trackLevels.values()).find(({level:c})=>c===l)?.track,o=Gi(this.hls,Ke.Events.LEVEL_SWITCHED).pipe(hn(({level:l})=>n(this.hls.levels[l])));o.pipe(KM(XM)).subscribe(t.currentVideoTrack$,i),this.subscription.add(Pt(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),l=>{if(JM(l))return;let c=this.trackLevels.get(l.id)?.level;if(!c)return;let d=this.hls.levels.indexOf(c),p=this.hls.currentLevel,h=this.hls.levels[p];!h||c.bitrate>h.bitrate?this.hls.nextLevel=d:(this.hls.loadLevel=d,this.hls.loadLevel=d)},{changed$:o,onError:i})),s(a.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);let u=ZM(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,tC(["init"])).pipe(zM(0));this.subscription.add(u.subscribe(this.syncPlayback,i))}prepare(){this.videoState.startTransitionTo("ready"),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}async playIfAllowed(){this.videoState.startTransitionTo("playing"),await Ae(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:pn.DOM,thrown:t}))||(this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused",!0))}pause(){this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.hls.stopLoad(),this.hls.detachMedia(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"),E(this.params.desiredState.playbackState,"stopped",!0)}};var WS="X-Playback-Duration",Fl=async r=>{let e=await st(r),t=await e.text(),i=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t)?.[1];return i?parseInt(i,10):e.headers.has(WS)?parseInt(e.headers.get(WS),10):void 0};import{assertNever as mC,combine as fC,debounce as bC,ErrorCategory as bn,filter as gC,filterChanged as vC,isNonNullable as KS,isNullable as gn,map as XS,merge as SC,observableFrom as yC,Subscription as TC,ValueSubject as Hl,VideoQuality as IC}from"@vkontakte/videoplayer-shared";var Ul=R(Oo(),1);import{videoSizeToQuality as aC,getExponentialDelay as sC}from"@vkontakte/videoplayer-shared";var nC=r=>{let e=null;if(r.QUALITY&&(e=At(r.QUALITY)),!e&&r.RESOLUTION){let[t,i]=r.RESOLUTION.split("x").map(a=>parseInt(a,10));e=aC({width:t,height:i})}return e??null},oC=(r,e)=>{let t=r.split(`
125
- `),i=[],a=[];for(let s=0;s<t.length;s++){let n=t[s],o=n.match(/^#EXT-X-STREAM-INF:(.+)/),u=n.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!o&&!u)){if(o){let l=(0,Ul.default)(o[1].split(",").map(g=>g.split("="))),c=l.QUALITY??`stream-${l.BANDWIDTH}`,d=nC(l),p;l.BANDWIDTH&&(p=parseInt(l.BANDWIDTH,10)/1e3||void 0),!p&&l["AVERAGE-BANDWIDTH"]&&(p=parseInt(l["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let h=l["FRAME-RATE"]?parseFloat(l["FRAME-RATE"]):void 0,f;if(l.RESOLUTION){let[g,v]=l.RESOLUTION.split("x").map(x=>parseInt(x,10));g&&v&&(f={width:g,height:v})}let b=new URL(t[++s],e).toString();d&&i.push({id:c,quality:d,url:b,bandwidth:p,size:f,fps:h})}if(u){let l=(0,Ul.default)(u[1].split(",").map(h=>{let f=h.indexOf("=");return[h.substring(0,f),h.substring(f+1)]}).map(([h,f])=>[h,f.replace(/^"|"$/g,"")])),c=l.URI?.replace(/playlist$/,"subtitles.vtt"),d=l.LANGUAGE,p=l.NAME;c&&d&&a.push({type:"internal",id:d,label:p,language:d,url:c,isAuto:!1})}}}if(!i.length)throw new Error("Empty manifest");return{qualityManifests:i,textTracks:a}},uC=r=>new Promise(e=>{setTimeout(()=>{e()},r)}),ql=0,YS=async(r,e=r,t,i)=>{let s=await(await st(r,i)).text();ql+=1;try{let{qualityManifests:n,textTracks:o}=oC(s,e);return{qualityManifests:n,textTracks:o}}catch{if(ql<=t.manifestRetryMaxCount)return await uC(sC(ql-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),YS(r,e,t)}return{qualityManifests:[],textTracks:[]}},mn=YS;import{isNonNullable as lC,Subscription as cC,throttle as dC,ValueSubject as zS,Subject as pC,ErrorCategory as hC}from"@vkontakte/videoplayer-shared";var fn=class{constructor(e,t,i,a,s){this.subscription=new cC;this.abortControllers={destroy:new pe,nextManifest:null};this.prepareUrl=void 0;this.currentTextTrackData=null;this.availableTextTracks$=new zS(null);this.getCurrentTime$=new zS(null);this.error$=new pC;this.params={fetchManifestData:i,sourceUrl:a,downloadThreshold:s},this.subscription.add(e.pipe(dC(1e3)).subscribe(n=>{this.processLiveTime(n)})),this.getCurrentTime$.next(()=>this.currentTextTrackData?this.currentTextTrackData.playlist.segmentStartTime/1e3+t.currentTime:0)}destroy(){this.subscription.unsubscribe(),this.abortControllers.destroy.abort()}async prepare(e){try{let t=new URL(e);t.searchParams.set("enable-subtitles","yes"),this.prepareUrl=t.toString();let{textTracks:i}=await this.fetchManifestData();await this.processTextTracks(i,this.params.sourceUrl)}catch(t){this.error("prepare",t)}}async processTextTracks(e,t){try{let i=await this.parseTextTracks(e,t);i&&(this.currentTextTrackData=i)}catch(i){this.error("processTextTracks",i)}}async parseTextTracks(e,t){for(let i of e){let a=new URL(i.url,t).toString(),n=await(await st(a,{signal:this.abortControllers.destroy.signal})).text(),o=this.parsePlaylist(n,a);return{textTrack:i,playlist:o}}}parsePlaylist(e,t){let i={mediaSequence:0,programDateTime:"",segments:[],targetDuration:0,vkPlaybackDuration:0,segmentStartTime:0,vkStartTime:""},a=e.split(`
126
- `),s=0;for(let n=0;n<a.length;++n){let o=a[n];switch(!0){case o.startsWith("#EXTINF:"):{let u=a[++n],l=new URL(u,t).toString(),c=Number(this.extractPlaylistRowValue("#EXTINF:",o))*1e3;if(i.segments.push({time:{from:s,to:s+c},url:l}),s=s+c,!i.segmentStartTime){let d=new Date(i.vkStartTime).valueOf(),p=new Date(i.programDateTime).valueOf();i.segmentStartTime=p-d}break}case o.startsWith("#EXT-X-TARGETDURATION:"):i.targetDuration=Number(this.extractPlaylistRowValue("#EXT-X-TARGETDURATION:",o));break;case o.startsWith("#EXT-X-MEDIA-SEQUENCE:"):i.mediaSequence=Number(this.extractPlaylistRowValue("#EXT-X-MEDIA-SEQUENCE:",o));break;case o.startsWith("#EXT-X-VK-PLAYBACK-DURATION:"):i.vkPlaybackDuration=Number(this.extractPlaylistRowValue("#EXT-X-VK-PLAYBACK-DURATION:",o));break;case o.startsWith("#EXT-X-PROGRAM-DATE-TIME:"):{let u=this.extractPlaylistRowValue("#EXT-X-PROGRAM-DATE-TIME:",o);i.programDateTime=u;let l=new Date(u);l.setMilliseconds(0),s=l.valueOf();break}case o.startsWith("#EXT-X-VK-START-TIME:"):i.vkStartTime=this.extractPlaylistRowValue("#EXT-X-VK-START-TIME:",o);break}}return i}extractPlaylistRowValue(e,t){switch(e){case"#EXTINF:":return t.substring(e.length,t.length-1);default:return t.substring(e.length)}}processLiveTime(e){if(lC(e)&&this.currentTextTrackData){let{segments:t}=this.currentTextTrackData.playlist,{from:i}=t[0].time,{to:a}=t[t.length-1].time;if(e<i||e>a)return;a-e<this.params.downloadThreshold&&this.fetchNextManifestData();for(let n of t)if(n.time.from<=e&&n.time.to>=e){this.availableTextTracks$.next([{...this.currentTextTrackData.textTrack,url:n.url,isAuto:!0}]);break}}}async fetchNextManifestData(){try{if(this.abortControllers.nextManifest)return;this.abortControllers.nextManifest=new pe;let{textTracks:e}=await this.fetchManifestData(),t=await this.parseTextTracks(e,this.params.sourceUrl);this.currentTextTrackData&&t&&(this.currentTextTrackData.playlist.segments=t.playlist.segments)}catch(e){this.error("fetchNextManifestData",e)}finally{this.abortControllers.nextManifest=null}}async fetchManifestData(){let e=this.prepareUrl??this.params.sourceUrl;return await this.params.fetchManifestData(e,{signal:this.abortControllers.destroy.signal})}error(e,t){this.error$.next({id:"[LiveTextManager][HLS_LIVE_CMAF]",category:hC.WTF,thrown:t,message:e})}};var Aa=class{constructor(e){this.subscription=new TC;this.videoState=new D("stopped");this.textTracksManager=null;this.liveTextManager=null;this.manifests$=new Hl([]);this.liveOffset=new Zt;this.manifestStartTime$=new Hl(void 0);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),E(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let c=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(c),this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if(a?.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"?E(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),E(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()):a?.to==="playing"&&E(this.params.desiredState.playbackState,"playing");return;case"paused":if(i==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let c=this.liveOffset.getTotalOffset();c>=this.maxSeekBackTime$.getValue()&&(c=0,this.liveOffset.resetTo(c)),this.liveOffset.resume(),this.params.output.position$.next(-c/1e3),this.prepare()}else a?.to==="paused"&&(E(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return mC(t)}};this.params=e,this.video=Ee(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:IC.INVARIANT,url:this.params.source.url};let t=(i,a)=>mn(i,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 fn(this.params.output.liveTime$,this.video,t,this.params.source.url,this.params.tuning.hlsLiveNewTextManagerDownloadThreshold):this.textTracksManager=new Fe(e.source.url),t(this.generateLiveUrl()).then(({qualityManifests:i,textTracks:a})=>{i.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:bn.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.liveTextManager?.processTextTracks(a,this.params.source.url),this.manifests$.next([this.masterManifest,...i])}).catch(i=>{this.params.output.error$.next({id:"ExtractHlsQualities",category:bn.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:i})}),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(ne(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new Hl(e.source.maxSeekBackTime??1/0),this.subscribe()}selectManifest(){let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),a=t.getTransition(),s=a?.to?.id??t.getState()?.id??"master",n=this.manifests$.getValue();if(!n.length)return;let o=i?"master":s;return i&&!a&&t.startTransitionTo(this.masterManifest),n.find(u=>u.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsLiveProvider",category:bn.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},a=we(this.video);this.subscription.add(()=>a.destroy());let s=(o,u)=>this.subscription.add(o.subscribe(u,i));s(a.ended$,e.endedEvent$),s(a.error$,e.error$),s(a.isBuffering$,e.isBuffering$),s(a.currentBuffer$,e.currentBuffer$),s(a.loadedMetadata$,e.firstBytesEvent$),s(a.loadedMetadata$,e.loadedMetadataEvent$),s(a.playing$,e.firstFrameEvent$),s(a.canplay$,e.canplay$),s(a.inPiP$,e.inPiP$),s(a.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(Pe(this.video,t.volume,a.volumeState$,i)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Ne(this.video,t.playbackRate,a.playbackRateState$,i)),s(qe(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(a.playing$.subscribe(()=>{this.videoState.setState("playing"),E(t.playbackState,"playing")},i)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),E(t.playbackState,"paused")},i)).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.liveTextManager&&this.subscription.add(this.liveTextManager.availableTextTracks$.subscribe(o=>{o&&this.params.output.availableTextTracks$.next(o)})),this.subscription.add(this.maxSeekBackTime$.pipe(vC(),XS(o=>-o/1e3)).subscribe(this.params.output.duration$,i)),this.subscription.add(a.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&KS(l.to)){let d=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let p=this.manifests$.getValue().find(h=>h.id===d);p&&(this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(ne(p.url)))}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o&&o.state==="requested"&&this.seek(o.position)},i)),this.subscription.add(a.loadedData$.subscribe(()=>{let o=this.video?.getStartDate?.()?.getTime();this.manifestStartTime$.next(o||void 0)},i)),this.subscription.add(fC({startTime:this.manifestStartTime$.pipe(gC(KS)),currentTime:a.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),i)),this.subscription.add(this.manifests$.pipe(XS(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:p})=>({id:u,quality:l,size:c,fps:p,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,i));let n=SC(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,yC(["init"])).pipe(bC(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager?.destroy(),this.liveTextManager?.destroy(),this.params.output.element$.next(void 0),xe(this.video)}prepare(){let e=this.selectManifest();if(gn(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),a=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:o,min:u}=t?.to??i??{};for(let[l,c]of[[o,"mq"],[u,"lq"]]){let d=String(parseFloat(l||""));c&&l&&a.searchParams.set(c,d)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,n=de(a.toString(),this.liveOffset.getTotalOffset(),s);this.liveTextManager?.prepare(n),this.video.setAttribute("src",n),this.video.load(),Fl(n).then(o=>{if(!gn(o))this.maxSeekBackTime$.next(o);else{let u=this.params.source.maxSeekBackTime??this.maxSeekBackTime$.getValue();(gn(u)||!isFinite(u))&&st(n).then(l=>l.text()).then(l=>{let c=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(l)?.[1];if(c){let d=new URL(c,n).toString();Fl(d).then(p=>{gn(p)||this.maxSeekBackTime$.next(p)})}}).catch(()=>{})}})}playIfAllowed(){Ae(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),E(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:bn.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3),this.params.output.seekedEvent$.next()}generateLiveUrl(){let e=de(this.params.source.url);if(this.params.tuning.useHlsLiveNewTextManager){let t=new URL(e);t.searchParams.set("enable-subtitles","yes"),e=t.toString()}return e}};import{assertNever as EC,debounce as xC,ErrorCategory as jl,fromEvent as Ql,isNonNullable as PC,isNullable as kC,map as JS,merge as ZS,observableFrom as ey,Subscription as wC,ValueSubject as AC,VideoQuality as LC}from"@vkontakte/videoplayer-shared";var La=class{constructor(e){this.subscription=new wC;this.videoState=new D("stopped");this.manifests$=new AC([]);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),E(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let c=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(c);let{currentTime:d}=this.video;this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:d*1e3,forcePrecise:!0});return}switch(a?.to!=="paused"&&l.state==="requested"&&this.seek(l.position),t){case"ready":i==="ready"?E(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),E(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()):a?.to==="playing"&&E(this.params.desiredState.playbackState,"playing");return;case"paused":i==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):a?.to==="paused"&&E(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return EC(t)}};this.textTracksManager=new Fe(e.source.url),this.params=e,this.video=Ee(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:LC.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),mn(de(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:t,textTracks:i})=>{this.manifests$.next([this.masterManifest,...t]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(i)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:jl.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),a=t.getTransition(),s=a?.to?.id??t.getState()?.id??"master",n=this.manifests$.getValue();if(!n.length)return;let o=i?"master":s;return i&&(!a||!a.from)&&t.startTransitionTo(this.masterManifest),n.find(u=>u.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsProvider",category:jl.WTF,message:"HlsProvider internal logic error",thrown:o})},a=we(this.video);this.subscription.add(()=>a.destroy());let s=(o,u)=>this.subscription.add(o.subscribe(u));if(s(a.timeUpdate$,e.position$),s(a.durationChange$,e.duration$),s(a.ended$,e.endedEvent$),s(a.looped$,e.loopedEvent$),s(a.error$,e.error$),s(a.isBuffering$,e.isBuffering$),s(a.currentBuffer$,e.currentBuffer$),s(a.loadedMetadata$,e.firstBytesEvent$),s(a.loadedMetadata$,e.loadedMetadataEvent$),s(a.playing$,e.firstFrameEvent$),s(a.canplay$,e.canplay$),s(a.seeked$,e.seekedEvent$),s(a.inPiP$,e.inPiP$),s(a.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe(JS(o=>o.to)),this.params.output.playbackState$),this.subscription.add(rt(this.video,t.isLooped,i)),this.subscription.add(Pe(this.video,t.volume,a.volumeState$,i)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Ne(this.video,t.playbackRate,a.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),E(t.playbackState,"playing")},i)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),E(t.playbackState,"paused")},i)).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i).add(a.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&PC(l.to)){let h=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let f=this.manifests$.getValue().find(b=>b.id===h);f&&(this.params.output.currentVideoTrack$.next(f),this.params.output.hostname$.next(ne(f.url)))}let d=this.params.desiredState.playbackRate.getState(),p=this.params.output.element$.getValue()?.playbackRate;if(d!==p){let h=this.params.output.element$.getValue();h&&(this.params.desiredState.playbackRate.setState(d),h.playbackRate=d)}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o.state==="requested"&&this.seek(o.position)},i))),this.subscription.add(this.manifests$.pipe(JS(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:p})=>({id:u,quality:l,size:c,fps:p,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,i)),!V.device.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(ZS(Ql(o,"addtrack"),Ql(o,"removetrack"),Ql(o,"change"),ey(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},i))}let n=ZS(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,ey(["init"])).pipe(xC(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),xe(this.video)}prepare(){let e=this.selectManifest();if(kC(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),a=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:s,min:n}=t?.to??i??{};for(let[o,u]of[[s,"mq"],[n,"lq"]]){let l=String(parseFloat(o||""));u&&o&&a.searchParams.set(u,l)}}this.video.setAttribute("src",a.toString()),this.video.load()}playIfAllowed(){Ae(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:jl.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var ry=R(Ii(),1),Gl=R(Ci(),1),ay=R(Lt(),1);import{assertNever as RC,assertNonNullable as ty,debounce as $C,ErrorCategory as iy,isHigherOrEqual as MC,isLowerOrEqual as CC,isNonNullable as DC,merge as VC,observableFrom as BC,Subscription as OC,map as _C}from"@vkontakte/videoplayer-shared";var Ra=class{constructor(e){this.subscription=new OC;this.videoState=new D("stopped");this.trackUrls={};this.textTracksManager=new Fe;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"),E(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.autoVideoTrackLimits.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.seekState.getState();if(s&&e!=="ready"&&!n){this.handleQualityLimitTransition(s.to);return}if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(n){let{currentTime:u}=this.video;this.prepare(),o.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:u*1e3,forcePrecise:!0});return}switch(i?.to!=="paused"&&o.state==="requested"&&this.seek(o.position),e){case"ready":t==="ready"?E(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):i?.to==="playing"&&E(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&E(this.params.desiredState.playbackState,"paused");return;default:return RC(e)}};this.params=e,this.video=Ee(e.container,e.tuning),this.params.output.element$.next(this.video),(0,ry.default)(this.params.source).reverse().forEach(([t,i],a)=>{let s=a.toString(10);this.trackUrls[s]={track:{quality:t,id:s},url:i}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next((0,Gl.default)(this.trackUrls).map(({track:t})=>t)),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.subscribe()}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"MpegProvider",category:iy.WTF,message:"MpegProvider internal logic error",thrown:o})},a=we(this.video);this.subscription.add(()=>a.destroy());let s=(o,u)=>this.subscription.add(o.subscribe(u,i));s(a.timeUpdate$,e.position$),s(a.durationChange$,e.duration$),s(a.ended$,e.endedEvent$),s(a.looped$,e.loopedEvent$),s(a.error$,e.error$),s(a.isBuffering$,e.isBuffering$),s(a.currentBuffer$,e.currentBuffer$),s(a.loadedMetadata$,e.firstBytesEvent$),s(a.loadedMetadata$,e.loadedMetadataEvent$),s(a.playing$,e.firstFrameEvent$),s(a.canplay$,e.canplay$),s(a.seeked$,e.seekedEvent$),s(a.inPiP$,e.inPiP$),s(a.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe(_C(o=>o.to)),this.params.output.playbackState$),this.subscription.add(rt(this.video,t.isLooped,i)),this.subscription.add(Pe(this.video,t.volume,a.volumeState$,i)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Ne(this.video,t.playbackRate,a.playbackRateState$,i)),s(qe(this.video),e.elementVisible$),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),E(t.playbackState,"playing")},i)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),E(t.playbackState,"paused")},i)).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready");let o=this.params.desiredState.videoTrack.getTransition();if(o&&DC(o.to)){this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to.id].track);let u=this.params.desiredState.playbackRate.getState(),l=this.params.output.element$.getValue()?.playbackRate;if(u!==l){let c=this.params.output.element$.getValue();c&&(this.params.desiredState.playbackRate.setState(u),c.playbackRate=u)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.textTracksManager.connect(this.video,t,e);let n=VC(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,BC(["init"])).pipe($C(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),xe(this.video)}prepare(){let e=this.params.desiredState.videoTrack.getState()?.id;ty(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];ty(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=fa(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(ne(t))}playIfAllowed(){Ae(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:iy.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){this.params.output.autoVideoTrackLimits$.next(e);let t=l=>{this.params.output.currentVideoTrack$.next(l),this.params.desiredState.videoTrack.startTransitionTo(l)},i=l=>{let c=$t(n,{container:this.video.getBoundingClientRect(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,limits:l,abrLogger:this.params.dependencies.abrLogger});t(c)},a=this.params.output.currentVideoTrack$.getValue()?.quality,s=!!(e.max||e.min),n=(0,Gl.default)(this.trackUrls).map(l=>l.track);if(!a||!s||Ar({limits:e,lowestAvailableQuality:(0,ay.default)(n,-1)?.quality,highestAvailableQuality:n[0].quality})){i();return}let o=e.max?CC(a,e.max):!0,u=e.min?MC(a,e.min):!0;o&&u||i(e)}};import{assertNever as ny,debounce as UC,merge as oy,observableFrom as HC,Subscription as jC,map as uy,ValueSubject as QC,ErrorCategory as Yl,VideoQuality as GC}from"@vkontakte/videoplayer-shared";import{ErrorCategory as NC}from"@vkontakte/videoplayer-shared";var sy=["stun:videostun.mycdn.me:80"],FC=1e3,qC=3,Wl=()=>null,vn=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=Wl;this.externalStopCallback=Wl;this.externalErrorCallback=Wl;this.options=this.normalizeOptions(t);let i=e.split("/");this.serverUrl=i.slice(0,i.length-1).join("/"),this.streamKey=i[i.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{let t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}async handleUpdateMessage(e){try{let t=await this.createOffer();this.peerConnection&&await this.peerConnection.setLocalDescription(t),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}}async handleLogin(){try{let e={iceServers:[{urls:sy}]};this.peerConnection=new RTCPeerConnection(e),this.peerConnection.ontrack=this.onPeerConnectionStream.bind(this),this.peerConnection.onicecandidate=this.onPeerConnectionIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onPeerConnectionIceConnectionStateChange.bind(this);let t=await this.createOffer();await this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}}async handleAnswer(e){try{this.peerConnection&&await this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e}))}catch(t){this.handleRTCError(t)}}async handleCandidate(e){if(e)try{this.peerConnection&&await this.peerConnection.addIceCandidate(e)}catch(t){this.handleRTCError(t)}}handleUnpublished(){try{this.closeConnections(),this.externalStopCallback()}catch(e){this.handleRTCError(e)}}handleSystemError(e){this.options.errorChanel&&this.options.errorChanel.next({id:"webrtc-provider-error",category:NC.WTF,message:e.message})}async onPeerConnectionStream(e){let t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){let e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}async createOffer(){let e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");let t=await this.peerConnection.createOffer(e),i=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(i))throw new Error("No h264 codec support error");return t}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch{throw new Error("Can not parse socket message")}}closeConnections(){let e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),FC)}normalizeOptions(e={}){let t={stunServerList:sy,maxRetryNumber:qC,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var $a=class{constructor(e){this.videoState=new D("stopped");this.maxSeekBackTime$=new QC(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"),E(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"),E(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):i?.to==="playing"&&E(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&E(this.params.desiredState.playbackState,"paused");return;default:return ny(e)}};this.subscription=new jC,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=Ee(e.container,e.tuning),this.liveStreamClient=new vn(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),xe(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,i=n=>{e.error$.next({id:"WebRTCLiveProvider",category:Yl.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};this.subscription.add(oy(this.videoState.stateChangeStarted$.pipe(uy(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(uy(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})}));let a=we(this.video);this.subscription.add(()=>a.destroy());let s=(n,o)=>this.subscription.add(n.subscribe(o,i));s(a.timeUpdate$,e.liveTime$),s(a.ended$,e.endedEvent$),s(a.looped$,e.loopedEvent$),s(a.error$,e.error$),s(a.isBuffering$,e.isBuffering$),s(a.currentBuffer$,e.currentBuffer$),s(qe(this.video),this.params.output.elementVisible$),this.subscription.add(a.durationChange$.subscribe(n=>{e.duration$.next(n===1/0?0:n)})).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready")},i)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused")},i)).add(a.playing$.subscribe(()=>{this.videoState.setState("playing")},i)).add(a.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(Pe(this.video,t.volume,a.volumeState$,i)).add(a.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 ny(n.to)}},i)).add(oy(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,HC(["init"])).pipe(UC(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:GC.INVARIANT}),this.video.srcObject=e,E(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:Yl.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){Ae(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Yl.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var Wi=class{constructor(e){this.length=e.length,this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next(),this.index=this.index===void 0?0:this.index+1}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return!!this.current.done}isLast(){return this.index===this.length-1}};import{assertNever as Ma,assertNonNullable as Bt,ErrorCategory as Sn,filter as my,isNonNullable as fy,isNullable as ZC,map as eD,merge as tD,once as iD,Subject as ue,Subscription as by,ValueSubject as $,flattenObject as gy}from"@vkontakte/videoplayer-shared";import{Observable as WC,map as ly,Subscription as YC,Subject as zC}from"@vkontakte/videoplayer-shared";var cy=r=>new WC(e=>{let t=new YC,i=r.desiredPlaybackState$.stateChangeStarted$.pipe(ly(({from:l,to:c})=>`${l}-${c}`)),a=r.desiredPlaybackState$.stateChangeEnded$,s=r.providerChanged$.pipe(ly(({type:l})=>l!==void 0)),n=new zC,o=0,u="unknown";return t.add(i.subscribe(l=>{o&&window.clearTimeout(o),u=l,o=window.setTimeout(()=>n.next(l),r.maxTransitionInterval)})),t.add(a.subscribe(()=>{window.clearTimeout(o),u="unknown",o=0})),t.add(s.subscribe(l=>{o&&(window.clearTimeout(o),o=0,l&&(o=window.setTimeout(()=>n.next(u),r.maxTransitionInterval)))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});import{ErrorCategory as KC,Subscription as XC,combine as JC,filter as py,once as hy}from"@vkontakte/videoplayer-shared";function dy(){return new(window.AudioContext||window.webkitAudioContext)}var Yi=class r{constructor(e,t,i,a){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=i;this.volumeMultiplier=a;this.destroyController=new pe;this.subscriptions=new XC;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe(py(s=>!!s.type),hy()).subscribe(({type:s})=>this.subscribe(s)))}static{this.errorId="VolumeMultiplierManager"}subscribe(e){V.browser.isSafari&&e!=="MPEG"||this.subscriptions.add(JC({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(py(({playbackState:t,video:i,volume:{muted:a,volume:s}})=>t==="playing"&&!!i&&!a&&!!s),hy()).subscribe(({video:t})=>{this.initAudioContextOnce(t).then(i=>{i||this.destroy()}).catch(i=>{this.handleError(i),this.destroy()})}))}static isSupported(){return"AudioContext"in window&&"GainNode"in window&&"MediaElementAudioSourceNode"in window}async initAudioContextOnce(e){let{volumeMultiplier:t}=this,i=dy();this.audioContext=i;let a=i.createGain();if(this.gainNode=a,a.gain.value=t,a.connect(i.destination),i.state==="suspended"&&(await i.resume(),this.destroyController.signal.aborted))return!1;let s=i.createMediaElementSource(e);return this.mediaElementSource=s,s.connect(a),!0}cleanup(){this.mediaElementSource&&(this.mediaElementSource.disconnect(),this.mediaElementSource=null),this.gainNode&&(this.gainNode.disconnect(),this.gainNode=null),this.audioContext&&(this.audioContext.state!=="closed"&&this.audioContext.close(),this.audioContext=null)}destroy(){this.destroyController.abort(),this.subscriptions.unsubscribe(),this.cleanup()}handleError(e){this.volumeMultiplierError$.next({id:r.errorId,category:KC.VIDEO_PIPELINE,message:e?.message??`${r.errorId} exception`,thrown:e})}};var rD={chunkDuration:5e3,maxParallelRequests:5},Ca=class{constructor(e){this.current$=new $({type:void 0});this.providerError$=new ue;this.noAvailableProvidersError$=new ue;this.volumeMultiplierError$=new ue;this.providerOutput={position$:new $(0),duration$:new $(1/0),volume$:new $({muted:!1,volume:1}),availableVideoStreams$:new $([]),currentVideoStream$:new $(void 0),availableVideoTracks$:new $([]),currentVideoTrack$:new $(void 0),availableVideoCodecs$:new $([]),availableAudioStreams$:new $([]),currentAudioStream$:new $(void 0),availableAudioTracks$:new $([]),availableAudioCodecs$:new $([]),currentVideoSegmentLength$:new $(0),currentAudioSegmentLength$:new $(0),isAudioAvailable$:new $(!0),autoVideoTrackLimitingAvailable$:new $(!1),autoVideoTrackLimits$:new $(void 0),currentBuffer$:new $(void 0),isBuffering$:new $(!0),error$:new ue,fetcherError$:new ue,fetcherRecoverableError$:new ue,warning$:new ue,willSeekEvent$:new ue,soundProhibitedEvent$:new ue,seekedEvent$:new ue,loopedEvent$:new ue,endedEvent$:new ue,firstBytesEvent$:new ue,loadedMetadataEvent$:new ue,firstFrameEvent$:new ue,canplay$:new ue,isLive$:new $(void 0),isLiveEnded$:new $(null),isLowLatency$:new $(!1),canChangePlaybackSpeed$:new $(!0),liveTime$:new $(void 0),liveBufferTime$:new $(void 0),liveLatency$:new $(void 0),severeStallOccurred$:new ue,availableTextTracks$:new $([]),currentTextTrack$:new $(void 0),hostname$:new $(void 0),httpConnectionType$:new $(void 0),httpConnectionReused$:new $(void 0),inPiP$:new $(!1),inFullscreen$:new $(!1),element$:new $(void 0),elementVisible$:new $(!0),availableSources$:new $(void 0),is3DVideo$:new $(!1),playbackState$:new $(""),getCurrentTime$:new $(null)};this.subscription=new by;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=ES([...PS(this.params.tuning),...xS(this.params.tuning)],this.params.tuning).filter(l=>fy(e.sources[l])),{forceFormat:i,formatsToAvoid:a}=this.params.tuning,s=[];i?s=[i]:a.length?s=[...t.filter(l=>!(0,zl.default)(a,l)),...t.filter(l=>(0,zl.default)(a,l))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",gy(s)),this.screenFormatsIterator=new Wi(s);let n=[...Pl(!0),...Pl(!1)];this.chromecastFormatsIterator=new Wi(n.filter(l=>fy(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:o=1,tuning:{useVolumeMultiplier:u}}=this.params;u&&o!==1&&Yi.isSupported()&&(this.volumeMultiplierManager=new Yi(this.providerOutput,this.current$,this.volumeMultiplierError$,o))}init(){this.subscription.add(this.initProviderErrorHandling()).add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()})).add(this.providerOutput.availableVideoCodecs$.subscribe(e=>{!this.videoCodecsIterator&&e.length>1&&(this.videoCodecsIterator=new Wi(e))}))}destroy(){this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe(),this.volumeMultiplierManager?.destroy(),this.volumeMultiplierManager=null,this.tracer.end()}initProvider(){let e=this.chooseDestination(),t=this.chooseFormat(e);if(ZC(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(a){this.providerError$.next({id:"ProviderNotConstructed",category:Sn.WTF,message:"Failed to create provider",thrown:a})}i?this.current$.next({type:t,provider:i,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.tracer.log("reinitProvider"),this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.tracer.log("switchToNextProvider",{destination:e}),this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}switchToNextVideoCodec(){this.params.tuning.dash.codecsPrioritizeEnabled&&!this.videoCodecsIterator.isLast()&&(this.tracer.log("switchToNextVideoCodec"),this.destroyProvider(),this.videoCodecsIterator.next(),this.initProvider())}destroyProvider(){let e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"}),this.tracer.log("destroyProvider");let t=this.providerOutput.position$.getValue()*1e3,i=this.params.desiredState.seekState.getState(),a=i.state!=="none";if(this.params.desiredState.seekState.setState({state:"requested",position:a?i.position:t,forcePrecise:a?i.forcePrecise:!1}),e.scene3D){let n=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:n.x,y:n.y})}e.destroy();let s=this.providerOutput.isBuffering$;s.getValue()||s.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),this.tracer.log("createProvider",{destination:e,format:t}),e){case"SCREEN":return this.createScreenProvider(t);case"CHROMECAST":return this.createChromecastProvider(t);default:return Ma(e)}}createScreenProvider(e){let{sources:t,container:i,desiredState:a,panelSize:s}=this.params,n=this.providerOutput,o={container:i,source:null,desiredState:a,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning,panelSize:s};switch(e){case"DASH_SEP":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_ONDEMAND":case"DASH_STREAMS":{let u=this.applyFailoverHost(t[e]),l=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return Bt(u),new xa({...o,source:u,sourceHls:l,forceVideoCodec:this.videoCodecsIterator?.getValue()})}case"DASH_LIVE_CMAF":{let u=this.applyFailoverHost(t[e]);return Bt(u),new Pa({...o,source:u})}case"HLS":case"HLS_ONDEMAND":{let u=this.applyFailoverHost(t[e]);return Bt(u),V.video.nativeHlsSupported||!this.params.tuning.useHlsJs?new La({...o,source:u}):new wa({...o,source:u})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let u=this.applyFailoverHost(t[e]);return Bt(u),new Aa({...o,source:u,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let u=this.applyFailoverHost(t[e]);return Bt(u),new Ra({...o,source:u})}case"DASH_LIVE":{let u=this.applyFailoverHost(t[e]);return Bt(u),new bg({...o,source:u,config:{...rD,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let u=this.applyFailoverHost(t[e]);return Bt(u),new $a({container:i,source:u,desiredState:a,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 Ma(e)}}createChromecastProvider(e){let{sources:t,container:i,desiredState:a,meta:s}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return Bt(o),new Ir({connection:o,meta:s,container:i,source:t,format:e,desiredState:a,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 Ma(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return Ma(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 Ma(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;let t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;let i=a=>{let s=new URL(a);return s.host=t,s.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return{...e,url:i(e.url)}}return(0,Sy.default)((0,vy.default)(e).map(([a,s])=>[a,i(s)]))}initProviderErrorHandling(){let e=new by,t=!1,i=0;return e.add(tD(this.providerOutput.error$.pipe(my(a=>!this.params.tuning.ignoreAudioRendererError||!a.message||!/AUDIO_RENDERER_ERROR/ig.test(a.message))),cy({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(eD(a=>({id:`ProviderHangup:${a}`,category:Sn.WTF,message:`A ${a} 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 a=this.params.desiredState.playbackState.transitionEnded$.pipe(my(({to:s})=>s==="playing"),iD()).subscribe(()=>t=!0);e.add(a)})),e.add(this.providerError$.subscribe(a=>{let s=this.current$.getValue().destination,n={error:a,currentDestination:s};if(s==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("SCREEN"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let o=a.category===Sn.NETWORK,u=a.category===Sn.FATAL,l=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),c=i<this.params.tuning.providerErrorLimit&&!u,d=this.videoCodecsIterator&&!this.videoCodecsIterator.isLast()&&this.params.tuning.dash.codecsPrioritizeEnabled,p=l&&!u&&(o&&t||!c);n={...n,isNetworkError:o,isFatalError:u,haveFailoverHost:l,tryFailover:p,canReinitProvider:c},c?(i++,this.reinitProvider()):p?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):d?this.switchToNextVideoCodec():(i=0,this.switchToNextProvider(s??"SCREEN"))}this.tracer.error("providerError",gy(n))})),e}};import{fromEvent as yn,once as aD,combine as sD,Subscription as yy,ValueSubject as Kl,map as nD,filter as oD,isNonNullable as Tn,now as Be,safeStorage as Xl}from"@vkontakte/videoplayer-shared";var uD=5e3,Ty="one_video_throughput",Iy="one_video_rtt",Da=window.navigator.connection,Ey=()=>{let r=Da?.downlink;if(Tn(r)&&r!==10)return r*1e3},xy=()=>{let r=Da?.rtt;if(Tn(r)&&r!==3e3)return r},Py=(r,e,t)=>{let i=t*8,a=i/r;return i/(a+e)},Jl=class r{constructor(e){this.subscription=new yy;this.concurrentDownloads=new Set;this.tuningConfig=e;let t=r.load(Ty)||(e.useBrowserEstimation?Ey():void 0)||uD,i=r.load(Iy)??(e.useBrowserEstimation?xy():void 0)??0;if(this.throughput$=new Kl(t),this.rtt$=new Kl(i),this.rttAdjustedThroughput$=new Kl(Py(t,i,e.rttPenaltyRequestSize)),this.throughput=ai.getSmoothedValue(t,-1,e),this.rtt=ai.getSmoothedValue(i,1,e),e.useBrowserEstimation){let a=()=>{let n=Ey();n&&this.throughput.next(n);let o=xy();Tn(o)&&this.rtt.next(o)};Da&&"onchange"in Da&&this.subscription.add(yn(Da,"change").subscribe(a)),a()}this.subscription.add(this.throughput.smoothed$.subscribe(a=>{Xl.set(Ty,a.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(a=>{Xl.set(Iy,a.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(sD({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(nD(({throughput:a,rtt:s})=>Py(a,s,e.rttPenaltyRequestSize)),oD(a=>{let s=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(a-s)/s>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,i=Be(),a=new yy;switch(this.subscription.add(a),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:a.add(yn(e,"progress").pipe(aD()).subscribe(s=>{t=s.loaded,i=Be()}));break;case 1:case 0:a.add(yn(e,"loadstart").subscribe(()=>{t=0,i=Be()}));break}a.add(yn(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=Be(),u=n-t,l=o-i;this.addRawSpeed(u,l,1)}this.concurrentDownloads.delete(e),a.unsubscribe()}))}trackStream(e,t=!1){let i=e.getReader();if(!i){e.cancel("Could not get reader");return}let a=0,s=Be(),n=0,o=Be(),u=c=>{this.concurrentDownloads.delete(e),i.releaseLock(),e.cancel(`Throughput Estimator error: ${c}`).catch(()=>{})},l=async({done:c,value:d})=>{if(c)!t&&this.addRawSpeed(a,Be()-s,1),this.concurrentDownloads.delete(e);else if(d){if(t){let p=Be();if(p-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||p-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let f=o-s;f&&this.addRawSpeed(n,f,1,t),n=d.byteLength,s=Be()}else n+=d.byteLength;o=Be()}else a+=d.byteLength,n+=d.byteLength,n>=this.tuningConfig.streamMinSampleSize&&Be()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,Be()-o,this.concurrentDownloads.size),n=0,o=Be());await i?.read().then(l,u)}};this.concurrentDownloads.add(e),i?.read().then(l,u)}addRawSpeed(e,t,i=1,a=!1){if(r.sanityCheck(e,t,a)){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 a=e*8/t;return!(!a||!isFinite(a)||a>1e6||a<30||i&&e<1e4||!i&&e<10*1024||!i&&t<=20)}static load(e){let t=Xl.get(e);if(Tn(t))return parseInt(t,10)??void 0}},ky=Jl;import{fillWithDefault as lD,VideoQuality as In}from"@vkontakte/videoplayer-shared";var wy={configName:["core"],throughputEstimator:{type:"EmaAndMa",emaAlphaSlow:.2,emaAlphaFast:.7,emaAlpha:.45,basisTrendChangeCount:10,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1*1024*1024,streamMinSampleSize:10*1024,streamMinSampleTime:300,deviationDepth:20,deviationFactor:.5,lowLatency:{continuesByteSequenceInterval:50,maxLastEvaluationTimeout:300}},autoTrackSelection:{bitrateFactorAtEmptyBuffer:2.8,bitrateAudioFactorAtEmptyBuffer:10,bitrateFactorAtFullBuffer:2,bitrateAudioFactorAtFullBuffer:7,minVideoAudioRatio:5,minAvailableThroughputAudioRatio:5,usePixelRatio:!0,pixelRatioMultiplier:void 0,pixelRatioLogBase:3,pixelRatioLogCoefficients:[1,0,1],limitByContainer:!0,containerSizeFactor:1.3,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldownIncreaseQuality:15e3,trackCooldownDecreaseQuality:3e3,backgroundVideoQualityLimit:In.Q_4320P,activeVideoAreaThreshold:.1,highQualityLimit:In.Q_720P,trafficSavingLimit:In.Q_480P},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:In.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,seekBiasInTheEnd:2e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,crashOnStallTimeout:25e3,crashOnStallTWithoutDataTimeout:5e3,enableSubSegmentBufferFeeding:!0,bufferEmptinessTolerance:100,useFetchPriorityHints:!0,qualityLimitsOnStall:{stallDurationNoDataBeforeQualityDecrease:500,stallDurationToBeCount:100,stallCountBeforeQualityDecrease:3,resetQualityRestrictionTimeout:1e4,ignoreStallsOnSeek:!1},enableBaseUrlSupport:!0,maxSegmentRetryCount:5,sourceOpenTimeout:1e3,rejectOnSourceOpenTimeout:!1,codecsPrioritizeEnabled:!1},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,maxLiveDuration:7200,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:250,playbackCatchupSpeedup:.05,isActiveOnDefault:!1,bufferEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:"07A4434E",useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"dash",preferCMAF:!1,preferWebRTC:!1,preferMultiStream:!1,preferHDR:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,seekNearDurationBias:1,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useHlsJs:!1,useNativeHLSTextTracks:!1,useManagedMediaSource:!0,useNewSwitchTo:!1,useSafariEndlessRequestBugfix:!0,useRefactoredSearchGap:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,audioVideoSyncRate:20,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50},useVolumeMultiplier:!1,ignoreAudioRendererError:!1,useEnableSubtitlesParam:!1,useOldMSEDetection:!1,useHlsLiveNewTextManager:!1,exposeInternalsToGlobal:!1,hlsLiveNewTextManagerDownloadThreshold:4e3,disableYandexPiP:!1,asyncResolveClientChecker:!1,autostartOnlyIfVisible:!1},Ay=r=>({...lD(r,wy),configName:[...r.configName??[],...wy.configName]});import{assertNonNullable as En,combine as gt,ErrorCategory as xn,filter as L,filterChanged as Q,fromEvent as ec,isNonNullable as My,isNullable as bD,Logger as gD,map as U,mapTo as Cy,merge as Ot,now as Pn,once as _,Subject as G,Subscription as Dy,tap as tc,ValueSubject as y,isHigher as vD,isInvariantQuality as Vy,flattenObject as _t,throttle as ic,getTraceSubscriptionMethod as By,Tracer as SD,InternalsExposure as yD}from"@vkontakte/videoplayer-shared";import{merge as cD,map as dD,filter as Ly,isNonNullable as pD}from"@vkontakte/videoplayer-shared";var Zl=({seekState:r,position$:e})=>cD(r.stateChangeEnded$.pipe(dD(({to:t})=>t.state==="none"?void 0:(t.position??NaN)/1e3),Ly(pD)),e.pipe(Ly(()=>r.getState().state==="none")));import{assertNonNullable as hD}from"@vkontakte/videoplayer-shared";var Ry=r=>{let e=typeof r.container=="string"?document.getElementById(r.container):r.container;return hD(e,`Wrong container or containerId {${r.container}}`),e};import{filter as mD,once as fD}from"@vkontakte/videoplayer-shared";var $y=(r,e,t,i)=>{r!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&t?.getValue().length===0?t.pipe(mD(a=>a.length>0),fD()).subscribe(a=>{a.find(i)&&e.startTransitionTo(r)}):(r===void 0||t?.getValue().find(i))&&e.startTransitionTo(r)};var kn=class{constructor(e={configName:[]},t=SD.createRootTracer(!1)){this.subscription=new Dy;this.logger=new gD;this.abrLogger=this.logger.createComponentLog("ABR");this.internalsExposure=null;this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new y(!1);this.hasLiveOffsetByPausedTimer=0;this.playerInitRequest=0;this.playerInited=new y(!1);this.wasSetStartedQuality=!1;this.desiredState={playbackState:new D("stopped"),seekState:new D({state:"none"}),volume:new D({volume:1,muted:!1}),videoTrack:new D(void 0),videoStream:new D(void 0),audioStream:new D(void 0),autoVideoTrackSwitching:new D(!0),autoVideoTrackLimits:new D({}),isLooped:new D(!1),isLowLatency:new D(!1),playbackRate:new D(1),externalTextTracks:new D([]),internalTextTracks:new D([]),currentTextTrack:new D(void 0),textTrackCuesSettings:new D({}),cameraOrientation:new D({x:0,y:0})};this.info={playbackState$:new y(void 0),position$:new y(0),duration$:new y(1/0),muted$:new y(!1),volume$:new y(1),availableVideoStreams$:new y([]),currentVideoStream$:new y(void 0),availableQualities$:new y([]),availableQualitiesFps$:new y({}),currentQuality$:new y(void 0),isAutoQualityEnabled$:new y(!0),autoQualityLimitingAvailable$:new y(!1),autoQualityLimits$:new y({}),predefinedQualityLimitType$:new y("unknown"),availableAudioStreams$:new y([]),currentAudioStream$:new y(void 0),availableAudioTracks$:new y([]),isAudioAvailable$:new y(!0),currentPlaybackRate$:new y(1),currentBuffer$:new y({start:0,end:0}),isBuffering$:new y(!0),isStalled$:new y(!1),isEnded$:new y(!1),isLooped$:new y(!1),isLive$:new y(void 0),isLiveEnded$:new y(null),canChangePlaybackSpeed$:new y(void 0),atLiveEdge$:new y(void 0),atLiveDurationEdge$:new y(void 0),liveTime$:new y(void 0),liveBufferTime$:new y(void 0),liveLatency$:new y(void 0),currentFormat$:new y(void 0),availableTextTracks$:new y([]),currentTextTrack$:new y(void 0),throughputEstimation$:new y(void 0),rttEstimation$:new y(void 0),videoBitrate$:new y(void 0),hostname$:new y(void 0),httpConnectionType$:new y(void 0),httpConnectionReused$:new y(void 0),surface$:new y("none"),chromecastState$:new y("NOT_AVAILABLE"),chromecastDeviceName$:new y(void 0),intrinsicVideoSize$:new y(void 0),availableSources$:new y(void 0),is3DVideo$:new y(!1),currentVideoSegmentLength$:new y(0),currentAudioSegmentLength$:new y(0)};this.events={inited$:new G,ready$:new G,started$:new G,playing$:new G,paused$:new G,stopped$:new G,willStart$:new G,willResume$:new G,willPause$:new G,willStop$:new G,willDestruct$:new G,watchCoverageRecord$:new G,watchCoverageLive$:new G,managedError$:new G,fatalError$:new G,fetcherRecoverableError$:new G,ended$:new G,looped$:new G,seeked$:new G,willSeek$:new G,autoplaySoundProhibited$:new G,firstBytes$:new G,loadedMetadata$:new G,firstFrame$:new G,canplay$:new G,log$:new G,fetcherError$:new G,severeStallOccured$:new G};this.experimental={element$:new y(void 0),tuningConfigName$:new y([]),enableDebugTelemetry$:new y(!1),dumpTelemetry:Fb,getCurrentTime$:new y(null)};if(this.initLogs(),this.tuning=Ay(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new Ka({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new ky(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new yD("CORE"),this.internalsExposure.expose({player:this})),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(i,a,s)=>{let n=Reflect.get(i,a,s);return typeof n!="function"?n:(...o)=>{try{return n.apply(i,o)}catch(u){let l=o.map(p=>JSON.stringify(p,(h,f)=>{let b=typeof f;return(0,Oy.default)(["number","string","boolean"],b)?f:f===null?null:`<${b}>`})),c=`Player.${String(a)}`,d=`Exception calling ${c} (${l.join(", ")})`;throw this.events.fatalError$.next({id:c,category:xn.WTF,message:d,thrown:u}),u}}}})}initVideo(e){this.config=e,this.internalsExposure?.expose({config:e,logger:this.logger,tuning:this.tuning});let t=()=>{let{container:s,...n}=e;this.tracer.log("initVideo",_t(n)),this.domContainer=Ry(e),this.chromecastInitializer.contentId=e.meta?.videoId,this.providerContainer=new Ca({sources:e.sources,meta:e.meta??{},failoverHosts:e.failoverHosts??[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,tracer:this.tracer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning,volumeMultiplier:e.volumeMultiplier,panelSize:e.panelSize}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.initTracerSubscription(),this.providerContainer.init(),this.setLiveLowLatency(this.tuning.dashCmafLive.lowLatency.isActiveOnDefault),this.setMuted(this.tuning.isAudioDisabled),this.initDebugTelemetry(),this.initWakeLock(),this.playerInited.next(!0)},i=()=>{this.tuning.autostartOnlyIfVisible&&window.requestAnimationFrame?this.playerInitRequest=window.requestAnimationFrame(()=>t()):t()},a=()=>{this.tuning.asyncResolveClientChecker?V.isInited$.pipe(L(s=>!!s),_()).subscribe(()=>{console.log("Core SDK async start"),i()}):i()};return this.isNotActiveTabCase()?(this.tracer.log("request play from hidden tab"),ec(document,"visibilitychange").pipe(_()).subscribe(a)):a(),this}destroy(){this.tracer.log("destroy"),window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.playerInitRequest&&window.cancelAnimationFrame(this.playerInitRequest),this.events.willDestruct$.next(),this.stop(),this.providerContainer?.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe(),this.tracer.end(),this.internalsExposure?.destroy()}prepare(){return this.subscription.add(this.playerInited.pipe(L(e=>!!e),_()).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(L(e=>!!e),_()).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(L(e=>!!e),_()).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(L(e=>!!e),_()).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(L(i=>!!i),_()).subscribe(()=>{let i=this.info.duration$.getValue(),a=this.info.isLive$.getValue(),s=e;e>=i&&!a&&(s=i-this.tuning.seekNearDurationBias),this.tracer.log("seekTime",{duration:i,isLive:a,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(L(t=>!!t),_()).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(L(i=>!!i),_()).subscribe(()=>{let i=this.desiredState.volume,s=i.getTransition()?.to.muted??this.info.muted$.getValue(),n=t??(this.tuning.isAudioDisabled||s);this.tracer.log("setVolume",{volume:e,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:n}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setVolume(e):i.startTransitionTo({volume:e,muted:n})})),this}setMuted(e){return this.subscription.add(this.playerInited.pipe(L(t=>!!t),_()).subscribe(()=>{let t=this.desiredState.volume,i=this.tuning.isAudioDisabled||e,s=t.getTransition()?.to.volume??this.info.volume$.getValue();this.tracer.log("setMuted",{isMuted:e,nextMuted:i,volume:s,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue()}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setMuted(i):t.startTransitionTo({volume:s,muted:i})})),this}setVideoStream(e){return this.subscription.add(this.playerInited.pipe(L(t=>!!t),_()).subscribe(()=>{this.desiredState.videoStream.startTransitionTo(e)})),this}setAudioStream(e){return this.subscription.add(this.playerInited.pipe(L(t=>!!t),_()).subscribe(()=>{this.desiredState.audioStream.startTransitionTo(e)})),this}setQuality(e){return this.subscription.add(this.playerInited.pipe(L(t=>!!t),_()).subscribe(()=>{En(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(L(i=>i.length>0),_()).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(L(t=>!!t),_()).subscribe(()=>{this.tracer.log("setAutoQuality",{enable:e}),this.desiredState.autoVideoTrackSwitching.startTransitionTo(e)})),this}setAutoQualityLimits(e){return this.subscription.add(this.playerInited.pipe(L(t=>!!t),_()).subscribe(()=>{this.tracer.log("setAutoQualityLimits",_t(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e)})),this}setPredefinedQualityLimits(e){return this.subscription.add(this.playerInited.pipe(L(t=>!!t),_()).subscribe(()=>{if(this.info.predefinedQualityLimitType$.getValue()===e)return this;let{highQualityLimit:t,trafficSavingLimit:i}=this.tuning.autoTrackSelection,a;switch(e){case"high_quality":a={min:t,max:void 0};break;case"traffic_saving":a={max:i,min:void 0};break;default:a={max:void 0,min:void 0}}this.setAutoQualityLimits(a)})),this}setPlaybackRate(e){return this.subscription.add(this.playerInited.pipe(L(t=>!!t),_()).subscribe(()=>{En(this.providerContainer);let t=this.providerContainer?.providerOutput.element$.getValue();this.tracer.log("setPlaybackRate",{playbackRate:e,isVideoElementAvailable:!!t}),t&&(this.desiredState.playbackRate.setState(e),t.playbackRate=e)})),this}setExternalTextTracks(e){return this.subscription.add(this.playerInited.pipe(L(t=>!!t),_()).subscribe(()=>{e.length&&this.tracer.log("setExternalTextTracks",_t(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t})))})),this}selectTextTrack(e){return this.subscription.add(this.playerInited.pipe(L(t=>!!t),_()).subscribe(()=>{$y(e,this.desiredState.currentTextTrack,this.providerContainer?.providerOutput.availableTextTracks$,t=>t.id===e),this.tracer.log("selectTextTrack",{textTrackId:e})})),this}setTextTrackCueSettings(e){return this.subscription.add(this.playerInited.pipe(L(t=>!!t),_()).subscribe(()=>{this.tracer.log("setTextTrackCueSettings",{...e}),this.desiredState.textTrackCuesSettings.startTransitionTo(e)})),this}setLiveLowLatency(e){let t=this.info.isLive$.getValue(),i=this.desiredState.isLowLatency.getState();return!t||i===e?this:(this.tracer.log("live switch to low latency "+e),this.desiredState.isLowLatency.setState(e),this.seekTime(0))}setLooped(e){return this.subscription.add(this.playerInited.pipe(L(t=>!!t),_()).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(L(i=>!!i),_()).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(L(t=>!!t),_()).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(L(i=>!!i),_()).subscribe(()=>{let i=this.getScene3D();if(this.tracer.log("moveCameraFocusPX",{isScene3DAvailable:!!i,dxpx:e,dypx:t}),i){let a=i.getCameraRotation(),s=i.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:a.x+s.x,y:a.y+s.y})}})),this}holdCamera(){return this.subscription.add(this.playerInited.pipe(L(e=>e),_()).subscribe(()=>{let e=this.getScene3D();e&&e.holdCamera()})),this}releaseCamera(){return this.subscription.add(this.playerInited.pipe(L(e=>!!e),_()).subscribe(()=>{let e=this.getScene3D();e&&e.releaseCamera()})),this}getExactTime(){if(!this.providerContainer)return 0;let e=this.providerContainer.providerOutput.element$.getValue();if(bD(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),i=t.state==="none"?void 0:t.position;return My(i)?i/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){let e=this.providerContainer?.current$.getValue();if(e?.provider?.scene3D)return e.provider.scene3D}setIntrinsicVideoSize(...e){let t={width:e.reduce((i,{width:a})=>i||a||0,0),height:e.reduce((i,{height:a})=>i||a||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(Ot(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(U(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(U(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(U(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(U(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(U(e=>e.to)).subscribe(e=>{this.info.autoQualityLimits$.next(e);let{highQualityLimit:t,trafficSavingLimit:i}=this.tuning.autoTrackSelection;this.info.predefinedQualityLimitType$.next(Vu({limits:e,highQualityLimit:t,trafficSavingLimit:i}))})),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(L(({from:e})=>e==="stopped"),_()).subscribe(()=>{this.initedAt=Pn(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case"ready":this.events.ready$.next();break;case"playing":this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case"paused":this.events.paused$.next();break;case"stopped":this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case"paused":this.events.willPause$.next();break;case"playing":this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case"stopped":this.events.willStop$.next();break;default:}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("willSeekEvent",_t(n)),n.state==="requested"?this.desiredState.seekState.setState({...n,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:xn.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe(_()).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",_t(n)),n.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe(U(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(U(n=>n.destination),Q()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(gt({availableVideoTracks:e.providerOutput.availableVideoTracks$,currentVideoStream:e.providerOutput.currentVideoStream$}).pipe(U(({availableVideoTracks:n,currentVideoStream:o})=>n.filter(u=>o?o.id===u.streamId:!0).map(({quality:u})=>u).sort((u,l)=>Vy(u)?1:Vy(l)?-1:vD(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(Q()).subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.pipe(L(n=>My(n))).subscribe(n=>{this.info.currentQuality$.next(n?.quality),this.info.videoBitrate$.next(n?.bitrate)})).add(e.providerOutput.currentVideoSegmentLength$.pipe(Q((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe(Q((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(Q()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(Q()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(Q()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.autoVideoTrackLimits$.subscribe(n=>{this.desiredState.autoVideoTrackLimits.setState(n??{})})).add(e.providerOutput.currentBuffer$.pipe(U(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(tc(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(gt({hasLiveOffsetByPaused:Ot(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(U(n=>n.to),Q(),U(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(gt({atLiveEdge:gt({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Zl({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(U(({isLive:n,position:o,isLowLatency:u})=>{let l=this.getActiveLiveDelay(u);return n&&Math.abs(o)<l/1e3}),Q(),tc(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(U(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add(gt({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(U(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),Q(),tc(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(U(n=>n.muted),Q()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(U(n=>n.volume),Q()).subscribe(this.info.volume$)).add(Zl({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(Ot(e.providerOutput.endedEvent$.pipe(Cy(!0)),e.providerOutput.seekedEvent$.pipe(Cy(!1))).pipe(Q()).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(U(n=>({id:n?`No${n}`:"NoProviders",category:xn.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(_(),U(n=>n??Pn()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(_(),U(()=>Pn()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(_(),U(()=>Pn()-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 y(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let i=new y(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(L(({to:n})=>n==="playing"),_()).subscribe(()=>i.next(!1)));let a=0,s=Ot(e.providerOutput.isBuffering$,t,i).pipe(U(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||i.getValue();return n&&!o}),Q());this.subscription.add(s.subscribe(n=>{n?a=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(a),this.info.isStalled$.next(!1))})),this.subscription.add(Ot(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{let n=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n?.videoWidth,height:n?.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{let o=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n?.size?.width,height:n?.size?.height},{width:o?.videoWidth,height:o?.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add(Ot(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,e.providerOutput.elementVisible$,this.chromecastInitializer.castState$).subscribe(()=>{let n=e.providerOutput.inPiP$.getValue(),o=e.providerOutput.inFullscreen$.getValue(),u=e.providerOutput.element$.getValue(),l=e.providerOutput.elementVisible$.getValue(),c=this.chromecastInitializer.castState$.getValue(),d;c==="CONNECTED"?d="second_screen":u?l?n?d="pip":o?d="fullscreen":d="inline":d="invisible":d="none",this.info.surface$.getValue()!==d&&this.info.surface$.next(d)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(U(e=>e?.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new Dy;this.subscription.add(t),this.subscription.add(e.current$.pipe(Q((i,a)=>i.provider===a.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(L(i=>i.length>0),_()).subscribe(i=>{this.setStartingVideoTrack(i)}))}))}setStartingVideoTrack(e){let t;this.wasSetStartedQuality=!0;let i=this.explicitInitialQuality??this.info.currentQuality$.getValue();i&&(t=e.find(({quality:a})=>a===i),t||this.setAutoQuality(!0)),t||(t=$t(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(Ot(this.desiredState.videoTrack.stateChangeStarted$.pipe(U(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(U(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(U(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(U(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(U(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(U(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(U(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(U(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(U(e=>({component:"desiredState",message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`}))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){let e=this.providerContainer?.providerOutput;En(this.providerContainer),En(e),Nb(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(t=>_b(t)),this.providerContainer.current$.subscribe(({type:t})=>wr("provider",t)),e.duration$.subscribe(t=>wr("duration",t)),e.availableVideoTracks$.pipe(L(t=>!!t.length),_()).subscribe(t=>wr("tracks",t)),this.events.fatalError$.subscribe(new be("fatalError")),this.events.managedError$.subscribe(new be("managedError")),e.position$.subscribe(new be("position")),e.currentVideoTrack$.pipe(U(t=>t?.quality)).subscribe(new be("quality")),this.info.currentBuffer$.subscribe(new be("buffer")),e.isBuffering$.subscribe(new be("isBuffering"))].forEach(t=>this.subscription.add(t)),wr("codecs",V.video.supportedCodecs)}initTracerSubscription(){let e=By(this.tracer.log.bind(this.tracer)),t=By(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(Q()).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(gt({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe(L(({currentQuality:i,videoBitrate:a})=>!!i&&!!a),Q((i,a)=>i.currentQuality===a.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe(L(i=>i>0),Q()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe(L(i=>i>0),Q()).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(gt({currentBuffer:this.info.currentBuffer$.pipe(L(i=>i.end>0),Q((i,a)=>i.end===a.end&&i.start===a.start)),position:this.info.position$.pipe(Q())}).pipe(ic(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe(Q()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe(Q()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe(Q()).subscribe(e("canChangePlaybackSpeed"))).add(gt({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(L(({liveTime:i,liveBufferTime:a})=>!!i&&!!a),ic(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(Q(),L(i=>i===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(Q(),L(i=>i===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe(Q()).subscribe(e("muted"))).add(this.info.volume$.pipe(Q()).subscribe(e("volume"))).add(this.info.isEnded$.pipe(Q(),L(i=>i===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add(gt({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(L(({throughputEstimation:i,rtt:a})=>!!i&&!!a),ic(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(Q(),L(i=>i===!0)).subscribe(e("is3DVideo"))).add(this.info.surface$.subscribe(e("surface"))).add(this.events.ended$.subscribe(e("ended"))).add(this.events.looped$.subscribe(e("looped"))).add(this.events.managedError$.subscribe(t("managedError"))).add(this.events.fatalError$.subscribe(t("fatalError"))).add(this.events.firstBytes$.subscribe(e("firstBytes"))).add(this.events.firstFrame$.subscribe(e("firstFrame"))).add(this.events.canplay$.subscribe(e("canplay")))}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e,t=()=>{e?.release(),e=void 0},i=async()=>{t(),e=await window.navigator.wakeLock.request("screen").catch(a=>{a instanceof DOMException&&a.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:xn.DOM,message:String(a)})})};this.subscription.add(Ot(ec(document,"visibilitychange"),ec(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let a=document.visibilityState==="visible",s=this.desiredState.playbackState.getState()==="playing",n=!!e&&!e?.released;a&&s?n||i():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let i=e.find(a=>a.quality===t);this.tracer.log("setVideoTrackIdByQuality",_t({quality:t,availableTracks:_t(e),track:_t(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&&!Dr()}};import{Subscription as v4,Observable as S4,Subject as y4,ValueSubject as T4,VideoQuality as I4}from"@vkontakte/videoplayer-shared";var E4=`@vkontakte/videoplayer-core@${sc}`;export{Ha as ChromecastState,Ln as HttpConnectionType,S4 as Observable,$e as PlaybackState,kn as Player,ja as PredefinedQualityLimits,E4 as SDK_VERSION,y4 as Subject,v4 as Subscription,Rn as Surface,sc as VERSION,T4 as ValueSubject,ut as VideoFormat,I4 as VideoQuality,V as clientChecker,Pr as isMobile};
68
+ `;var an=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 a=this.canvas.getContext("webgl");if(!a)throw new Error("Could not initialize WebGL context");this.gl=a,this.container.appendChild(this.canvas),this.camera=new tn(this.params.fov,this.params.orientation),this.cameraRotationManager=new rn(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"),a=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(a,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(Tg,this.gl.VERTEX_SHADER),i=this.createShader(Ig,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,a=this.frameHeight/(this.frameWidth/this.viewportWidth);return a>this.viewportHeight?t=this.viewportHeight/a:i=a/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,a=this.camera.fov.y/180/2,s=e-i,n=t-a,o=e+i,u=t-a,l=e+i,d=t+a,c=e-i,p=t+a;return[s,n,o,u,l,d,c,p]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){let e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}};import{isNullable as m$,now as Eg,Subscription as f$,filter as b$,combine as v$,debounce as S$,ValueSubject as Pl,isNonNullable as g$}from"@vkontakte/videoplayer-shared";var kl=class{constructor(){this.isSeeked$=new Pl(!1);this.isBuffering$=new Pl(!1);this.currentStallsCount=0;this.maxQualityLimit=void 0;this.lastUniqueVideoTrackSelectedTimestamp=0;this.predictedThroughputWithoutData=0;this.subscription=new f$;this.severeStallOccurred$=new Pl(!1)}connect(e){this.currentStallDuration$=e.currentStallDuration$,this.videoLastDataObtainedTimestamp$=e.videoLastDataObtainedTimestamp$,this.throughput$=e.throughput$,this.rtt$=e.rtt$,this.qualityLimitsOnStall=e.qualityLimitsOnStall,this.subscription.add(e.isSeeked$.subscribe(this.isSeeked$)),this.subscription.add(e.isBuffering$.subscribe(this.isBuffering$)),this.subscription.add(e.looped$.subscribe(t=>this.currentStallsCount=0)),this.subscription.add(v$({isBuffering:this.isBuffering$,isSeeked:this.isSeeked$}).pipe(S$(this.qualityLimitsOnStall.stallDurationToBeCount),b$(({isBuffering:t,isSeeked:i})=>t&&!i)).subscribe(t=>{this.currentStallsCount++})),this.subscription.add(this.currentStallDuration$.subscribe(t=>{let{ignoreStallsOnSeek:i}=this.qualityLimitsOnStall;if(m$(this.lastUniqueVideoTrackSelected)||i&&this.isSeeked$.getValue())return;let{stallDurationNoDataBeforeQualityDecrease:a,stallCountBeforeQualityDecrease:s,resetQualityRestrictionTimeout:n}=this.qualityLimitsOnStall,o=this.rtt$.getValue(),u=this.throughput$.getValue(),l=this.videoLastDataObtainedTimestamp$.getValue(),d=Eg(),c=s&&this.currentStallsCount>=s,p=a&&d-this.lastUniqueVideoTrackSelectedTimestamp>=a+o&&d-l>=a+o&&t>=a;(c||p)&&(this.severeStallOccurred$.next(!0),window.clearTimeout(this.qualityRestrictionTimer),this.maxQualityLimit=this.lastUniqueVideoTrackSelected.quality,g$(this.lastUniqueVideoTrackSelected.bitrate)&&u>this.lastUniqueVideoTrackSelected.bitrate&&(this.predictedThroughputWithoutData=this.lastUniqueVideoTrackSelected.bitrate)),t||(this.severeStallOccurred$.next(!1),window.clearTimeout(this.qualityRestrictionTimer),this.qualityRestrictionTimer=window.setTimeout(()=>{this.maxQualityLimit=void 0,this.predictedThroughputWithoutData=0},n))}))}get videoMaxQualityLimit(){return this.maxQualityLimit}get predictedThroughput(){return this.predictedThroughputWithoutData}set lastVideoTrackSelected(e){this.lastUniqueVideoTrackSelected?.id!==e.id&&(this.lastUniqueVideoTrackSelected=e,this.lastUniqueVideoTrackSelectedTimestamp=Eg(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe()}},xg=kl;import{combine as y$,map as T$,observeElementSize as I$,Subscription as E$,ValueSubject as wl,noop as x$}from"@vkontakte/videoplayer-shared";var sn=class{constructor(){this.subscription=new E$;this.pipSize$=new wl(void 0);this.videoSize$=new wl(void 0);this.elementSize$=new wl(void 0);this.pictureInPictureWindowRemoveEventListener=x$}connect({observableVideo:e,video:t}){let i=a=>{let s=a.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add(I$(t).subscribe(this.videoSize$)).add(e.enterPip$.subscribe(({pictureInPictureWindow:a})=>{this.pipSize$.next({width:a.width,height:a.height}),a.addEventListener("resize",i),this.pictureInPictureWindowRemoveEventListener=()=>{a.removeEventListener("resize",i)}})).add(e.leavePip$.subscribe(()=>{this.pictureInPictureWindowRemoveEventListener()})).add(y$({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(T$(({videoSize:a,inPip:s,pipSize:n})=>s?n:a)).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 ii=class{constructor(e){this.subscription=new L$;this.videoState=new A("stopped");this.droppedFramesManager=new Vs;this.stallsManager=new xg;this.elementSizeManager=new sn;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Er;this.audioTrackSwitchHistory=new Er;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(),a=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(a.state==="requested"&&i?.to!=="paused"&&e!=="stopped"&&t!=="stopped"&&this.seek(a.position,a.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"),x(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"),x(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="ready"&&x(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):t==="playing"&&this.video.paused?this.playIfAllowed():i?.to==="playing"&&x(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&x(this.params.desiredState.playbackState,"paused");return;default:return k$(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new an(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:e.projectionData?.pose.yaw||0,y:e.projectionData?.pose.pitch||0,z:e.projectionData?.pose.roll||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSizeManager.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.textTracksManager=new Ce(e.source.url),this.params=e,this.video=fe(e.container,e.tuning),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(re(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 en({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params,i=ge(this.video);this.subscription.add(()=>i.destroy());let a=this.constructor.name,s=o=>{e.error$.next({id:a,category:Pg.WTF,message:`${a} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:i,genericErrorListener:s,connect:(o,u)=>this.subscription.add(o.subscribe(u,s))}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:a,connect:s}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(Al(c=>!!c.length),wg()).subscribe(c=>{this.droppedFramesManager.connect({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(Rl(c=>c.to.state!=="none"),ma());this.stallsManager.connect({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$.pipe(ma()),videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,qualityLimitsOnStall:this.params.tuning.dash.qualityLimitsOnStall,isBuffering$:i.isBuffering$,looped$:i.looped$}),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(this.player.error$,e.error$),s(this.player.fetcherRecoverableError$,e.fetcherRecoverableError$),s(this.player.fetcherError$,e.fetcherError$),s(this.player.lastConnectionType$,e.httpConnectionType$),s(this.player.lastConnectionReused$,e.httpConnectionReused$),s(this.player.isLive$,e.isLive$),s(this.player.lastRequestFirstBytes$.pipe(Al(kg),wg()),e.firstBytesEvent$),s(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),s(this.videoState.stateChangeEnded$.pipe(Rl(c=>c.to)),this.params.output.playbackState$),this.subscription.add(i.loopExpected$.subscribe(c=>{t.seekState.setState({state:"requested",position:0,forcePrecise:!1})})),this.subscription.add(i.looped$.subscribe(()=>this.player.warmUpMediaSourceIfNeeded(),a)),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,a)),this.subscription.add(tt(this.video,t.isLooped,a)),this.subscription.add(ve(this.video,t.volume,i.volumeState$,a)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,a)),this.subscription.add(De(this.video,t.playbackRate,i.playbackRateState$,a)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),s(Ve(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),x(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},a)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),x(t.playbackState,"paused")},a)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},a)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:c})=>{if(c==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let p=this.player.getStreams();if(w$(p,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let f=[];for(let b of p.audio){f.push(ol(b));let S=[];for(let v of b.representations){let P=WS(v);S.push(P),this.audioTracksMap.set(P,{stream:b,representation:v})}this.audioStreamsMap.set(b,S)}this.params.output.availableAudioStreams$.next(f)}let h=[];for(let f of p.video){h.push(ul(f));let b=[];for(let S of f.representations){let v=QS({...S,streamId:f.id});v&&(b.push(v),this.videoTracksMap.set(v,{stream:f,representation:S}))}this.videoStreamsMap.set(f,b)}this.params.output.availableVideoStreams$.next(h);for(let f of p.text)for(let b of f.representations){let S=YS(f,b);this.textTracksMap.set(S,{stream:f,representation:b})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else c==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},a));let{vktvAbrThrottle:o}=this.params.tuning.dash,u=o&&XS(o)||null;this.subscription.add(nn(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$,R$(this.video,"progress")).pipe(Al(()=>this.videoTracksMap.size>0)).subscribe(async()=>{let c=this.player.state$.getState(),p=this.player.state$.getTransition();if(c!=="manifest_ready"&&c!=="running"||p||c==="running"&&u&&!u())return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState()),this.selectVideoAudioRepresentations();let{video:h,audio:f}=this.selectedRepresentations;if(!h)return;let b=Kt(this.videoTracksMap.keys(),v=>this.videoTracksMap.get(v)?.representation.id===h.id);kg(b)&&(this.stallsManager.lastVideoTrackSelected=b);let S=this.params.desiredState.autoVideoTrackLimits.getTransition();if(S&&this.params.output.autoVideoTrackLimits$.next(S.to),c==="manifest_ready")await this.player.initRepresentations(h.id,f?.id,this.params.sourceHls);else if(await this.player.switchRepresentation("video",h.id),f){let v=!!t.audioStream.getTransition();await this.player.switchRepresentation("audio",f.id,v)}},a)),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(ma()).subscribe(c=>{let p=Kt(this.videoTracksMap.entries(),([,{representation:S}])=>S.id===c);if(!p){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[h,{stream:f}]=p,b=this.params.desiredState.videoStream.getTransition();b&&b.to&&b.to.id===f.id&&this.params.desiredState.videoStream.setState(b.to),e.currentVideoTrack$.next(h),e.currentVideoStream$.next(ul(f))},a)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(ma()).subscribe(c=>{let p=Kt(this.audioTracksMap.entries(),([,{representation:S}])=>S.id===c);if(!p){e.currentAudioStream$.next(void 0);return}let[h,{stream:f}]=p,b=this.params.desiredState.audioStream.getTransition();b&&b.to&&b.to.id===f.id&&this.params.desiredState.audioStream.setState(b.to),e.currentAudioStream$.next(ol(f))},a)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(c=>{if(c?.is3dVideo&&this.params.tuning.spherical?.enabled)try{this.init3DScene(c),e.is3DVideo$.next(!0)}catch(p){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${p}`})}else this.destroy3DScene(),this.params.tuning.spherical?.enabled&&e.is3DVideo$.next(!1)},a)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,a)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,a)),this.textTracksManager.connect(this.video,t,e);let l=t.playbackState.stateChangeStarted$.pipe(Rl(({to:c})=>c==="ready"),ma());this.subscription.add(nn(l,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,Ll(["init"])).subscribe(()=>{let c=t.autoVideoTrackSwitching.getState(),h=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:c?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(h)})),this.subscription.add(nn(l,this.player.state$.stateChangeEnded$,Ll(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let d=nn(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Ll(["init"])).pipe(A$(0));this.subscription.add(d.subscribe(this.syncPlayback,a))}selectVideoAudioRepresentations(){if(this.player.isStreamEnded)return;let{desiredState:e,output:t}=this.params,i=e.autoVideoTrackSwitching.getState(),a=e.videoTrack.getState()?.id,s=Kt(this.videoTracksMap.keys(),k=>k.id===a),n=t.currentVideoTrack$.getValue(),o=e.videoStream.getState()??(s&&this.videoTracksMap.get(s)?.stream)??this.videoStreamsMap.size===1?this.videoStreamsMap.keys().next().value:void 0;if(!o)return;let u=Kt(this.videoStreamsMap.keys(),k=>k.id===o.id),l=u&&this.videoStreamsMap.get(u);if(!l)return;let d=Ge(this.video.buffered,this.video.currentTime*1e3),c;this.player.isActiveLive$.getValue()?c=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?c=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:c=i?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let p=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,h=Math.min(d/Math.min(c,p||1/0),1),f=e.audioStream.getState()??(this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0),b=f?.id&&Kt(this.audioStreamsMap.keys(),k=>k.id===f.id)||this.audioStreamsMap.keys().next().value,S=0;if(b){if(s&&!i){let k=Ms(s,l,this.audioStreamsMap.get(b)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);S=Math.max(S,k?.bitrate??-1/0)}if(n){let k=Ms(n,l,this.audioStreamsMap.get(b)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);S=Math.max(S,k?.bitrate??-1/0)}}let v=s;(i||!v)&&(v=Pt(l,{container:this.elementSizeManager.getValue(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:S,forwardBufferHealth:h,current:n,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}));let P=b&&Ub(v,l,this.audioStreamsMap.get(b)??[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:h,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate}),y=this.videoTracksMap.get(v)?.representation,I=P&&this.audioTracksMap.get(P)?.representation;y&&I?(this.selectedRepresentations.video=y,this.selectedRepresentations.audio=I):y&&!I&&this.audioTracksMap.size===0&&(this.selectedRepresentations.video=y,this.selectedRepresentations.audio=null)}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){ye(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Pg.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),be(this.video)}};var fa=class extends ii{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};import{combine as Ml,merge as Ag,filter as Rg,filterChanged as M$,isNullable as $l,map as Lg,ValueSubject as Dl,isNonNullable as $$}from"@vkontakte/videoplayer-shared";var ba=class extends ii{constructor(e){super(e),this.textTracksManager.destroy()}subscribe(){super.subscribe();let e=-1,{output:t,observableVideo:i,desiredState:a,connect:s}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),s(i.timeUpdate$,t.liveBufferTime$),s(this.player.liveSeekableDuration$,t.duration$),s(this.player.liveLatency$,t.liveLatency$);let n=new Dl(1);s(i.playbackRateState$,n),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(a.isLowLatency.stateChangeEnded$.pipe(Lg(o=>o.to)).subscribe(this.player.isLowLatency$)).add(Ml({liveBufferTime:t.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(Lg(({liveBufferTime:o,liveAvailabilityStartTime:u})=>o&&u?o+u:void 0)).subscribe(t.liveTime$)).add(this.player.liveStreamStatus$.pipe(Rg(o=>$$(o))).subscribe(o=>t.isLiveEnded$.next(o!=="active"&&t.position$.getValue()===0))).add(Ml({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:Ag(i.playbackRateState$,new Dl(1))}).pipe(Rg(({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||$l(l)||(e=o-l)})).add(Ml({time:t.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:Ag(i.playbackRateState$,new Dl(1))}).pipe(M$((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||$l(o)||$l(u))return;let p=-1*(u-o-e);t.position$.next(Math.min(p,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(o=>{if(o){let u=zS(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 $g=D(Ss(),1);import{assertNever as va,assertNonNullable as Mg,debounce as D$,ErrorCategory as on,filter as C$,isNonNullable as V$,isNullable as B$,map as un,merge as O$,Observable as _$,observableFrom as N$,Subscription as F$,videoSizeToQuality as q$}from"@vkontakte/videoplayer-shared";var We={};var qi=(r,e)=>new _$(t=>{let i=(a,s)=>t.next(s);return r.on(e,i),()=>r.off(e,i)}),Sa=class{constructor(e){this.subscription=new F$;this.videoState=new A("initializing");this.trackLevels=new Map;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(e!=="initializing")switch(i?.to!=="paused"&&a.state==="requested"&&this.seek(a.position),t){case"stopped":switch(e){case"stopped":break;case"ready":case"playing":case"paused":this.stop();break;default:va(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:va(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:va(e)}break;case"paused":switch(e){case"paused":break;case"stopped":this.prepare();break;case"ready":this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused");break;case"playing":this.pause();break;default:va(e)}break;default:va(t)}};this.textTracksManager=new Ce(e.source.url),this.video=fe(e.container,e.tuning),this.params=e,this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(re(this.params.source.url)),this.loadHlsJs()}destroy(){this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),this.hls?.detachMedia(),this.hls?.destroy(),this.params.output.element$.next(void 0),be(this.video)}loadHlsJs(){let e=!1,t=a=>{e||this.params.output.error$.next({id:a==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:on.NETWORK,message:"Failed to load Hls.js",thrown:a}),e=!0},i=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);(0,$g.default)(import("hls.js").then(a=>{e||(We.Hls=a.default,We.Events=a.default.Events,this.init())},t),()=>{window.clearTimeout(i),e=!0})}init(){Mg(We.Hls,"hls.js not loaded"),this.hls=new We.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){Mg(We.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,i=l=>{t.error$.next({id:"HlsJsProvider",category:on.WTF,message:"HlsJsProvider internal logic error",thrown:l})},a=ge(this.video);this.subscription.add(()=>a.destroy());let s=(l,d)=>this.subscription.add(l.subscribe(d,i));s(a.timeUpdate$,t.position$),s(a.durationChange$,t.duration$),s(a.ended$,t.endedEvent$),s(a.looped$,t.loopedEvent$),s(a.error$,t.error$),s(a.isBuffering$,t.isBuffering$),s(a.currentBuffer$,t.currentBuffer$),s(a.loadStart$,t.firstBytesEvent$),s(a.loadedMetadata$,t.loadedMetadataEvent$),s(a.playing$,t.firstFrameEvent$),s(a.canplay$,t.canplay$),s(a.seeked$,t.seekedEvent$),s(a.inPiP$,t.inPiP$),s(a.inFullscreen$,t.inFullscreen$),this.subscription.add(tt(this.video,e.isLooped,i)),this.subscription.add(ve(this.video,e.volume,a.volumeState$,i)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(De(this.video,e.playbackRate,a.playbackRateState$,i)),s(Ve(this.video),t.elementVisible$),s(this.videoState.stateChangeEnded$.pipe(un(l=>l.to)),this.params.output.playbackState$),this.subscription.add(qi(this.hls,We.Events.ERROR).subscribe(l=>{l.fatal&&t.error$.next({id:["HlsJsFatal",l.type,l.details].join("_"),category:on.WTF,message:`HlsJs fatal ${l.type} ${l.details}, ${l.err?.message} ${l.reason}`,thrown:l.error})})),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),x(e.playbackState,"playing")},i)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),x(e.playbackState,"paused")},i)).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),s(qi(this.hls,We.Events.MANIFEST_PARSED).pipe(un(({levels:l})=>l.reduce((d,c)=>{let p=c.name||c.height.toString(10),{width:h,height:f}=c,b=It(c.attrs.QUALITY??"")??q$({width:h,height:f});if(!b)return d;let S=c.attrs["FRAME-RATE"]?parseFloat(c.attrs["FRAME-RATE"]):void 0,v={id:p.toString(),quality:b,bitrate:c.bitrate/1e3,size:{width:h,height:f},fps:S};return this.trackLevels.set(p,{track:v,level:c}),d.push(v),d},[]))),t.availableVideoTracks$),s(qi(this.hls,We.Events.MANIFEST_PARSED),l=>{if(l.subtitleTracks.length>0){let d=[];for(let c of l.subtitleTracks){let p=c.name,h=c.attrs.URI||"",f=c.lang;d.push({id:p,url:h,language:f,type:"internal"})}e.internalTextTracks.startTransitionTo(d)}}),s(qi(this.hls,We.Events.LEVEL_LOADING).pipe(un(({url:l})=>re(l))),t.hostname$),s(qi(this.hls,We.Events.FRAG_CHANGED),l=>{let{video:d,audio:c}=l.frag.elementaryStreams;t.currentVideoSegmentLength$.next(((d?.endPTS??0)-(d?.startPTS??0))*1e3),t.currentAudioSegmentLength$.next(((c?.endPTS??0)-(c?.startPTS??0))*1e3)}),this.subscription.add(gt(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,l=>{this.hls.nextLevel=l?-1:this.hls.currentLevel,this.hls.loadLevel=l?-1:this.hls.loadLevel},{onError:i}));let n=l=>Array.from(this.trackLevels.values()).find(({level:d})=>d===l)?.track,o=qi(this.hls,We.Events.LEVEL_SWITCHED).pipe(un(({level:l})=>n(this.hls.levels[l])));o.pipe(C$(V$)).subscribe(t.currentVideoTrack$,i),this.subscription.add(gt(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),l=>{if(B$(l))return;let d=this.trackLevels.get(l.id)?.level;if(!d)return;let c=this.hls.levels.indexOf(d),p=this.hls.currentLevel,h=this.hls.levels[p];!h||d.bitrate>h.bitrate?this.hls.nextLevel=c:(this.hls.loadLevel=c,this.hls.loadLevel=c)},{changed$:o,onError:i})),s(a.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);let u=O$(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,N$(["init"])).pipe(D$(0));this.subscription.add(u.subscribe(this.syncPlayback,i))}prepare(){this.videoState.startTransitionTo("ready"),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}async playIfAllowed(){this.videoState.startTransitionTo("playing"),await ye(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:on.DOM,thrown:t}))||(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused",!0))}pause(){this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.hls.stopLoad(),this.hls.detachMedia(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"),x(this.params.desiredState.playbackState,"stopped",!0)}};var Dg="X-Playback-Duration",Cl=async r=>{let e=await rt(r),t=await e.text(),i=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t)?.[1];return i?parseInt(i,10):e.headers.has(Dg)?parseInt(e.headers.get(Dg),10):void 0};import{assertNever as J$,combine as Z$,debounce as eD,ErrorCategory as dn,filter as tD,filterChanged as iD,isNonNullable as Bg,isNullable as pn,map as Og,merge as rD,observableFrom as aD,Subscription as sD,ValueSubject as Ol,VideoQuality as nD}from"@vkontakte/videoplayer-shared";var Bl=D($o(),1);import{videoSizeToQuality as U$,getExponentialDelay as H$}from"@vkontakte/videoplayer-shared";var j$=r=>{let e=null;if(r.QUALITY&&(e=It(r.QUALITY)),!e&&r.RESOLUTION){let[t,i]=r.RESOLUTION.split("x").map(a=>parseInt(a,10));e=U$({width:t,height:i})}return e??null},G$=(r,e)=>{let t=r.split(`
69
+ `),i=[],a=[];for(let s=0;s<t.length;s++){let n=t[s],o=n.match(/^#EXT-X-STREAM-INF:(.+)/),u=n.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!o&&!u)){if(o){let l=(0,Bl.default)(o[1].split(",").map(S=>S.split("="))),d=l.QUALITY??`stream-${l.BANDWIDTH}`,c=j$(l),p;l.BANDWIDTH&&(p=parseInt(l.BANDWIDTH,10)/1e3||void 0),!p&&l["AVERAGE-BANDWIDTH"]&&(p=parseInt(l["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let h=l["FRAME-RATE"]?parseFloat(l["FRAME-RATE"]):void 0,f;if(l.RESOLUTION){let[S,v]=l.RESOLUTION.split("x").map(P=>parseInt(P,10));S&&v&&(f={width:S,height:v})}let b=new URL(t[++s],e).toString();c&&i.push({id:d,quality:c,url:b,bandwidth:p,size:f,fps:h})}if(u){let l=(0,Bl.default)(u[1].split(",").map(h=>{let f=h.indexOf("=");return[h.substring(0,f),h.substring(f+1)]}).map(([h,f])=>[h,f.replace(/^"|"$/g,"")])),d=l.URI?.replace(/playlist$/,"subtitles.vtt"),c=l.LANGUAGE,p=l.NAME;d&&c&&a.push({type:"internal",id:c,label:p,language:c,url:d,isAuto:!1})}}}if(!i.length)throw new Error("Empty manifest");return{qualityManifests:i,textTracks:a}},Q$=r=>new Promise(e=>{setTimeout(()=>{e()},r)}),Vl=0,Cg=async(r,e=r,t,i)=>{let s=await(await rt(r,i)).text();Vl+=1;try{let{qualityManifests:n,textTracks:o}=G$(s,e);return{qualityManifests:n,textTracks:o}}catch{if(Vl<=t.manifestRetryMaxCount)return await Q$(H$(Vl-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),Cg(r,e,t)}return{qualityManifests:[],textTracks:[]}},ln=Cg;import{isNonNullable as W$,Subscription as Y$,throttle as z$,ValueSubject as Vg,Subject as K$,ErrorCategory as X$}from"@vkontakte/videoplayer-shared";var cn=class{constructor(e,t,i,a,s){this.subscription=new Y$;this.abortControllers={destroy:new le,nextManifest:null};this.prepareUrl=void 0;this.currentTextTrackData=null;this.availableTextTracks$=new Vg(null);this.getCurrentTime$=new Vg(null);this.error$=new K$;this.params={fetchManifestData:i,sourceUrl:a,downloadThreshold:s},this.subscription.add(e.pipe(z$(1e3)).subscribe(n=>{this.processLiveTime(n)})),this.getCurrentTime$.next(()=>this.currentTextTrackData?this.currentTextTrackData.playlist.segmentStartTime/1e3+t.currentTime:0)}destroy(){this.subscription.unsubscribe(),this.abortControllers.destroy.abort()}async prepare(e){try{let t=new URL(e);t.searchParams.set("enable-subtitles","yes"),this.prepareUrl=t.toString();let{textTracks:i}=await this.fetchManifestData();await this.processTextTracks(i,this.params.sourceUrl)}catch(t){this.error("prepare",t)}}async processTextTracks(e,t){try{let i=await this.parseTextTracks(e,t);i&&(this.currentTextTrackData=i)}catch(i){this.error("processTextTracks",i)}}async parseTextTracks(e,t){for(let i of e){let a=new URL(i.url,t).toString(),n=await(await rt(a,{signal:this.abortControllers.destroy.signal})).text(),o=this.parsePlaylist(n,a);return{textTrack:i,playlist:o}}}parsePlaylist(e,t){let i={mediaSequence:0,programDateTime:"",segments:[],targetDuration:0,vkPlaybackDuration:0,segmentStartTime:0,vkStartTime:""},a=e.split(`
70
+ `),s=0;for(let n=0;n<a.length;++n){let o=a[n];switch(!0){case o.startsWith("#EXTINF:"):{let u=a[++n],l=new URL(u,t).toString(),d=Number(this.extractPlaylistRowValue("#EXTINF:",o))*1e3;if(i.segments.push({time:{from:s,to:s+d},url:l}),s=s+d,!i.segmentStartTime){let c=new Date(i.vkStartTime).valueOf(),p=new Date(i.programDateTime).valueOf();i.segmentStartTime=p-c}break}case o.startsWith("#EXT-X-TARGETDURATION:"):i.targetDuration=Number(this.extractPlaylistRowValue("#EXT-X-TARGETDURATION:",o));break;case o.startsWith("#EXT-X-MEDIA-SEQUENCE:"):i.mediaSequence=Number(this.extractPlaylistRowValue("#EXT-X-MEDIA-SEQUENCE:",o));break;case o.startsWith("#EXT-X-VK-PLAYBACK-DURATION:"):i.vkPlaybackDuration=Number(this.extractPlaylistRowValue("#EXT-X-VK-PLAYBACK-DURATION:",o));break;case o.startsWith("#EXT-X-PROGRAM-DATE-TIME:"):{let u=this.extractPlaylistRowValue("#EXT-X-PROGRAM-DATE-TIME:",o);i.programDateTime=u;let l=new Date(u);l.setMilliseconds(0),s=l.valueOf();break}case o.startsWith("#EXT-X-VK-START-TIME:"):i.vkStartTime=this.extractPlaylistRowValue("#EXT-X-VK-START-TIME:",o);break}}return i}extractPlaylistRowValue(e,t){switch(e){case"#EXTINF:":return t.substring(e.length,t.length-1);default:return t.substring(e.length)}}processLiveTime(e){if(W$(e)&&this.currentTextTrackData){let{segments:t}=this.currentTextTrackData.playlist,{from:i}=t[0].time,{to:a}=t[t.length-1].time;if(e<i||e>a)return;a-e<this.params.downloadThreshold&&this.fetchNextManifestData();for(let n of t)if(n.time.from<=e&&n.time.to>=e){this.availableTextTracks$.next([{...this.currentTextTrackData.textTrack,url:n.url,isAuto:!0}]);break}}}async fetchNextManifestData(){try{if(this.abortControllers.nextManifest)return;this.abortControllers.nextManifest=new le;let{textTracks:e}=await this.fetchManifestData(),t=await this.parseTextTracks(e,this.params.sourceUrl);this.currentTextTrackData&&t&&(this.currentTextTrackData.playlist.segments=t.playlist.segments)}catch(e){this.error("fetchNextManifestData",e)}finally{this.abortControllers.nextManifest=null}}async fetchManifestData(){let e=this.prepareUrl??this.params.sourceUrl;return await this.params.fetchManifestData(e,{signal:this.abortControllers.destroy.signal})}error(e,t){this.error$.next({id:"[LiveTextManager][HLS_LIVE_CMAF]",category:X$.WTF,thrown:t,message:e})}};var ga=class{constructor(e){this.subscription=new sD;this.videoState=new A("stopped");this.textTracksManager=null;this.liveTextManager=null;this.manifests$=new Ol([]);this.liveOffset=new Wt;this.manifestStartTime$=new Ol(void 0);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),x(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let d=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(d),this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if(a?.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"?x(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),x(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()):a?.to==="playing"&&x(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 a?.to==="paused"&&(x(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return J$(t)}};this.params=e,this.video=fe(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:nD.INVARIANT,url:this.params.source.url};let t=(i,a)=>ln(i,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 cn(this.params.output.liveTime$,this.video,t,this.params.source.url,this.params.tuning.hlsLiveNewTextManagerDownloadThreshold):this.textTracksManager=new Ce(e.source.url),t(this.generateLiveUrl()).then(({qualityManifests:i,textTracks:a})=>{i.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:dn.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.liveTextManager?.processTextTracks(a,this.params.source.url),this.manifests$.next([this.masterManifest,...i])}).catch(i=>{this.params.output.error$.next({id:"ExtractHlsQualities",category:dn.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:i})}),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(re(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new Ol(e.source.maxSeekBackTime??1/0),this.subscribe()}selectManifest(){let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),a=t.getTransition(),s=a?.to?.id??t.getState()?.id??"master",n=this.manifests$.getValue();if(!n.length)return;let o=i?"master":s;return i&&!a&&t.startTransitionTo(this.masterManifest),n.find(u=>u.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsLiveProvider",category:dn.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},a=ge(this.video);this.subscription.add(()=>a.destroy());let s=(o,u)=>this.subscription.add(o.subscribe(u,i));s(a.ended$,e.endedEvent$),s(a.error$,e.error$),s(a.isBuffering$,e.isBuffering$),s(a.currentBuffer$,e.currentBuffer$),s(a.loadedMetadata$,e.firstBytesEvent$),s(a.loadedMetadata$,e.loadedMetadataEvent$),s(a.playing$,e.firstFrameEvent$),s(a.canplay$,e.canplay$),s(a.inPiP$,e.inPiP$),s(a.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(ve(this.video,t.volume,a.volumeState$,i)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(De(this.video,t.playbackRate,a.playbackRateState$,i)),s(Ve(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(a.playing$.subscribe(()=>{this.videoState.setState("playing"),x(t.playbackState,"playing")},i)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),x(t.playbackState,"paused")},i)).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.liveTextManager&&this.subscription.add(this.liveTextManager.availableTextTracks$.subscribe(o=>{o&&this.params.output.availableTextTracks$.next(o)})),this.subscription.add(this.maxSeekBackTime$.pipe(iD(),Og(o=>-o/1e3)).subscribe(this.params.output.duration$,i)),this.subscription.add(a.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&&Bg(l.to)){let c=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let p=this.manifests$.getValue().find(h=>h.id===c);p&&(this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(re(p.url)))}d&&this.params.desiredState.autoVideoTrackSwitching.setState(d.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o&&o.state==="requested"&&this.seek(o.position)},i)),this.subscription.add(a.loadedData$.subscribe(()=>{let o=this.video?.getStartDate?.()?.getTime();this.manifestStartTime$.next(o||void 0)},i)),this.subscription.add(Z$({startTime:this.manifestStartTime$.pipe(tD(Bg)),currentTime:a.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),i)),this.subscription.add(this.manifests$.pipe(Og(o=>o.map(({id:u,quality:l,size:d,bandwidth:c,fps:p})=>({id:u,quality:l,size:d,fps:p,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,i));let n=rD(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,aD(["init"])).pipe(eD(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager?.destroy(),this.liveTextManager?.destroy(),this.params.output.element$.next(void 0),be(this.video)}prepare(){let e=this.selectManifest();if(pn(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),a=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:o,min:u}=t?.to??i??{};for(let[l,d]of[[o,"mq"],[u,"lq"]]){let c=String(parseFloat(l||""));d&&l&&a.searchParams.set(d,c)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,n=ue(a.toString(),this.liveOffset.getTotalOffset(),s);this.liveTextManager?.prepare(n),this.video.setAttribute("src",n),this.video.load(),Cl(n).then(o=>{if(!pn(o))this.maxSeekBackTime$.next(o);else{let u=this.params.source.maxSeekBackTime??this.maxSeekBackTime$.getValue();(pn(u)||!isFinite(u))&&rt(n).then(l=>l.text()).then(l=>{let d=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(l)?.[1];if(d){let c=new URL(d,n).toString();Cl(c).then(p=>{pn(p)||this.maxSeekBackTime$.next(p)})}}).catch(()=>{})}})}playIfAllowed(){ye(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),x(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:dn.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=ue(this.params.source.url);if(this.params.tuning.useHlsLiveNewTextManager){let t=new URL(e);t.searchParams.set("enable-subtitles","yes"),e=t.toString()}return e}};import{assertNever as oD,debounce as uD,ErrorCategory as _l,fromEvent as Nl,isNonNullable as lD,isNullable as cD,map as _g,merge as Ng,observableFrom as Fg,Subscription as dD,ValueSubject as pD,VideoQuality as hD}from"@vkontakte/videoplayer-shared";var ya=class{constructor(e){this.subscription=new dD;this.videoState=new A("stopped");this.manifests$=new pD([]);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),x(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let d=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(d);let{currentTime:c}=this.video;this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:c*1e3,forcePrecise:!0});return}switch(a?.to!=="paused"&&l.state==="requested"&&this.seek(l.position),t){case"ready":i==="ready"?x(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),x(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()):a?.to==="playing"&&x(this.params.desiredState.playbackState,"playing");return;case"paused":i==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):a?.to==="paused"&&x(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return oD(t)}};this.textTracksManager=new Ce(e.source.url),this.params=e,this.video=fe(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:hD.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(re(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),ln(ue(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:_l.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),a=t.getTransition(),s=a?.to?.id??t.getState()?.id??"master",n=this.manifests$.getValue();if(!n.length)return;let o=i?"master":s;return i&&(!a||!a.from)&&t.startTransitionTo(this.masterManifest),n.find(u=>u.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsProvider",category:_l.WTF,message:"HlsProvider internal logic error",thrown:o})},a=ge(this.video);this.subscription.add(()=>a.destroy());let s=(o,u)=>this.subscription.add(o.subscribe(u));if(s(a.timeUpdate$,e.position$),s(a.durationChange$,e.duration$),s(a.ended$,e.endedEvent$),s(a.looped$,e.loopedEvent$),s(a.error$,e.error$),s(a.isBuffering$,e.isBuffering$),s(a.currentBuffer$,e.currentBuffer$),s(a.loadedMetadata$,e.firstBytesEvent$),s(a.loadedMetadata$,e.loadedMetadataEvent$),s(a.playing$,e.firstFrameEvent$),s(a.canplay$,e.canplay$),s(a.seeked$,e.seekedEvent$),s(a.inPiP$,e.inPiP$),s(a.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe(_g(o=>o.to)),this.params.output.playbackState$),this.subscription.add(tt(this.video,t.isLooped,i)),this.subscription.add(ve(this.video,t.volume,a.volumeState$,i)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(De(this.video,t.playbackRate,a.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),x(t.playbackState,"playing")},i)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),x(t.playbackState,"paused")},i)).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i).add(a.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&&lD(l.to)){let h=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let f=this.manifests$.getValue().find(b=>b.id===h);f&&(this.params.output.currentVideoTrack$.next(f),this.params.output.hostname$.next(re(f.url)))}let c=this.params.desiredState.playbackRate.getState(),p=this.params.output.element$.getValue()?.playbackRate;if(c!==p){let h=this.params.output.element$.getValue();h&&(this.params.desiredState.playbackRate.setState(c),h.playbackRate=c)}d&&this.params.desiredState.autoVideoTrackSwitching.setState(d.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o.state==="requested"&&this.seek(o.position)},i))),this.subscription.add(this.manifests$.pipe(_g(o=>o.map(({id:u,quality:l,size:d,bandwidth:c,fps:p})=>({id:u,quality:l,size:d,fps:p,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,i)),!C.device.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(Ng(Nl(o,"addtrack"),Nl(o,"removetrack"),Nl(o,"change"),Fg(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},i))}let n=Ng(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,Fg(["init"])).pipe(uD(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),be(this.video)}prepare(){let e=this.selectManifest();if(cD(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),a=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:s,min:n}=t?.to??i??{};for(let[o,u]of[[s,"mq"],[n,"lq"]]){let l=String(parseFloat(o||""));u&&o&&a.searchParams.set(u,l)}}this.video.setAttribute("src",a.toString()),this.video.load()}playIfAllowed(){ye(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:_l.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var Hg=D(ar(),1),Fl=D(Ri(),1),jg=D(Et(),1);import{assertNever as mD,assertNonNullable as qg,debounce as fD,ErrorCategory as Ug,isHigherOrEqual as bD,isLowerOrEqual as vD,isNonNullable as SD,merge as gD,observableFrom as yD,Subscription as TD,map as ID}from"@vkontakte/videoplayer-shared";var Ta=class{constructor(e){this.subscription=new TD;this.videoState=new A("stopped");this.trackUrls={};this.textTracksManager=new Ce;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"),x(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.autoVideoTrackLimits.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.seekState.getState();if(s&&e!=="ready"&&!n){this.handleQualityLimitTransition(s.to);return}if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(n){let{currentTime:u}=this.video;this.prepare(),o.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:u*1e3,forcePrecise:!0});return}switch(i?.to!=="paused"&&o.state==="requested"&&this.seek(o.position),e){case"ready":t==="ready"?x(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):i?.to==="playing"&&x(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&x(this.params.desiredState.playbackState,"paused");return;default:return mD(e)}};this.params=e,this.video=fe(e.container,e.tuning),this.params.output.element$.next(this.video),(0,Hg.default)(this.params.source).reverse().forEach(([t,i],a)=>{let s=a.toString(10);this.trackUrls[s]={track:{quality:t,id:s},url:i}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next((0,Fl.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:Ug.WTF,message:"MpegProvider internal logic error",thrown:o})},a=ge(this.video);this.subscription.add(()=>a.destroy());let s=(o,u)=>this.subscription.add(o.subscribe(u,i));s(a.timeUpdate$,e.position$),s(a.durationChange$,e.duration$),s(a.ended$,e.endedEvent$),s(a.looped$,e.loopedEvent$),s(a.error$,e.error$),s(a.isBuffering$,e.isBuffering$),s(a.currentBuffer$,e.currentBuffer$),s(a.loadedMetadata$,e.firstBytesEvent$),s(a.loadedMetadata$,e.loadedMetadataEvent$),s(a.playing$,e.firstFrameEvent$),s(a.canplay$,e.canplay$),s(a.seeked$,e.seekedEvent$),s(a.inPiP$,e.inPiP$),s(a.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe(ID(o=>o.to)),this.params.output.playbackState$),this.subscription.add(tt(this.video,t.isLooped,i)),this.subscription.add(ve(this.video,t.volume,a.volumeState$,i)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(De(this.video,t.playbackRate,a.playbackRateState$,i)),s(Ve(this.video),e.elementVisible$),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),x(t.playbackState,"playing")},i)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),x(t.playbackState,"paused")},i)).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready");let o=this.params.desiredState.videoTrack.getTransition();if(o&&SD(o.to)){this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to.id].track);let u=this.params.desiredState.playbackRate.getState(),l=this.params.output.element$.getValue()?.playbackRate;if(u!==l){let d=this.params.output.element$.getValue();d&&(this.params.desiredState.playbackRate.setState(u),d.playbackRate=u)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.textTracksManager.connect(this.video,t,e);let n=gD(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,yD(["init"])).pipe(fD(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),be(this.video)}prepare(){let e=this.params.desiredState.videoTrack.getState()?.id;qg(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];qg(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=la(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(re(t))}playIfAllowed(){ye(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Ug.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){this.params.output.autoVideoTrackLimits$.next(e);let t=l=>{this.params.output.currentVideoTrack$.next(l),this.params.desiredState.videoTrack.startTransitionTo(l)},i=l=>{let d=Pt(n,{container:this.video.getBoundingClientRect(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,limits:l});t(d)},a=this.params.output.currentVideoTrack$.getValue()?.quality,s=!!(e.max||e.min),n=(0,Fl.default)(this.trackUrls).map(l=>l.track);if(!a||!s||Ir(e,n[0].quality,(0,jg.default)(n,-1)?.quality)){i();return}let o=e.max?vD(a,e.max):!0,u=e.min?bD(a,e.min):!0;o&&u||i(e)}};import{assertNever as Qg,debounce as kD,merge as wD,observableFrom as AD,Subscription as RD,ValueSubject as LD,ErrorCategory as Ul,VideoQuality as MD}from"@vkontakte/videoplayer-shared";import{ErrorCategory as ED}from"@vkontakte/videoplayer-shared";var Gg=["stun:videostun.mycdn.me:80"],xD=1e3,PD=3,ql=()=>null,hn=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=ql;this.externalStopCallback=ql;this.externalErrorCallback=ql;this.options=this.normalizeOptions(t);let i=e.split("/");this.serverUrl=i.slice(0,i.length-1).join("/"),this.streamKey=i[i.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{let t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}async handleUpdateMessage(e){try{let t=await this.createOffer();this.peerConnection&&await this.peerConnection.setLocalDescription(t),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}}async handleLogin(){try{let e={iceServers:[{urls:Gg}]};this.peerConnection=new RTCPeerConnection(e),this.peerConnection.ontrack=this.onPeerConnectionStream.bind(this),this.peerConnection.onicecandidate=this.onPeerConnectionIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onPeerConnectionIceConnectionStateChange.bind(this);let t=await this.createOffer();await this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}}async handleAnswer(e){try{this.peerConnection&&await this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e}))}catch(t){this.handleRTCError(t)}}async handleCandidate(e){if(e)try{this.peerConnection&&await this.peerConnection.addIceCandidate(e)}catch(t){this.handleRTCError(t)}}handleUnpublished(){try{this.closeConnections(),this.externalStopCallback()}catch(e){this.handleRTCError(e)}}handleSystemError(e){this.options.errorChanel&&this.options.errorChanel.next({id:"webrtc-provider-error",category:ED.WTF,message:e.message})}async onPeerConnectionStream(e){let t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){let e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}async createOffer(){let e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");let t=await this.peerConnection.createOffer(e),i=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(i))throw new Error("No h264 codec support error");return t}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch{throw new Error("Can not parse socket message")}}closeConnections(){let e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),xD)}normalizeOptions(e={}){let t={stunServerList:Gg,maxRetryNumber:PD,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var Ia=class{constructor(e){this.videoState=new A("stopped");this.maxSeekBackTime$=new LD(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"),x(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"),x(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):i?.to==="playing"&&x(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&x(this.params.desiredState.playbackState,"paused");return;default:return Qg(e)}};this.subscription=new RD,this.params=e,this.video=fe(e.container,e.tuning),this.liveStreamClient=new hn(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),be(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,i=n=>{e.error$.next({id:"WebRTCLiveProvider",category:Ul.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})},a=ge(this.video);this.subscription.add(()=>a.destroy());let s=(n,o)=>this.subscription.add(n.subscribe(o,i));s(a.timeUpdate$,e.liveTime$),s(a.ended$,e.endedEvent$),s(a.looped$,e.loopedEvent$),s(a.error$,e.error$),s(a.isBuffering$,e.isBuffering$),s(a.currentBuffer$,e.currentBuffer$),s(Ve(this.video),this.params.output.elementVisible$),this.subscription.add(a.durationChange$.subscribe(n=>{e.duration$.next(n===1/0?0:n)})).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready")},i)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused")},i)).add(a.playing$.subscribe(()=>{this.videoState.setState("playing")},i)).add(a.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(ve(this.video,t.volume,a.volumeState$,i)).add(a.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 Qg(n.to)}},i)).add(wD(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,AD(["init"])).pipe(kD(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(re(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:MD.INVARIANT}),this.video.srcObject=e,x(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:Ul.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){ye(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Ul.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var Ea=class{constructor(e){this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next()}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return!!this.current.done}};import{assertNever as xa,assertNonNullable as Lt,ErrorCategory as mn,filter as Jg,isNonNullable as Zg,isNullable as _D,map as ND,merge as FD,once as qD,Subject as se,Subscription as ey,ValueSubject as R}from"@vkontakte/videoplayer-shared";import{Observable as $D,map as Wg,Subscription as DD,Subject as CD}from"@vkontakte/videoplayer-shared";var Yg=r=>new $D(e=>{let t=new DD,i=r.desiredPlaybackState$.stateChangeStarted$.pipe(Wg(({from:l,to:d})=>`${l}-${d}`)),a=r.desiredPlaybackState$.stateChangeEnded$,s=r.providerChanged$.pipe(Wg(({type:l})=>l!==void 0)),n=new CD,o=0,u="unknown";return t.add(i.subscribe(l=>{o&&window.clearTimeout(o),u=l,o=window.setTimeout(()=>n.next(l),r.maxTransitionInterval)})),t.add(a.subscribe(()=>{window.clearTimeout(o),u="unknown",o=0})),t.add(s.subscribe(l=>{o&&(window.clearTimeout(o),o=0,l&&(o=window.setTimeout(()=>n.next(u),r.maxTransitionInterval)))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});import{ErrorCategory as VD,Subscription as BD,combine as OD,filter as Kg,once as Xg}from"@vkontakte/videoplayer-shared";function zg(){return new(window.AudioContext||window.webkitAudioContext)}var Ui=class r{constructor(e,t,i,a){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=i;this.volumeMultiplier=a;this.destroyController=new le;this.subscriptions=new BD;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe(Kg(s=>!!s.type),Xg()).subscribe(({type:s})=>this.subscribe(s)))}static{this.errorId="VolumeMultiplierManager"}subscribe(e){C.browser.isSafari&&e!=="MPEG"||this.subscriptions.add(OD({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(Kg(({playbackState:t,video:i,volume:{muted:a,volume:s}})=>t==="playing"&&!!i&&!a&&!!s),Xg()).subscribe(({video:t})=>{this.initAudioContextOnce(t).then(i=>{i||this.destroy()}).catch(i=>{this.handleError(i),this.destroy()})}))}static isSupported(){return"AudioContext"in window&&"GainNode"in window&&"MediaElementAudioSourceNode"in window}async initAudioContextOnce(e){let{volumeMultiplier:t}=this,i=zg();this.audioContext=i;let a=i.createGain();if(this.gainNode=a,a.gain.value=t,a.connect(i.destination),i.state==="suspended"&&(await i.resume(),this.destroyController.signal.aborted))return!1;let s=i.createMediaElementSource(e);return this.mediaElementSource=s,s.connect(a),!0}cleanup(){this.mediaElementSource&&(this.mediaElementSource.disconnect(),this.mediaElementSource=null),this.gainNode&&(this.gainNode.disconnect(),this.gainNode=null),this.audioContext&&(this.audioContext.state!=="closed"&&this.audioContext.close(),this.audioContext=null)}destroy(){this.destroyController.abort(),this.subscriptions.unsubscribe(),this.cleanup()}handleError(e){this.volumeMultiplierError$.next({id:r.errorId,category:VD.VIDEO_PIPELINE,message:e?.message??`${r.errorId} exception`,thrown:e})}};var UD={chunkDuration:5e3,maxParallelRequests:5},Pa=class{constructor(e){this.current$=new R({type:void 0});this.providerError$=new se;this.noAvailableProvidersError$=new se;this.volumeMultiplierError$=new se;this.providerOutput={position$:new R(0),duration$:new R(1/0),volume$:new R({muted:!1,volume:1}),availableVideoStreams$:new R([]),currentVideoStream$:new R(void 0),availableVideoTracks$:new R([]),currentVideoTrack$:new R(void 0),availableAudioStreams$:new R([]),currentAudioStream$:new R(void 0),availableAudioTracks$:new R([]),currentVideoSegmentLength$:new R(0),currentAudioSegmentLength$:new R(0),isAudioAvailable$:new R(!0),autoVideoTrackLimitingAvailable$:new R(!1),autoVideoTrackLimits$:new R(void 0),currentBuffer$:new R(void 0),isBuffering$:new R(!0),error$:new se,fetcherError$:new se,fetcherRecoverableError$:new se,warning$:new se,willSeekEvent$:new se,soundProhibitedEvent$:new se,seekedEvent$:new se,loopedEvent$:new se,endedEvent$:new se,firstBytesEvent$:new se,loadedMetadataEvent$:new se,firstFrameEvent$:new se,canplay$:new se,isLive$:new R(void 0),isLiveEnded$:new R(null),isLowLatency$:new R(!1),canChangePlaybackSpeed$:new R(!0),liveTime$:new R(void 0),liveBufferTime$:new R(void 0),liveLatency$:new R(void 0),severeStallOccurred$:new se,availableTextTracks$:new R([]),currentTextTrack$:new R(void 0),hostname$:new R(void 0),httpConnectionType$:new R(void 0),httpConnectionReused$:new R(void 0),inPiP$:new R(!1),inFullscreen$:new R(!1),element$:new R(void 0),elementVisible$:new R(!0),availableSources$:new R(void 0),is3DVideo$:new R(!1),playbackState$:new R(""),getCurrentTime$:new R(null)};this.subscription=new ey;this.volumeMultiplierManager=null;this.params=e;let t=mg([...bg(this.params.tuning),...fg(this.params.tuning)],this.params.tuning).filter(l=>Zg(e.sources[l])),{forceFormat:i,formatsToAvoid:a}=this.params.tuning,s=[];i?s=[i]:a.length?s=[...t.filter(l=>!(0,Hl.default)(a,l)),...t.filter(l=>(0,Hl.default)(a,l))]:s=t,this.screenFormatsIterator=new Ea(s);let n=[...Sl(!0),...Sl(!1)];this.chromecastFormatsIterator=new Ea(n.filter(l=>Zg(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:o=1,tuning:{useVolumeMultiplier:u}}=this.params;u&&o!==1&&Ui.isSupported()&&(this.volumeMultiplierManager=new Ui(this.providerOutput,this.current$,this.volumeMultiplierError$,o))}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()}))}destroy(){this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe(),this.volumeMultiplierManager?.destroy(),this.volumeMultiplierManager=null}initProvider(){let e=this.chooseDestination(),t=this.chooseFormat(e);if(_D(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(a){this.providerError$.next({id:"ProviderNotConstructed",category:mn.WTF,message:"Failed to create provider",thrown:a})}i?this.current$.next({type:t,provider:i,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}destroyProvider(){let e=this.current$.getValue().provider;if(!e)return;let t=this.providerOutput.position$.getValue()*1e3,i=this.params.desiredState.seekState.getState(),a=i.state!=="none";if(this.params.desiredState.seekState.setState({state:"requested",position:a?i.position:t,forcePrecise:a?i.forcePrecise:!1}),e.scene3D){let n=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:n.x,y:n.y})}e.destroy();let s=this.providerOutput.isBuffering$;s.getValue()||s.next(!0)}createProvider(e,t){switch(e){case"SCREEN":return this.createScreenProvider(t);case"CHROMECAST":return this.createChromecastProvider(t);default:return xa(e)}}createScreenProvider(e){let{sources:t,container:i,desiredState:a,panelSize:s}=this.params,n=this.providerOutput,o={container:i,source:null,desiredState:a,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning,panelSize:s};switch(e){case"DASH_SEP":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_ONDEMAND":case"DASH_STREAMS":{let u=this.applyFailoverHost(t[e]),l=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return Lt(u),new fa({...o,source:u,sourceHls:l})}case"DASH_LIVE_CMAF":{let u=this.applyFailoverHost(t[e]);return Lt(u),new ba({...o,source:u})}case"HLS":case"HLS_ONDEMAND":{let u=this.applyFailoverHost(t[e]);return Lt(u),C.video.nativeHlsSupported||!this.params.tuning.useHlsJs?new ya({...o,source:u}):new Sa({...o,source:u})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let u=this.applyFailoverHost(t[e]);return Lt(u),new ga({...o,source:u,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let u=this.applyFailoverHost(t[e]);return Lt(u),new Ta({...o,source:u})}case"DASH_LIVE":{let u=this.applyFailoverHost(t[e]);return Lt(u),new sv({...o,source:u,config:{...UD,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let u=this.applyFailoverHost(t[e]);return Lt(u),new Ia({container:i,source:u,desiredState:a,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 xa(e)}}createChromecastProvider(e){let{sources:t,container:i,desiredState:a,meta:s}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return Lt(o),new vr({connection:o,meta:s,container:i,source:t,format:e,desiredState:a,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 xa(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return xa(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 xa(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;let t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;let i=a=>{let s=new URL(a);return s.host=t,s.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return{...e,url:i(e.url)}}return(0,iy.default)((0,ty.default)(e).map(([a,s])=>[a,i(s)]))}initProviderErrorHandling(){let e=new ey,t=!1,i=0;return e.add(FD(this.providerOutput.error$.pipe(Jg(a=>!this.params.tuning.ignoreAudioRendererError||!a.message||!/AUDIO_RENDERER_ERROR/ig.test(a.message))),Yg({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(ND(a=>({id:`ProviderHangup:${a}`,category:mn.WTF,message:`A ${a} 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 a=this.params.desiredState.playbackState.transitionEnded$.pipe(Jg(({to:s})=>s==="playing"),qD()).subscribe(()=>t=!0);e.add(a)})),e.add(this.providerError$.subscribe(a=>{let s=this.current$.getValue().destination;if(s==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("SCREEN"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let n=a.category===mn.NETWORK,o=a.category===mn.FATAL,u=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),l=i<this.params.tuning.providerErrorLimit&&!o;l?(i++,this.reinitProvider()):u&&!o&&(n&&t||!l)?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):(i=0,this.switchToNextProvider(s??"SCREEN"))}})),e}};import{fromEvent as fn,once as HD,combine as jD,Subscription as ry,ValueSubject as jl,map as GD,filter as QD,isNonNullable as bn,now as Re,safeStorage as Gl}from"@vkontakte/videoplayer-shared";var WD=5e3,ay="one_video_throughput",sy="one_video_rtt",ka=window.navigator.connection,ny=()=>{let r=ka?.downlink;if(bn(r)&&r!==10)return r*1e3},oy=()=>{let r=ka?.rtt;if(bn(r)&&r!==3e3)return r},uy=(r,e,t)=>{let i=t*8,a=i/r;return i/(a+e)},Ql=class r{constructor(e){this.subscription=new ry;this.concurrentDownloads=new Set;this.tuningConfig=e;let t=r.load(ay)||(e.useBrowserEstimation?ny():void 0)||WD,i=r.load(sy)??(e.useBrowserEstimation?oy():void 0)??0;if(this.throughput$=new jl(t),this.rtt$=new jl(i),this.rttAdjustedThroughput$=new jl(uy(t,i,e.rttPenaltyRequestSize)),this.throughput=ei.getSmoothedValue(t,-1,e),this.rtt=ei.getSmoothedValue(i,1,e),e.useBrowserEstimation){let a=()=>{let n=ny();n&&this.throughput.next(n);let o=oy();bn(o)&&this.rtt.next(o)};ka&&"onchange"in ka&&this.subscription.add(fn(ka,"change").subscribe(a)),a()}this.subscription.add(this.throughput.smoothed$.subscribe(a=>{Gl.set(ay,a.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(a=>{Gl.set(sy,a.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(jD({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(GD(({throughput:a,rtt:s})=>uy(a,s,e.rttPenaltyRequestSize)),QD(a=>{let s=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(a-s)/s>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,i=Re(),a=new ry;switch(this.subscription.add(a),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:a.add(fn(e,"progress").pipe(HD()).subscribe(s=>{t=s.loaded,i=Re()}));break;case 1:case 0:a.add(fn(e,"loadstart").subscribe(()=>{t=0,i=Re()}));break}a.add(fn(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=Re(),u=n-t,l=o-i;this.addRawSpeed(u,l,1)}this.concurrentDownloads.delete(e),a.unsubscribe()}))}trackStream(e,t=!1){let i=e.getReader();if(!i){e.cancel("Could not get reader");return}let a=0,s=Re(),n=0,o=Re(),u=d=>{this.concurrentDownloads.delete(e),i.releaseLock(),e.cancel(`Throughput Estimator error: ${d}`).catch(()=>{})},l=async({done:d,value:c})=>{if(d)!t&&this.addRawSpeed(a,Re()-s,1),this.concurrentDownloads.delete(e);else if(c){if(t){let p=Re();if(p-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||p-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let f=o-s;f&&this.addRawSpeed(n,f,1,t),n=c.byteLength,s=Re()}else n+=c.byteLength;o=Re()}else a+=c.byteLength,n+=c.byteLength,n>=this.tuningConfig.streamMinSampleSize&&Re()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,Re()-o,this.concurrentDownloads.size),n=0,o=Re());await i?.read().then(l,u)}};this.concurrentDownloads.add(e),i?.read().then(l,u)}addRawSpeed(e,t,i=1,a=!1){if(r.sanityCheck(e,t,a)){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 a=e*8/t;return!(!a||!isFinite(a)||a>1e6||a<30||i&&e<1e4||!i&&e<10*1024||!i&&t<=20)}static load(e){let t=Gl.get(e);if(bn(t))return parseInt(t,10)??void 0}},ly=Ql;import{fillWithDefault as YD,VideoQuality as vn}from"@vkontakte/videoplayer-shared";var cy={configName:["core"],throughputEstimator:{type:"EmaAndMa",emaAlphaSlow:.2,emaAlphaFast:.7,emaAlpha:.45,basisTrendChangeCount:10,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1*1024*1024,streamMinSampleSize:10*1024,streamMinSampleTime:300,deviationDepth:20,deviationFactor:.5,lowLatency:{continuesByteSequenceInterval:50,maxLastEvaluationTimeout:300}},autoTrackSelection:{bitrateFactorAtEmptyBuffer:2.8,bitrateAudioFactorAtEmptyBuffer:10,bitrateFactorAtFullBuffer:2,bitrateAudioFactorAtFullBuffer:7,minVideoAudioRatio:5,minAvailableThroughputAudioRatio:5,usePixelRatio:!0,pixelRatioMultiplier:void 0,pixelRatioLogBase:3,pixelRatioLogCoefficients:[1,0,1],limitByContainer:!0,containerSizeFactor:1.3,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldownIncreaseQuality:15e3,trackCooldownDecreaseQuality:3e3,backgroundVideoQualityLimit:vn.Q_4320P,activeVideoAreaThreshold:.1,highQualityLimit:vn.Q_720P,trafficSavingLimit:vn.Q_480P},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:vn.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,seekBiasInTheEnd:2e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,crashOnStallTimeout:25e3,crashOnStallTWithoutDataTimeout:5e3,enableSubSegmentBufferFeeding:!0,bufferEmptinessTolerance:100,useFetchPriorityHints:!0,qualityLimitsOnStall:{stallDurationNoDataBeforeQualityDecrease:500,stallDurationToBeCount:100,stallCountBeforeQualityDecrease:3,resetQualityRestrictionTimeout:1e4,ignoreStallsOnSeek:!1},enableBaseUrlSupport:!0,maxSegmentRetryCount:5,sourceOpenTimeout:1e3,rejectOnSourceOpenTimeout:!1,pruneBufferInterval:null,vktvAbrThrottle:null},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,maxLiveDuration:7200,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:250,playbackCatchupSpeedup:.05,isActiveOnDefault:!1,bufferEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:"07A4434E",useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"dash",preferCMAF:!1,preferWebRTC:!1,preferMultiStream:!1,preferHDR:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,seekNearDurationBias:1,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useHlsJs:!1,useNativeHLSTextTracks:!1,useManagedMediaSource:!0,useNewSwitchTo:!1,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},dy=r=>({...YD(r,cy),configName:[...r.configName??[],...cy.configName]});import{assertNonNullable as Sn,combine as wa,ErrorCategory as gn,filter as _,filterChanged as he,fromEvent as Yl,isNonNullable as fy,isNullable as t0,map as Y,mapTo as by,merge as ri,now as yn,once as V,Subject as q,Subscription as vy,tap as zl,ValueSubject as E,isHigher as i0,isInvariantQuality as Sy,InternalsExposure as r0}from"@vkontakte/videoplayer-shared";import{merge as zD,map as KD,filter as py,isNonNullable as XD}from"@vkontakte/videoplayer-shared";var Wl=({seekState:r,position$:e})=>zD(r.stateChangeEnded$.pipe(KD(({to:t})=>t.state==="none"?void 0:(t.position??NaN)/1e3),py(XD)),e.pipe(py(()=>r.getState().state==="none")));import{assertNonNullable as JD}from"@vkontakte/videoplayer-shared";var hy=r=>{let e=typeof r.container=="string"?document.getElementById(r.container):r.container;return JD(e,`Wrong container or containerId {${r.container}}`),e};import{filter as ZD,once as e0}from"@vkontakte/videoplayer-shared";var my=(r,e,t,i)=>{r!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&t?.getValue().length===0?t.pipe(ZD(a=>a.length>0),e0()).subscribe(a=>{a.find(i)&&e.startTransitionTo(r)}):(r===void 0||t?.getValue().find(i))&&e.startTransitionTo(r)};var Tn=class{constructor(e={configName:[]}){this.subscription=new vy;this.internalsExposure=null;this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new E(!1);this.hasLiveOffsetByPausedTimer=0;this.playerInitRequest=0;this.playerInited=new E(!1);this.wasSetStartedQuality=!1;this.desiredState={playbackState:new A("stopped"),seekState:new A({state:"none"}),volume:new A({volume:1,muted:!1}),videoTrack:new A(void 0),videoStream:new A(void 0),audioStream:new A(void 0),autoVideoTrackSwitching:new A(!0),autoVideoTrackLimits:new A({}),isLooped:new A(!1),isLowLatency:new A(!1),playbackRate:new A(1),externalTextTracks:new A([]),internalTextTracks:new A([]),currentTextTrack:new A(void 0),textTrackCuesSettings:new A({}),cameraOrientation:new A({x:0,y:0})};this.info={playbackState$:new E(void 0),position$:new E(0),duration$:new E(1/0),muted$:new E(!1),volume$:new E(1),availableVideoStreams$:new E([]),currentVideoStream$:new E(void 0),availableQualities$:new E([]),availableQualitiesFps$:new E({}),currentQuality$:new E(void 0),isAutoQualityEnabled$:new E(!0),autoQualityLimitingAvailable$:new E(!1),autoQualityLimits$:new E({}),predefinedQualityLimitType$:new E("unknown"),availableAudioStreams$:new E([]),currentAudioStream$:new E(void 0),availableAudioTracks$:new E([]),isAudioAvailable$:new E(!0),currentPlaybackRate$:new E(1),currentBuffer$:new E({start:0,end:0}),isBuffering$:new E(!0),isStalled$:new E(!1),isEnded$:new E(!1),isLooped$:new E(!1),isLive$:new E(void 0),isLiveEnded$:new E(null),canChangePlaybackSpeed$:new E(void 0),atLiveEdge$:new E(void 0),atLiveDurationEdge$:new E(void 0),liveTime$:new E(void 0),liveBufferTime$:new E(void 0),liveLatency$:new E(void 0),currentFormat$:new E(void 0),availableTextTracks$:new E([]),currentTextTrack$:new E(void 0),throughputEstimation$:new E(void 0),rttEstimation$:new E(void 0),videoBitrate$:new E(void 0),hostname$:new E(void 0),httpConnectionType$:new E(void 0),httpConnectionReused$:new E(void 0),surface$:new E("none"),chromecastState$:new E("NOT_AVAILABLE"),chromecastDeviceName$:new E(void 0),intrinsicVideoSize$:new E(void 0),availableSources$:new E(void 0),is3DVideo$:new E(!1),currentVideoSegmentLength$:new E(0),currentAudioSegmentLength$:new E(0)};this.events={inited$:new q,ready$:new q,started$:new q,playing$:new q,paused$:new q,stopped$:new q,willStart$:new q,willResume$:new q,willPause$:new q,willStop$:new q,willDestruct$:new q,watchCoverageRecord$:new q,watchCoverageLive$:new q,managedError$:new q,fatalError$:new q,fetcherRecoverableError$:new q,ended$:new q,looped$:new q,seeked$:new q,willSeek$:new q,autoplaySoundProhibited$:new q,firstBytes$:new q,loadedMetadata$:new q,firstFrame$:new q,canplay$:new q,log$:new q,fetcherError$:new q,severeStallOccured$:new q};this.experimental={element$:new E(void 0),tuningConfigName$:new E([]),enableDebugTelemetry$:new E(!1),getCurrentTime$:new E(null)};if(this.tuning=dy(e),this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new ja({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast}),this.throughputEstimator=new ly(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new r0("CORE"),this.internalsExposure.expose({player:this})),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(t,i,a)=>{let s=Reflect.get(t,i,a);return typeof s!="function"?s:(...n)=>{try{return s.apply(t,n)}catch(o){let u=n.map(c=>JSON.stringify(c,(p,h)=>{let f=typeof h;return(0,gy.default)(["number","string","boolean"],f)?h:h===null?null:`<${f}>`})),l=`Player.${String(i)}`,d=`Exception calling ${l} (${u.join(", ")})`;throw this.events.fatalError$.next({id:l,category:gn.WTF,message:d,thrown:o}),o}}}})}initVideo(e){this.config=e,this.internalsExposure?.expose({config:e,tuning:this.tuning});let t=()=>{this.domContainer=hy(e),this.chromecastInitializer.contentId=e.meta?.videoId,this.providerContainer=new Pa({sources:e.sources,meta:e.meta??{},failoverHosts:e.failoverHosts??[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer},tuning:this.tuning,volumeMultiplier:e.volumeMultiplier,panelSize:e.panelSize}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.providerContainer.init(),this.setLiveLowLatency(this.tuning.dashCmafLive.lowLatency.isActiveOnDefault),this.setMuted(this.tuning.isAudioDisabled),this.initDebugTelemetry(),this.initWakeLock(),this.playerInited.next(!0)},i=()=>{this.tuning.autostartOnlyIfVisible&&window.requestAnimationFrame?this.playerInitRequest=window.requestAnimationFrame(()=>t()):t()},a=()=>{this.tuning.asyncResolveClientChecker?C.isInited$.pipe(_(s=>!!s),V()).subscribe(()=>{console.log("Core SDK async start"),i()}):i()};return this.isNotActiveTabCase()?Yl(document,"visibilitychange").pipe(V()).subscribe(a):a(),this}destroy(){window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.playerInitRequest&&window.cancelAnimationFrame(this.playerInitRequest),this.events.willDestruct$.next(),this.stop(),this.providerContainer?.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe(),this.internalsExposure?.destroy()}prepare(){return this.subscription.add(this.playerInited.pipe(_(e=>!!e),V()).subscribe(()=>{let e=this.desiredState.playbackState;e.getState()==="stopped"&&e.startTransitionTo("ready")})),this}play(){return this.subscription.add(this.playerInited.pipe(_(e=>!!e),V()).subscribe(()=>{let e=this.desiredState.playbackState;e.getState()!=="playing"&&e.startTransitionTo("playing")})),this}pause(){return this.subscription.add(this.playerInited.pipe(_(e=>!!e),V()).subscribe(()=>{let e=this.desiredState.playbackState;e.getState()!=="paused"&&e.startTransitionTo("paused")})),this}stop(){return this.subscription.add(this.playerInited.pipe(_(e=>!!e),V()).subscribe(()=>{let e=this.desiredState.playbackState;e.getState()!=="stopped"&&e.startTransitionTo("stopped")})),this}seekTime(e,t=!0){return this.subscription.add(this.playerInited.pipe(_(i=>!!i),V()).subscribe(()=>{let i=this.info.duration$.getValue(),a=this.info.isLive$.getValue(),s=e;e>=i&&!a&&(s=i-this.tuning.seekNearDurationBias),Number.isFinite(s)&&(this.events.willSeek$.next({from:this.getExactTime(),to:s}),this.desiredState.seekState.setState({state:"requested",position:s*1e3,forcePrecise:t}))})),this}seekPercent(e){return this.subscription.add(this.playerInited.pipe(_(t=>!!t),V()).subscribe(()=>{let t=this.info.duration$.getValue();isFinite(t)&&this.seekTime(Math.abs(t)*e,!1)})),this}setVolume(e,t){return this.subscription.add(this.playerInited.pipe(_(i=>!!i),V()).subscribe(()=>{let i=this.desiredState.volume,s=i.getTransition()?.to.muted??this.info.muted$.getValue(),n=t??(this.tuning.isAudioDisabled||s);this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setVolume(e):i.startTransitionTo({volume:e,muted:n})})),this}setMuted(e){return this.subscription.add(this.playerInited.pipe(_(t=>!!t),V()).subscribe(()=>{let t=this.desiredState.volume,i=this.tuning.isAudioDisabled||e,s=t.getTransition()?.to.volume??this.info.volume$.getValue();this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setMuted(i):t.startTransitionTo({volume:s,muted:i})})),this}setVideoStream(e){return this.subscription.add(this.playerInited.pipe(_(t=>!!t),V()).subscribe(()=>{this.desiredState.videoStream.startTransitionTo(e)})),this}setAudioStream(e){return this.subscription.add(this.playerInited.pipe(_(t=>!!t),V()).subscribe(()=>{this.desiredState.audioStream.startTransitionTo(e)})),this}setQuality(e){return this.subscription.add(this.playerInited.pipe(_(t=>!!t),V()).subscribe(()=>{Sn(this.providerContainer);let t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();this.desiredState.videoTrack.getState()===void 0&&this.desiredState.videoTrack.getPrevState()===void 0&&t.length===0?this.wasSetStartedQuality?this.providerContainer.providerOutput.availableVideoTracks$.pipe(_(i=>i.length>0),V()).subscribe(i=>{this.setVideoTrackIdByQuality(i,e)}):this.explicitInitialQuality=e:t.length>0&&this.setVideoTrackIdByQuality(t,e)})),this}setAutoQuality(e){return this.subscription.add(this.playerInited.pipe(_(t=>!!t),V()).subscribe(()=>{this.desiredState.autoVideoTrackSwitching.startTransitionTo(e)})),this}setAutoQualityLimits(e){return this.subscription.add(this.playerInited.pipe(_(t=>!!t),V()).subscribe(()=>{this.desiredState.autoVideoTrackLimits.startTransitionTo(e)})),this}setPredefinedQualityLimits(e){return this.subscription.add(this.playerInited.pipe(_(t=>!!t),V()).subscribe(()=>{if(this.info.predefinedQualityLimitType$.getValue()===e)return this;let{highQualityLimit:t,trafficSavingLimit:i}=this.tuning.autoTrackSelection,a;switch(e){case"high_quality":a={min:t,max:void 0};break;case"traffic_saving":a={max:i,min:void 0};break;default:a={max:void 0,min:void 0}}this.setAutoQualityLimits(a)})),this}setPlaybackRate(e){return this.subscription.add(this.playerInited.pipe(_(t=>!!t),V()).subscribe(()=>{Sn(this.providerContainer);let t=this.providerContainer?.providerOutput.element$.getValue();t&&(this.desiredState.playbackRate.setState(e),t.playbackRate=e)})),this}setExternalTextTracks(e){return this.subscription.add(this.playerInited.pipe(_(t=>!!t),V()).subscribe(()=>{this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t})))})),this}selectTextTrack(e){return this.subscription.add(this.playerInited.pipe(_(t=>!!t),V()).subscribe(()=>{my(e,this.desiredState.currentTextTrack,this.providerContainer?.providerOutput.availableTextTracks$,t=>t.id===e)})),this}setTextTrackCueSettings(e){return this.subscription.add(this.playerInited.pipe(_(t=>!!t),V()).subscribe(()=>{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.desiredState.isLowLatency.setState(e),this.seekTime(0))}setLooped(e){return this.subscription.add(this.playerInited.pipe(_(t=>!!t),V()).subscribe(()=>{this.desiredState.isLooped.startTransitionTo(e)})),this}toggleChromecast(){this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){return this.subscription.add(this.playerInited.pipe(_(i=>!!i),V()).subscribe(()=>{let i=this.getScene3D();i&&i.startCameraManualRotation(e,t)})),this}stopCameraManualRotation(e=!1){return this.subscription.add(this.playerInited.pipe(_(t=>!!t),V()).subscribe(()=>{let t=this.getScene3D();t&&t.stopCameraManualRotation(e)})),this}moveCameraFocusPX(e,t){return this.subscription.add(this.playerInited.pipe(_(i=>!!i),V()).subscribe(()=>{let i=this.getScene3D();if(i){let a=i.getCameraRotation(),s=i.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:a.x+s.x,y:a.y+s.y})}})),this}holdCamera(){return this.subscription.add(this.playerInited.pipe(_(e=>e),V()).subscribe(()=>{let e=this.getScene3D();e&&e.holdCamera()})),this}releaseCamera(){return this.subscription.add(this.playerInited.pipe(_(e=>!!e),V()).subscribe(()=>{let e=this.getScene3D();e&&e.releaseCamera()})),this}getExactTime(){if(!this.providerContainer)return 0;let e=this.providerContainer.providerOutput.element$.getValue();if(t0(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),i=t.state==="none"?void 0:t.position;return fy(i)?i/1e3:e.currentTime}getScene3D(){let e=this.providerContainer?.current$.getValue();if(e?.provider?.scene3D)return e.provider.scene3D}setIntrinsicVideoSize(...e){let t={width:e.reduce((i,{width:a})=>i||a||0,0),height:e.reduce((i,{height:a})=>i||a||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(ri(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(Y(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(Y(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(Y(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(Y(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(Y(e=>e.to)).subscribe(e=>{this.info.autoQualityLimits$.next(e);let{highQualityLimit:t,trafficSavingLimit:i}=this.tuning.autoTrackSelection;this.info.predefinedQualityLimitType$.next(Ru(e,t,i))})),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(_(({from:e})=>e==="stopped"),V()).subscribe(()=>{this.initedAt=yn(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case"ready":this.events.ready$.next();break;case"playing":this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case"paused":this.events.paused$.next();break;case"stopped":this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case"paused":this.events.willPause$.next();break;case"playing":this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case"stopped":this.events.willStop$.next();break;default:}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();n.state==="requested"?this.desiredState.seekState.setState({...n,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:gn.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe(V()).subscribe(this.events.autoplaySoundProhibited$)).add(e.providerOutput.severeStallOccurred$.subscribe(this.events.severeStallOccured$)).add(e.providerOutput.seekedEvent$.subscribe(()=>{this.desiredState.seekState.getState().state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe(Y(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(Y(n=>n.destination),he()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(wa({availableVideoTracks:e.providerOutput.availableVideoTracks$,currentVideoStream:e.providerOutput.currentVideoStream$}).pipe(Y(({availableVideoTracks:n,currentVideoStream:o})=>n.filter(u=>o?o.id===u.streamId:!0).map(({quality:u})=>u).sort((u,l)=>Sy(u)?1:Sy(l)?-1:i0(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(he()).subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.pipe(_(n=>fy(n))).subscribe(n=>{this.info.currentQuality$.next(n?.quality),this.info.videoBitrate$.next(n?.bitrate)})).add(e.providerOutput.currentVideoSegmentLength$.pipe(he((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe(he((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(he()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(he()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(he()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.autoVideoTrackLimits$.subscribe(n=>{this.desiredState.autoVideoTrackLimits.setState(n??{})})).add(e.providerOutput.currentBuffer$.pipe(Y(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(zl(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(wa({hasLiveOffsetByPaused:ri(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(Y(n=>n.to),he(),Y(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(wa({atLiveEdge:wa({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Wl({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(Y(({isLive:n,position:o,isLowLatency:u})=>{let l=this.getActiveLiveDelay(u);return n&&Math.abs(o)<l/1e3}),he(),zl(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(Y(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add(wa({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(Y(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),he(),zl(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(Y(n=>n.muted),he()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(Y(n=>n.volume),he()).subscribe(this.info.volume$)).add(Wl({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(ri(e.providerOutput.endedEvent$.pipe(by(!0)),e.providerOutput.seekedEvent$.pipe(by(!1))).pipe(he()).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(Y(n=>({id:n?`No${n}`:"NoProviders",category:gn.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(V(),Y(n=>n??yn()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(V(),Y(()=>yn()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(V(),Y(()=>yn()-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 E(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let i=new E(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(_(({to:n})=>n==="playing"),V()).subscribe(()=>i.next(!1)));let a=0,s=ri(e.providerOutput.isBuffering$,t,i).pipe(Y(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||i.getValue();return n&&!o}),he());this.subscription.add(s.subscribe(n=>{n?a=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(a),this.info.isStalled$.next(!1))})),this.subscription.add(ri(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{let n=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n?.videoWidth,height:n?.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{let o=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n?.size?.width,height:n?.size?.height},{width:o?.videoWidth,height:o?.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add(ri(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(Y(e=>e?.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new vy;this.subscription.add(t),this.subscription.add(e.current$.pipe(he((i,a)=>i.provider===a.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(_(i=>i.length>0),V()).subscribe(i=>{this.setStartingVideoTrack(i)}))}))}setStartingVideoTrack(e){let t;this.wasSetStartedQuality=!0;let i=this.explicitInitialQuality??this.info.currentQuality$.getValue();i&&(t=e.find(({quality:a})=>a===i),t||this.setAutoQuality(!0)),t||(t=Pt(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})),this.desiredState.videoTrack.startTransitionTo(t),this.info.currentQuality$.next(t.quality),this.info.videoBitrate$.next(t.bitrate)}initDebugTelemetry(){let e=this.providerContainer?.providerOutput;Sn(this.providerContainer),Sn(e),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart)}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e,t=()=>{e?.release(),e=void 0},i=async()=>{t(),e=await window.navigator.wakeLock.request("screen").catch(a=>{a instanceof DOMException&&a.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:gn.DOM,message:String(a)})})};this.subscription.add(ri(Yl(document,"visibilitychange"),Yl(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let a=document.visibilityState==="visible",s=this.desiredState.playbackState.getState()==="playing",n=!!e&&!e?.released;a&&s?n||i():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let i=e.find(a=>a.quality===t);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&&!Ar()}};import{Subscription as B3,Observable as O3,Subject as _3,ValueSubject as N3,VideoQuality as F3}from"@vkontakte/videoplayer-shared";var q3=`@vkontakte/videoplayer-core@${Jl}`;export{Oa as ChromecastState,xn as HttpConnectionType,O3 as Observable,Ie as PlaybackState,Tn as Player,_a as PredefinedQualityLimits,q3 as SDK_VERSION,_3 as Subject,B3 as Subscription,Pn as Surface,Jl as VERSION,N3 as ValueSubject,ut as VideoFormat,F3 as VideoQuality,C as clientChecker,yr as isMobile};