@vkontakte/videoplayer-core 2.0.148-dev.f4244a7e.0 → 2.0.149-dev.a444d83a.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/es2015.cjs.js +55 -51
- package/es2015.esm.js +53 -49
- package/es2018.cjs.js +53 -49
- package/es2018.esm.js +53 -49
- package/es2024.cjs.js +52 -48
- package/es2024.esm.js +55 -51
- package/esnext.cjs.js +52 -48
- package/esnext.esm.js +55 -51
- package/evergreen.esm.js +46 -42
- package/package.json +2 -2
- package/types/player/Player.d.ts +1 -0
- package/types/player/types.d.ts +7 -1
- package/types/providers/ChromecastPresentationApiProvider/ChromecastPresentationApiConnector.d.ts +124 -0
- package/types/providers/ChromecastPresentationApiProvider/ChromecastPresentationApiInitializer.d.ts +25 -0
- package/types/providers/ChromecastPresentationApiProvider/ChromecastPresentationApiProvider.d.ts +36 -0
- package/types/providers/ChromecastPresentationApiProvider/ProgressTicker.d.ts +11 -0
- package/types/providers/ChromecastPresentationApiProvider/index.d.ts +3 -0
- package/types/providers/ChromecastPresentationApiProvider/types.d.ts +49 -0
- package/types/providers/ChromecastPresentationApiProvider/utils.d.ts +4 -0
- package/types/providers/ChromecastProvider/ChromecastInitializer/index.d.ts +2 -10
- package/types/providers/ChromecastProvider/ChromecastInitializer/types.d.ts +8 -1
- package/types/providers/ChromecastProvider/index.d.ts +2 -10
- package/types/providers/ChromecastProvider/types.d.ts +8 -0
- package/types/providers/ChromecastProvider/utils.d.ts +2 -0
- package/types/providers/DashLiveProvider/utils/LiveDashPlayer.d.ts +1 -0
- package/types/providers/DashProvider/lib/fetcher.d.ts +0 -1
- package/types/providers/DashProvider/lib/sourceBufferTaskQueue.d.ts +2 -1
- package/types/providers/DashProviderNew/lib/fetcher.d.ts +0 -1
- package/types/providers/DashProviderNew/lib/sourceBufferTaskQueue.d.ts +2 -1
- package/types/providers/DashProviderVirtual/baseDashProvider.d.ts +61 -0
- package/types/providers/DashProviderVirtual/consts.d.ts +3 -0
- package/types/providers/DashProviderVirtual/dashCmafLiveProvider.d.ts +10 -0
- package/types/providers/DashProviderVirtual/dashProvider.d.ts +8 -0
- package/types/providers/DashProviderVirtual/index.d.ts +2 -0
- package/types/providers/DashProviderVirtual/lib/ElementSizeManager.d.ts +19 -0
- package/types/providers/DashProviderVirtual/lib/LiveTextManager.d.ts +23 -0
- package/types/providers/DashProviderVirtual/lib/buffer/nativeBufferManager.d.ts +19 -0
- package/types/providers/DashProviderVirtual/lib/buffer/sourceBufferTaskQueue.d.ts +19 -0
- package/types/providers/DashProviderVirtual/lib/buffer/types.d.ts +46 -0
- package/types/providers/DashProviderVirtual/lib/buffer/virtualBuffer/baseVirtualBufferManager.d.ts +93 -0
- package/types/providers/DashProviderVirtual/lib/buffer/virtualBuffer/byteRangeVirtualBufferManager.d.ts +21 -0
- package/types/providers/DashProviderVirtual/lib/buffer/virtualBuffer/liveVirtualBuffer.d.ts +27 -0
- package/types/providers/DashProviderVirtual/lib/buffer/virtualBuffer/templateVirtualBufferManager.d.ts +21 -0
- package/types/providers/DashProviderVirtual/lib/buffer/virtualBuffer/virtualBufferFactory.d.ts +6 -0
- package/types/providers/DashProviderVirtual/lib/fetcher.d.ts +63 -0
- package/types/providers/DashProviderVirtual/lib/player/basePlayer.d.ts +100 -0
- package/types/providers/DashProviderVirtual/lib/player/livePlayer.d.ts +36 -0
- package/types/providers/DashProviderVirtual/lib/player/player.d.ts +11 -0
- package/types/providers/DashProviderVirtual/lib/player/types.d.ts +17 -0
- package/types/providers/DashProviderVirtual/lib/types.d.ts +29 -0
- package/types/providers/DashProviderVirtual/lib/utils.d.ts +14 -0
- package/types/providers/types.d.ts +1 -0
- package/types/providers/utils/debug.d.ts +16 -0
- package/types/providers/utils/mergeIntervals.d.ts +3 -0
- package/types/providers/utils/parsers/types.d.ts +28 -7
- package/types/utils/ClientChecker/services/DeviceChecker.d.ts +19 -0
- package/types/utils/tuningConfig.d.ts +11 -0
package/es2024.esm.js
CHANGED
|
@@ -1,127 +1,120 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @vkontakte/videoplayer-core v2.0.
|
|
3
|
-
* Thu,
|
|
4
|
-
* https://st.mycdn.me/static/vkontakte-videoplayer/2-0-
|
|
2
|
+
* @vkontakte/videoplayer-core v2.0.149-dev.a444d83a.0
|
|
3
|
+
* Thu, 11 Dec 2025 14:48:07 GMT
|
|
4
|
+
* https://st.mycdn.me/static/vkontakte-videoplayer/2-0-149/doc/
|
|
5
5
|
*/
|
|
6
|
-
var WI=Object.create;var qd=Object.defineProperty;var QI=Object.getOwnPropertyDescriptor;var GI=Object.getOwnPropertyNames;var zI=Object.getPrototypeOf,YI=Object.prototype.hasOwnProperty;var b=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports);var KI=(a,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of GI(e))!YI.call(a,r)&&r!==t&&qd(a,r,{get:()=>e[r],enumerable:!(i=QI(e,r))||i.enumerable});return a};var C=(a,e,t)=>(t=a!=null?WI(zI(a)):{},KI(e||!a||!a.__esModule?qd(t,"default",{value:a,enumerable:!0}):t,a));var ie=b((ru,jd)=>{"use strict";var Nr=function(a){return a&&a.Math===Math&&a};jd.exports=Nr(typeof globalThis=="object"&&globalThis)||Nr(typeof window=="object"&&window)||Nr(typeof self=="object"&&self)||Nr(typeof global=="object"&&global)||Nr(typeof ru=="object"&&ru)||function(){return this}()||Function("return this")()});var de=b((uV,Hd)=>{"use strict";Hd.exports=function(a){try{return!!a()}catch{return!0}}});var qr=b((lV,Wd)=>{"use strict";var XI=de();Wd.exports=!XI(function(){var a=function(){}.bind();return typeof a!="function"||a.hasOwnProperty("prototype")})});var au=b((cV,Yd)=>{"use strict";var JI=qr(),zd=Function.prototype,Qd=zd.apply,Gd=zd.call;Yd.exports=typeof Reflect=="object"&&Reflect.apply||(JI?Gd.bind(Qd):function(){return Gd.apply(Qd,arguments)})});var pe=b((dV,Jd)=>{"use strict";var Kd=qr(),Xd=Function.prototype,su=Xd.call,ZI=Kd&&Xd.bind.bind(su,su);Jd.exports=Kd?ZI:function(a){return function(){return su.apply(a,arguments)}}});var ui=b((pV,ep)=>{"use strict";var Zd=pe(),eE=Zd({}.toString),tE=Zd("".slice);ep.exports=function(a){return tE(eE(a),8,-1)}});var nu=b((hV,tp)=>{"use strict";var iE=ui(),rE=pe();tp.exports=function(a){if(iE(a)==="Function")return rE(a)}});var re=b((fV,ip)=>{"use strict";var ou=typeof document=="object"&&document.all;ip.exports=typeof ou>"u"&&ou!==void 0?function(a){return typeof a=="function"||a===ou}:function(a){return typeof a=="function"}});var Fe=b((mV,rp)=>{"use strict";var aE=de();rp.exports=!aE(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var Ne=b((bV,ap)=>{"use strict";var sE=qr(),Qs=Function.prototype.call;ap.exports=sE?Qs.bind(Qs):function(){return Qs.apply(Qs,arguments)}});var uu=b(op=>{"use strict";var sp={}.propertyIsEnumerable,np=Object.getOwnPropertyDescriptor,nE=np&&!sp.call({1:2},1);op.f=nE?function(e){var t=np(this,e);return!!t&&t.enumerable}:sp});var Ur=b((vV,up)=>{"use strict";up.exports=function(a,e){return{enumerable:!(a&1),configurable:!(a&2),writable:!(a&4),value:e}}});var cp=b((SV,lp)=>{"use strict";var oE=pe(),uE=de(),lE=ui(),lu=Object,cE=oE("".split);lp.exports=uE(function(){return!lu("z").propertyIsEnumerable(0)})?function(a){return lE(a)==="String"?cE(a,""):lu(a)}:lu});var jr=b((yV,dp)=>{"use strict";dp.exports=function(a){return a==null}});var qt=b((TV,pp)=>{"use strict";var dE=jr(),pE=TypeError;pp.exports=function(a){if(dE(a))throw new pE("Can't call method on "+a);return a}});var li=b((IV,hp)=>{"use strict";var hE=cp(),fE=qt();hp.exports=function(a){return hE(fE(a))}});var Me=b((EV,fp)=>{"use strict";var mE=re();fp.exports=function(a){return typeof a=="object"?a!==null:mE(a)}});var ci=b((xV,mp)=>{"use strict";mp.exports={}});var wt=b((wV,gp)=>{"use strict";var cu=ci(),du=ie(),bE=re(),bp=function(a){return bE(a)?a:void 0};gp.exports=function(a,e){return arguments.length<2?bp(cu[a])||bp(du[a]):cu[a]&&cu[a][e]||du[a]&&du[a][e]}});var Hr=b((AV,vp)=>{"use strict";var gE=pe();vp.exports=gE({}.isPrototypeOf)});var di=b((kV,Tp)=>{"use strict";var vE=ie(),Sp=vE.navigator,yp=Sp&&Sp.userAgent;Tp.exports=yp?String(yp):""});var hu=b((PV,kp)=>{"use strict";var Ap=ie(),pu=di(),Ip=Ap.process,Ep=Ap.Deno,xp=Ip&&Ip.versions||Ep&&Ep.version,wp=xp&&xp.v8,it,Gs;wp&&(it=wp.split("."),Gs=it[0]>0&&it[0]<4?1:+(it[0]+it[1]));!Gs&&pu&&(it=pu.match(/Edge\/(\d+)/),(!it||it[1]>=74)&&(it=pu.match(/Chrome\/(\d+)/),it&&(Gs=+it[1])));kp.exports=Gs});var fu=b((RV,Rp)=>{"use strict";var Pp=hu(),SE=de(),yE=ie(),TE=yE.String;Rp.exports=!!Object.getOwnPropertySymbols&&!SE(function(){var a=Symbol("symbol detection");return!TE(a)||!(Object(a)instanceof Symbol)||!Symbol.sham&&Pp&&Pp<41})});var mu=b(($V,$p)=>{"use strict";var IE=fu();$p.exports=IE&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var bu=b((LV,Lp)=>{"use strict";var EE=wt(),xE=re(),wE=Hr(),AE=mu(),kE=Object;Lp.exports=AE?function(a){return typeof a=="symbol"}:function(a){var e=EE("Symbol");return xE(e)&&wE(e.prototype,kE(a))}});var Wr=b((MV,Mp)=>{"use strict";var PE=String;Mp.exports=function(a){try{return PE(a)}catch{return"Object"}}});var ft=b((DV,Dp)=>{"use strict";var RE=re(),$E=Wr(),LE=TypeError;Dp.exports=function(a){if(RE(a))return a;throw new LE($E(a)+" is not a function")}});var Qr=b((CV,Cp)=>{"use strict";var ME=ft(),DE=jr();Cp.exports=function(a,e){var t=a[e];return DE(t)?void 0:ME(t)}});var Vp=b((BV,Bp)=>{"use strict";var gu=Ne(),vu=re(),Su=Me(),CE=TypeError;Bp.exports=function(a,e){var t,i;if(e==="string"&&vu(t=a.toString)&&!Su(i=gu(t,a))||vu(t=a.valueOf)&&!Su(i=gu(t,a))||e!=="string"&&vu(t=a.toString)&&!Su(i=gu(t,a)))return i;throw new CE("Can't convert object to primitive value")}});var rt=b((VV,_p)=>{"use strict";_p.exports=!0});var Np=b((_V,Fp)=>{"use strict";var Op=ie(),BE=Object.defineProperty;Fp.exports=function(a,e){try{BE(Op,a,{value:e,configurable:!0,writable:!0})}catch{Op[a]=e}return e}});var Gr=b((OV,jp)=>{"use strict";var VE=rt(),_E=ie(),OE=Np(),qp="__core-js_shared__",Up=jp.exports=_E[qp]||OE(qp,{});(Up.versions||(Up.versions=[])).push({version:"3.43.0",mode:VE?"pure":"global",copyright:"© 2014-2025 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.43.0/LICENSE",source:"https://github.com/zloirock/core-js"})});var yu=b((FV,Wp)=>{"use strict";var Hp=Gr();Wp.exports=function(a,e){return Hp[a]||(Hp[a]=e||{})}});var Qi=b((NV,Qp)=>{"use strict";var FE=qt(),NE=Object;Qp.exports=function(a){return NE(FE(a))}});var at=b((qV,Gp)=>{"use strict";var qE=pe(),UE=Qi(),jE=qE({}.hasOwnProperty);Gp.exports=Object.hasOwn||function(e,t){return jE(UE(e),t)}});var Tu=b((UV,zp)=>{"use strict";var HE=pe(),WE=0,QE=Math.random(),GE=HE(1.1.toString);zp.exports=function(a){return"Symbol("+(a===void 0?"":a)+")_"+GE(++WE+QE,36)}});var ve=b((jV,Kp)=>{"use strict";var zE=ie(),YE=yu(),Yp=at(),KE=Tu(),XE=fu(),JE=mu(),Gi=zE.Symbol,Iu=YE("wks"),ZE=JE?Gi.for||Gi:Gi&&Gi.withoutSetter||KE;Kp.exports=function(a){return Yp(Iu,a)||(Iu[a]=XE&&Yp(Gi,a)?Gi[a]:ZE("Symbol."+a)),Iu[a]}});var eh=b((HV,Zp)=>{"use strict";var ex=Ne(),Xp=Me(),Jp=bu(),tx=Qr(),ix=Vp(),rx=ve(),ax=TypeError,sx=rx("toPrimitive");Zp.exports=function(a,e){if(!Xp(a)||Jp(a))return a;var t=tx(a,sx),i;if(t){if(e===void 0&&(e="default"),i=ex(t,a,e),!Xp(i)||Jp(i))return i;throw new ax("Can't convert object to primitive value")}return e===void 0&&(e="number"),ix(a,e)}});var Eu=b((WV,th)=>{"use strict";var nx=eh(),ox=bu();th.exports=function(a){var e=nx(a,"string");return ox(e)?e:e+""}});var zs=b((QV,rh)=>{"use strict";var ux=ie(),ih=Me(),xu=ux.document,lx=ih(xu)&&ih(xu.createElement);rh.exports=function(a){return lx?xu.createElement(a):{}}});var wu=b((GV,ah)=>{"use strict";var cx=Fe(),dx=de(),px=zs();ah.exports=!cx&&!dx(function(){return Object.defineProperty(px("div"),"a",{get:function(){return 7}}).a!==7})});var oh=b(nh=>{"use strict";var hx=Fe(),fx=Ne(),mx=uu(),bx=Ur(),gx=li(),vx=Eu(),Sx=at(),yx=wu(),sh=Object.getOwnPropertyDescriptor;nh.f=hx?sh:function(e,t){if(e=gx(e),t=vx(t),yx)try{return sh(e,t)}catch{}if(Sx(e,t))return bx(!fx(mx.f,e,t),e[t])}});var Au=b((YV,uh)=>{"use strict";var Tx=de(),Ix=re(),Ex=/#|\.prototype\./,zr=function(a,e){var t=wx[xx(a)];return t===kx?!0:t===Ax?!1:Ix(e)?Tx(e):!!e},xx=zr.normalize=function(a){return String(a).replace(Ex,".").toLowerCase()},wx=zr.data={},Ax=zr.NATIVE="N",kx=zr.POLYFILL="P";uh.exports=zr});var zi=b((KV,ch)=>{"use strict";var lh=nu(),Px=ft(),Rx=qr(),$x=lh(lh.bind);ch.exports=function(a,e){return Px(a),e===void 0?a:Rx?$x(a,e):function(){return a.apply(e,arguments)}}});var ku=b((XV,dh)=>{"use strict";var Lx=Fe(),Mx=de();dh.exports=Lx&&Mx(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var mt=b((JV,ph)=>{"use strict";var Dx=Me(),Cx=String,Bx=TypeError;ph.exports=function(a){if(Dx(a))return a;throw new Bx(Cx(a)+" is not an object")}});var pi=b(fh=>{"use strict";var Vx=Fe(),_x=wu(),Ox=ku(),Ys=mt(),hh=Eu(),Fx=TypeError,Pu=Object.defineProperty,Nx=Object.getOwnPropertyDescriptor,Ru="enumerable",$u="configurable",Lu="writable";fh.f=Vx?Ox?function(e,t,i){if(Ys(e),t=hh(t),Ys(i),typeof e=="function"&&t==="prototype"&&"value"in i&&Lu in i&&!i[Lu]){var r=Nx(e,t);r&&r[Lu]&&(e[t]=i.value,i={configurable:$u in i?i[$u]:r[$u],enumerable:Ru in i?i[Ru]:r[Ru],writable:!1})}return Pu(e,t,i)}:Pu:function(e,t,i){if(Ys(e),t=hh(t),Ys(i),_x)try{return Pu(e,t,i)}catch{}if("get"in i||"set"in i)throw new Fx("Accessors not supported");return"value"in i&&(e[t]=i.value),e}});var Yi=b((e_,mh)=>{"use strict";var qx=Fe(),Ux=pi(),jx=Ur();mh.exports=qx?function(a,e,t){return Ux.f(a,e,jx(1,t))}:function(a,e,t){return a[e]=t,a}});var se=b((t_,gh)=>{"use strict";var Yr=ie(),Hx=au(),Wx=nu(),Qx=re(),Gx=oh().f,zx=Au(),Ki=ci(),Yx=zi(),Xi=Yi(),bh=at();Gr();var Kx=function(a){var e=function(t,i,r){if(this instanceof e){switch(arguments.length){case 0:return new a;case 1:return new a(t);case 2:return new a(t,i)}return new a(t,i,r)}return Hx(a,this,arguments)};return e.prototype=a.prototype,e};gh.exports=function(a,e){var t=a.target,i=a.global,r=a.stat,s=a.proto,n=i?Yr:r?Yr[t]:Yr[t]&&Yr[t].prototype,u=i?Ki:Ki[t]||Xi(Ki,t,{})[t],o=u.prototype,l,p,c,d,h,f,m,g,v;for(d in e)l=zx(i?d:t+(r?".":"#")+d,a.forced),p=!l&&n&&bh(n,d),f=u[d],p&&(a.dontCallGetSet?(v=Gx(n,d),m=v&&v.value):m=n[d]),h=p&&m?m:e[d],!(!l&&!s&&typeof f==typeof h)&&(a.bind&&p?g=Yx(h,Yr):a.wrap&&p?g=Kx(h):s&&Qx(h)?g=Wx(h):g=h,(a.sham||h&&h.sham||f&&f.sham)&&Xi(g,"sham",!0),Xi(u,d,g),s&&(c=t+"Prototype",bh(Ki,c)||Xi(Ki,c,{}),Xi(Ki[c],d,h),a.real&&o&&(l||!o[d])&&Xi(o,d,h)))}});var Ks=b((i_,Sh)=>{"use strict";var Xx=yu(),Jx=Tu(),vh=Xx("keys");Sh.exports=function(a){return vh[a]||(vh[a]=Jx(a))}});var Th=b((r_,yh)=>{"use strict";var Zx=de();yh.exports=!Zx(function(){function a(){}return a.prototype.constructor=null,Object.getPrototypeOf(new a)!==a.prototype})});var Xs=b((a_,Eh)=>{"use strict";var ew=at(),tw=re(),iw=Qi(),rw=Ks(),aw=Th(),Ih=rw("IE_PROTO"),Mu=Object,sw=Mu.prototype;Eh.exports=aw?Mu.getPrototypeOf:function(a){var e=iw(a);if(ew(e,Ih))return e[Ih];var t=e.constructor;return tw(t)&&e instanceof t?t.prototype:e instanceof Mu?sw:null}});var wh=b((s_,xh)=>{"use strict";var nw=Math.ceil,ow=Math.floor;xh.exports=Math.trunc||function(e){var t=+e;return(t>0?ow:nw)(t)}});var Kr=b((n_,Ah)=>{"use strict";var uw=wh();Ah.exports=function(a){var e=+a;return e!==e||e===0?0:uw(e)}});var Ph=b((o_,kh)=>{"use strict";var lw=Kr(),cw=Math.max,dw=Math.min;kh.exports=function(a,e){var t=lw(a);return t<0?cw(t+e,0):dw(t,e)}});var Du=b((u_,Rh)=>{"use strict";var pw=Kr(),hw=Math.min;Rh.exports=function(a){var e=pw(a);return e>0?hw(e,9007199254740991):0}});var Ji=b((l_,$h)=>{"use strict";var fw=Du();$h.exports=function(a){return fw(a.length)}});var Cu=b((c_,Mh)=>{"use strict";var mw=li(),bw=Ph(),gw=Ji(),Lh=function(a){return function(e,t,i){var r=mw(e),s=gw(r);if(s===0)return!a&&-1;var n=bw(i,s),u;if(a&&t!==t){for(;s>n;)if(u=r[n++],u!==u)return!0}else for(;s>n;n++)if((a||n in r)&&r[n]===t)return a||n||0;return!a&&-1}};Mh.exports={includes:Lh(!0),indexOf:Lh(!1)}});var Js=b((d_,Dh)=>{"use strict";Dh.exports={}});var Vh=b((p_,Bh)=>{"use strict";var vw=pe(),Bu=at(),Sw=li(),yw=Cu().indexOf,Tw=Js(),Ch=vw([].push);Bh.exports=function(a,e){var t=Sw(a),i=0,r=[],s;for(s in t)!Bu(Tw,s)&&Bu(t,s)&&Ch(r,s);for(;e.length>i;)Bu(t,s=e[i++])&&(~yw(r,s)||Ch(r,s));return r}});var Vu=b((h_,_h)=>{"use strict";_h.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var _u=b((f_,Oh)=>{"use strict";var Iw=Vh(),Ew=Vu();Oh.exports=Object.keys||function(e){return Iw(e,Ew)}});var Ou=b((m_,jh)=>{"use strict";var Nh=Fe(),xw=de(),qh=pe(),ww=Xs(),Aw=_u(),kw=li(),Pw=uu().f,Uh=qh(Pw),Rw=qh([].push),$w=Nh&&xw(function(){var a=Object.create(null);return a[2]=2,!Uh(a,2)}),Fh=function(a){return function(e){for(var t=kw(e),i=Aw(t),r=$w&&ww(t)===null,s=i.length,n=0,u=[],o;s>n;)o=i[n++],(!Nh||(r?o in t:Uh(t,o)))&&Rw(u,a?[o,t[o]]:t[o]);return u}};jh.exports={entries:Fh(!0),values:Fh(!1)}});var Hh=b(()=>{"use strict";var Lw=se(),Mw=Ou().values;Lw({target:"Object",stat:!0},{values:function(e){return Mw(e)}})});var Qh=b((v_,Wh)=>{"use strict";Hh();var Dw=ci();Wh.exports=Dw.Object.values});var zh=b((S_,Gh)=>{"use strict";var Cw=Qh();Gh.exports=Cw});var hi=b((y_,Yh)=>{"use strict";var Bw=zh();Yh.exports=Bw});var Xr=b((T_,Kh)=>{"use strict";Kh.exports=function(){}});var Xh=b(()=>{"use strict";var Vw=se(),_w=Cu().includes,Ow=de(),Fw=Xr(),Nw=Ow(function(){return!Array(1).includes()});Vw({target:"Array",proto:!0,forced:Nw},{includes:function(e){return _w(this,e,arguments.length>1?arguments[1]:void 0)}});Fw("includes")});var Ut=b((x_,Jh)=>{"use strict";var qw=wt();Jh.exports=qw});var ef=b((w_,Zh)=>{"use strict";Xh();var Uw=Ut();Zh.exports=Uw("Array","includes")});var rf=b((A_,tf)=>{"use strict";var jw=ef();tf.exports=jw});var xe=b((k_,af)=>{"use strict";var Hw=rf();af.exports=Hw});var df=b(()=>{"use strict";var Jw=se(),Zw=Ou().entries;Jw({target:"Object",stat:!0},{entries:function(e){return Zw(e)}})});var hf=b((q_,pf)=>{"use strict";df();var eA=ci();pf.exports=eA.Object.entries});var mf=b((U_,ff)=>{"use strict";var tA=hf();ff.exports=tA});var fi=b((j_,bf)=>{"use strict";var iA=mf();bf.exports=iA});var mi=b((H_,gf)=>{"use strict";gf.exports={}});var yf=b((W_,Sf)=>{"use strict";var rA=ie(),aA=re(),vf=rA.WeakMap;Sf.exports=aA(vf)&&/native code/.test(String(vf))});var Hu=b((Q_,Ef)=>{"use strict";var sA=yf(),If=ie(),nA=Me(),oA=Yi(),qu=at(),Uu=Gr(),uA=Ks(),lA=Js(),Tf="Object already initialized",ju=If.TypeError,cA=If.WeakMap,tn,Jr,rn,dA=function(a){return rn(a)?Jr(a):tn(a,{})},pA=function(a){return function(e){var t;if(!nA(e)||(t=Jr(e)).type!==a)throw new ju("Incompatible receiver, "+a+" required");return t}};sA||Uu.state?(st=Uu.state||(Uu.state=new cA),st.get=st.get,st.has=st.has,st.set=st.set,tn=function(a,e){if(st.has(a))throw new ju(Tf);return e.facade=a,st.set(a,e),e},Jr=function(a){return st.get(a)||{}},rn=function(a){return st.has(a)}):(bi=uA("state"),lA[bi]=!0,tn=function(a,e){if(qu(a,bi))throw new ju(Tf);return e.facade=a,oA(a,bi,e),e},Jr=function(a){return qu(a,bi)?a[bi]:{}},rn=function(a){return qu(a,bi)});var st,bi;Ef.exports={set:tn,get:Jr,has:rn,enforce:dA,getterFor:pA}});var Gu=b((G_,wf)=>{"use strict";var Wu=Fe(),hA=at(),xf=Function.prototype,fA=Wu&&Object.getOwnPropertyDescriptor,Qu=hA(xf,"name"),mA=Qu&&function(){}.name==="something",bA=Qu&&(!Wu||Wu&&fA(xf,"name").configurable);wf.exports={EXISTS:Qu,PROPER:mA,CONFIGURABLE:bA}});var kf=b(Af=>{"use strict";var gA=Fe(),vA=ku(),SA=pi(),yA=mt(),TA=li(),IA=_u();Af.f=gA&&!vA?Object.defineProperties:function(e,t){yA(e);for(var i=TA(t),r=IA(t),s=r.length,n=0,u;s>n;)SA.f(e,u=r[n++],i[u]);return e}});var zu=b((Y_,Pf)=>{"use strict";var EA=wt();Pf.exports=EA("document","documentElement")});var Ju=b((K_,Bf)=>{"use strict";var xA=mt(),wA=kf(),Rf=Vu(),AA=Js(),kA=zu(),PA=zs(),RA=Ks(),$f=">",Lf="<",Ku="prototype",Xu="script",Df=RA("IE_PROTO"),Yu=function(){},Cf=function(a){return Lf+Xu+$f+a+Lf+"/"+Xu+$f},Mf=function(a){a.write(Cf("")),a.close();var e=a.parentWindow.Object;return a=null,e},$A=function(){var a=PA("iframe"),e="java"+Xu+":",t;return a.style.display="none",kA.appendChild(a),a.src=String(e),t=a.contentWindow.document,t.open(),t.write(Cf("document.F=Object")),t.close(),t.F},an,sn=function(){try{an=new ActiveXObject("htmlfile")}catch{}sn=typeof document<"u"?document.domain&&an?Mf(an):$A():Mf(an);for(var a=Rf.length;a--;)delete sn[Ku][Rf[a]];return sn()};AA[Df]=!0;Bf.exports=Object.create||function(e,t){var i;return e!==null?(Yu[Ku]=xA(e),i=new Yu,Yu[Ku]=null,i[Df]=e):i=sn(),t===void 0?i:wA.f(i,t)}});var Zi=b((X_,Vf)=>{"use strict";var LA=Yi();Vf.exports=function(a,e,t,i){return i&&i.enumerable?a[e]=t:LA(a,e,t),a}});var il=b((J_,Ff)=>{"use strict";var MA=de(),DA=re(),CA=Me(),BA=Ju(),_f=Xs(),VA=Zi(),_A=ve(),OA=rt(),tl=_A("iterator"),Of=!1,At,Zu,el;[].keys&&(el=[].keys(),"next"in el?(Zu=_f(_f(el)),Zu!==Object.prototype&&(At=Zu)):Of=!0);var FA=!CA(At)||MA(function(){var a={};return At[tl].call(a)!==a});FA?At={}:OA&&(At=BA(At));DA(At[tl])||VA(At,tl,function(){return this});Ff.exports={IteratorPrototype:At,BUGGY_SAFARI_ITERATORS:Of}});var nn=b((Z_,qf)=>{"use strict";var NA=ve(),qA=NA("toStringTag"),Nf={};Nf[qA]="z";qf.exports=String(Nf)==="[object z]"});var Zr=b((eO,Uf)=>{"use strict";var UA=nn(),jA=re(),on=ui(),HA=ve(),WA=HA("toStringTag"),QA=Object,GA=on(function(){return arguments}())==="Arguments",zA=function(a,e){try{return a[e]}catch{}};Uf.exports=UA?on:function(a){var e,t,i;return a===void 0?"Undefined":a===null?"Null":typeof(t=zA(e=QA(a),WA))=="string"?t:GA?on(e):(i=on(e))==="Object"&&jA(e.callee)?"Arguments":i}});var Hf=b((tO,jf)=>{"use strict";var YA=nn(),KA=Zr();jf.exports=YA?{}.toString:function(){return"[object "+KA(this)+"]"}});var ea=b((iO,Qf)=>{"use strict";var XA=nn(),JA=pi().f,ZA=Yi(),ek=at(),tk=Hf(),ik=ve(),Wf=ik("toStringTag");Qf.exports=function(a,e,t,i){var r=t?a:a&&a.prototype;r&&(ek(r,Wf)||JA(r,Wf,{configurable:!0,value:e}),i&&!XA&&ZA(r,"toString",tk))}});var zf=b((rO,Gf)=>{"use strict";var rk=il().IteratorPrototype,ak=Ju(),sk=Ur(),nk=ea(),ok=mi(),uk=function(){return this};Gf.exports=function(a,e,t,i){var r=e+" Iterator";return a.prototype=ak(rk,{next:sk(+!i,t)}),nk(a,r,!1,!0),ok[r]=uk,a}});var Kf=b((aO,Yf)=>{"use strict";var lk=pe(),ck=ft();Yf.exports=function(a,e,t){try{return lk(ck(Object.getOwnPropertyDescriptor(a,e)[t]))}catch{}}});var Jf=b((sO,Xf)=>{"use strict";var dk=Me();Xf.exports=function(a){return dk(a)||a===null}});var em=b((nO,Zf)=>{"use strict";var pk=Jf(),hk=String,fk=TypeError;Zf.exports=function(a){if(pk(a))return a;throw new fk("Can't set "+hk(a)+" as a prototype")}});var rl=b((oO,tm)=>{"use strict";var mk=Kf(),bk=Me(),gk=qt(),vk=em();tm.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var a=!1,e={},t;try{t=mk(Object.prototype,"__proto__","set"),t(e,[]),a=e instanceof Array}catch{}return function(r,s){return gk(r),vk(s),bk(r)&&(a?t(r,s):r.__proto__=s),r}}():void 0)});var pm=b((uO,dm)=>{"use strict";var Sk=se(),yk=Ne(),un=rt(),lm=Gu(),Tk=re(),Ik=zf(),im=Xs(),rm=rl(),Ek=ea(),xk=Yi(),al=Zi(),wk=ve(),am=mi(),cm=il(),Ak=lm.PROPER,kk=lm.CONFIGURABLE,sm=cm.IteratorPrototype,ln=cm.BUGGY_SAFARI_ITERATORS,ta=wk("iterator"),nm="keys",ia="values",om="entries",um=function(){return this};dm.exports=function(a,e,t,i,r,s,n){Ik(t,e,i);var u=function(v){if(v===r&&d)return d;if(!ln&&v&&v in p)return p[v];switch(v){case nm:return function(){return new t(this,v)};case ia:return function(){return new t(this,v)};case om:return function(){return new t(this,v)}}return function(){return new t(this)}},o=e+" Iterator",l=!1,p=a.prototype,c=p[ta]||p["@@iterator"]||r&&p[r],d=!ln&&c||u(r),h=e==="Array"&&p.entries||c,f,m,g;if(h&&(f=im(h.call(new a)),f!==Object.prototype&&f.next&&(!un&&im(f)!==sm&&(rm?rm(f,sm):Tk(f[ta])||al(f,ta,um)),Ek(f,o,!0,!0),un&&(am[o]=um))),Ak&&r===ia&&c&&c.name!==ia&&(!un&&kk?xk(p,"name",ia):(l=!0,d=function(){return yk(c,this)})),r)if(m={values:u(ia),keys:s?d:u(nm),entries:u(om)},n)for(g in m)(ln||l||!(g in p))&&al(p,g,m[g]);else Sk({target:e,proto:!0,forced:ln||l},m);return(!un||n)&&p[ta]!==d&&al(p,ta,d,{name:r}),am[e]=d,m}});var fm=b((lO,hm)=>{"use strict";hm.exports=function(a,e){return{value:a,done:e}}});var nl=b((cO,Sm)=>{"use strict";var Pk=li(),sl=Xr(),mm=mi(),gm=Hu(),Rk=pi().f,$k=pm(),cn=fm(),Lk=rt(),Mk=Fe(),vm="Array Iterator",Dk=gm.set,Ck=gm.getterFor(vm);Sm.exports=$k(Array,"Array",function(a,e){Dk(this,{type:vm,target:Pk(a),index:0,kind:e})},function(){var a=Ck(this),e=a.target,t=a.index++;if(!e||t>=e.length)return a.target=null,cn(void 0,!0);switch(a.kind){case"keys":return cn(t,!1);case"values":return cn(e[t],!1)}return cn([t,e[t]],!1)},"values");var bm=mm.Arguments=mm.Array;sl("keys");sl("values");sl("entries");if(!Lk&&Mk&&bm.name!=="values")try{Rk(bm,"name",{value:"values"})}catch{}});var Tm=b((dO,ym)=>{"use strict";var Bk=ve(),Vk=mi(),_k=Bk("iterator"),Ok=Array.prototype;ym.exports=function(a){return a!==void 0&&(Vk.Array===a||Ok[_k]===a)}});var ol=b((pO,Em)=>{"use strict";var Fk=Zr(),Im=Qr(),Nk=jr(),qk=mi(),Uk=ve(),jk=Uk("iterator");Em.exports=function(a){if(!Nk(a))return Im(a,jk)||Im(a,"@@iterator")||qk[Fk(a)]}});var wm=b((hO,xm)=>{"use strict";var Hk=Ne(),Wk=ft(),Qk=mt(),Gk=Wr(),zk=ol(),Yk=TypeError;xm.exports=function(a,e){var t=arguments.length<2?zk(a):e;if(Wk(t))return Qk(Hk(t,a));throw new Yk(Gk(a)+" is not iterable")}});var Pm=b((fO,km)=>{"use strict";var Kk=Ne(),Am=mt(),Xk=Qr();km.exports=function(a,e,t){var i,r;Am(a);try{if(i=Xk(a,"return"),!i){if(e==="throw")throw t;return t}i=Kk(i,a)}catch(s){r=!0,i=s}if(e==="throw")throw t;if(r)throw i;return Am(i),t}});var pn=b((mO,Mm)=>{"use strict";var Jk=zi(),Zk=Ne(),eP=mt(),tP=Wr(),iP=Tm(),rP=Ji(),Rm=Hr(),aP=wm(),sP=ol(),$m=Pm(),nP=TypeError,dn=function(a,e){this.stopped=a,this.result=e},Lm=dn.prototype;Mm.exports=function(a,e,t){var i=t&&t.that,r=!!(t&&t.AS_ENTRIES),s=!!(t&&t.IS_RECORD),n=!!(t&&t.IS_ITERATOR),u=!!(t&&t.INTERRUPTED),o=Jk(e,i),l,p,c,d,h,f,m,g=function(S){return l&&$m(l,"normal"),new dn(!0,S)},v=function(S){return r?(eP(S),u?o(S[0],S[1],g):o(S[0],S[1])):u?o(S,g):o(S)};if(s)l=a.iterator;else if(n)l=a;else{if(p=sP(a),!p)throw new nP(tP(a)+" is not iterable");if(iP(p)){for(c=0,d=rP(a);d>c;c++)if(h=v(a[c]),h&&Rm(Lm,h))return h;return new dn(!1)}l=aP(a,p)}for(f=s?a.next:l.next;!(m=Zk(f,l)).done;){try{h=v(m.value)}catch(S){$m(l,"throw",S)}if(typeof h=="object"&&h&&Rm(Lm,h))return h}return new dn(!1)}});var Cm=b((bO,Dm)=>{"use strict";var oP=Fe(),uP=pi(),lP=Ur();Dm.exports=function(a,e,t){oP?uP.f(a,e,lP(0,t)):a[e]=t}});var Bm=b(()=>{"use strict";var cP=se(),dP=pn(),pP=Cm();cP({target:"Object",stat:!0},{fromEntries:function(e){var t={};return dP(e,function(i,r){pP(t,i,r)},{AS_ENTRIES:!0}),t}})});var _m=b((SO,Vm)=>{"use strict";nl();Bm();var hP=ci();Vm.exports=hP.Object.fromEntries});var Fm=b((yO,Om)=>{"use strict";Om.exports={CSSRuleList:0,CSSStyleDeclaration:0,CSSValueList:0,ClientRectList:0,DOMRectList:0,DOMStringList:0,DOMTokenList:1,DataTransferItemList:0,FileList:0,HTMLAllCollection:0,HTMLCollection:0,HTMLFormElement:0,HTMLSelectElement:0,MediaList:0,MimeTypeArray:0,NamedNodeMap:0,NodeList:1,PaintRequestList:0,Plugin:0,PluginArray:0,SVGLengthList:0,SVGNumberList:0,SVGPathSegList:0,SVGPointList:0,SVGStringList:0,SVGTransformList:0,SourceBufferList:0,StyleSheetList:0,TextTrackCueList:0,TextTrackList:0,TouchList:0}});var qm=b(()=>{"use strict";nl();var fP=Fm(),mP=ie(),bP=ea(),Nm=mi();for(hn in fP)bP(mP[hn],hn),Nm[hn]=Nm.Array;var hn});var jm=b((EO,Um)=>{"use strict";var gP=_m();qm();Um.exports=gP});var ul=b((xO,Hm)=>{"use strict";var vP=jm();Hm.exports=vP});var Wm=b(()=>{"use strict"});var ll=b((kO,Qm)=>{"use strict";var ra=ie(),SP=di(),yP=ui(),fn=function(a){return SP.slice(0,a.length)===a};Qm.exports=function(){return fn("Bun/")?"BUN":fn("Cloudflare-Workers")?"CLOUDFLARE":fn("Deno/")?"DENO":fn("Node.js/")?"NODE":ra.Bun&&typeof Bun.version=="string"?"BUN":ra.Deno&&typeof Deno.version=="object"?"DENO":yP(ra.process)==="process"?"NODE":ra.window&&ra.document?"BROWSER":"REST"}()});var mn=b((PO,Gm)=>{"use strict";var TP=ll();Gm.exports=TP==="NODE"});var Ym=b((RO,zm)=>{"use strict";var IP=pi();zm.exports=function(a,e,t){return IP.f(a,e,t)}});var Jm=b(($O,Xm)=>{"use strict";var EP=wt(),xP=Ym(),wP=ve(),AP=Fe(),Km=wP("species");Xm.exports=function(a){var e=EP(a);AP&&e&&!e[Km]&&xP(e,Km,{configurable:!0,get:function(){return this}})}});var eb=b((LO,Zm)=>{"use strict";var kP=Hr(),PP=TypeError;Zm.exports=function(a,e){if(kP(e,a))return a;throw new PP("Incorrect invocation")}});var dl=b((MO,tb)=>{"use strict";var RP=pe(),$P=re(),cl=Gr(),LP=RP(Function.toString);$P(cl.inspectSource)||(cl.inspectSource=function(a){return LP(a)});tb.exports=cl.inspectSource});var hl=b((DO,nb)=>{"use strict";var MP=pe(),DP=de(),ib=re(),CP=Zr(),BP=wt(),VP=dl(),rb=function(){},ab=BP("Reflect","construct"),pl=/^\s*(?:class|function)\b/,_P=MP(pl.exec),OP=!pl.test(rb),aa=function(e){if(!ib(e))return!1;try{return ab(rb,[],e),!0}catch{return!1}},sb=function(e){if(!ib(e))return!1;switch(CP(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return OP||!!_P(pl,VP(e))}catch{return!0}};sb.sham=!0;nb.exports=!ab||DP(function(){var a;return aa(aa.call)||!aa(Object)||!aa(function(){a=!0})||a})?sb:aa});var ub=b((CO,ob)=>{"use strict";var FP=hl(),NP=Wr(),qP=TypeError;ob.exports=function(a){if(FP(a))return a;throw new qP(NP(a)+" is not a constructor")}});var fl=b((BO,cb)=>{"use strict";var lb=mt(),UP=ub(),jP=jr(),HP=ve(),WP=HP("species");cb.exports=function(a,e){var t=lb(a).constructor,i;return t===void 0||jP(i=lb(t)[WP])?e:UP(i)}});var pb=b((VO,db)=>{"use strict";var QP=pe();db.exports=QP([].slice)});var fb=b((_O,hb)=>{"use strict";var GP=TypeError;hb.exports=function(a,e){if(a<e)throw new GP("Not enough arguments");return a}});var ml=b((OO,mb)=>{"use strict";var zP=di();mb.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(zP)});var xl=b((FO,xb)=>{"use strict";var qe=ie(),YP=au(),KP=zi(),bb=re(),XP=at(),Eb=de(),gb=zu(),JP=pb(),vb=zs(),ZP=fb(),eR=ml(),tR=mn(),Tl=qe.setImmediate,Il=qe.clearImmediate,iR=qe.process,bl=qe.Dispatch,rR=qe.Function,Sb=qe.MessageChannel,aR=qe.String,gl=0,sa={},yb="onreadystatechange",na,gi,vl,Sl;Eb(function(){na=qe.location});var El=function(a){if(XP(sa,a)){var e=sa[a];delete sa[a],e()}},yl=function(a){return function(){El(a)}},Tb=function(a){El(a.data)},Ib=function(a){qe.postMessage(aR(a),na.protocol+"//"+na.host)};(!Tl||!Il)&&(Tl=function(e){ZP(arguments.length,1);var t=bb(e)?e:rR(e),i=JP(arguments,1);return sa[++gl]=function(){YP(t,void 0,i)},gi(gl),gl},Il=function(e){delete sa[e]},tR?gi=function(a){iR.nextTick(yl(a))}:bl&&bl.now?gi=function(a){bl.now(yl(a))}:Sb&&!eR?(vl=new Sb,Sl=vl.port2,vl.port1.onmessage=Tb,gi=KP(Sl.postMessage,Sl)):qe.addEventListener&&bb(qe.postMessage)&&!qe.importScripts&&na&&na.protocol!=="file:"&&!Eb(Ib)?(gi=Ib,qe.addEventListener("message",Tb,!1)):yb in vb("script")?gi=function(a){gb.appendChild(vb("script"))[yb]=function(){gb.removeChild(this),El(a)}}:gi=function(a){setTimeout(yl(a),0)});xb.exports={set:Tl,clear:Il}});var kb=b((NO,Ab)=>{"use strict";var wb=ie(),sR=Fe(),nR=Object.getOwnPropertyDescriptor;Ab.exports=function(a){if(!sR)return wb[a];var e=nR(wb,a);return e&&e.value}});var wl=b((qO,Rb)=>{"use strict";var Pb=function(){this.head=null,this.tail=null};Pb.prototype={add:function(a){var e={item:a,next:null},t=this.tail;t?t.next=e:this.head=e,this.tail=e},get:function(){var a=this.head;if(a){var e=this.head=a.next;return e===null&&(this.tail=null),a.item}}};Rb.exports=Pb});var Lb=b((UO,$b)=>{"use strict";var oR=di();$b.exports=/ipad|iphone|ipod/i.test(oR)&&typeof Pebble<"u"});var Db=b((jO,Mb)=>{"use strict";var uR=di();Mb.exports=/web0s(?!.*chrome)/i.test(uR)});var Nb=b((HO,Fb)=>{"use strict";var tr=ie(),lR=kb(),Cb=zi(),Al=xl().set,cR=wl(),dR=ml(),pR=Lb(),hR=Db(),kl=mn(),Bb=tr.MutationObserver||tr.WebKitMutationObserver,Vb=tr.document,_b=tr.process,bn=tr.Promise,$l=lR("queueMicrotask"),er,Pl,Rl,gn,Ob;$l||(oa=new cR,ua=function(){var a,e;for(kl&&(a=_b.domain)&&a.exit();e=oa.get();)try{e()}catch(t){throw oa.head&&er(),t}a&&a.enter()},!dR&&!kl&&!hR&&Bb&&Vb?(Pl=!0,Rl=Vb.createTextNode(""),new Bb(ua).observe(Rl,{characterData:!0}),er=function(){Rl.data=Pl=!Pl}):!pR&&bn&&bn.resolve?(gn=bn.resolve(void 0),gn.constructor=bn,Ob=Cb(gn.then,gn),er=function(){Ob(ua)}):kl?er=function(){_b.nextTick(ua)}:(Al=Cb(Al,tr),er=function(){Al(ua)}),$l=function(a){oa.head||er(),oa.add(a)});var oa,ua;Fb.exports=$l});var Ub=b((WO,qb)=>{"use strict";qb.exports=function(a,e){try{arguments.length===1?console.error(a):console.error(a,e)}catch{}}});var vn=b((QO,jb)=>{"use strict";jb.exports=function(a){try{return{error:!1,value:a()}}catch(e){return{error:!0,value:e}}}});var vi=b((GO,Hb)=>{"use strict";var fR=ie();Hb.exports=fR.Promise});var ir=b((zO,zb)=>{"use strict";var mR=ie(),la=vi(),bR=re(),gR=Au(),vR=dl(),SR=ve(),Wb=ll(),yR=rt(),Ll=hu(),Qb=la&&la.prototype,TR=SR("species"),Ml=!1,Gb=bR(mR.PromiseRejectionEvent),IR=gR("Promise",function(){var a=vR(la),e=a!==String(la);if(!e&&Ll===66||yR&&!(Qb.catch&&Qb.finally))return!0;if(!Ll||Ll<51||!/native code/.test(a)){var t=new la(function(s){s(1)}),i=function(s){s(function(){},function(){})},r=t.constructor={};if(r[TR]=i,Ml=t.then(function(){})instanceof i,!Ml)return!0}return!e&&(Wb==="BROWSER"||Wb==="DENO")&&!Gb});zb.exports={CONSTRUCTOR:IR,REJECTION_EVENT:Gb,SUBCLASSING:Ml}});var rr=b((YO,Kb)=>{"use strict";var Yb=ft(),ER=TypeError,xR=function(a){var e,t;this.promise=new a(function(i,r){if(e!==void 0||t!==void 0)throw new ER("Bad Promise constructor");e=i,t=r}),this.resolve=Yb(e),this.reject=Yb(t)};Kb.exports.f=function(a){return new xR(a)}});var bg=b(()=>{"use strict";var wR=se(),AR=rt(),In=mn(),jt=ie(),kR=ci(),or=Ne(),Xb=Zi(),Jb=rl(),PR=ea(),RR=Jm(),$R=ft(),Tn=re(),LR=Me(),MR=eb(),DR=fl(),rg=xl().set,_l=Nb(),CR=Ub(),BR=vn(),VR=wl(),ag=Hu(),En=vi(),Ol=ir(),sg=rr(),xn="Promise",ng=Ol.CONSTRUCTOR,_R=Ol.REJECTION_EVENT,OR=Ol.SUBCLASSING,Dl=ag.getterFor(xn),FR=ag.set,ar=En&&En.prototype,Si=En,Sn=ar,og=jt.TypeError,Cl=jt.document,Fl=jt.process,Bl=sg.f,NR=Bl,qR=!!(Cl&&Cl.createEvent&&jt.dispatchEvent),ug="unhandledrejection",UR="rejectionhandled",Zb=0,lg=1,jR=2,Nl=1,cg=2,yn,eg,dg,tg,pg=function(a){var e;return LR(a)&&Tn(e=a.then)?e:!1},hg=function(a,e){var t=e.value,i=e.state===lg,r=i?a.ok:a.fail,s=a.resolve,n=a.reject,u=a.domain,o,l,p;try{r?(i||(e.rejection===cg&&WR(e),e.rejection=Nl),r===!0?o=t:(u&&u.enter(),o=r(t),u&&(u.exit(),p=!0)),o===a.promise?n(new og("Promise-chain cycle")):(l=pg(o))?or(l,o,s,n):s(o)):n(t)}catch(c){u&&!p&&u.exit(),n(c)}},fg=function(a,e){a.notified||(a.notified=!0,_l(function(){for(var t=a.reactions,i;i=t.get();)hg(i,a);a.notified=!1,e&&!a.rejection&&HR(a)}))},mg=function(a,e,t){var i,r;qR?(i=Cl.createEvent("Event"),i.promise=e,i.reason=t,i.initEvent(a,!1,!0),jt.dispatchEvent(i)):i={promise:e,reason:t},!_R&&(r=jt["on"+a])?r(i):a===ug&&CR("Unhandled promise rejection",t)},HR=function(a){or(rg,jt,function(){var e=a.facade,t=a.value,i=ig(a),r;if(i&&(r=BR(function(){In?Fl.emit("unhandledRejection",t,e):mg(ug,e,t)}),a.rejection=In||ig(a)?cg:Nl,r.error))throw r.value})},ig=function(a){return a.rejection!==Nl&&!a.parent},WR=function(a){or(rg,jt,function(){var e=a.facade;In?Fl.emit("rejectionHandled",e):mg(UR,e,a.value)})},sr=function(a,e,t){return function(i){a(e,i,t)}},nr=function(a,e,t){a.done||(a.done=!0,t&&(a=t),a.value=e,a.state=jR,fg(a,!0))},Vl=function(a,e,t){if(!a.done){a.done=!0,t&&(a=t);try{if(a.facade===e)throw new og("Promise can't be resolved itself");var i=pg(e);i?_l(function(){var r={done:!1};try{or(i,e,sr(Vl,r,a),sr(nr,r,a))}catch(s){nr(r,s,a)}}):(a.value=e,a.state=lg,fg(a,!1))}catch(r){nr({done:!1},r,a)}}};if(ng&&(Si=function(e){MR(this,Sn),$R(e),or(yn,this);var t=Dl(this);try{e(sr(Vl,t),sr(nr,t))}catch(i){nr(t,i)}},Sn=Si.prototype,yn=function(e){FR(this,{type:xn,done:!1,notified:!1,parent:!1,reactions:new VR,rejection:!1,state:Zb,value:null})},yn.prototype=Xb(Sn,"then",function(e,t){var i=Dl(this),r=Bl(DR(this,Si));return i.parent=!0,r.ok=Tn(e)?e:!0,r.fail=Tn(t)&&t,r.domain=In?Fl.domain:void 0,i.state===Zb?i.reactions.add(r):_l(function(){hg(r,i)}),r.promise}),eg=function(){var a=new yn,e=Dl(a);this.promise=a,this.resolve=sr(Vl,e),this.reject=sr(nr,e)},sg.f=Bl=function(a){return a===Si||a===dg?new eg(a):NR(a)},!AR&&Tn(En)&&ar!==Object.prototype)){tg=ar.then,OR||Xb(ar,"then",function(e,t){var i=this;return new Si(function(r,s){or(tg,i,r,s)}).then(e,t)},{unsafe:!0});try{delete ar.constructor}catch{}Jb&&Jb(ar,Sn)}wR({global:!0,constructor:!0,wrap:!0,forced:ng},{Promise:Si});dg=kR.Promise;PR(Si,xn,!1,!0);RR(xn)});var Tg=b((JO,yg)=>{"use strict";var QR=ve(),vg=QR("iterator"),Sg=!1;try{gg=0,ql={next:function(){return{done:!!gg++}},return:function(){Sg=!0}},ql[vg]=function(){return this},Array.from(ql,function(){throw 2})}catch{}var gg,ql;yg.exports=function(a,e){try{if(!e&&!Sg)return!1}catch{return!1}var t=!1;try{var i={};i[vg]=function(){return{next:function(){return{done:t=!0}}}},a(i)}catch{}return t}});var Ul=b((ZO,Ig)=>{"use strict";var GR=vi(),zR=Tg(),YR=ir().CONSTRUCTOR;Ig.exports=YR||!zR(function(a){GR.all(a).then(void 0,function(){})})});var Eg=b(()=>{"use strict";var KR=se(),XR=Ne(),JR=ft(),ZR=rr(),e$=vn(),t$=pn(),i$=Ul();KR({target:"Promise",stat:!0,forced:i$},{all:function(e){var t=this,i=ZR.f(t),r=i.resolve,s=i.reject,n=e$(function(){var u=JR(t.resolve),o=[],l=0,p=1;t$(e,function(c){var d=l++,h=!1;p++,XR(u,t,c).then(function(f){h||(h=!0,o[d]=f,--p||r(o))},s)}),--p||r(o)});return n.error&&s(n.value),i.promise}})});var wg=b(()=>{"use strict";var r$=se(),a$=rt(),s$=ir().CONSTRUCTOR,Hl=vi(),n$=wt(),o$=re(),u$=Zi(),xg=Hl&&Hl.prototype;r$({target:"Promise",proto:!0,forced:s$,real:!0},{catch:function(a){return this.then(void 0,a)}});!a$&&o$(Hl)&&(jl=n$("Promise").prototype.catch,xg.catch!==jl&&u$(xg,"catch",jl,{unsafe:!0}));var jl});var Ag=b(()=>{"use strict";var l$=se(),c$=Ne(),d$=ft(),p$=rr(),h$=vn(),f$=pn(),m$=Ul();l$({target:"Promise",stat:!0,forced:m$},{race:function(e){var t=this,i=p$.f(t),r=i.reject,s=h$(function(){var n=d$(t.resolve);f$(e,function(u){c$(n,t,u).then(i.resolve,r)})});return s.error&&r(s.value),i.promise}})});var kg=b(()=>{"use strict";var b$=se(),g$=rr(),v$=ir().CONSTRUCTOR;b$({target:"Promise",stat:!0,forced:v$},{reject:function(e){var t=g$.f(this),i=t.reject;return i(e),t.promise}})});var Wl=b((uF,Pg)=>{"use strict";var S$=mt(),y$=Me(),T$=rr();Pg.exports=function(a,e){if(S$(a),y$(e)&&e.constructor===a)return e;var t=T$.f(a),i=t.resolve;return i(e),t.promise}});var Lg=b(()=>{"use strict";var I$=se(),E$=wt(),Rg=rt(),x$=vi(),$g=ir().CONSTRUCTOR,w$=Wl(),A$=E$("Promise"),k$=Rg&&!$g;I$({target:"Promise",stat:!0,forced:Rg||$g},{resolve:function(e){return w$(k$&&this===A$?x$:this,e)}})});var Mg=b(()=>{"use strict";bg();Eg();wg();Ag();kg();Lg()});var Vg=b(()=>{"use strict";var P$=se(),R$=rt(),wn=vi(),$$=de(),Cg=wt(),Bg=re(),L$=fl(),Dg=Wl(),M$=Zi(),Gl=wn&&wn.prototype,D$=!!wn&&$$(function(){Gl.finally.call({then:function(){}},function(){})});P$({target:"Promise",proto:!0,real:!0,forced:D$},{finally:function(a){var e=L$(this,Cg("Promise")),t=Bg(a);return this.then(t?function(i){return Dg(e,a()).then(function(){return i})}:a,t?function(i){return Dg(e,a()).then(function(){throw i})}:a)}});!R$&&Bg(wn)&&(Ql=Cg("Promise").prototype.finally,Gl.finally!==Ql&&M$(Gl,"finally",Ql,{unsafe:!0}));var Ql});var Og=b((mF,_g)=>{"use strict";Wm();Mg();Vg();var C$=Ut();_g.exports=C$("Promise","finally")});var Ng=b((bF,Fg)=>{"use strict";var B$=Og();Fg.exports=B$});var An=b((gF,qg)=>{"use strict";var V$=Ng();qg.exports=V$});var gv=b(()=>{"use strict";var vL=se(),SL=Qi(),yL=Ji(),TL=Kr(),IL=Xr();vL({target:"Array",proto:!0},{at:function(e){var t=SL(this),i=yL(t),r=TL(e),s=r>=0?r:i+r;return s<0||s>=i?void 0:t[s]}});IL("at")});var Sv=b((uq,vv)=>{"use strict";gv();var EL=Ut();vv.exports=EL("Array","at")});var Tv=b((lq,yv)=>{"use strict";var xL=Sv();yv.exports=xL});var nt=b((cq,Iv)=>{"use strict";var wL=Tv();Iv.exports=wL});var gc=b((t1,aS)=>{"use strict";var sM=ui();aS.exports=Array.isArray||function(e){return sM(e)==="Array"}});var nS=b((i1,sS)=>{"use strict";var nM=TypeError,oM=9007199254740991;sS.exports=function(a){if(a>oM)throw nM("Maximum allowed index exceeded");return a}});var lS=b((r1,uS)=>{"use strict";var uM=gc(),lM=Ji(),cM=nS(),dM=zi(),oS=function(a,e,t,i,r,s,n,u){for(var o=r,l=0,p=n?dM(n,u):!1,c,d;l<i;)l in t&&(c=p?p(t[l],l,e):t[l],s>0&&uM(c)?(d=lM(c),o=oS(a,e,c,d,o,s-1)-1):(cM(o+1),a[o]=c),o++),l++;return o};uS.exports=oS});var hS=b((a1,pS)=>{"use strict";var cS=gc(),pM=hl(),hM=Me(),fM=ve(),mM=fM("species"),dS=Array;pS.exports=function(a){var e;return cS(a)&&(e=a.constructor,pM(e)&&(e===dS||cS(e.prototype))?e=void 0:hM(e)&&(e=e[mM],e===null&&(e=void 0))),e===void 0?dS:e}});var mS=b((s1,fS)=>{"use strict";var bM=hS();fS.exports=function(a,e){return new(bM(a))(e===0?0:e)}});var bS=b(()=>{"use strict";var gM=se(),vM=lS(),SM=ft(),yM=Qi(),TM=Ji(),IM=mS();gM({target:"Array",proto:!0},{flatMap:function(e){var t=yM(this),i=TM(t),r;return SM(e),r=IM(t,0),r.length=vM(r,t,t,i,0,1,e,arguments.length>1?arguments[1]:void 0),r}})});var gS=b(()=>{"use strict";var EM=Xr();EM("flatMap")});var SS=b((c1,vS)=>{"use strict";bS();gS();var xM=Ut();vS.exports=xM("Array","flatMap")});var TS=b((d1,yS)=>{"use strict";var wM=SS();yS.exports=wM});var wa=b((p1,IS)=>{"use strict";var AM=TS();IS.exports=AM});var Aa=b((h1,ES)=>{"use strict";var kM=Zr(),PM=String;ES.exports=function(a){if(kM(a)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return PM(a)}});var vc=b((f1,xS)=>{"use strict";xS.exports=`
|
|
7
|
-
\v\f\r \u2028\u2029\uFEFF`});var kS=b((m1,AS)=>{"use strict";var RM=pe(),$M=qt(),LM=Aa(),yc=vc(),wS=RM("".replace),MM=RegExp("^["+yc+"]+"),DM=RegExp("(^|[^"+yc+"])["+yc+"]+$"),Sc=function(a){return function(e){var t=LM($M(e));return a&1&&(t=wS(t,MM,"")),a&2&&(t=wS(t,DM,"$1")),t}};AS.exports={start:Sc(1),end:Sc(2),trim:Sc(3)}});var LS=b((b1,$S)=>{"use strict";var CM=Gu().PROPER,BM=de(),PS=vc(),RS="
";$S.exports=function(a){return BM(function(){return!!PS[a]()||RS[a]()!==RS||CM&&PS[a].name!==a})}});var Tc=b((g1,MS)=>{"use strict";var VM=kS().start,_M=LS();MS.exports=_M("trimStart")?function(){return VM(this)}:"".trimStart});var CS=b(()=>{"use strict";var OM=se(),DS=Tc();OM({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==DS},{trimLeft:DS})});var VS=b(()=>{"use strict";CS();var FM=se(),BS=Tc();FM({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==BS},{trimStart:BS})});var OS=b((I1,_S)=>{"use strict";VS();var NM=Ut();_S.exports=NM("String","trimLeft")});var NS=b((E1,FS)=>{"use strict";var qM=OS();FS.exports=qM});var US=b((x1,qS)=>{"use strict";var UM=NS();qS.exports=UM});var ay=b(()=>{"use strict"});var sy=b(()=>{"use strict"});var oy=b((cW,ny)=>{"use strict";var pD=Me(),hD=ui(),fD=ve(),mD=fD("match");ny.exports=function(a){var e;return pD(a)&&((e=a[mD])!==void 0?!!e:hD(a)==="RegExp")}});var cy=b((dW,ly)=>{"use strict";var bD=ie(),gD=de(),uy=bD.RegExp,vD=!gD(function(){var a=!0;try{uy(".","d")}catch{a=!1}var e={},t="",i=a?"dgimsy":"gimsy",r=function(o,l){Object.defineProperty(e,o,{get:function(){return t+=l,!0}})},s={dotAll:"s",global:"g",ignoreCase:"i",multiline:"m",sticky:"y"};a&&(s.hasIndices="d");for(var n in s)r(n,s[n]);var u=Object.getOwnPropertyDescriptor(uy.prototype,"flags").get.call(e);return u!==i||t!==i});ly.exports={correct:vD}});var py=b((pW,dy)=>{"use strict";var SD=mt();dy.exports=function(){var a=SD(this),e="";return a.hasIndices&&(e+="d"),a.global&&(e+="g"),a.ignoreCase&&(e+="i"),a.multiline&&(e+="m"),a.dotAll&&(e+="s"),a.unicode&&(e+="u"),a.unicodeSets&&(e+="v"),a.sticky&&(e+="y"),e}});var my=b((hW,fy)=>{"use strict";var yD=Ne(),TD=at(),ID=Hr(),hy=cy(),ED=py(),xD=RegExp.prototype;fy.exports=hy.correct?function(a){return a.flags}:function(a){return!hy.correct&&ID(xD,a)&&!TD(a,"flags")?yD(ED,a):a.flags}});var gy=b((fW,by)=>{"use strict";var Ac=pe(),wD=Qi(),AD=Math.floor,xc=Ac("".charAt),kD=Ac("".replace),wc=Ac("".slice),PD=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,RD=/\$([$&'`]|\d{1,2})/g;by.exports=function(a,e,t,i,r,s){var n=t+a.length,u=i.length,o=RD;return r!==void 0&&(r=wD(r),o=PD),kD(s,o,function(l,p){var c;switch(xc(p,0)){case"$":return"$";case"&":return a;case"`":return wc(e,0,t);case"'":return wc(e,n);case"<":c=r[wc(p,1,-1)];break;default:var d=+p;if(d===0)return l;if(d>u){var h=AD(d/10);return h===0?l:h<=u?i[h-1]===void 0?xc(p,1):i[h-1]+xc(p,1):l}c=i[d-1]}return c===void 0?"":c})}});var yy=b(()=>{"use strict";var $D=se(),LD=Ne(),Pc=pe(),vy=qt(),MD=re(),DD=Me(),CD=oy(),Sr=Aa(),BD=Qr(),VD=my(),_D=gy(),OD=ve(),FD=rt(),ND=OD("replace"),qD=TypeError,kc=Pc("".indexOf),UD=Pc("".replace),Sy=Pc("".slice),jD=Math.max;$D({target:"String",proto:!0},{replaceAll:function(e,t){var i=vy(this),r,s,n,u,o,l,p,c,d,h,f=0,m="";if(DD(e)){if(r=CD(e),r&&(s=Sr(vy(VD(e))),!~kc(s,"g")))throw new qD("`.replaceAll` does not allow non-global regexes");if(n=BD(e,ND),n)return LD(n,e,i,t);if(FD&&r)return UD(Sr(i),e,t)}for(u=Sr(i),o=Sr(e),l=MD(t),l||(t=Sr(t)),p=o.length,c=jD(1,p),d=kc(u,o);d!==-1;)h=l?Sr(t(o,d,u)):_D(o,u,d,[],void 0,t),m+=Sy(u,f,d)+h,f=d+p,d=d+c>u.length?-1:kc(u,o,d+c);return f<u.length&&(m+=Sy(u,f)),m}})});var Iy=b((gW,Ty)=>{"use strict";ay();sy();yy();var HD=Ut();Ty.exports=HD("String","replaceAll")});var xy=b((vW,Ey)=>{"use strict";var WD=Iy();Ey.exports=WD});var Ay=b((SW,wy)=>{"use strict";var QD=xy();wy.exports=QD});var Py=b((yW,ky)=>{"use strict";var GD=Kr(),zD=Aa(),YD=qt(),KD=RangeError;ky.exports=function(e){var t=zD(YD(this)),i="",r=GD(e);if(r<0||r===1/0)throw new KD("Wrong number of repetitions");for(;r>0;(r>>>=1)&&(t+=t))r&1&&(i+=t);return i}});var Dy=b((TW,My)=>{"use strict";var Ly=pe(),XD=Du(),Ry=Aa(),JD=Py(),ZD=qt(),eC=Ly(JD),tC=Ly("".slice),iC=Math.ceil,$y=function(a){return function(e,t,i){var r=Ry(ZD(e)),s=XD(t),n=r.length,u=i===void 0?" ":Ry(i),o,l;return s<=n||u===""?r:(o=s-n,l=eC(u,iC(o/u.length)),l.length>o&&(l=tC(l,0,o)),a?r+l:l+r)}};My.exports={start:$y(!1),end:$y(!0)}});var By=b((IW,Cy)=>{"use strict";var rC=di();Cy.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(rC)});var Vy=b(()=>{"use strict";var aC=se(),sC=Dy().start,nC=By();aC({target:"String",proto:!0,forced:nC},{padStart:function(e){return sC(this,e,arguments.length>1?arguments[1]:void 0)}})});var Oy=b((wW,_y)=>{"use strict";Vy();var oC=Ut();_y.exports=oC("String","padStart")});var Ny=b((AW,Fy)=>{"use strict";var uC=Oy();Fy.exports=uC});var Uy=b((kW,qy)=>{"use strict";var lC=Ny();qy.exports=lC});var Ud="2.0.148-dev.f4244a7e.0";var Le=(r=>(r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused",r))(Le||{}),xt=(y=>(y.MPEG="MPEG",y.DASH="DASH",y.DASH_SEP="DASH_SEP",y.DASH_SEP_VK="DASH_SEP",y.DASH_WEBM="DASH_WEBM",y.DASH_WEBM_AV1="DASH_WEBM_AV1",y.DASH_STREAMS="DASH_STREAMS",y.DASH_WEBM_VK="DASH_WEBM",y.DASH_ONDEMAND="DASH_ONDEMAND",y.DASH_ONDEMAND_VK="DASH_ONDEMAND",y.DASH_LIVE="DASH_LIVE",y.DASH_LIVE_CMAF="DASH_LIVE_CMAF",y.DASH_LIVE_WEBM="DASH_LIVE_WEBM",y.HLS="HLS",y.HLS_ONDEMAND="HLS_ONDEMAND",y.HLS_JS="HLS",y.HLS_FMP4="HLS_FMP4",y.HLS_LIVE="HLS_LIVE",y.HLS_LIVE_CMAF="HLS_LIVE_CMAF",y.WEB_RTC_LIVE="WEB_RTC_LIVE",y))(xt||{});var Hs=(r=>(r.NOT_AVAILABLE="NOT_AVAILABLE",r.AVAILABLE="AVAILABLE",r.CONNECTING="CONNECTING",r.CONNECTED="CONNECTED",r))(Hs||{}),tu=(i=>(i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic",i))(tu||{});var iu=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(iu||{}),Ws=(i=>(i.TRAFFIC_SAVING="traffic_saving",i.HIGH_QUALITY="high_quality",i.UNKNOWN="unknown",i))(Ws||{});var Fd=C(hi(),1),NI=C(xe(),1);import{assertNever as cf,assertNonNullable as Ww,isNonNullable as Zs,ValueSubject as Fu,Subject as Qw,Subscription as Gw,merge as zw,observableFrom as Yw,fromEvent as nf,map as of,tap as uf,filterChanged as Kw,isNullable as Nu,ErrorCategory as lf}from"@vkontakte/videoplayer-shared/es2024";var sf=a=>new Promise((e,t)=>{let i=document.createElement("script");i.setAttribute("src",a),i.onload=()=>e(),i.onerror=r=>t(r),document.body.appendChild(i)});var en=class{constructor(e){this.connection$=new Fu(void 0);this.castState$=new Fu("NOT_AVAILABLE");this.errorEvent$=new Qw;this.realCastState$=new Fu("NOT_AVAILABLE");this.subscription=new Gw;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=Zs(window.chrome?.cast),r=!!window.__onGCastApiAvailable;i?this.initializeCastApi():(window.__onGCastApiAvailable=s=>{delete window.__onGCastApiAvailable,s&&!this.isDestroyed&&this.initializeCastApi()},r||sf("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:lf.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(){Zs(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();Nu(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();Nu(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(nf(i,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(r=>{switch(r.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=i.getCurrentSession()?.getMediaSession()?.media?.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return cf(r.sessionState)}})).add(zw(nf(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(uf(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),of(r=>r.castState)),Yw([i.getCastState()])).pipe(Kw(),of(Xw),uf(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{let s=r==="CONNECTED",n=Zs(this.connection$.getValue());if(s&&!n){let u=i.getCurrentSession();Ww(u);let o=u.getCastDevice(),l=u.getMediaSession()?.media?.contentId;(Nu(l)||l===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:u,castDevice:o}))}else!s&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(r==="CONNECTED"?Zs(this.connection$.getValue())?"CONNECTED":"AVAILABLE":r)}))}initializeCastApi(){let e,t,i;try{e=cast.framework.CastContext.getInstance(),t=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,i=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch{return}try{e.setOptions({receiverApplicationId:this.params.receiverApplicationId??t,autoJoinPolicy:i}),this.initListeners()}catch(r){this.errorEvent$.next({id:"ChromecastInitializer",category:lf.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:r})}}},Xw=a=>{switch(a){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return"NOT_AVAILABLE";case cast.framework.CastState.NOT_CONNECTED:return"AVAILABLE";case cast.framework.CastState.CONNECTING:return"CONNECTING";case cast.framework.CastState.CONNECTED:return"CONNECTED";default:return cf(a)}};var $d=C(xe(),1),vI=C(fi(),1),SI=C(ul(),1);var av=C(An(),1);import{assertNever as Ug}from"@vkontakte/videoplayer-shared/es2024";var ae=(a,e=0,t=0)=>{switch(t){case 0:return a.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case 1:{if(e===0)return a;let i=new URL(a);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}case 2:{let i=new URL(a);return!i.searchParams.get("offset_p")&&e===0?a:(i.searchParams.set("offset_p",e.toFixed(0)),i.toString())}default:Ug(t)}return a},Ht=(a,e)=>{switch(e){case 0:return NaN;case 1:{let t=new URL(a);return Number(t.searchParams.get("playback_shift"))}case 2:{let t=new URL(a);return Number(t.searchParams.get("offset_p")??0)}default:Ug(e)}};var k=(a,e,t=!1)=>{let i=a.getTransition();(t||!i||i.to===e)&&a.setState(e)};import{isNonNullable as _$,Subject as kn,merge as jg}from"@vkontakte/videoplayer-shared/es2024";var O=class{constructor(e){this.transitionStarted$=new kn;this.transitionEnded$=new kn;this.transitionUpdated$=new kn;this.forceChanged$=new kn;this.stateChangeStarted$=jg(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=jg(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||_$(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 Xg}from"@vkontakte/videoplayer-shared/es2024";var Hg=C(xe(),1);var Pn=class{constructor(){this._isMiuiBrowser=!1}get current(){return this._current}get isChrome(){return this.current==="Chrome"}get isChromiumBased(){return(0,Hg.default)(["Chrome","Chromium","Opera","Yandex","Edge","SamsungBrowser"],this.current)}get isFirefox(){return this.current==="Firefox"}get isSafari(){return this.current==="Safari"}get isOpera(){return this.current==="Opera"}get isEdge(){return this.current==="Edge"}get isYandex(){return this.current==="Yandex"}get isSamsungBrowser(){return this.current==="SamsungBrowser"}get currentVersion(){return this._current_version}get chromeVersion(){return this._chromeVersion}get firefoxVersion(){return this._firefoxVersion}get safariVersion(){return this._safariVersion}get operaVersion(){return this._operaVersion}get edgeVersion(){return this._edgeVersion}get yandexVersion(){return this._yandexVersion}get isMiuiBrowser(){return this._isMiuiBrowser}detect(){let{userAgent:e}=navigator;try{let t=/yabrowser/i.test(e)?"Yandex":void 0,i=/samsungbrowser/i.test(e)?"SamsungBrowser":void 0,r=/chrome|crios/i.test(e)?"Chrome":void 0,s=/chromium/i.test(e)?"Chromium":void 0,n=/firefox|fxios/i.test(e)?"Firefox":void 0,u=/webkit|safari|khtml/i.test(e)?"Safari":void 0,o=/opr\//i.test(e)?"Opera":void 0,l=/edg/i.test(e)?"Edge":void 0;this._isMiuiBrowser=/(XiaoMi)|(MiuiBrowser)/i.test(e),this._current=t||i||n||o||l||r||s||u||"Rest"}catch(t){console.error(t)}this.isChrome&&this.detectChromeVersion(),this.isFirefox&&this.detectFirefoxVersion(),this.isSafari&&this.detectSafariVersion(),this.isOpera&&this.detectOperaVersion(),this.isEdge&&this.detectEdgeVersion(),this.isYandex&&this.detectYandexVersion()}detectVersion(e){try{let{userAgent:t}=window.navigator,i=t.match(e);if(!i)return;let r=i[1],s=parseInt(r,10);if(!isNaN(s))return this._current_version=s,s}catch(t){console.error(t)}}detectChromeVersion(){this._chromeVersion=this.detectVersion(/Chrome\/(\d+\.\d+)/)}detectFirefoxVersion(){this._firefoxVersion=this.detectVersion(/Firefox\/(\d+\.\d+)/)}detectSafariVersion(){this._safariVersion=this.detectVersion(/Version\/(\d+)/)}detectOperaVersion(){this._operaVersion=this.detectVersion(/OPR\/(\d+\.\d+)/)}detectEdgeVersion(){this._edgeVersion=this.detectVersion(/Edg\/(\d+\.\d+)/)}detectYandexVersion(){this._yandexVersion=this.detectVersion(/YaBrowser\/(\d+\.\d+\.\d+)/)}};var Wg=C(xe(),1);var ca=()=>/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test(navigator.appVersion??navigator.userAgent)||navigator?.userAgentData?.mobile;var Rn=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,Wg.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=ca()}catch(t){console.error(t)}this.detectDevice(e),this.detectHighEntropyValues(),this.isIOS&&this.detectIOSVersion()}async detectHighEntropyValues(){let{userAgentData:e}=navigator;if(e?.getHighEntropyValues){let t=await e.getHighEntropyValues(["architecture","bitness","brands","mobile","platform","formFactor","model","platformVersion","wow64"]);this._highEntropyValues=t}}detectDevice(e){try{let t=/android/i.test(e)?"Android":void 0,i=/iphone/i.test(e)?"iPhone":void 0,r=/ipad/i.test(e)?"iPad":void 0,s=/ipod/i.test(e)?"iPod":void 0,n=/mac/i.test(e)?"Mac":void 0,u=/webOS|BlackBerry|IEMobile|Opera Mini/i.test(e)?"RestMobile":void 0;this._current=t||i||r||s||u||n||"Desktop"}catch(t){console.error(t)}}detectIOSVersion(){try{if(this._highEntropyValues.platformVersion){let s=this._highEntropyValues.platformVersion.split(".").slice(0,2).join("."),n=parseFloat(s);this._iosVersion=n;return}let{userAgent:e}=window.navigator,t=e.match(/OS (\d+(_\d+)?)/i);if(!t)return;let i=t[1].replace(/_/g,".");if(!i)return;let r=parseFloat(i);if(isNaN(r))return;this._iosVersion=r}catch(e){console.error(e)}}};var $n=class{get isTouch(){return typeof this._maxTouchPoints=="number"?this._maxTouchPoints>1:"ontouchstart"in window}get maxTouchPoints(){return this._maxTouchPoints}get height(){return this._height}get width(){return this._width}get screenHeight(){return this._screenHeight}get screenWidth(){return this._screenWidth}get pixelRatio(){return this._pixelRatio}get isHDR(){return this._isHdr}get colorDepth(){return this._colorDepth}detect(){let{maxTouchPoints:e}=navigator;try{this._maxTouchPoints=e??0,this._isHdr=!!matchMedia("(dynamic-range: high)")?.matches,this._colorDepth=screen.colorDepth}catch(t){console.error(t)}try{this._pixelRatio=window.devicePixelRatio||1,this._height=screen.height,this._width=screen.width,this._height=screen.height,this._screenHeight=this._height*this._pixelRatio,this._screenWidth=this._width*this._pixelRatio}catch(t){console.error(t)}}};var Ue=()=>window.ManagedMediaSource||window.MediaSource,ur=()=>!!(window.ManagedMediaSource&&window.ManagedSourceBuffer?.prototype?.appendBuffer),Qg=()=>!!(window.MediaSource&&window.SourceBuffer?.prototype?.appendBuffer),Ln=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var O$=document.createElement("video"),F$='video/mp4; codecs="avc1.42000a,mp4a.40.2"',N$='video/mp4; codecs="hev1.1.6.L93.B0"',Gg='video/webm; codecs="vp09.00.10.08"',zg='video/webm; codecs="av01.0.00M.08"',q$='audio/mp4; codecs="mp4a.40.2"',U$='audio/webm; codecs="opus"',Yg,j$=async()=>{if(!window.navigator.mediaCapabilities)return;let a={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=await Promise.all([window.navigator.mediaCapabilities.decodingInfo({...a,video:{...a.video,contentType:zg}}),window.navigator.mediaCapabilities.decodingInfo({...a,video:{...a.video,contentType:Gg}})]);Yg={DASH_WEBM_AV1:e,DASH_WEBM:t}};j$().catch(a=>{console.log(O$),console.error(a)});var Mn=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 Yg}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:ur(),mse:Qg(),hls:!!(this._video.canPlayType?.("application/x-mpegurl")||this._video.canPlayType?.("vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},this._containers={mp4:!!this._video.canPlayType?.("video/mp4"),webm:!!this._video.canPlayType?.("video/webm"),cmaf:!0};let e=!!Ue()?.isTypeSupported?.(F$),t=!!Ue()?.isTypeSupported?.(N$),i=!!Ue()?.isTypeSupported?.(q$);this._codecs={h264:e,h265:t,vp9:!!Ue()?.isTypeSupported?.(Gg),av1:!!Ue()?.isTypeSupported?.(zg),aac:i,opus:!!Ue()?.isTypeSupported?.(U$),mpeg:(e||t)&&i},this._nativeHlsSupported=this._protocols.hls&&this._containers.mp4}catch(e){console.error(e)}try{this.destroyVideoElement()}catch(e){console.error("Error destroying video element:",e)}}destroyVideoElement(){if(!this._video)return;if(this._video.pause(),this._video.currentTime=0,this._video.removeAttribute("src"),this._video.src="",this._video.load(),this._video.remove){this._video.remove(),this._video=null;return}this._video.parentNode&&this._video.parentNode.removeChild(this._video);let e=this._video.cloneNode(!1);this._video.parentNode?.replaceChild(e,this._video),this._video=null}};var Kg="audio/mpeg",Dn=class{supportMp3(){return this._codecs.mp3&&this._containers.mpeg}detect(){this._audio=document.createElement("audio");try{this._containers={mpeg:!!this._audio.canPlayType?.(Kg)},this._codecs={mp3:!!Ue()?.isTypeSupported?.(Kg)}}catch(e){console.error(e)}try{this.destroyAudioElement()}catch(e){console.error("Error destroying audio element:",e)}}destroyAudioElement(){if(!this._audio)return;if(this._audio.pause(),this._audio.currentTime=0,this._audio.removeAttribute("src"),this._audio.src="",this._audio.load(),this._audio.remove){this._audio.remove(),this._audio=null;return}this._audio.parentNode&&this._audio.parentNode.removeChild(this._audio);let e=this._audio.cloneNode(!1);this._audio.parentNode?.replaceChild(e,this._audio),this._audio=null}};import{ValueSubject as H$}from"@vkontakte/videoplayer-shared/es2024";var zl=class{constructor(){this.isInited$=new H$(!1);this._displayChecker=new $n,this._deviceChecker=new Rn(this._displayChecker),this._browserChecker=new Pn,this._videoChecker=new Mn(this._deviceChecker,this._browserChecker),this._audioChecker=new Dn,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)}},D=new zl;var Yl=a=>{let{containers:e,protocols:t,codecs:i,nativeHlsSupported:r}=D.video,s=(i.h264||i.h265)&&i.aac,n=t.mse||t.mms;return a.filter(u=>{switch(u){case"DASH_SEP":return n&&e.mp4&&s;case"DASH_WEBM":return n&&e.webm&&i.vp9&&i.opus;case"DASH_WEBM_AV1":return n&&e.webm&&i.av1&&i.opus;case"DASH_STREAMS":return n&&(e.mp4&&s||e.webm&&(i.vp9||i.av1)&&(i.opus||i.aac));case"DASH_LIVE":return n&&e.mp4&&s;case"DASH_LIVE_CMAF":return n&&e.mp4&&s&&e.cmaf;case"DASH_ONDEMAND":return n&&e.mp4&&s;case"HLS":case"HLS_ONDEMAND":case"HLS_FMP4":case"HLS_LIVE":case"HLS_LIVE_CMAF":return r;case"MPEG":return e.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return t.webrtc&&t.ws&&i.h264&&(e.mp4||e.webm);default:return Xg(u)}})},Kl=a=>{switch(a){case"MPEG":case"DASH":case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":case"HLS":case"HLS_FMP4":case"HLS_ONDEMAND":return!1;case"DASH_LIVE":case"DASH_LIVE_CMAF":case"HLS_LIVE":case"HLS_LIVE_CMAF":case"DASH_LIVE_WEBM":case"WEB_RTC_LIVE":return!0;default:return Xg(a)}},W$=a=>{let t=Object.keys(a).filter(i=>!Kl(i));return Yl(t).length>0};import{assertNever as lr,assertNonNullable as yi,debounce as Jg,ErrorCategory as Zg,fromEvent as Ti,isNonNullable as ev,map as tv,merge as iv,observableFrom as Q$,Subject as G$,Subscription as Xl,timeout as z$,getHighestQuality as Y$}from"@vkontakte/videoplayer-shared/es2024";var K$=5,X$=5,J$=500,rv=7e3,da=class{constructor(e){this.subscription=new Xl;this.loadMediaTimeoutSubscription=new Xl;this.videoState=new O("stopped");this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(s)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.stop());return}if(!t){if(r?.to!=="paused"&&s.state==="requested"&&e!=="stopped"){this.seek(s.position/1e3);return}switch(i){case"ready":{switch(e){case"playing":case"paused":case"ready":break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:lr(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:lr(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:lr(e)}break}default:lr(i)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(Kl(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 Xl;this.subscription.add(e),this.subscription.add(iv(this.videoState.stateChangeStarted$.pipe(tv(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe(tv(r=>`stateChangeEnded$ ${JSON.stringify(r)}`))).subscribe(r=>this.log({message:`[videoState] ${r}`})));let t=(r,s)=>this.subscription.add(r.subscribe(s));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{let r=new G$;e.add(r.pipe(Jg(J$)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add(Ti(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(n=>{this.logRemoteEvent(n);let u=n.value;this.params.output.position$.next(u),(this.params.desiredState.seekState.getState().state==="applying"||Math.abs(u-s)>K$)&&r.next(u),s=u})),e.add(Ti(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(Ti(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(Ti(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t(Ti(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),r=>{this.logRemoteEvent(r);let{remotePlayer:s}=this.params.connection,n=r.value,u=this.params.output.isBuffering$.getValue(),o=n===chrome.cast.media.PlayerState.BUFFERING;switch(u!==o&&this.params.output.isBuffering$.next(o),n){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&s.duration-s.currentTime<X$&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),k(this.params.desiredState.playbackState,"stopped");break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:lr(n)}}),t(Ti(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t(Ti(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});let i=iv(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Q$(["init"])).pipe(Jg(0));t(i,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});let{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),k(this.params.desiredState.playbackState,"playing"));let i=this.params.output.isLive$.getValue();this.params.output.duration$.next(i?0:t.duration),this.params.output.position$.next(i?0:t.currentTime),this.params.desiredState.seekState.setState({state:"none"})}}prepare(){let e=this.params.format;this.log({message:`[prepare] format: ${e}`});let t=this.createMediaInfo(e),i=this.createLoadRequest(t);this.loadMedia(i)}handleRemotePause(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="paused"||e==="playing")&&(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="playing"||e==="paused")&&(this.videoState.setState("playing"),k(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.params.desiredState.playbackState.getTransition()?.to==="ready"&&k(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){let t=this.params.output.volume$.getValue(),i={volume:e.volume??t.volume,muted:e.muted??t.muted};(i.volume!==t.volume||i.muted!==i.muted)&&this.params.output.volume$.next(i)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:i}=this.params.connection;t.currentTime=e,i.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){let t=this.params.source,i,r,s;switch(e){case"MPEG":{let l=t[e];yi(l);let p=Y$(Object.keys(l));yi(p);let c=l[p];yi(c),i=c,r="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_FMP4":case"HLS_ONDEMAND":{let l=t[e];yi(l),i=l.url,r="application/x-mpegurl",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":{let l=t[e];yi(l),i=l.url,r="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let l=t[e];yi(l),i=l.url,r="application/dash+xml",s=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let l=t[e];yi(l),i=ae(l.url),r="application/x-mpegurl",s=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let l="Unsupported format for Chromecast",p=new Error(l);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:Zg.VIDEO_PIPELINE,message:l,thrown:p}),p}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return lr(e)}let n=new chrome.cast.media.MediaInfo(this.params.meta.videoId??i,r);n.contentUrl=i,n.streamType=s,n.metadata=new chrome.cast.media.GenericMediaMetadata;let{title:u,subtitle:o}=this.params.meta;return ev(u)&&(n.metadata.title=u),ev(o)&&(n.metadata.subtitle=o),n}createLoadRequest(e){let t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;let i=this.params.desiredState.seekState.getState();return i.state==="applying"||i.state==="requested"?t.currentTime=this.params.output.isLive$.getValue()?0:i.position/1e3:t.currentTime=0,t}loadMedia(e){let t=this.params.connection.session.loadMedia(e),i=new Promise((r,s)=>{this.loadMediaTimeoutSubscription.add(z$(rv).subscribe(()=>s(`timeout(${rv})`)))});(0,av.default)(Promise.race([t,i]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},r=>{let s=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${r}`;this.log({message:s}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:Zg.VIDEO_PIPELINE,message:s,thrown:r})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var mc=C(xe(),1);import{clearVideoElement as nv}from"@vkontakte/videoplayer-shared/es2024";import{clearVideoElement as Z$}from"@vkontakte/videoplayer-shared/es2024";var sv=a=>{try{a.pause(),a.playbackRate=0,Z$(a),a.remove()}catch(e){console.error(e)}};import{fromEvent as eL,Subscription as tL}from"@vkontakte/videoplayer-shared/es2024";var Jl=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)}},Zl=window.WeakMap?new WeakMap:new Jl,ec=window.WeakMap?new WeakMap:new Map,iL=(a,e=20)=>{let t=0;return eL(a,"ratechange").subscribe(i=>{t++,t>=e&&(a.currentTime=a.currentTime,t=0)})},De=(a,{audioVideoSyncRate:e,disableYandexPiP:t})=>{let i=a.querySelector("video"),r=!!i;i?nv(i):(i=document.createElement("video"),a.appendChild(i)),Zl.set(i,r);let s=new tL;return s.add(iL(i,e)),ec.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},Ce=a=>{ec.get(a)?.unsubscribe(),ec.delete(a);let t=Zl.get(a);Zl.delete(a),t?nv(a):sv(a)};var ic=C(hi(),1);import{assertNonNullable as ha,isNonNullable as gt,isNullable as sL,fromEvent as cr,merge as ov,observableFrom as uv,filterChanged as lv,map as fa,Subject as cv,Subscription as nL,ValueSubject as oL,ErrorCategory as uL}from"@vkontakte/videoplayer-shared/es2024";import{isNonNullable as tc,isNullable as rL,Subscription as aL}from"@vkontakte/videoplayer-shared/es2024";var Cn=(a,e,t,{equal:i=(n,u)=>n===u,changed$:r,onError:s}={})=>{let n=a.getState(),u=e(),o=rL(r),l=new aL;return r&&l.add(r.subscribe(p=>{let c=a.getState();i(p,c)&&a.setState(p)},s)),i(u,n)||(t(n),o&&a.setState(n)),l.add(a.stateChangeStarted$.subscribe(p=>{t(p.to),o&&a.setState(p.to)},s)),l},bt=(a,e,t)=>Cn(e,()=>a.loop,i=>{tc(i)&&(a.loop=i)},{onError:t}),Be=(a,e,t,i)=>Cn(e,()=>({muted:a.muted,volume:a.volume}),r=>{tc(r)&&(a.muted=r.muted,a.volume=r.volume)},{equal:(r,s)=>r===s||r?.muted===s?.muted&&r?.volume===s?.volume,changed$:t,onError:i}),ze=(a,e,t,i)=>Cn(e,()=>a.playbackRate,r=>{tc(r)&&(a.playbackRate=r)},{changed$:t,onError:i}),pa=Cn;var lL=a=>["__",a.language,a.label].join("|"),cL=(a,e)=>{if(a.id===e)return!0;let[t,i,r]=e.split("|");return a.language===i&&a.label===r},rc=class a{constructor(e){this.available$=new cv;this.current$=new oL(void 0);this.error$=new cv;this.subscription=new nL;this.externalTracks=new Map;this.internalTracks=new Map;this.baseURL=e}connect(e,t,i){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();let r=s=>{this.error$.next({id:"TextTracksManager",category:uL.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(pa(t.internalTextTracks,()=>(0,ic.default)(this.internalTracks),s=>{gt(s)&&this.setInternal(s)},{equal:(s,n)=>gt(s)&>(n)&&s.length===n.length&&s.every(({id:u},o)=>u===n[o].id),changed$:this.available$.pipe(fa(s=>s.filter(({type:n})=>n==="internal"))),onError:r})),this.subscription.add(pa(t.externalTextTracks,()=>(0,ic.default)(this.externalTracks),s=>{gt(s)&&this.setExternal(s)},{equal:(s,n)=>gt(s)&>(n)&&s.length===n.length&&s.every(({id:u},o)=>u===n[o].id),changed$:this.available$.pipe(fa(s=>s.filter(({type:n})=>n==="external"))),onError:r})),this.subscription.add(pa(t.currentTextTrack,()=>{if(this.video)return;let s=this.htmlTextTracksAsArray().find(({mode:n})=>n==="showing");return s&&this.htmlTextTrackToITextTrack(s).id},s=>this.select(s),{changed$:this.current$,onError:r})),this.subscription.add(pa(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){ha(this.video);let{textTracks:e}=this.video;this.subscription.add(cr(e,"addtrack").subscribe(()=>{let i=this.current$.getValue();i&&this.select(i)})),this.subscription.add(ov(cr(e,"addtrack"),cr(e,"removetrack"),uv(["init"])).pipe(fa(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),lv((i,r)=>i.length===r.length&&i.every(({id:s},n)=>s===r[n].id))).subscribe(this.available$)),this.subscription.add(ov(cr(e,"change"),uv(["init"])).pipe(fa(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),fa(i=>i&&this.htmlTextTrackToITextTrack(i).id),lv()).subscribe(this.current$));let t=i=>this.applyCueSettings(i.target?.activeCues??null);this.subscription.add(cr(e,"addtrack").subscribe(i=>{i.track?.addEventListener("cuechange",t);let r=s=>{let n=s.target?.cues??null;n&&n.length&&(this.applyCueSettings(s.target?.cues??null),s.target?.removeEventListener("cuechange",r))};i.track?.addEventListener("cuechange",r)})),this.subscription.add(cr(e,"removetrack").subscribe(i=>{i.track?.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;let t=this.cueSettings.getState();for(let i of Array.from(e)){let r=i;gt(t.align)&&(r.align=t.align),gt(t.position)&&(r.position=t.position),gt(t.size)&&(r.size=t.size),gt(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){ha(this.video);let t=[...this.video.textTracks];return e?t:t.filter(a.isHealthyTrack)}htmlTextTrackToITextTrack(e){let{language:t,label:i}=e,r=e.id?e.id:lL(e),s=this.externalTracks.has(r),n=(s?this.externalTracks.get(r)?.isAuto:this.internalTracks.get(r)?.isAuto)??r.includes("auto");return s?{id:r,type:"external",isAuto:n,language:t,label:i,url:this.externalTracks.get(r)?.url}:{id:r,type:"internal",isAuto:n,language:t,label:i,url:this.internalTracks.get(r)?.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(i=>i.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){let t=[...this.externalTracks];e.filter(({id:i,language:r,isAuto:s})=>!this.internalTracks.has(i)&&!t.some(([,n])=>n.language===r&&n.isAuto===s)).forEach(i=>this.attach(i)),Array.from(this.internalTracks).filter(([i])=>!e.find(r=>r.id===i)).forEach(([,i])=>this.detach(i))}select(e){ha(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(sL(e)||!cL(t,e))&&(t.mode="disabled")}destroy(){if(this.subscription.unsubscribe(),this.video)for(let e of Array.from(this.video.getElementsByTagName("track"))){let t=e.getAttribute("id");t&&this.externalTracks.has(t)&&this.video.removeChild(e)}this.externalTracks.clear()}attach(e){ha(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){ha(this.video);let t=Array.prototype.find.call(this.video.getElementsByTagName("track"),i=>i.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}},Ye=rc;var Ii=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 dv=a=>{let e=a;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e?.parentNode;return e??void 0},ac=a=>{let e=dv(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},pv=a=>{let e=dv(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)};import{fromEvent as we,map as vt,merge as Bn,filterChanged as fv,isNonNullable as mv,Subject as pL,filter as sc,mapTo as nc,combine as hL,once as fL,shareReplay as Ae,throttle as mL,ErrorCategory as bL,ValueSubject as bv,Subscription as gL}from"@vkontakte/videoplayer-shared/es2024";var dL=3,hv=(a,e,t=dL)=>{let i=0,r=0;for(let s=0;s<a.length;s++){let n=a.start(s),u=a.end(s);if(n<=e&&e<=u){if(i=n,r=u,!t)return{from:i,to:r};for(let o=s-1;o>=0;o--)a.end(o)+t>=i&&(i=a.start(o));for(let o=s+1;o<a.length;o++)a.start(o)-t<=r&&(r=a.end(o))}}return{from:i,to:r}};var Ve=a=>{let e=x=>we(a,x).pipe(nc(void 0),Ae(1)),t=new gL,i=()=>t.unsubscribe(),r=Bn(we(a,"progress"),we(a,"timeupdate")).pipe(vt(()=>hv(a.buffered,a.currentTime)),Ae(1)),s=D.browser.isSafari?hL({play:e("play").pipe(fL()),playing:e("playing")}).pipe(nc(void 0),Ae(1)):e("playing"),n=we(a,"volumechange").pipe(vt(()=>({muted:a.muted,volume:a.volume})),Ae(1)),u=we(a,"ratechange").pipe(vt(()=>a.playbackRate),Ae(1)),o=we(a,"error").pipe(sc(()=>!!(a.error||a.played.length)),vt(()=>{let x=a.error;return{id:x?`MediaError#${x.code}`:"HtmlVideoError",category:bL.VIDEO_PIPELINE,message:x?x.message:"Error event from HTML video element",thrown:a.error??void 0}}),Ae(1)),l=we(a,"timeupdate").pipe(vt(()=>a.currentTime),Ae(1)),p=["waiting","seeking","seeked","timeupdate"],c=new pL,d=.3,h;t.add(Bn(...p.map(x=>we(a,x))).subscribe(x=>{let F=a.currentTime;a.loop&&mv(h)&&mv(F)&&h>=a.duration-d&&F<=d&&c.next(h),h=F}));let f=e("pause").pipe(sc(()=>!a.error&&h!==a.duration),Ae(1)),m=we(a,"enterpictureinpicture").pipe(Ae(1)),g=we(a,"leavepictureinpicture").pipe(Ae(1)),v=new bv(pv(a));t.add(m.subscribe(()=>v.next(!0))),t.add(g.subscribe(()=>v.next(!1)));let S=new bv(ac(a)),T=we(a,"fullscreenchange").pipe(Ae(1));t.add(T.pipe(vt(()=>ac(a))).subscribe(S));let y=.1,A=1e3,P=we(a,"timeupdate").pipe(vt(x=>a.duration-a.currentTime<y),fv(),Ae(1)),L=Bn(P.pipe(sc(x=>!a.loop&&x)),we(a,"ended")).pipe(mL(A),nc(void 0),Ae(1)),M=Bn(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(x=>we(a,x)),P.pipe(vt(x=>({type:x?"ended":"unknown"})))).pipe(vt(x=>D.browser.isFirefox&&x.type==="ended"?a.readyState<2:a.readyState<3),fv(),Ae(1));return{playing$:s,pause$:f,canplay$:e("canplay"),ended$:L,looped$:c,error$:o,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:l,durationChange$:we(a,"durationchange").pipe(vt(()=>a.duration),Ae(1)),isBuffering$:M,currentBuffer$:r,volumeState$:n,playbackRateState$:u,inPiP$:v,inFullscreen$:S,enterPip$:m,leavePip$:g,destroy:i}};import{VideoQuality as Wt}from"@vkontakte/videoplayer-shared/es2024";var Qt=a=>{switch(a){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 Pe=C(nt(),1),uc=C(xe(),1),xi=C(fi(),1);import{isNonNullable as z,isNullable as Fn,now as Dv,isHigher as Nn,isHigherOrEqual as Ei,isInvariantQuality as qn,isLowerOrEqual as pr,videoSizeToQuality as Cv,assertNotEmptyArray as Un,assertNonNullable as Bv}from"@vkontakte/videoplayer-shared/es2024";var oc=!1,Pt={},Ev=a=>{oc=a},xv=()=>{Pt={}},wv=a=>{a(Pt)},ma=(a,e)=>{oc&&(Pt.meta=Pt.meta??{},Pt.meta[a]=e)},ke=class{constructor(e){this.name=e}next(e){if(!oc)return;Pt.series=Pt.series??{};let t=Pt.series[this.name]??[];t.push([Date.now(),e]),Pt.series[this.name]=t}};import{isHigher as AL,isHigherOrEqual as bq,isLower as Av,isLowerOrEqual as gq,isNonNullable as Vn,isNullable as kL,videoHeightToQuality as _n}from"@vkontakte/videoplayer-shared/es2024";function kv(a,e,t){return!a.max&&a.min===e?"high_quality":!a.min&&a.max===t?"traffic_saving":"unknown"}function dr(a,e,t){return kL(a)||Vn(a.min)&&Vn(a.max)&&Av(a.max,a.min)||Vn(a.min)&&e&&AL(a.min,e)||Vn(a.max)&&t&&Av(a.max,t)}function Pv({limits:a,highestAvailableHeight:e,lowestAvailableHeight:t}){return dr({max:a?.max?_n(a.max):void 0,min:a?.min?_n(a.min):void 0},e?_n(e):void 0,t?_n(t):void 0)}var Vv=new ke("best_bitrate"),jn=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t;var hr=a=>(e,t)=>a*(Number(e.bitrate)-Number(t.bitrate)),Gt=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=Dv()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},Hn='Assertion "ABR Tracks is empty array" failed',On=new WeakMap,Rv=new WeakMap,$v=new WeakMap,ba=(a,e,t,i)=>{let r=[...e].sort(hr(1)),s=[...t].sort(hr(1)),n=s.filter(o=>z(o.bitrate)&&z(a.bitrate)?a.bitrate/o.bitrate>i:!0),u=(0,Pe.default)(s,Math.round(s.length*r.indexOf(a)/(r.length+1)))??(0,Pe.default)(s,-1);return u&&(0,uc.default)(n,u)?u:n.length?(0,Pe.default)(n,-1):(0,Pe.default)(s,0)},ga=(a,e,t,i)=>{let r=On.get(e);r||(r=[...e].sort(hr(1)),On.set(e,r));let s=On.get(t);s||(s=[...t].sort(hr(1)),On.set(t,s));let n=$v.get(a);n||(n=s.filter(o=>z(o.bitrate)&&z(a.bitrate)?a.bitrate/o.bitrate>i:!0),$v.set(a,n));let u=(0,Pe.default)(s,Math.round(s.length*r.indexOf(a)/(r.length+1)))??(0,Pe.default)(s,-1);return u&&(0,uc.default)(n,u)?u:n.length?(0,Pe.default)(n,-1):(0,Pe.default)(s,0)},Lv=a=>"quality"in a,Wn=(a,e,t,i)=>{let r=z(i?.last?.bitrate)&&z(t?.bitrate)&&i.last.bitrate<t.bitrate?a.trackCooldownIncreaseQuality:a.trackCooldownDecreaseQuality,s=t&&i&&i.history[t.id]&&Dv()-i.history[t.id]<=r&&(!i.last||t.id!==i.last.id);if(t?.id&&i&&!s&&i.recordSelection(t),s&&i?.last){let n=i.last;i?.recordSwitch(n);let u=Lv(n)?"video":"audio",o=Lv(n)?n.quality:n.bitrate;return e({message:`
|
|
8
|
-
[last ${
|
|
9
|
-
`}),n}return i?.recordSwitch(t),t},
|
|
6
|
+
var Uw=Object.create;var ch=Object.defineProperty;var qw=Object.getOwnPropertyDescriptor;var jw=Object.getOwnPropertyNames;var Hw=Object.getPrototypeOf,zw=Object.prototype.hasOwnProperty;var b=(s,e)=>()=>(e||s((e={exports:{}}).exports,e),e.exports);var Qw=(s,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of jw(e))!zw.call(s,r)&&r!==t&&ch(s,r,{get:()=>e[r],enumerable:!(i=qw(e,r))||i.enumerable});return s};var D=(s,e,t)=>(t=s!=null?Uw(Hw(s)):{},Qw(e||!s||!s.__esModule?ch(t,"default",{value:s,enumerable:!0}):t,s));var se=b((el,ph)=>{"use strict";var xs=function(s){return s&&s.Math===Math&&s};ph.exports=xs(typeof globalThis=="object"&&globalThis)||xs(typeof window=="object"&&window)||xs(typeof self=="object"&&self)||xs(typeof global=="object"&&global)||xs(typeof el=="object"&&el)||function(){return this}()||Function("return this")()});var be=b((mN,hh)=>{"use strict";hh.exports=function(s){try{return!!s()}catch{return!0}}});var ks=b((bN,fh)=>{"use strict";var Ww=be();fh.exports=!Ww(function(){var s=function(){}.bind();return typeof s!="function"||s.hasOwnProperty("prototype")})});var tl=b((gN,Sh)=>{"use strict";var Gw=ks(),gh=Function.prototype,mh=gh.apply,bh=gh.call;Sh.exports=typeof Reflect=="object"&&Reflect.apply||(Gw?bh.bind(mh):function(){return bh.apply(mh,arguments)})});var ge=b((SN,Th)=>{"use strict";var vh=ks(),yh=Function.prototype,il=yh.call,Yw=vh&&yh.bind.bind(il,il);Th.exports=vh?Yw:function(s){return function(){return il.apply(s,arguments)}}});var Ai=b((vN,Eh)=>{"use strict";var Ih=ge(),Kw=Ih({}.toString),Xw=Ih("".slice);Eh.exports=function(s){return Xw(Kw(s),8,-1)}});var rl=b((yN,wh)=>{"use strict";var Jw=Ai(),Zw=ge();wh.exports=function(s){if(Jw(s)==="Function")return Zw(s)}});var ae=b((TN,xh)=>{"use strict";var sl=typeof document=="object"&&document.all;xh.exports=typeof sl>"u"&&sl!==void 0?function(s){return typeof s=="function"||s===sl}:function(s){return typeof s=="function"}});var Je=b((IN,kh)=>{"use strict";var ex=be();kh.exports=!ex(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var Ze=b((EN,Ph)=>{"use strict";var tx=ks(),Un=Function.prototype.call;Ph.exports=tx?Un.bind(Un):function(){return Un.apply(Un,arguments)}});var al=b($h=>{"use strict";var Ah={}.propertyIsEnumerable,Rh=Object.getOwnPropertyDescriptor,ix=Rh&&!Ah.call({1:2},1);$h.f=ix?function(e){var t=Rh(this,e);return!!t&&t.enumerable}:Ah});var Ps=b((xN,Mh)=>{"use strict";Mh.exports=function(s,e){return{enumerable:!(s&1),configurable:!(s&2),writable:!(s&4),value:e}}});var Dh=b((kN,Lh)=>{"use strict";var rx=ge(),sx=be(),ax=Ai(),nl=Object,nx=rx("".split);Lh.exports=sx(function(){return!nl("z").propertyIsEnumerable(0)})?function(s){return ax(s)==="String"?nx(s,""):nl(s)}:nl});var As=b((PN,Bh)=>{"use strict";Bh.exports=function(s){return s==null}});var ii=b((AN,Ch)=>{"use strict";var ox=As(),ux=TypeError;Ch.exports=function(s){if(ox(s))throw new ux("Can't call method on "+s);return s}});var Ri=b((RN,Vh)=>{"use strict";var lx=Dh(),cx=ii();Vh.exports=function(s){return lx(cx(s))}});var ze=b(($N,_h)=>{"use strict";var dx=ae();_h.exports=function(s){return typeof s=="object"?s!==null:dx(s)}});var $i=b((MN,Oh)=>{"use strict";Oh.exports={}});var Vt=b((LN,Fh)=>{"use strict";var ol=$i(),ul=se(),px=ae(),Nh=function(s){return px(s)?s:void 0};Fh.exports=function(s,e){return arguments.length<2?Nh(ol[s])||Nh(ul[s]):ol[s]&&ol[s][e]||ul[s]&&ul[s][e]}});var Rs=b((DN,Uh)=>{"use strict";var hx=ge();Uh.exports=hx({}.isPrototypeOf)});var Mi=b((BN,Hh)=>{"use strict";var fx=se(),qh=fx.navigator,jh=qh&&qh.userAgent;Hh.exports=jh?String(jh):""});var cl=b((CN,Kh)=>{"use strict";var Yh=se(),ll=Mi(),zh=Yh.process,Qh=Yh.Deno,Wh=zh&&zh.versions||Qh&&Qh.version,Gh=Wh&&Wh.v8,mt,qn;Gh&&(mt=Gh.split("."),qn=mt[0]>0&&mt[0]<4?1:+(mt[0]+mt[1]));!qn&&ll&&(mt=ll.match(/Edge\/(\d+)/),(!mt||mt[1]>=74)&&(mt=ll.match(/Chrome\/(\d+)/),mt&&(qn=+mt[1])));Kh.exports=qn});var dl=b((VN,Jh)=>{"use strict";var Xh=cl(),mx=be(),bx=se(),gx=bx.String;Jh.exports=!!Object.getOwnPropertySymbols&&!mx(function(){var s=Symbol("symbol detection");return!gx(s)||!(Object(s)instanceof Symbol)||!Symbol.sham&&Xh&&Xh<41})});var pl=b((_N,Zh)=>{"use strict";var Sx=dl();Zh.exports=Sx&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var hl=b((ON,ef)=>{"use strict";var vx=Vt(),yx=ae(),Tx=Rs(),Ix=pl(),Ex=Object;ef.exports=Ix?function(s){return typeof s=="symbol"}:function(s){var e=vx("Symbol");return yx(e)&&Tx(e.prototype,Ex(s))}});var $s=b((NN,tf)=>{"use strict";var wx=String;tf.exports=function(s){try{return wx(s)}catch{return"Object"}}});var kt=b((FN,rf)=>{"use strict";var xx=ae(),kx=$s(),Px=TypeError;rf.exports=function(s){if(xx(s))return s;throw new Px(kx(s)+" is not a function")}});var Ms=b((UN,sf)=>{"use strict";var Ax=kt(),Rx=As();sf.exports=function(s,e){var t=s[e];return Rx(t)?void 0:Ax(t)}});var nf=b((qN,af)=>{"use strict";var fl=Ze(),ml=ae(),bl=ze(),$x=TypeError;af.exports=function(s,e){var t,i;if(e==="string"&&ml(t=s.toString)&&!bl(i=fl(t,s))||ml(t=s.valueOf)&&!bl(i=fl(t,s))||e!=="string"&&ml(t=s.toString)&&!bl(i=fl(t,s)))return i;throw new $x("Can't convert object to primitive value")}});var bt=b((jN,of)=>{"use strict";of.exports=!0});var cf=b((HN,lf)=>{"use strict";var uf=se(),Mx=Object.defineProperty;lf.exports=function(s,e){try{Mx(uf,s,{value:e,configurable:!0,writable:!0})}catch{uf[s]=e}return e}});var Ls=b((zN,hf)=>{"use strict";var Lx=bt(),Dx=se(),Bx=cf(),df="__core-js_shared__",pf=hf.exports=Dx[df]||Bx(df,{});(pf.versions||(pf.versions=[])).push({version:"3.43.0",mode:Lx?"pure":"global",copyright:"© 2014-2025 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.43.0/LICENSE",source:"https://github.com/zloirock/core-js"})});var gl=b((QN,mf)=>{"use strict";var ff=Ls();mf.exports=function(s,e){return ff[s]||(ff[s]=e||{})}});var mr=b((WN,bf)=>{"use strict";var Cx=ii(),Vx=Object;bf.exports=function(s){return Vx(Cx(s))}});var gt=b((GN,gf)=>{"use strict";var _x=ge(),Ox=mr(),Nx=_x({}.hasOwnProperty);gf.exports=Object.hasOwn||function(e,t){return Nx(Ox(e),t)}});var Sl=b((YN,Sf)=>{"use strict";var Fx=ge(),Ux=0,qx=Math.random(),jx=Fx(1.1.toString);Sf.exports=function(s){return"Symbol("+(s===void 0?"":s)+")_"+jx(++Ux+qx,36)}});var xe=b((KN,yf)=>{"use strict";var Hx=se(),zx=gl(),vf=gt(),Qx=Sl(),Wx=dl(),Gx=pl(),br=Hx.Symbol,vl=zx("wks"),Yx=Gx?br.for||br:br&&br.withoutSetter||Qx;yf.exports=function(s){return vf(vl,s)||(vl[s]=Wx&&vf(br,s)?br[s]:Yx("Symbol."+s)),vl[s]}});var wf=b((XN,Ef)=>{"use strict";var Kx=Ze(),Tf=ze(),If=hl(),Xx=Ms(),Jx=nf(),Zx=xe(),ek=TypeError,tk=Zx("toPrimitive");Ef.exports=function(s,e){if(!Tf(s)||If(s))return s;var t=Xx(s,tk),i;if(t){if(e===void 0&&(e="default"),i=Kx(t,s,e),!Tf(i)||If(i))return i;throw new ek("Can't convert object to primitive value")}return e===void 0&&(e="number"),Jx(s,e)}});var yl=b((JN,xf)=>{"use strict";var ik=wf(),rk=hl();xf.exports=function(s){var e=ik(s,"string");return rk(e)?e:e+""}});var jn=b((ZN,Pf)=>{"use strict";var sk=se(),kf=ze(),Tl=sk.document,ak=kf(Tl)&&kf(Tl.createElement);Pf.exports=function(s){return ak?Tl.createElement(s):{}}});var Il=b((eF,Af)=>{"use strict";var nk=Je(),ok=be(),uk=jn();Af.exports=!nk&&!ok(function(){return Object.defineProperty(uk("div"),"a",{get:function(){return 7}}).a!==7})});var Mf=b($f=>{"use strict";var lk=Je(),ck=Ze(),dk=al(),pk=Ps(),hk=Ri(),fk=yl(),mk=gt(),bk=Il(),Rf=Object.getOwnPropertyDescriptor;$f.f=lk?Rf:function(e,t){if(e=hk(e),t=fk(t),bk)try{return Rf(e,t)}catch{}if(mk(e,t))return pk(!ck(dk.f,e,t),e[t])}});var El=b((iF,Lf)=>{"use strict";var gk=be(),Sk=ae(),vk=/#|\.prototype\./,Ds=function(s,e){var t=Tk[yk(s)];return t===Ek?!0:t===Ik?!1:Sk(e)?gk(e):!!e},yk=Ds.normalize=function(s){return String(s).replace(vk,".").toLowerCase()},Tk=Ds.data={},Ik=Ds.NATIVE="N",Ek=Ds.POLYFILL="P";Lf.exports=Ds});var gr=b((rF,Bf)=>{"use strict";var Df=rl(),wk=kt(),xk=ks(),kk=Df(Df.bind);Bf.exports=function(s,e){return wk(s),e===void 0?s:xk?kk(s,e):function(){return s.apply(e,arguments)}}});var wl=b((sF,Cf)=>{"use strict";var Pk=Je(),Ak=be();Cf.exports=Pk&&Ak(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var Pt=b((aF,Vf)=>{"use strict";var Rk=ze(),$k=String,Mk=TypeError;Vf.exports=function(s){if(Rk(s))return s;throw new Mk($k(s)+" is not an object")}});var Li=b(Of=>{"use strict";var Lk=Je(),Dk=Il(),Bk=wl(),Hn=Pt(),_f=yl(),Ck=TypeError,xl=Object.defineProperty,Vk=Object.getOwnPropertyDescriptor,kl="enumerable",Pl="configurable",Al="writable";Of.f=Lk?Bk?function(e,t,i){if(Hn(e),t=_f(t),Hn(i),typeof e=="function"&&t==="prototype"&&"value"in i&&Al in i&&!i[Al]){var r=Vk(e,t);r&&r[Al]&&(e[t]=i.value,i={configurable:Pl in i?i[Pl]:r[Pl],enumerable:kl in i?i[kl]:r[kl],writable:!1})}return xl(e,t,i)}:xl:function(e,t,i){if(Hn(e),t=_f(t),Hn(i),Dk)try{return xl(e,t,i)}catch{}if("get"in i||"set"in i)throw new Ck("Accessors not supported");return"value"in i&&(e[t]=i.value),e}});var Sr=b((oF,Nf)=>{"use strict";var _k=Je(),Ok=Li(),Nk=Ps();Nf.exports=_k?function(s,e,t){return Ok.f(s,e,Nk(1,t))}:function(s,e,t){return s[e]=t,s}});var ue=b((uF,Uf)=>{"use strict";var Bs=se(),Fk=tl(),Uk=rl(),qk=ae(),jk=Mf().f,Hk=El(),vr=$i(),zk=gr(),yr=Sr(),Ff=gt();Ls();var Qk=function(s){var e=function(t,i,r){if(this instanceof e){switch(arguments.length){case 0:return new s;case 1:return new s(t);case 2:return new s(t,i)}return new s(t,i,r)}return Fk(s,this,arguments)};return e.prototype=s.prototype,e};Uf.exports=function(s,e){var t=s.target,i=s.global,r=s.stat,a=s.proto,n=i?Bs:r?Bs[t]:Bs[t]&&Bs[t].prototype,o=i?vr:vr[t]||yr(vr,t,{})[t],u=o.prototype,l,p,c,d,h,f,m,S,g;for(d in e)l=Hk(i?d:t+(r?".":"#")+d,s.forced),p=!l&&n&&Ff(n,d),f=o[d],p&&(s.dontCallGetSet?(g=jk(n,d),m=g&&g.value):m=n[d]),h=p&&m?m:e[d],!(!l&&!a&&typeof f==typeof h)&&(s.bind&&p?S=zk(h,Bs):s.wrap&&p?S=Qk(h):a&&qk(h)?S=Uk(h):S=h,(s.sham||h&&h.sham||f&&f.sham)&&yr(S,"sham",!0),yr(o,d,S),a&&(c=t+"Prototype",Ff(vr,c)||yr(vr,c,{}),yr(vr[c],d,h),s.real&&u&&(l||!u[d])&&yr(u,d,h)))}});var zn=b((lF,jf)=>{"use strict";var Wk=gl(),Gk=Sl(),qf=Wk("keys");jf.exports=function(s){return qf[s]||(qf[s]=Gk(s))}});var zf=b((cF,Hf)=>{"use strict";var Yk=be();Hf.exports=!Yk(function(){function s(){}return s.prototype.constructor=null,Object.getPrototypeOf(new s)!==s.prototype})});var Qn=b((dF,Wf)=>{"use strict";var Kk=gt(),Xk=ae(),Jk=mr(),Zk=zn(),eP=zf(),Qf=Zk("IE_PROTO"),Rl=Object,tP=Rl.prototype;Wf.exports=eP?Rl.getPrototypeOf:function(s){var e=Jk(s);if(Kk(e,Qf))return e[Qf];var t=e.constructor;return Xk(t)&&e instanceof t?t.prototype:e instanceof Rl?tP:null}});var Yf=b((pF,Gf)=>{"use strict";var iP=Math.ceil,rP=Math.floor;Gf.exports=Math.trunc||function(e){var t=+e;return(t>0?rP:iP)(t)}});var Cs=b((hF,Kf)=>{"use strict";var sP=Yf();Kf.exports=function(s){var e=+s;return e!==e||e===0?0:sP(e)}});var Jf=b((fF,Xf)=>{"use strict";var aP=Cs(),nP=Math.max,oP=Math.min;Xf.exports=function(s,e){var t=aP(s);return t<0?nP(t+e,0):oP(t,e)}});var $l=b((mF,Zf)=>{"use strict";var uP=Cs(),lP=Math.min;Zf.exports=function(s){var e=uP(s);return e>0?lP(e,9007199254740991):0}});var Tr=b((bF,em)=>{"use strict";var cP=$l();em.exports=function(s){return cP(s.length)}});var Ml=b((gF,im)=>{"use strict";var dP=Ri(),pP=Jf(),hP=Tr(),tm=function(s){return function(e,t,i){var r=dP(e),a=hP(r);if(a===0)return!s&&-1;var n=pP(i,a),o;if(s&&t!==t){for(;a>n;)if(o=r[n++],o!==o)return!0}else for(;a>n;n++)if((s||n in r)&&r[n]===t)return s||n||0;return!s&&-1}};im.exports={includes:tm(!0),indexOf:tm(!1)}});var Wn=b((SF,rm)=>{"use strict";rm.exports={}});var nm=b((vF,am)=>{"use strict";var fP=ge(),Ll=gt(),mP=Ri(),bP=Ml().indexOf,gP=Wn(),sm=fP([].push);am.exports=function(s,e){var t=mP(s),i=0,r=[],a;for(a in t)!Ll(gP,a)&&Ll(t,a)&&sm(r,a);for(;e.length>i;)Ll(t,a=e[i++])&&(~bP(r,a)||sm(r,a));return r}});var Dl=b((yF,om)=>{"use strict";om.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var Bl=b((TF,um)=>{"use strict";var SP=nm(),vP=Dl();um.exports=Object.keys||function(e){return SP(e,vP)}});var Cl=b((IF,hm)=>{"use strict";var cm=Je(),yP=be(),dm=ge(),TP=Qn(),IP=Bl(),EP=Ri(),wP=al().f,pm=dm(wP),xP=dm([].push),kP=cm&&yP(function(){var s=Object.create(null);return s[2]=2,!pm(s,2)}),lm=function(s){return function(e){for(var t=EP(e),i=IP(t),r=kP&&TP(t)===null,a=i.length,n=0,o=[],u;a>n;)u=i[n++],(!cm||(r?u in t:pm(t,u)))&&xP(o,s?[u,t[u]]:t[u]);return o}};hm.exports={entries:lm(!0),values:lm(!1)}});var fm=b(()=>{"use strict";var PP=ue(),AP=Cl().values;PP({target:"Object",stat:!0},{values:function(e){return AP(e)}})});var bm=b((xF,mm)=>{"use strict";fm();var RP=$i();mm.exports=RP.Object.values});var Sm=b((kF,gm)=>{"use strict";var $P=bm();gm.exports=$P});var Di=b((PF,vm)=>{"use strict";var MP=Sm();vm.exports=MP});var Vs=b((AF,ym)=>{"use strict";ym.exports=function(){}});var Tm=b(()=>{"use strict";var LP=ue(),DP=Ml().includes,BP=be(),CP=Vs(),VP=BP(function(){return!Array(1).includes()});LP({target:"Array",proto:!0,forced:VP},{includes:function(e){return DP(this,e,arguments.length>1?arguments[1]:void 0)}});CP("includes")});var ri=b((MF,Im)=>{"use strict";var _P=Vt();Im.exports=_P});var wm=b((LF,Em)=>{"use strict";Tm();var OP=ri();Em.exports=OP("Array","includes")});var km=b((DF,xm)=>{"use strict";var NP=wm();xm.exports=NP});var ke=b((BF,Pm)=>{"use strict";var FP=km();Pm.exports=FP});var Xm=b(()=>{"use strict";var vA=ue(),yA=Cl().entries;vA({target:"Object",stat:!0},{entries:function(e){return yA(e)}})});var Zm=b((Rq,Jm)=>{"use strict";Xm();var TA=$i();Jm.exports=TA.Object.entries});var tb=b(($q,eb)=>{"use strict";var IA=Zm();eb.exports=IA});var ni=b((Mq,ib)=>{"use strict";var EA=tb();ib.exports=EA});var Vi=b((Lq,rb)=>{"use strict";rb.exports={}});var nb=b((Dq,ab)=>{"use strict";var wA=se(),xA=ae(),sb=wA.WeakMap;ab.exports=xA(sb)&&/native code/.test(String(sb))});var Kl=b((Bq,lb)=>{"use strict";var kA=nb(),ub=se(),PA=ze(),AA=Sr(),Wl=gt(),Gl=Ls(),RA=zn(),$A=Wn(),ob="Object already initialized",Yl=ub.TypeError,MA=ub.WeakMap,so,Us,ao,LA=function(s){return ao(s)?Us(s):so(s,{})},DA=function(s){return function(e){var t;if(!PA(e)||(t=Us(e)).type!==s)throw new Yl("Incompatible receiver, "+s+" required");return t}};kA||Gl.state?(vt=Gl.state||(Gl.state=new MA),vt.get=vt.get,vt.has=vt.has,vt.set=vt.set,so=function(s,e){if(vt.has(s))throw new Yl(ob);return e.facade=s,vt.set(s,e),e},Us=function(s){return vt.get(s)||{}},ao=function(s){return vt.has(s)}):(_i=RA("state"),$A[_i]=!0,so=function(s,e){if(Wl(s,_i))throw new Yl(ob);return e.facade=s,AA(s,_i,e),e},Us=function(s){return Wl(s,_i)?s[_i]:{}},ao=function(s){return Wl(s,_i)});var vt,_i;lb.exports={set:so,get:Us,has:ao,enforce:LA,getterFor:DA}});var Zl=b((Cq,db)=>{"use strict";var Xl=Je(),BA=gt(),cb=Function.prototype,CA=Xl&&Object.getOwnPropertyDescriptor,Jl=BA(cb,"name"),VA=Jl&&function(){}.name==="something",_A=Jl&&(!Xl||Xl&&CA(cb,"name").configurable);db.exports={EXISTS:Jl,PROPER:VA,CONFIGURABLE:_A}});var hb=b(pb=>{"use strict";var OA=Je(),NA=wl(),FA=Li(),UA=Pt(),qA=Ri(),jA=Bl();pb.f=OA&&!NA?Object.defineProperties:function(e,t){UA(e);for(var i=qA(t),r=jA(t),a=r.length,n=0,o;a>n;)FA.f(e,o=r[n++],i[o]);return e}});var ec=b((_q,fb)=>{"use strict";var HA=Vt();fb.exports=HA("document","documentElement")});var sc=b((Oq,Tb)=>{"use strict";var zA=Pt(),QA=hb(),mb=Dl(),WA=Wn(),GA=ec(),YA=jn(),KA=zn(),bb=">",gb="<",ic="prototype",rc="script",vb=KA("IE_PROTO"),tc=function(){},yb=function(s){return gb+rc+bb+s+gb+"/"+rc+bb},Sb=function(s){s.write(yb("")),s.close();var e=s.parentWindow.Object;return s=null,e},XA=function(){var s=YA("iframe"),e="java"+rc+":",t;return s.style.display="none",GA.appendChild(s),s.src=String(e),t=s.contentWindow.document,t.open(),t.write(yb("document.F=Object")),t.close(),t.F},no,oo=function(){try{no=new ActiveXObject("htmlfile")}catch{}oo=typeof document<"u"?document.domain&&no?Sb(no):XA():Sb(no);for(var s=mb.length;s--;)delete oo[ic][mb[s]];return oo()};WA[vb]=!0;Tb.exports=Object.create||function(e,t){var i;return e!==null?(tc[ic]=zA(e),i=new tc,tc[ic]=null,i[vb]=e):i=oo(),t===void 0?i:QA.f(i,t)}});var xr=b((Nq,Ib)=>{"use strict";var JA=Sr();Ib.exports=function(s,e,t,i){return i&&i.enumerable?s[e]=t:JA(s,e,t),s}});var uc=b((Fq,xb)=>{"use strict";var ZA=be(),eR=ae(),tR=ze(),iR=sc(),Eb=Qn(),rR=xr(),sR=xe(),aR=bt(),oc=sR("iterator"),wb=!1,Ot,ac,nc;[].keys&&(nc=[].keys(),"next"in nc?(ac=Eb(Eb(nc)),ac!==Object.prototype&&(Ot=ac)):wb=!0);var nR=!tR(Ot)||ZA(function(){var s={};return Ot[oc].call(s)!==s});nR?Ot={}:aR&&(Ot=iR(Ot));eR(Ot[oc])||rR(Ot,oc,function(){return this});xb.exports={IteratorPrototype:Ot,BUGGY_SAFARI_ITERATORS:wb}});var uo=b((Uq,Pb)=>{"use strict";var oR=xe(),uR=oR("toStringTag"),kb={};kb[uR]="z";Pb.exports=String(kb)==="[object z]"});var qs=b((qq,Ab)=>{"use strict";var lR=uo(),cR=ae(),lo=Ai(),dR=xe(),pR=dR("toStringTag"),hR=Object,fR=lo(function(){return arguments}())==="Arguments",mR=function(s,e){try{return s[e]}catch{}};Ab.exports=lR?lo:function(s){var e,t,i;return s===void 0?"Undefined":s===null?"Null":typeof(t=mR(e=hR(s),pR))=="string"?t:fR?lo(e):(i=lo(e))==="Object"&&cR(e.callee)?"Arguments":i}});var $b=b((jq,Rb)=>{"use strict";var bR=uo(),gR=qs();Rb.exports=bR?{}.toString:function(){return"[object "+gR(this)+"]"}});var js=b((Hq,Lb)=>{"use strict";var SR=uo(),vR=Li().f,yR=Sr(),TR=gt(),IR=$b(),ER=xe(),Mb=ER("toStringTag");Lb.exports=function(s,e,t,i){var r=t?s:s&&s.prototype;r&&(TR(r,Mb)||vR(r,Mb,{configurable:!0,value:e}),i&&!SR&&yR(r,"toString",IR))}});var Bb=b((zq,Db)=>{"use strict";var wR=uc().IteratorPrototype,xR=sc(),kR=Ps(),PR=js(),AR=Vi(),RR=function(){return this};Db.exports=function(s,e,t,i){var r=e+" Iterator";return s.prototype=xR(wR,{next:kR(+!i,t)}),PR(s,r,!1,!0),AR[r]=RR,s}});var Vb=b((Qq,Cb)=>{"use strict";var $R=ge(),MR=kt();Cb.exports=function(s,e,t){try{return $R(MR(Object.getOwnPropertyDescriptor(s,e)[t]))}catch{}}});var Ob=b((Wq,_b)=>{"use strict";var LR=ze();_b.exports=function(s){return LR(s)||s===null}});var Fb=b((Gq,Nb)=>{"use strict";var DR=Ob(),BR=String,CR=TypeError;Nb.exports=function(s){if(DR(s))return s;throw new CR("Can't set "+BR(s)+" as a prototype")}});var lc=b((Yq,Ub)=>{"use strict";var VR=Vb(),_R=ze(),OR=ii(),NR=Fb();Ub.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var s=!1,e={},t;try{t=VR(Object.prototype,"__proto__","set"),t(e,[]),s=e instanceof Array}catch{}return function(r,a){return OR(r),NR(a),_R(r)&&(s?t(r,a):r.__proto__=a),r}}():void 0)});var Jb=b((Kq,Xb)=>{"use strict";var FR=ue(),UR=Ze(),co=bt(),Yb=Zl(),qR=ae(),jR=Bb(),qb=Qn(),jb=lc(),HR=js(),zR=Sr(),cc=xr(),QR=xe(),Hb=Vi(),Kb=uc(),WR=Yb.PROPER,GR=Yb.CONFIGURABLE,zb=Kb.IteratorPrototype,po=Kb.BUGGY_SAFARI_ITERATORS,Hs=QR("iterator"),Qb="keys",zs="values",Wb="entries",Gb=function(){return this};Xb.exports=function(s,e,t,i,r,a,n){jR(t,e,i);var o=function(g){if(g===r&&d)return d;if(!po&&g&&g in p)return p[g];switch(g){case Qb:return function(){return new t(this,g)};case zs:return function(){return new t(this,g)};case Wb:return function(){return new t(this,g)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,p=s.prototype,c=p[Hs]||p["@@iterator"]||r&&p[r],d=!po&&c||o(r),h=e==="Array"&&p.entries||c,f,m,S;if(h&&(f=qb(h.call(new s)),f!==Object.prototype&&f.next&&(!co&&qb(f)!==zb&&(jb?jb(f,zb):qR(f[Hs])||cc(f,Hs,Gb)),HR(f,u,!0,!0),co&&(Hb[u]=Gb))),WR&&r===zs&&c&&c.name!==zs&&(!co&&GR?zR(p,"name",zs):(l=!0,d=function(){return UR(c,this)})),r)if(m={values:o(zs),keys:a?d:o(Qb),entries:o(Wb)},n)for(S in m)(po||l||!(S in p))&&cc(p,S,m[S]);else FR({target:e,proto:!0,forced:po||l},m);return(!co||n)&&p[Hs]!==d&&cc(p,Hs,d,{name:r}),Hb[e]=d,m}});var eg=b((Xq,Zb)=>{"use strict";Zb.exports=function(s,e){return{value:s,done:e}}});var pc=b((Jq,ag)=>{"use strict";var YR=Ri(),dc=Vs(),tg=Vi(),rg=Kl(),KR=Li().f,XR=Jb(),ho=eg(),JR=bt(),ZR=Je(),sg="Array Iterator",e$=rg.set,t$=rg.getterFor(sg);ag.exports=XR(Array,"Array",function(s,e){e$(this,{type:sg,target:YR(s),index:0,kind:e})},function(){var s=t$(this),e=s.target,t=s.index++;if(!e||t>=e.length)return s.target=null,ho(void 0,!0);switch(s.kind){case"keys":return ho(t,!1);case"values":return ho(e[t],!1)}return ho([t,e[t]],!1)},"values");var ig=tg.Arguments=tg.Array;dc("keys");dc("values");dc("entries");if(!JR&&ZR&&ig.name!=="values")try{KR(ig,"name",{value:"values"})}catch{}});var og=b((Zq,ng)=>{"use strict";var i$=xe(),r$=Vi(),s$=i$("iterator"),a$=Array.prototype;ng.exports=function(s){return s!==void 0&&(r$.Array===s||a$[s$]===s)}});var hc=b((e1,lg)=>{"use strict";var n$=qs(),ug=Ms(),o$=As(),u$=Vi(),l$=xe(),c$=l$("iterator");lg.exports=function(s){if(!o$(s))return ug(s,c$)||ug(s,"@@iterator")||u$[n$(s)]}});var dg=b((t1,cg)=>{"use strict";var d$=Ze(),p$=kt(),h$=Pt(),f$=$s(),m$=hc(),b$=TypeError;cg.exports=function(s,e){var t=arguments.length<2?m$(s):e;if(p$(t))return h$(d$(t,s));throw new b$(f$(s)+" is not iterable")}});var fg=b((i1,hg)=>{"use strict";var g$=Ze(),pg=Pt(),S$=Ms();hg.exports=function(s,e,t){var i,r;pg(s);try{if(i=S$(s,"return"),!i){if(e==="throw")throw t;return t}i=g$(i,s)}catch(a){r=!0,i=a}if(e==="throw")throw t;if(r)throw i;return pg(i),t}});var mo=b((r1,Sg)=>{"use strict";var v$=gr(),y$=Ze(),T$=Pt(),I$=$s(),E$=og(),w$=Tr(),mg=Rs(),x$=dg(),k$=hc(),bg=fg(),P$=TypeError,fo=function(s,e){this.stopped=s,this.result=e},gg=fo.prototype;Sg.exports=function(s,e,t){var i=t&&t.that,r=!!(t&&t.AS_ENTRIES),a=!!(t&&t.IS_RECORD),n=!!(t&&t.IS_ITERATOR),o=!!(t&&t.INTERRUPTED),u=v$(e,i),l,p,c,d,h,f,m,S=function(v){return l&&bg(l,"normal"),new fo(!0,v)},g=function(v){return r?(T$(v),o?u(v[0],v[1],S):u(v[0],v[1])):o?u(v,S):u(v)};if(a)l=s.iterator;else if(n)l=s;else{if(p=k$(s),!p)throw new P$(I$(s)+" is not iterable");if(E$(p)){for(c=0,d=w$(s);d>c;c++)if(h=g(s[c]),h&&mg(gg,h))return h;return new fo(!1)}l=x$(s,p)}for(f=a?s.next:l.next;!(m=y$(f,l)).done;){try{h=g(m.value)}catch(v){bg(l,"throw",v)}if(typeof h=="object"&&h&&mg(gg,h))return h}return new fo(!1)}});var yg=b((s1,vg)=>{"use strict";var A$=Je(),R$=Li(),$$=Ps();vg.exports=function(s,e,t){A$?R$.f(s,e,$$(0,t)):s[e]=t}});var Tg=b(()=>{"use strict";var M$=ue(),L$=mo(),D$=yg();M$({target:"Object",stat:!0},{fromEntries:function(e){var t={};return L$(e,function(i,r){D$(t,i,r)},{AS_ENTRIES:!0}),t}})});var Eg=b((o1,Ig)=>{"use strict";pc();Tg();var B$=$i();Ig.exports=B$.Object.fromEntries});var xg=b((u1,wg)=>{"use strict";wg.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 Pg=b(()=>{"use strict";pc();var C$=xg(),V$=se(),_$=js(),kg=Vi();for(bo in C$)_$(V$[bo],bo),kg[bo]=kg.Array;var bo});var Rg=b((d1,Ag)=>{"use strict";var O$=Eg();Pg();Ag.exports=O$});var fc=b((p1,$g)=>{"use strict";var N$=Rg();$g.exports=N$});var Mg=b(()=>{"use strict"});var mc=b((m1,Lg)=>{"use strict";var Qs=se(),F$=Mi(),U$=Ai(),go=function(s){return F$.slice(0,s.length)===s};Lg.exports=function(){return go("Bun/")?"BUN":go("Cloudflare-Workers")?"CLOUDFLARE":go("Deno/")?"DENO":go("Node.js/")?"NODE":Qs.Bun&&typeof Bun.version=="string"?"BUN":Qs.Deno&&typeof Deno.version=="object"?"DENO":U$(Qs.process)==="process"?"NODE":Qs.window&&Qs.document?"BROWSER":"REST"}()});var So=b((b1,Dg)=>{"use strict";var q$=mc();Dg.exports=q$==="NODE"});var Cg=b((g1,Bg)=>{"use strict";var j$=Li();Bg.exports=function(s,e,t){return j$.f(s,e,t)}});var Og=b((S1,_g)=>{"use strict";var H$=Vt(),z$=Cg(),Q$=xe(),W$=Je(),Vg=Q$("species");_g.exports=function(s){var e=H$(s);W$&&e&&!e[Vg]&&z$(e,Vg,{configurable:!0,get:function(){return this}})}});var Fg=b((v1,Ng)=>{"use strict";var G$=Rs(),Y$=TypeError;Ng.exports=function(s,e){if(G$(e,s))return s;throw new Y$("Incorrect invocation")}});var gc=b((y1,Ug)=>{"use strict";var K$=ge(),X$=ae(),bc=Ls(),J$=K$(Function.toString);X$(bc.inspectSource)||(bc.inspectSource=function(s){return J$(s)});Ug.exports=bc.inspectSource});var vc=b((T1,Qg)=>{"use strict";var Z$=ge(),eM=be(),qg=ae(),tM=qs(),iM=Vt(),rM=gc(),jg=function(){},Hg=iM("Reflect","construct"),Sc=/^\s*(?:class|function)\b/,sM=Z$(Sc.exec),aM=!Sc.test(jg),Ws=function(e){if(!qg(e))return!1;try{return Hg(jg,[],e),!0}catch{return!1}},zg=function(e){if(!qg(e))return!1;switch(tM(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return aM||!!sM(Sc,rM(e))}catch{return!0}};zg.sham=!0;Qg.exports=!Hg||eM(function(){var s;return Ws(Ws.call)||!Ws(Object)||!Ws(function(){s=!0})||s})?zg:Ws});var Gg=b((I1,Wg)=>{"use strict";var nM=vc(),oM=$s(),uM=TypeError;Wg.exports=function(s){if(nM(s))return s;throw new uM(oM(s)+" is not a constructor")}});var yc=b((E1,Kg)=>{"use strict";var Yg=Pt(),lM=Gg(),cM=As(),dM=xe(),pM=dM("species");Kg.exports=function(s,e){var t=Yg(s).constructor,i;return t===void 0||cM(i=Yg(t)[pM])?e:lM(i)}});var Jg=b((w1,Xg)=>{"use strict";var hM=ge();Xg.exports=hM([].slice)});var eS=b((x1,Zg)=>{"use strict";var fM=TypeError;Zg.exports=function(s,e){if(s<e)throw new fM("Not enough arguments");return s}});var Tc=b((k1,tS)=>{"use strict";var mM=Mi();tS.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(mM)});var $c=b((P1,cS)=>{"use strict";var et=se(),bM=tl(),gM=gr(),iS=ae(),SM=gt(),lS=be(),rS=ec(),vM=Jg(),sS=jn(),yM=eS(),TM=Tc(),IM=So(),Pc=et.setImmediate,Ac=et.clearImmediate,EM=et.process,Ic=et.Dispatch,wM=et.Function,aS=et.MessageChannel,xM=et.String,Ec=0,Gs={},nS="onreadystatechange",Ys,Oi,wc,xc;lS(function(){Ys=et.location});var Rc=function(s){if(SM(Gs,s)){var e=Gs[s];delete Gs[s],e()}},kc=function(s){return function(){Rc(s)}},oS=function(s){Rc(s.data)},uS=function(s){et.postMessage(xM(s),Ys.protocol+"//"+Ys.host)};(!Pc||!Ac)&&(Pc=function(e){yM(arguments.length,1);var t=iS(e)?e:wM(e),i=vM(arguments,1);return Gs[++Ec]=function(){bM(t,void 0,i)},Oi(Ec),Ec},Ac=function(e){delete Gs[e]},IM?Oi=function(s){EM.nextTick(kc(s))}:Ic&&Ic.now?Oi=function(s){Ic.now(kc(s))}:aS&&!TM?(wc=new aS,xc=wc.port2,wc.port1.onmessage=oS,Oi=gM(xc.postMessage,xc)):et.addEventListener&&iS(et.postMessage)&&!et.importScripts&&Ys&&Ys.protocol!=="file:"&&!lS(uS)?(Oi=uS,et.addEventListener("message",oS,!1)):nS in sS("script")?Oi=function(s){rS.appendChild(sS("script"))[nS]=function(){rS.removeChild(this),Rc(s)}}:Oi=function(s){setTimeout(kc(s),0)});cS.exports={set:Pc,clear:Ac}});var hS=b((A1,pS)=>{"use strict";var dS=se(),kM=Je(),PM=Object.getOwnPropertyDescriptor;pS.exports=function(s){if(!kM)return dS[s];var e=PM(dS,s);return e&&e.value}});var Mc=b((R1,mS)=>{"use strict";var fS=function(){this.head=null,this.tail=null};fS.prototype={add:function(s){var e={item:s,next:null},t=this.tail;t?t.next=e:this.head=e,this.tail=e},get:function(){var s=this.head;if(s){var e=this.head=s.next;return e===null&&(this.tail=null),s.item}}};mS.exports=fS});var gS=b(($1,bS)=>{"use strict";var AM=Mi();bS.exports=/ipad|iphone|ipod/i.test(AM)&&typeof Pebble<"u"});var vS=b((M1,SS)=>{"use strict";var RM=Mi();SS.exports=/web0s(?!.*chrome)/i.test(RM)});var kS=b((L1,xS)=>{"use strict";var Pr=se(),$M=hS(),yS=gr(),Lc=$c().set,MM=Mc(),LM=Tc(),DM=gS(),BM=vS(),Dc=So(),TS=Pr.MutationObserver||Pr.WebKitMutationObserver,IS=Pr.document,ES=Pr.process,vo=Pr.Promise,Vc=$M("queueMicrotask"),kr,Bc,Cc,yo,wS;Vc||(Ks=new MM,Xs=function(){var s,e;for(Dc&&(s=ES.domain)&&s.exit();e=Ks.get();)try{e()}catch(t){throw Ks.head&&kr(),t}s&&s.enter()},!LM&&!Dc&&!BM&&TS&&IS?(Bc=!0,Cc=IS.createTextNode(""),new TS(Xs).observe(Cc,{characterData:!0}),kr=function(){Cc.data=Bc=!Bc}):!DM&&vo&&vo.resolve?(yo=vo.resolve(void 0),yo.constructor=vo,wS=yS(yo.then,yo),kr=function(){wS(Xs)}):Dc?kr=function(){ES.nextTick(Xs)}:(Lc=yS(Lc,Pr),kr=function(){Lc(Xs)}),Vc=function(s){Ks.head||kr(),Ks.add(s)});var Ks,Xs;xS.exports=Vc});var AS=b((D1,PS)=>{"use strict";PS.exports=function(s,e){try{arguments.length===1?console.error(s):console.error(s,e)}catch{}}});var To=b((B1,RS)=>{"use strict";RS.exports=function(s){try{return{error:!1,value:s()}}catch(e){return{error:!0,value:e}}}});var Ni=b((C1,$S)=>{"use strict";var CM=se();$S.exports=CM.Promise});var Ar=b((V1,BS)=>{"use strict";var VM=se(),Js=Ni(),_M=ae(),OM=El(),NM=gc(),FM=xe(),MS=mc(),UM=bt(),_c=cl(),LS=Js&&Js.prototype,qM=FM("species"),Oc=!1,DS=_M(VM.PromiseRejectionEvent),jM=OM("Promise",function(){var s=NM(Js),e=s!==String(Js);if(!e&&_c===66||UM&&!(LS.catch&&LS.finally))return!0;if(!_c||_c<51||!/native code/.test(s)){var t=new Js(function(a){a(1)}),i=function(a){a(function(){},function(){})},r=t.constructor={};if(r[qM]=i,Oc=t.then(function(){})instanceof i,!Oc)return!0}return!e&&(MS==="BROWSER"||MS==="DENO")&&!DS});BS.exports={CONSTRUCTOR:jM,REJECTION_EVENT:DS,SUBCLASSING:Oc}});var Rr=b((_1,VS)=>{"use strict";var CS=kt(),HM=TypeError,zM=function(s){var e,t;this.promise=new s(function(i,r){if(e!==void 0||t!==void 0)throw new HM("Bad Promise constructor");e=i,t=r}),this.resolve=CS(e),this.reject=CS(t)};VS.exports.f=function(s){return new zM(s)}});var iv=b(()=>{"use strict";var QM=ue(),WM=bt(),xo=So(),oi=se(),GM=$i(),Dr=Ze(),_S=xr(),OS=lc(),YM=js(),KM=Og(),XM=kt(),wo=ae(),JM=ze(),ZM=Fg(),eL=yc(),jS=$c().set,jc=kS(),tL=AS(),iL=To(),rL=Mc(),HS=Kl(),ko=Ni(),Hc=Ar(),zS=Rr(),Po="Promise",QS=Hc.CONSTRUCTOR,sL=Hc.REJECTION_EVENT,aL=Hc.SUBCLASSING,Nc=HS.getterFor(Po),nL=HS.set,$r=ko&&ko.prototype,Fi=ko,Io=$r,WS=oi.TypeError,Fc=oi.document,zc=oi.process,Uc=zS.f,oL=Uc,uL=!!(Fc&&Fc.createEvent&&oi.dispatchEvent),GS="unhandledrejection",lL="rejectionhandled",NS=0,YS=1,cL=2,Qc=1,KS=2,Eo,FS,XS,US,JS=function(s){var e;return JM(s)&&wo(e=s.then)?e:!1},ZS=function(s,e){var t=e.value,i=e.state===YS,r=i?s.ok:s.fail,a=s.resolve,n=s.reject,o=s.domain,u,l,p;try{r?(i||(e.rejection===KS&&pL(e),e.rejection=Qc),r===!0?u=t:(o&&o.enter(),u=r(t),o&&(o.exit(),p=!0)),u===s.promise?n(new WS("Promise-chain cycle")):(l=JS(u))?Dr(l,u,a,n):a(u)):n(t)}catch(c){o&&!p&&o.exit(),n(c)}},ev=function(s,e){s.notified||(s.notified=!0,jc(function(){for(var t=s.reactions,i;i=t.get();)ZS(i,s);s.notified=!1,e&&!s.rejection&&dL(s)}))},tv=function(s,e,t){var i,r;uL?(i=Fc.createEvent("Event"),i.promise=e,i.reason=t,i.initEvent(s,!1,!0),oi.dispatchEvent(i)):i={promise:e,reason:t},!sL&&(r=oi["on"+s])?r(i):s===GS&&tL("Unhandled promise rejection",t)},dL=function(s){Dr(jS,oi,function(){var e=s.facade,t=s.value,i=qS(s),r;if(i&&(r=iL(function(){xo?zc.emit("unhandledRejection",t,e):tv(GS,e,t)}),s.rejection=xo||qS(s)?KS:Qc,r.error))throw r.value})},qS=function(s){return s.rejection!==Qc&&!s.parent},pL=function(s){Dr(jS,oi,function(){var e=s.facade;xo?zc.emit("rejectionHandled",e):tv(lL,e,s.value)})},Mr=function(s,e,t){return function(i){s(e,i,t)}},Lr=function(s,e,t){s.done||(s.done=!0,t&&(s=t),s.value=e,s.state=cL,ev(s,!0))},qc=function(s,e,t){if(!s.done){s.done=!0,t&&(s=t);try{if(s.facade===e)throw new WS("Promise can't be resolved itself");var i=JS(e);i?jc(function(){var r={done:!1};try{Dr(i,e,Mr(qc,r,s),Mr(Lr,r,s))}catch(a){Lr(r,a,s)}}):(s.value=e,s.state=YS,ev(s,!1))}catch(r){Lr({done:!1},r,s)}}};if(QS&&(Fi=function(e){ZM(this,Io),XM(e),Dr(Eo,this);var t=Nc(this);try{e(Mr(qc,t),Mr(Lr,t))}catch(i){Lr(t,i)}},Io=Fi.prototype,Eo=function(e){nL(this,{type:Po,done:!1,notified:!1,parent:!1,reactions:new rL,rejection:!1,state:NS,value:null})},Eo.prototype=_S(Io,"then",function(e,t){var i=Nc(this),r=Uc(eL(this,Fi));return i.parent=!0,r.ok=wo(e)?e:!0,r.fail=wo(t)&&t,r.domain=xo?zc.domain:void 0,i.state===NS?i.reactions.add(r):jc(function(){ZS(r,i)}),r.promise}),FS=function(){var s=new Eo,e=Nc(s);this.promise=s,this.resolve=Mr(qc,e),this.reject=Mr(Lr,e)},zS.f=Uc=function(s){return s===Fi||s===XS?new FS(s):oL(s)},!WM&&wo(ko)&&$r!==Object.prototype)){US=$r.then,aL||_S($r,"then",function(e,t){var i=this;return new Fi(function(r,a){Dr(US,i,r,a)}).then(e,t)},{unsafe:!0});try{delete $r.constructor}catch{}OS&&OS($r,Io)}QM({global:!0,constructor:!0,wrap:!0,forced:QS},{Promise:Fi});XS=GM.Promise;YM(Fi,Po,!1,!0);KM(Po)});var ov=b((F1,nv)=>{"use strict";var hL=xe(),sv=hL("iterator"),av=!1;try{rv=0,Wc={next:function(){return{done:!!rv++}},return:function(){av=!0}},Wc[sv]=function(){return this},Array.from(Wc,function(){throw 2})}catch{}var rv,Wc;nv.exports=function(s,e){try{if(!e&&!av)return!1}catch{return!1}var t=!1;try{var i={};i[sv]=function(){return{next:function(){return{done:t=!0}}}},s(i)}catch{}return t}});var Gc=b((U1,uv)=>{"use strict";var fL=Ni(),mL=ov(),bL=Ar().CONSTRUCTOR;uv.exports=bL||!mL(function(s){fL.all(s).then(void 0,function(){})})});var lv=b(()=>{"use strict";var gL=ue(),SL=Ze(),vL=kt(),yL=Rr(),TL=To(),IL=mo(),EL=Gc();gL({target:"Promise",stat:!0,forced:EL},{all:function(e){var t=this,i=yL.f(t),r=i.resolve,a=i.reject,n=TL(function(){var o=vL(t.resolve),u=[],l=0,p=1;IL(e,function(c){var d=l++,h=!1;p++,SL(o,t,c).then(function(f){h||(h=!0,u[d]=f,--p||r(u))},a)}),--p||r(u)});return n.error&&a(n.value),i.promise}})});var dv=b(()=>{"use strict";var wL=ue(),xL=bt(),kL=Ar().CONSTRUCTOR,Kc=Ni(),PL=Vt(),AL=ae(),RL=xr(),cv=Kc&&Kc.prototype;wL({target:"Promise",proto:!0,forced:kL,real:!0},{catch:function(s){return this.then(void 0,s)}});!xL&&AL(Kc)&&(Yc=PL("Promise").prototype.catch,cv.catch!==Yc&&RL(cv,"catch",Yc,{unsafe:!0}));var Yc});var pv=b(()=>{"use strict";var $L=ue(),ML=Ze(),LL=kt(),DL=Rr(),BL=To(),CL=mo(),VL=Gc();$L({target:"Promise",stat:!0,forced:VL},{race:function(e){var t=this,i=DL.f(t),r=i.reject,a=BL(function(){var n=LL(t.resolve);CL(e,function(o){ML(n,t,o).then(i.resolve,r)})});return a.error&&r(a.value),i.promise}})});var hv=b(()=>{"use strict";var _L=ue(),OL=Rr(),NL=Ar().CONSTRUCTOR;_L({target:"Promise",stat:!0,forced:NL},{reject:function(e){var t=OL.f(this),i=t.reject;return i(e),t.promise}})});var Xc=b((K1,fv)=>{"use strict";var FL=Pt(),UL=ze(),qL=Rr();fv.exports=function(s,e){if(FL(s),UL(e)&&e.constructor===s)return e;var t=qL.f(s),i=t.resolve;return i(e),t.promise}});var gv=b(()=>{"use strict";var jL=ue(),HL=Vt(),mv=bt(),zL=Ni(),bv=Ar().CONSTRUCTOR,QL=Xc(),WL=HL("Promise"),GL=mv&&!bv;jL({target:"Promise",stat:!0,forced:mv||bv},{resolve:function(e){return QL(GL&&this===WL?zL:this,e)}})});var Sv=b(()=>{"use strict";iv();lv();dv();pv();hv();gv()});var Iv=b(()=>{"use strict";var YL=ue(),KL=bt(),Ao=Ni(),XL=be(),yv=Vt(),Tv=ae(),JL=yc(),vv=Xc(),ZL=xr(),Zc=Ao&&Ao.prototype,eD=!!Ao&&XL(function(){Zc.finally.call({then:function(){}},function(){})});YL({target:"Promise",proto:!0,real:!0,forced:eD},{finally:function(s){var e=JL(this,yv("Promise")),t=Tv(s);return this.then(t?function(i){return vv(e,s()).then(function(){return i})}:s,t?function(i){return vv(e,s()).then(function(){throw i})}:s)}});!KL&&Tv(Ao)&&(Jc=yv("Promise").prototype.finally,Zc.finally!==Jc&&ZL(Zc,"finally",Jc,{unsafe:!0}));var Jc});var wv=b((rj,Ev)=>{"use strict";Mg();Sv();Iv();var tD=ri();Ev.exports=tD("Promise","finally")});var kv=b((sj,xv)=>{"use strict";var iD=wv();xv.exports=iD});var Ro=b((aj,Pv)=>{"use strict";var rD=kv();Pv.exports=rD});var Qv=b(()=>{"use strict";var MD=ue(),LD=mr(),DD=Tr(),BD=Cs(),CD=Vs();MD({target:"Array",proto:!0},{at:function(e){var t=LD(this),i=DD(t),r=BD(e),a=r>=0?r:i+r;return a<0||a>=i?void 0:t[a]}});CD("at")});var Gv=b((nH,Wv)=>{"use strict";Qv();var VD=ri();Wv.exports=VD("Array","at")});var Kv=b((oH,Yv)=>{"use strict";var _D=Gv();Yv.exports=_D});var Ge=b((uH,Xv)=>{"use strict";var OD=Kv();Xv.exports=OD});var Ld=b((TW,Hy)=>{"use strict";var UB=Ai();Hy.exports=Array.isArray||function(e){return UB(e)==="Array"}});var Qy=b((IW,zy)=>{"use strict";var qB=TypeError,jB=9007199254740991;zy.exports=function(s){if(s>jB)throw qB("Maximum allowed index exceeded");return s}});var Yy=b((EW,Gy)=>{"use strict";var HB=Ld(),zB=Tr(),QB=Qy(),WB=gr(),Wy=function(s,e,t,i,r,a,n,o){for(var u=r,l=0,p=n?WB(n,o):!1,c,d;l<i;)l in t&&(c=p?p(t[l],l,e):t[l],a>0&&HB(c)?(d=zB(c),u=Wy(s,e,c,d,u,a-1)-1):(QB(u+1),s[u]=c),u++),l++;return u};Gy.exports=Wy});var Zy=b((wW,Jy)=>{"use strict";var Ky=Ld(),GB=vc(),YB=ze(),KB=xe(),XB=KB("species"),Xy=Array;Jy.exports=function(s){var e;return Ky(s)&&(e=s.constructor,GB(e)&&(e===Xy||Ky(e.prototype))?e=void 0:YB(e)&&(e=e[XB],e===null&&(e=void 0))),e===void 0?Xy:e}});var tT=b((xW,eT)=>{"use strict";var JB=Zy();eT.exports=function(s,e){return new(JB(s))(e===0?0:e)}});var iT=b(()=>{"use strict";var ZB=ue(),eC=Yy(),tC=kt(),iC=mr(),rC=Tr(),sC=tT();ZB({target:"Array",proto:!0},{flatMap:function(e){var t=iC(this),i=rC(t),r;return tC(e),r=sC(t,0),r.length=eC(r,t,t,i,0,1,e,arguments.length>1?arguments[1]:void 0),r}})});var rT=b(()=>{"use strict";var aC=Vs();aC("flatMap")});var aT=b(($W,sT)=>{"use strict";iT();rT();var nC=ri();sT.exports=nC("Array","flatMap")});var oT=b((MW,nT)=>{"use strict";var oC=aT();nT.exports=oC});var Wi=b((LW,uT)=>{"use strict";var uC=oT();uT.exports=uC});var fa=b((WW,pT)=>{"use strict";var cC=qs(),dC=String;pT.exports=function(s){if(cC(s)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return dC(s)}});var Bd=b((GW,hT)=>{"use strict";hT.exports=`
|
|
7
|
+
\v\f\r \u2028\u2029\uFEFF`});var bT=b((YW,mT)=>{"use strict";var pC=ge(),hC=ii(),fC=fa(),Vd=Bd(),fT=pC("".replace),mC=RegExp("^["+Vd+"]+"),bC=RegExp("(^|[^"+Vd+"])["+Vd+"]+$"),Cd=function(s){return function(e){var t=fC(hC(e));return s&1&&(t=fT(t,mC,"")),s&2&&(t=fT(t,bC,"$1")),t}};mT.exports={start:Cd(1),end:Cd(2),trim:Cd(3)}});var yT=b((KW,vT)=>{"use strict";var gC=Zl().PROPER,SC=be(),gT=Bd(),ST="
";vT.exports=function(s){return SC(function(){return!!gT[s]()||ST[s]()!==ST||gC&&gT[s].name!==s})}});var _d=b((XW,TT)=>{"use strict";var vC=bT().start,yC=yT();TT.exports=yC("trimStart")?function(){return vC(this)}:"".trimStart});var ET=b(()=>{"use strict";var TC=ue(),IT=_d();TC({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==IT},{trimLeft:IT})});var xT=b(()=>{"use strict";ET();var IC=ue(),wT=_d();IC({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==wT},{trimStart:wT})});var PT=b((i2,kT)=>{"use strict";xT();var EC=ri();kT.exports=EC("String","trimLeft")});var RT=b((r2,AT)=>{"use strict";var wC=PT();AT.exports=wC});var MT=b((s2,$T)=>{"use strict";var xC=RT();$T.exports=xC});var CT=b(()=>{"use strict"});var VT=b(()=>{"use strict"});var OT=b((U2,_T)=>{"use strict";var AC=ze(),RC=Ai(),$C=xe(),MC=$C("match");_T.exports=function(s){var e;return AC(s)&&((e=s[MC])!==void 0?!!e:RC(s)==="RegExp")}});var UT=b((q2,FT)=>{"use strict";var LC=se(),DC=be(),NT=LC.RegExp,BC=!DC(function(){var s=!0;try{NT(".","d")}catch{s=!1}var e={},t="",i=s?"dgimsy":"gimsy",r=function(u,l){Object.defineProperty(e,u,{get:function(){return t+=l,!0}})},a={dotAll:"s",global:"g",ignoreCase:"i",multiline:"m",sticky:"y"};s&&(a.hasIndices="d");for(var n in a)r(n,a[n]);var o=Object.getOwnPropertyDescriptor(NT.prototype,"flags").get.call(e);return o!==i||t!==i});FT.exports={correct:BC}});var jT=b((j2,qT)=>{"use strict";var CC=Pt();qT.exports=function(){var s=CC(this),e="";return s.hasIndices&&(e+="d"),s.global&&(e+="g"),s.ignoreCase&&(e+="i"),s.multiline&&(e+="m"),s.dotAll&&(e+="s"),s.unicode&&(e+="u"),s.unicodeSets&&(e+="v"),s.sticky&&(e+="y"),e}});var QT=b((H2,zT)=>{"use strict";var VC=Ze(),_C=gt(),OC=Rs(),HT=UT(),NC=jT(),FC=RegExp.prototype;zT.exports=HT.correct?function(s){return s.flags}:function(s){return!HT.correct&&OC(FC,s)&&!_C(s,"flags")?VC(NC,s):s.flags}});var GT=b((z2,WT)=>{"use strict";var qd=ge(),UC=mr(),qC=Math.floor,Fd=qd("".charAt),jC=qd("".replace),Ud=qd("".slice),HC=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,zC=/\$([$&'`]|\d{1,2})/g;WT.exports=function(s,e,t,i,r,a){var n=t+s.length,o=i.length,u=zC;return r!==void 0&&(r=UC(r),u=HC),jC(a,u,function(l,p){var c;switch(Fd(p,0)){case"$":return"$";case"&":return s;case"`":return Ud(e,0,t);case"'":return Ud(e,n);case"<":c=r[Ud(p,1,-1)];break;default:var d=+p;if(d===0)return l;if(d>o){var h=qC(d/10);return h===0?l:h<=o?i[h-1]===void 0?Fd(p,1):i[h-1]+Fd(p,1):l}c=i[d-1]}return c===void 0?"":c})}});var XT=b(()=>{"use strict";var QC=ue(),WC=Ze(),Hd=ge(),YT=ii(),GC=ae(),YC=ze(),KC=OT(),Kr=fa(),XC=Ms(),JC=QT(),ZC=GT(),eV=xe(),tV=bt(),iV=eV("replace"),rV=TypeError,jd=Hd("".indexOf),sV=Hd("".replace),KT=Hd("".slice),aV=Math.max;QC({target:"String",proto:!0},{replaceAll:function(e,t){var i=YT(this),r,a,n,o,u,l,p,c,d,h,f=0,m="";if(YC(e)){if(r=KC(e),r&&(a=Kr(YT(JC(e))),!~jd(a,"g")))throw new rV("`.replaceAll` does not allow non-global regexes");if(n=XC(e,iV),n)return WC(n,e,i,t);if(tV&&r)return sV(Kr(i),e,t)}for(o=Kr(i),u=Kr(e),l=GC(t),l||(t=Kr(t)),p=u.length,c=aV(1,p),d=jd(o,u);d!==-1;)h=l?Kr(t(u,d,o)):ZC(u,o,d,[],void 0,t),m+=KT(o,f,d)+h,f=d+p,d=d+c>o.length?-1:jd(o,u,d+c);return f<o.length&&(m+=KT(o,f)),m}})});var ZT=b((G2,JT)=>{"use strict";CT();VT();XT();var nV=ri();JT.exports=nV("String","replaceAll")});var tI=b((Y2,eI)=>{"use strict";var oV=ZT();eI.exports=oV});var rI=b((K2,iI)=>{"use strict";var uV=tI();iI.exports=uV});var aI=b((X2,sI)=>{"use strict";var lV=Cs(),cV=fa(),dV=ii(),pV=RangeError;sI.exports=function(e){var t=cV(dV(this)),i="",r=lV(e);if(r<0||r===1/0)throw new pV("Wrong number of repetitions");for(;r>0;(r>>>=1)&&(t+=t))r&1&&(i+=t);return i}});var cI=b((J2,lI)=>{"use strict";var uI=ge(),hV=$l(),nI=fa(),fV=aI(),mV=ii(),bV=uI(fV),gV=uI("".slice),SV=Math.ceil,oI=function(s){return function(e,t,i){var r=nI(mV(e)),a=hV(t),n=r.length,o=i===void 0?" ":nI(i),u,l;return a<=n||o===""?r:(u=a-n,l=bV(o,SV(u/o.length)),l.length>u&&(l=gV(l,0,u)),s?r+l:l+r)}};lI.exports={start:oI(!1),end:oI(!0)}});var pI=b((Z2,dI)=>{"use strict";var vV=Mi();dI.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(vV)});var hI=b(()=>{"use strict";var yV=ue(),TV=cI().start,IV=pI();yV({target:"String",proto:!0,forced:IV},{padStart:function(e){return TV(this,e,arguments.length>1?arguments[1]:void 0)}})});var mI=b((iG,fI)=>{"use strict";hI();var EV=ri();fI.exports=EV("String","padStart")});var gI=b((rG,bI)=>{"use strict";var wV=mI();bI.exports=wV});var vI=b((sG,SI)=>{"use strict";var xV=gI();SI.exports=xV});var dh="2.0.149-dev.a444d83a.0";var we=(r=>(r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused",r))(we||{}),Ct=(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_FMP4="HLS_FMP4",y.HLS_LIVE="HLS_LIVE",y.HLS_LIVE_CMAF="HLS_LIVE_CMAF",y.WEB_RTC_LIVE="WEB_RTC_LIVE",y))(Ct||{});var ws=(r=>(r.NOT_AVAILABLE="NOT_AVAILABLE",r.AVAILABLE="AVAILABLE",r.CONNECTING="CONNECTING",r.CONNECTED="CONNECTED",r))(ws||{}),Ju=(i=>(i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic",i))(Ju||{});var Zu=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(Zu||{}),Fn=(i=>(i.TRAFFIC_SAVING="traffic_saving",i.HIGH_QUALITY="high_quality",i.UNKNOWN="unknown",i))(Fn||{});var uh=D(Di(),1),Vw=D(ke(),1);import{assertNever as Dm,assertNonNullable as UP,isNonNullable as Gn,ValueSubject as Vl,Subject as qP,Subscription as jP,merge as HP,observableFrom as zP,fromEvent as Rm,map as $m,tap as Mm,filterChanged as QP,isNullable as _l,ErrorCategory as Lm}from"@vkontakte/videoplayer-shared/es2024";var Am=s=>new Promise((e,t)=>{let i=document.createElement("script");i.setAttribute("src",s),i.onload=()=>e(),i.onerror=r=>t(r),document.body.appendChild(i)});var Yn=class{constructor(e){this.connection$=new Vl(void 0);this.castState$=new Vl("NOT_AVAILABLE");this.errorEvent$=new qP;this.realCastState$=new Vl("NOT_AVAILABLE");this.subscription=new jP;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=Gn(window.chrome?.cast),r=!!window.__onGCastApiAvailable;i?this.initializeCastApi():(window.__onGCastApiAvailable=a=>{delete window.__onGCastApiAvailable,a&&!this.isDestroyed&&this.initializeCastApi()},r||Am("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:Lm.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(){Gn(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();_l(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();_l(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(Rm(i,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(r=>{switch(r.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=i.getCurrentSession()?.getMediaSession()?.media?.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return Dm(r.sessionState)}})).add(HP(Rm(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(Mm(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),$m(r=>r.castState)),zP([i.getCastState()])).pipe(QP(),$m(WP),Mm(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{let a=r==="CONNECTED",n=Gn(this.connection$.getValue());if(a&&!n){let o=i.getCurrentSession();UP(o);let u=o.getCastDevice(),l=o.getMediaSession()?.media?.contentId;(_l(l)||l===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:o,castDevice:u}))}else!a&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(r==="CONNECTED"?Gn(this.connection$.getValue())?"CONNECTED":"AVAILABLE":r)}))}initializeCastApi(){let e,t,i;try{e=cast.framework.CastContext.getInstance(),t=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,i=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch{return}try{e.setOptions({receiverApplicationId:this.params.receiverApplicationId??t,autoJoinPolicy:i}),this.initListeners()}catch(r){this.errorEvent$.next({id:"ChromecastInitializer",category:Lm.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:r})}}},WP=s=>{switch(s){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return"NOT_AVAILABLE";case cast.framework.CastState.NOT_CONNECTED:return"AVAILABLE";case cast.framework.CastState.CONNECTING:return"CONNECTING";case cast.framework.CastState.CONNECTED:return"CONNECTED";default:return Dm(s)}};import{assertNonNullable as Fl,combine as Ul,debounce as ql,ErrorCategory as oA,filter as Er,filterChanged as zm,isNonNullable as jl,isNullable as Qm,map as uA,Subscription as lA,ValueSubject as Hl}from"@vkontakte/videoplayer-shared/es2024";import{assertNever as GP,assertNonNullable as Bi,ErrorCategory as YP,getHighestQuality as KP,isNonNullable as Cm}from"@vkontakte/videoplayer-shared/es2024";import{assertNever as Bm}from"@vkontakte/videoplayer-shared/es2024";var ne=(s,e=0,t=0)=>{switch(t){case 0:return s.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case 1:{if(e===0)return s;let i=new URL(s);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}case 2:{let i=new URL(s);return!i.searchParams.get("offset_p")&&e===0?s:(i.searchParams.set("offset_p",e.toFixed(0)),i.toString())}default:Bm(t)}return s},si=(s,e)=>{switch(e){case 0:return NaN;case 1:{let t=new URL(s);return Number(t.searchParams.get("playback_shift"))}case 2:{let t=new URL(s);return Number(t.searchParams.get("offset_p")??0)}default:Bm(e)}};var Xn=s=>{let{source:e,format:t,meta:i,output:r}=s,a,n,o;switch(t){case"MPEG":{let c=e[t];Bi(c);let d=KP(Object.keys(c));Bi(d);let h=c[d];Bi(h),a=h,n="video/mp4",o=Kn();break}case"HLS":case"HLS_FMP4":case"HLS_ONDEMAND":{let c=e[t];Bi(c),a=c.url,n="application/x-mpegurl",o=Kn();break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":{let c=e[t];Bi(c),a=c.url,n="application/dash+xml",o=Kn();break}case"DASH_LIVE_CMAF":{let c=e[t];Bi(c),a=c.url,n="application/dash+xml",o=Vm();break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let c=e[t];Bi(c),a=ne(c.url),n="application/x-mpegurl",o=Vm();break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let c="Unsupported format for Chromecast",d=new Error(c);throw r.error$.next({id:"ChromecastProvider.createMediaInfo()",category:YP.VIDEO_PIPELINE,message:c,thrown:d}),d}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${t} is no longer supported`);default:return GP(t)}let u=XP(i.videoId??a,n);u.contentUrl=a,u.streamType=o,u.metadata=JP();let{title:l,subtitle:p}=i;return Cm(l)&&(u.metadata.title=l),Cm(p)&&(u.metadata.subtitle=p),u};function Kn(){return chrome.cast?.media?.StreamType?.BUFFERED??"BUFFERED"}function Vm(){return chrome.cast?.media?.StreamType?.LIVE??"LIVE"}function XP(s,e){return chrome.cast?.media?.MediaInfo?new chrome.cast.media.MediaInfo(s,e):{contentId:s,contentType:e,metadata:{title:"",subtitle:""},streamType:Kn()}}function JP(){return chrome.cast?.media?.GenericMediaMetadata?new chrome.cast.media.GenericMediaMetadata:{images:[],metadataType:0,releaseDate:"",subtitle:"",title:"",releaseYear:1970,type:0}}var P=(s,e,t=!1)=>{let i=s.getTransition();(t||!i||i.to===e)&&s.setState(e)};var Jn=class{constructor(e){this.interval=0;this.params=e}start(e=0){clearInterval(this.interval),this.startVideoPosition=e,this.startTs=Date.now(),this.interval=window.setInterval(()=>{let t=(Date.now()-this.startTs)/1e3,i=this.startVideoPosition+t;this.params.output.position$.next(i)},1e3)}pause(){clearInterval(this.interval)}destroy(){clearInterval(this.interval)}};import{assertNever as Hm}from"@vkontakte/videoplayer-shared/es2024";var _m=D(ke(),1);var Zn=class{constructor(){this._isMiuiBrowser=!1}get current(){return this._current}get isChrome(){return this.current==="Chrome"}get isChromiumBased(){return(0,_m.default)(["Chrome","Chromium","Opera","Yandex","Edge","SamsungBrowser"],this.current)}get isFirefox(){return this.current==="Firefox"}get isSafari(){return this.current==="Safari"}get isOpera(){return this.current==="Opera"}get isEdge(){return this.current==="Edge"}get isYandex(){return this.current==="Yandex"}get isSamsungBrowser(){return this.current==="SamsungBrowser"}get currentVersion(){return this._current_version}get chromeVersion(){return this._chromeVersion}get firefoxVersion(){return this._firefoxVersion}get safariVersion(){return this._safariVersion}get operaVersion(){return this._operaVersion}get edgeVersion(){return this._edgeVersion}get yandexVersion(){return this._yandexVersion}get isMiuiBrowser(){return this._isMiuiBrowser}detect(){let{userAgent:e}=navigator;try{let t=/yabrowser/i.test(e)?"Yandex":void 0,i=/samsungbrowser/i.test(e)?"SamsungBrowser":void 0,r=/chrome|crios/i.test(e)?"Chrome":void 0,a=/chromium/i.test(e)?"Chromium":void 0,n=/firefox|fxios/i.test(e)?"Firefox":void 0,o=/webkit|safari|khtml/i.test(e)?"Safari":void 0,u=/opr\//i.test(e)?"Opera":void 0,l=/edg/i.test(e)?"Edge":void 0;this._isMiuiBrowser=/(XiaoMi)|(MiuiBrowser)/i.test(e),this._current=t||i||n||u||l||r||a||o||"Rest"}catch(t){console.error(t)}this.isChrome&&this.detectChromeVersion(),this.isFirefox&&this.detectFirefoxVersion(),this.isSafari&&this.detectSafariVersion(),this.isOpera&&this.detectOperaVersion(),this.isEdge&&this.detectEdgeVersion(),this.isYandex&&this.detectYandexVersion()}detectVersion(e){try{let{userAgent:t}=window.navigator,i=t.match(e);if(!i)return;let r=i[1],a=parseInt(r,10);if(!isNaN(a))return this._current_version=a,a}catch(t){console.error(t)}}detectChromeVersion(){this._chromeVersion=this.detectVersion(/Chrome\/(\d+\.\d+)/)}detectFirefoxVersion(){this._firefoxVersion=this.detectVersion(/Firefox\/(\d+\.\d+)/)}detectSafariVersion(){this._safariVersion=this.detectVersion(/Version\/(\d+)/)}detectOperaVersion(){this._operaVersion=this.detectVersion(/OPR\/(\d+\.\d+)/)}detectEdgeVersion(){this._edgeVersion=this.detectVersion(/Edg\/(\d+\.\d+)/)}detectYandexVersion(){this._yandexVersion=this.detectVersion(/YaBrowser\/(\d+\.\d+\.\d+)/)}};var Om=D(ke(),1);var Ci=()=>/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test(navigator.appVersion??navigator.userAgent)||navigator?.userAgentData?.mobile;var eo=class{constructor(e){this._highEntropyValues={};this._os={name:"Unknown",version:"Unknown",full:"Unknown"};this._details={vendor:"Unknown",model:"Unknown"};this._displayChecker=e}get current(){return this._current}get os(){return this._os}get details(){return this._details}get isIOS(){let e=["iPhone","iPad","iPod"];return this._highEntropyValues.platform==="iOS"||this.os.name.toLowerCase().includes("ios")||(0,Om.default)(e,this.current)}get isMac(){return this._highEntropyValues.platform==="macOS"||this.os.name.toLowerCase().includes("mac")||this.current==="Mac"}get isApple(){return this.isIOS||this.isMac}get isIphoneOrOldIpad(){if(!this.isApple||!this._displayChecker.isTouch)return!1;let e=this.current==="iPad"||this._displayChecker.width>700,t=this._iosVersion;return!e||e&&!!t&&t<16}get isAndroid(){return this._highEntropyValues.platform==="Android"||this.os.name.toLowerCase().includes("android")||this.current==="Android"}get isWindows(){return this.os.name.toLowerCase().includes("windows")}get isLinux(){return this.os.name.toLowerCase().includes("linux")&&!this.isAndroid}get isMobile(){return this._highEntropyValues.mobile||this._isMobile}get iOSVersion(){return this._iosVersion}detect(){let{userAgent:e}=navigator;try{this._isMobile=Ci()}catch(t){console.error(t)}this.detectDevice(e),this.detectOS(e),this.detectDeviceDetails(e),this.detectHighEntropyValues(),this.isIOS&&this.detectIOSVersion()}async detectHighEntropyValues(){let{userAgentData:e}=navigator;if(e?.getHighEntropyValues){let t=await e.getHighEntropyValues(["architecture","bitness","brands","mobile","platform","formFactor","model","platformVersion","wow64"]);this._highEntropyValues=t,t.platform&&(this._os.name=this.normalizeOSName(t.platform),t.platformVersion&&(this._os.version=this.normalizeOSVersion(t.platformVersion),this._os.full=`${this._os.name} ${this._os.version}`)),t.model&&(this._details.model=t.model)}}detectDevice(e){try{let t=/android/i.test(e)?"Android":void 0,i=/iphone/i.test(e)?"iPhone":void 0,r=/ipad/i.test(e)?"iPad":void 0,a=/ipod/i.test(e)?"iPod":void 0,n=/mac/i.test(e)?"Mac":void 0,o=/webOS|BlackBerry|IEMobile|Opera Mini/i.test(e)?"RestMobile":void 0;this._current=t||i||r||a||o||n||"Desktop"}catch(t){console.error(t)}}detectOS(e){try{let t=[[/(windows nt) (6\.[23]); arm/i,["Windows RT"]],[/(windows (?:phone|mobile|iot))(?: os)?[/ ]?([\d.]*( se)?)/i,["Windows Mobile",2]],[/(windows)[/ ](1[01]|2000|3\.1|7|8(\.1)?|9[58]|me|server 20\d\d( r2)?|vista|xp)/i,[1,2]],[/windows nt ?([\d.)]*)(?!.+xbox)/i,[2]],[/\bwin(?=3| ?9|n)(?:nt| 9x )?([\d.;]*)/i,[1]],[/(mac os x) ?([\w. ]*)/i,["macOS",2]],[/(macintosh|mac_powerpc\b)(?!.+(haiku|morphos))/i,["macOS"]],[/(?:ios;fbsv|ios(?=.+ip(?:ad|hone))|ip(?:ad|hone)(?: |.+i(?:pad)?)os)[/ ]([\w.]+)/i,["iOS",1]],[/cfnetwork\/.+darwin/i,["iOS"]],[/(android|harmonyos)[/ ]?([\d.]*)/i,[1,2]],[/(linux|ubuntu|debian|fedora|red hat|centos)[-/ ]?([\w.]*)/i,[1,2]],[/(cros) \w+(?:\)| ([\w.]+)\b)/i,["Chrome OS",2]]];for(let[i,r]of t){let a=e.match(i);if(a){let n=r[0],o=r[1],u=typeof n=="number"?a[n]:n,l=typeof o=="number"?a[o]:o;u.toLowerCase().includes("mac")?u="macOS":u.toLowerCase().includes("windows")?u="Windows":u.toLowerCase().includes("android")?u="Android":(u.toLowerCase().includes("ios")||u.toLowerCase().includes("iphone")||u.toLowerCase().includes("ipad"))&&(u="iOS"),l&&(l=l.replace(/_/g,".")),this._os={name:u,version:l||"Unknown",full:l?`${u} ${l}`:u};break}}this._os.name==="Unknown"&&(e.includes("Mac")?this._os={name:"macOS",version:"Unknown",full:"macOS"}:e.includes("Win")?this._os={name:"Windows",version:"Unknown",full:"Windows"}:e.includes("Linux")&&(this._os={name:"Linux",version:"Unknown",full:"Linux"}))}catch(t){console.error("OS detection error:",t)}}detectDeviceDetails(e){try{let t=[[/(ip(hone|od|ad))/i,["Apple",1]],[/(macintosh)/i,["Apple","Macintosh"]],[/\b(sch-i[89]0\d|shw-m380s|sm-[ptx]\w{2,4}|gt-[pn]\d{2,4}|sgh-t8[56]9|nexus 10)/i,["Samsung",1]],[/\b((?:s[cgp]h|gt|sm)-(?![lr])\w+|sc[g-]?[\d]+a?|galaxy nexus)/i,["Samsung",1]],[/samsung[- ]((?!sm-[lr]|browser)[-\w]+)/i,["Samsung",1]],[/sec-(sgh\w+)/i,["Samsung",1]],[/(?:huawei) ?([-\w ]+)[;)]/i,["Huawei",1]],[/\b(nexus 6p|\w{2,4}e?-[atu]?[ln][\dx][\dc][adnt]?)\b(?!.+d\/s)/i,["Huawei",1]],[/\b((?:ag[rs][2356]?k?|bah[234]?|bg[2o]|bt[kv]|cmr|cpn|db[ry]2?|jdn2|got|kob2?k?|mon|pce|scm|sht?|[tw]gr|vrd)-[ad]?[lw][0125][09]b?)/i,["Huawei",1]],[/(redmi[-_ ]?(?:note|k)?[\w_ ]+)(?: bui|\))/i,["Xiaomi",1]],[/\b(mi[-_ ]?(?:a\d|one|one[_ ]plus|note|max|cc)?[_ ]?(?:\d{0,2}\w?)[_ ]?(?:plus|se|lite|pro)?( 5g|lte)?)(?: bui|\))/i,["Xiaomi",1]],[/\b(poco[\w ]+)(?: bui|\))/i,["Xiaomi",1]],[/\b(hm[-_ ]?note?[_ ]?(?:\d\w)?) bui/i,["Xiaomi",1]],[/\b(?:xiao)?((?:red)?mi[-_ ]?pad[\w- ]*)(?: bui|\))/i,["Xiaomi",1]],[/(?:one)?(?:plus)? (a\d0\d\d)(?: b|\))/i,["OnePlus",1]],[/droid.+; (cph2[3-6]\d[13579]|((gm|hd)19|(ac|be|in|kb)20|(d[en]|eb|le|mt)21|ne22)[0-2]\d)(?: bui|\))/i,["OnePlus",1]],[/; (\w+) bui.+ oppo/i,["OPPO",1]],[/\b(cph[12]\d{3}|p(?:af|c[al]|d\w|e[ar])[mt]\d0|x9007|a101op)\b/i,["OPPO",1]],[/\b(opd2(\d{3}a?))(?: bui|\))/i,["OPPO",1]],[/\b(rmx[1-3]\d{3})(?: bui|;|\))/i,["Realme",1]],[/; vivo (\w+)(?: bui|\))/i,["Vivo",1]],[/\b(v[12]\d{3}\w?[at])(?: bui|;)/i,["Vivo",1]],[/\bmot(?:orola)?[- ]([\w\s]+)(\)| bui)/i,["Motorola",1]],[/((?:moto(?! 360)[-\w() ]+|xt\d{3,4}[cgkosw+]?[-\d]*|nexus 6)(?= bui|\)))/i,["Motorola",1]],[/\b(milestone|droid(?:[2-4x]| (?:bionic|x2|pro|razr))?:?( 4g)?)\b/i,["Motorola",1]],[/\b(mz60\d|xoom[2 ]{0,2}) build\//i,["Motorola",1]],[/\blg[-e;/ ]+(?!.*(?:browser|netcast|android tv|watch|webos))(\w+)/i,["LG",1]],[/\blg-?([\d\w]+) bui/i,["LG",1]],[/(lm(?:-?f100[nv]?|-[\w.]+)(?= bui|\))|nexus [45])/i,["LG",1]],[/((?=lg)?[vl]k-?\d{3}) bui/i,["LG",1]],[/droid.+; (a?\d[0-2]{2}so|[c-g]\d{4}|so[-gl]\w+|xq-\w\w\d\d)(?= bui|\))/i,["Sony",1]],[/sony tablet [ps]/i,["Sony","Xperia Tablet"]],[/(sonyericsson)[-_ ]?([-\w]*)/i,["Sony Ericsson",2]],[/\b(?:sony)?sgp\w+(?: bui|\))/i,["Sony",1]],[/(pixel (c|tablet))\b/i,["Google",1]],[/droid.+;(?: google)? (g(01[13]a|020[aem]|025[jn]|1b60|1f8f|2ybb|4s1m|576d|5nz6|8hhn|8vou|a02099|c15s|d1yq|e2ae|ec77|gh2x|kv4x|p4bc|pj41|r83y|tt9q|ur25|wvk6)|pixel[\d ]*a?( pro)?( xl)?( fold)?( \(5g\))?)( bui|\))/i,["Google",1]],[/(google) (pixelbook( go)?)/i,["Google",2]],[/(?:maemo|nokia).*(n900|lumia \d+|rm-\d+)/i,["Nokia",1]],[/nokia[-_ ]?(([-\w. ]*?))( bui|\)|;|\/)/i,["Nokia",1]],[/(nokia) (t[12][01])/i,["Nokia",2]],[/(?:\b|asus_)(transfo[prime ]{4,10} \w+|eeepc|slider \w+|nexus 7|padfone|p00[cj])/i,["ASUS",1]],[/ (z[bes]6[027][012][km][ls]|zenfone \d\w?)\b/i,["ASUS",1]],[/lenovo[-_ ]?([-\w ]+?)(?: bui|\)|\/)/i,["Lenovo",1]],[/(ideatab[-\w ]+|602lv|d-42a|a101lv|a2109a|a3500-hv|s[56]000|pb-6505[my]|tb-?x?\d{3,4}(?:f[cu]|xu|[av])|yt\d?-[jx]?\d+[lfmx])( bui|;|\)|\/)/i,["Lenovo",1]],[/(kf[a-z]{2}wi|aeo(?!bc)\w\w)( bui|\))/i,["Amazon",1]],[/(kf[a-z]+)( bui|\)).+silk\//i,["Amazon",1]],[/(alexa)webm/i,["Amazon","Echo"]],[/((?:sd|kf)[0349hijorstuw]+)( bui|\)).+silk\//i,["Amazon",1]],[/(?:blackberry|\(bb10;) (\w+)/i,["BlackBerry",1]],[/\b((?:bb[a-f]|st[hv])100-\d)/i,["BlackBerry",1]],[/(playbook);[-\w),; ]+(rim)/i,["BlackBerry",1]],[/(zte)[- ]([\w ]+?)(?: bui|\/|\))/i,["ZTE",2]],[/(alcatel|geeksphone|nexian|panasonic)[-_ ]?([-\w]*)/i,[1,2]],[/(htc)[-;_ ]{1,2}([\w ]+(?=\)| bui)|\w+)/i,["HTC",2]],[/(microsoft); (lumia[\w ]+)/i,["Microsoft",2]],[/(surface duo)/i,["Microsoft","Surface Duo"]],[/(dell) (streak)/i,["Dell",2]],[/(hp) ([\w ]+\w)/i,["HP",2]],[/(sharp)\/?([-\w]*)/i,["Sharp",2]],[/(benq)[-_ ]?([-\w]*)/i,["BenQ",2]],[/(palm)[-_ ]?([-\w]*)/i,["Palm",2]],[/(meizu)[-_ ]?([-\w]*)/i,["Meizu",2]],[/(tecno)[-_ ]?([-\w]*)/i,["Tecno",2]],[/(infinix)[-_ ]?([-\w]*)/i,["Infinix",2]],[/(micromax)[-_ ]?([-\w]*)/i,["Micromax",2]],[/(lava)[-_ ]?([-\w]*)/i,["Lava",2]],[/(spice)[-_ ]?([-\w]*)/i,["Spice",2]],[/(fairphone)[-_ ]?([-\w]*)/i,["Fairphone",2]],[/(cat)[-_ ]?([-\w]*)/i,["Cat",2]],[/(energy)[-_ ]?([-\w]*)/i,["Energizer",2]],[/(ulefone)[-_ ]?([-\w]*)/i,["Ulefone",2]],[/(doogee)[-_ ]?([-\w]*)/i,["Doogee",2]],[/(blackview)[-_ ]?([-\w]*)/i,["Blackview",2]],[/(shield \w+ tv)/i,["Nvidia",1]],[/(crkey)/i,["Google","Chromecast"]],[/(roku)[\dx]*[)/]((?:dvp-)?[\d.]*)/i,["Roku",1]],[/(apple) ?tv/i,["Apple","TV"]],[/(amazon) ?tv/i,["Amazon","Fire TV"]]];for(let[i,r]of t){let a=e.match(i);if(a){let n=r[0],o=r[1],u=typeof n=="number"?a[n]:n,l=typeof o=="number"?a[o]:o;this._details.vendor=u,this._details.model=l||"Unknown";break}}}catch(t){console.error("Device details detection error:",t)}}detectIOSVersion(){try{if(this._highEntropyValues.platformVersion){let a=this._highEntropyValues.platformVersion.split(".").slice(0,2).join("."),n=parseFloat(a);this._iosVersion=n;return}let{userAgent:e}=window.navigator,t=e.match(/OS (\d+(_\d+)?)/i);if(!t)return;let i=t[1].replace(/_/g,".");if(!i)return;let r=parseFloat(i);if(isNaN(r))return;this._iosVersion=r}catch(e){console.error(e)}}normalizeOSName(e){let t=e.toLowerCase();return t.includes("mac")?"macOS":t.includes("win")?"Windows":t.includes("linux")?"Linux":t.includes("android")?"Android":t.includes("ios")||t.includes("iphone")?"iOS":e}normalizeOSVersion(e){return e.replace(/_/g,".")}};var to=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 Ve=()=>window.ManagedMediaSource||window.MediaSource,ai=()=>!!(window.ManagedMediaSource&&window.ManagedSourceBuffer?.prototype?.appendBuffer),Nm=()=>!!(window.MediaSource&&window.SourceBuffer?.prototype?.appendBuffer),Ir=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var ZP=document.createElement("video"),eA='video/mp4; codecs="avc1.42000a,mp4a.40.2"',tA='video/mp4; codecs="hev1.1.6.L93.B0"',Fm='video/webm; codecs="vp09.00.10.08"',Um='video/webm; codecs="av01.0.00M.08"',iA='audio/mp4; codecs="mp4a.40.2"',rA='audio/webm; codecs="opus"',qm,sA=async()=>{if(!window.navigator.mediaCapabilities)return;let s={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=await Promise.all([window.navigator.mediaCapabilities.decodingInfo({...s,video:{...s.video,contentType:Um}}),window.navigator.mediaCapabilities.decodingInfo({...s,video:{...s.video,contentType:Fm}})]);qm={DASH_WEBM_AV1:e,DASH_WEBM:t}};sA().catch(s=>{console.log(ZP),console.error(s)});var io=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 qm}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:ai(),mse:Nm(),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=!!Ve()?.isTypeSupported?.(eA),t=!!Ve()?.isTypeSupported?.(tA),i=!!Ve()?.isTypeSupported?.(iA);this._codecs={h264:e,h265:t,vp9:!!Ve()?.isTypeSupported?.(Fm),av1:!!Ve()?.isTypeSupported?.(Um),aac:i,opus:!!Ve()?.isTypeSupported?.(rA),mpeg:(e||t)&&i},this._nativeHlsSupported=this._protocols.hls&&this._containers.mp4}catch(e){console.error(e)}try{this.destroyVideoElement()}catch(e){console.error("Error destroying video element:",e)}}destroyVideoElement(){if(!this._video)return;if(this._video.pause(),this._video.currentTime=0,this._video.removeAttribute("src"),this._video.src="",this._video.load(),this._video.remove){this._video.remove(),this._video=null;return}this._video.parentNode&&this._video.parentNode.removeChild(this._video);let e=this._video.cloneNode(!1);this._video.parentNode?.replaceChild(e,this._video),this._video=null}};var jm="audio/mpeg",ro=class{supportMp3(){return this._codecs.mp3&&this._containers.mpeg}detect(){this._audio=document.createElement("audio");try{this._containers={mpeg:!!this._audio.canPlayType?.(jm)},this._codecs={mp3:!!Ve()?.isTypeSupported?.(jm)}}catch(e){console.error(e)}try{this.destroyAudioElement()}catch(e){console.error("Error destroying audio element:",e)}}destroyAudioElement(){if(!this._audio)return;if(this._audio.pause(),this._audio.currentTime=0,this._audio.removeAttribute("src"),this._audio.src="",this._audio.load(),this._audio.remove){this._audio.remove(),this._audio=null;return}this._audio.parentNode&&this._audio.parentNode.removeChild(this._audio);let e=this._audio.cloneNode(!1);this._audio.parentNode?.replaceChild(e,this._audio),this._audio=null}};import{ValueSubject as aA}from"@vkontakte/videoplayer-shared/es2024";var Ol=class{constructor(){this.isInited$=new aA(!1);this._displayChecker=new to,this._deviceChecker=new eo(this._displayChecker),this._browserChecker=new Zn,this._videoChecker=new io(this._deviceChecker,this._browserChecker),this._audioChecker=new ro,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)}},$=new Ol;var Nl=s=>{let{containers:e,protocols:t,codecs:i,nativeHlsSupported:r}=$.video,a=(i.h264||i.h265)&&i.aac,n=t.mse||t.mms;return s.filter(o=>{switch(o){case"DASH_SEP":return n&&e.mp4&&a;case"DASH_WEBM":return n&&e.webm&&i.vp9&&i.opus;case"DASH_WEBM_AV1":return n&&e.webm&&i.av1&&i.opus;case"DASH_STREAMS":return n&&(e.mp4&&a||e.webm&&(i.vp9||i.av1)&&(i.opus||i.aac));case"DASH_LIVE":return n&&e.mp4&&a;case"DASH_LIVE_CMAF":return n&&e.mp4&&a&&e.cmaf;case"DASH_ONDEMAND":return n&&e.mp4&&a;case"HLS":case"HLS_ONDEMAND":case"HLS_FMP4":case"HLS_LIVE":case"HLS_LIVE_CMAF":return r;case"MPEG":return e.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return t.webrtc&&t.ws&&i.h264&&(e.mp4||e.webm);default:return Hm(o)}})},_s=s=>{switch(s){case"MPEG":case"DASH":case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":case"HLS":case"HLS_FMP4":case"HLS_ONDEMAND":return!1;case"DASH_LIVE":case"DASH_LIVE_CMAF":case"HLS_LIVE":case"HLS_LIVE_CMAF":case"DASH_LIVE_WEBM":case"WEB_RTC_LIVE":return!0;default:return Hm(s)}},nA=s=>{let t=Object.keys(s).filter(i=>!_s(i));return Nl(t).length>0};var Os=class{constructor(e){this.subscription=new lA;this.sessionId$=new Hl(null);this.mediaSessionId$=new Hl(null);this.contentId$=new Hl(null);this.isMobile=Ci();this.mobileVolumeState={muted:!1,volume:0};this.media=null;this.lastRequestedVolume=null;this.syncMediaState=e=>{if(Qm(e))return;this.media=e,this.mediaSessionId$.next(e.mediaSessionId??null);let t=e.media?.contentId;t&&this.contentId$.next(t),this.syncPlaybackState(e);let i=e.media?.duration;jl(i)&&this.params.output.duration$.next(Math.max(0,i));let r=e.currentTime;if(jl(r)){this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.params.output.position$.next(r);let n=this.params.output.isLive$.getValue();e.playerState==="PLAYING"&&!n?this.progressTicker.start(r):this.progressTicker.pause()}};this.params=e,this.progressTicker=new Jn(e),this.log=this.params.dependencies.logger.createComponentLog("ChromecastPresentationApiProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(_s(e.format)),this.subscribe()}subscribe(){let e=r=>{this.params.output.error$.next({category:oA.WTF,id:"ChromecastPresentationApiProvider",message:r?.message??"Unknown error",thrown:r})};this.subscription.add(this.params.chromecastConnector.message$.pipe(Er(r=>!!r)).subscribe(r=>{this.handleMessage(r)},e)),this.subscription.add(this.sessionId$.pipe(Er(jl),zm(),ql(0)).subscribe(()=>{this.loadMedia()},e));let t=this.contentId$.pipe(zm(),uA(Boolean));this.subscription.add(Ul({seekState:this.params.desiredState.seekState.stateChangeEnded$,mediaLoaded:t}).pipe(Er(({mediaLoaded:r})=>r)).subscribe(()=>{let r=this.params.desiredState.seekState.getState();r.state==="requested"&&this.seek(r.position/1e3)},e));let i=Ul({playbackState:this.params.desiredState.playbackState.stateChangeStarted$,mediaLoaded:t});this.subscription.add(i.pipe(Er(({mediaLoaded:r})=>r),ql(0)).subscribe(()=>{this.syncPlayback()},e)),this.subscription.add(i.pipe(Er(({mediaLoaded:r,playbackState:{from:a,to:n}})=>!r&&a==="stopped"&&n==="playing")).subscribe(()=>{this.loadMedia()},e)),this.subscription.add(Ul({volumeState:this.params.desiredState.volume.stateChangeStarted$.pipe(ql(30)),mediaLoaded:t}).pipe(Er(({mediaLoaded:r})=>r)).subscribe(({volumeState:r})=>{let{muted:a,volume:n}=r.to;this.setVolume(n,a)},e))}handleMessage(e){switch(e.type){case"new_session":case"update_session":{this.sessionId$.next(e.message.sessionId);let t=e.message?.media?.[0];this.syncMediaState(t);let i=e.message?.receiver.volume;this.syncVolumeState(i)}break;case"v2_message":{switch(e.message?.type){case"MEDIA_STATUS":{let t=e.message?.status?.[0];this.syncMediaState(t);break}}break}}}loadMedia(){let e=Xn(this.params),t=this.media?.currentTime,i=this.params.desiredState.seekState.getState(),r=t??(i.state!=="none"?i.position/1e3:0),n=this.params.desiredState.playbackState.getState()==="playing";this.params.chromecastConnector.sendV2Message({type:"LOAD",requestId:0,media:e,autoplay:n,currentTime:r,customData:null,activeTrackIds:null}),this.params.output.willSeekEvent$.next()}stop(){this.params.chromecastConnector.stopMedia()}play(){let e=this.mediaSessionId$.getValue();Fl(e,"play on null mediaSessionId"),this.params.chromecastConnector.sendV2Message({type:"PLAY",mediaSessionId:e,customData:null})}pause(){let e=this.mediaSessionId$.getValue();Fl(e,"pause on null mediaSessionId"),this.params.chromecastConnector.sendV2Message({type:"PAUSE",mediaSessionId:e,customData:null})}seek(e){let t=this.mediaSessionId$.getValue();Fl(t,"seek on null mediaSessionId"),this.params.chromecastConnector.sendV2Message({type:"SEEK",currentTime:e,mediaSessionId:t}),this.params.output.willSeekEvent$.next()}setVolume(e,t){let i=e,r=`[setVolume] volume: ${e}, muted: ${t}`;this.isMobile&&(i=this.mobileVolumeState.volume,r+=`, mobile next volume: ${i}`),this.log({message:r}),this.lastRequestedVolume={volume:i,muted:t},this.params.chromecastConnector.sendV2Message({type:"SET_VOLUME",requestId:0,volume:{level:t?0:i,muted:t?!0:null}})}syncPlaybackState({playerState:e,idleReason:t}){let i=this.params.output.isBuffering$.getValue(),r=e==="BUFFERING";switch(i!==r&&this.params.output.isBuffering$.next(r),e){case"PAUSED":P(this.params.desiredState.playbackState,"paused");break;case"PLAYING":P(this.params.desiredState.playbackState,"playing");break;case"IDLE":{t==="FINISHED"?(this.params.output.endedEvent$.next(),P(this.params.desiredState.playbackState,"stopped"),this.contentId$.next(null)):P(this.params.desiredState.playbackState,"ready");break}case"BUFFERING":break}}syncPlayback(){let e=this.params.desiredState.playbackState.getState();switch(this.log({message:`[syncPlayback] ${e}`}),e){case"ready":break;case"playing":this.play();break;case"paused":this.pause();break;case"stopped":this.stop();break}}syncVolumeState(e){if(Qm(e))return;let{level:t,muted:i}=e,r={muted:i??!1,volume:t??0};this.lastRequestedVolume&&(i&&(r.volume=this.lastRequestedVolume.volume),this.lastRequestedVolume.muted&&!t&&!i&&(r.volume=this.lastRequestedVolume.volume,r.muted=!0),this.lastRequestedVolume=null);let a=`[syncVolumeState] volume: ${r.volume}, muted: ${r.muted}`;this.isMobile&&(this.mobileVolumeState.volume=r.volume,this.mobileVolumeState.muted=r.muted,r.volume=this.params.output.volume$.getValue().volume,a+=`, volume passed to state machine: ${r.volume}`),this.log({message:a}),this.params.output.volume$.next(r)}destroy(){this.progressTicker.destroy(),this.subscription.unsubscribe()}};import{assertNonNullable as cA,ErrorCategory as zl,filter as dA,Subject as pA,Subscription as Ql,tap as hA,ValueSubject as wr,fromEvent as Ns}from"@vkontakte/videoplayer-shared/es2024";var Wm=s=>({castDevice:{friendlyName:s},remotePlayer:{},remotePlayerController:{},session:{}}),Gm=()=>String(Date.now())+String(Math.floor(Math.random()*1e5));var Fs=class{constructor(e){this.capabilities=["WEB"];this.presentationRequest$=new wr(null);this.sessionId$=new wr(null);this.broadcastChannel=new BroadcastChannel("vk_player_chromecast_events");this.subscription=new Ql;this.subscriptionEvents=new Ql;this.isDestroyed=!1;this.sequenceNumber=0;this.presentationAvailable$=new wr(!1);this.presentationConnection$=new wr(null);this.message$=new wr(null);this.friendlyName$=new wr(null);this.errorEvent$=new pA;this.clientId=this.getClientId(),this.params=e,this.log=e.logger.createComponentLog("ChromecastPresentationApiConnector"),this.log({message:"constructor"}),this.reinitPresentation(),this.subscribe()}destroy(){this.log({message:"destroy"}),this.subscription.unsubscribe(),this.subscriptionEvents.unsubscribe(),this.broadcastChannel.close(),this.isDestroyed=!0}disconnect(e=!0){this.log({message:"disconnect"}),e&&this.stopMedia(),this.presentationRequest$.next(null);let t=this.presentationConnection$.getValue();t&&t.close(),this.presentationConnection$.next(null),this.friendlyName$.next(null),this.resetSequenceNumber(),this.resetSubscriptionEvents()}stopMedia(){this.log({message:"stopMedia"}),this.sendV2Message({type:"STOP"})}reinitPresentation(e=!0){let t=this.createCastUrl(),i=new PresentationRequest(t);this.presentationRequest$.next(i),this.log({message:"PresentationRequest created"}),i.getAvailability().then(r=>{let a=()=>{this.log({message:`PresentationRequest presentation availability: ${r.value}`}),this.presentationAvailable$.next(r.value)};this.subscriptionEvents.add(Ns(r,"change").subscribe(()=>{a()})),a()}).catch(()=>{this.presentationAvailable$.next(!0)}),window.navigator.presentation.defaultRequest=i,e&&i.reconnect("auto-join").then(r=>{this.log({message:"PresentationRequest reconnect success"}),this.handleConnection(r)}).catch(()=>{this.log({message:"PresentationRequest reconnect failed"})})}async connect(){this.log({message:"connect"});try{this.presentationRequest$.getValue()||(this.log({message:"reinitPresentation"}),this.reinitPresentation(!1));let e=this.presentationRequest$.getValue();cA(e,"connect with null presentationRequest");let t=await e.start();this.handleConnection(t)}catch(e){switch(e?.name){case"AbortError":case"NotAllowedError":break;default:this.errorEvent$.next({category:zl.WTF,id:"ChromecastPresentationApiConnector",message:e?.message??"connect error",thrown:e});break}}}subscribe(){this.subscription.add(Ns(this.broadcastChannel,"message").subscribe(e=>{this.log({message:`broadcast connection data: ${e.data}`}),e.data==="connection"&&this.disconnect(!1)})),this.subscription.add(this.presentationAvailable$.subscribe(e=>{this.log({message:`presentationAvailable$: ${e}`})})),this.subscription.add(this.presentationConnection$.pipe(hA(e=>{this.log({message:`presentationConnection$: ${!!e}`})}),dA(e=>!!e)).subscribe(e=>{let t=Ns(e,"message").subscribe(a=>{let n=JSON.parse(a.data);n.clientId===this.clientId&&(this.log({message:`[onmessage] ${a.data}`}),this.handleMessage(n),this.message$.next(n))}),i=Ns(e,"connect").subscribe(()=>{this.send("client_connect")}),r=Ns(e,"close").subscribe(a=>{switch(a.reason){case"error":this.errorEvent$.next({category:zl.WTF,id:"ChromecastPresentationApiConnector",message:"Session error",thrown:a});break;case"closed":break}});this.subscriptionEvents.add(t),this.subscriptionEvents.add(i),this.subscriptionEvents.add(r)}))}send(e){switch(e){case"client_connect":{let t={type:"client_connect",message:this.clientId,sequenceNumber:-1,timeoutMillis:0,clientId:this.clientId};this.safeSend(JSON.stringify(t));break}}}sendV2Message(e){let t=this.sessionId$.getValue();if(t){let i={type:"v2_message",sequenceNumber:this.getSequenceNumber(),timeoutMillis:0,clientId:this.clientId,message:{...e,sessionId:t}};this.safeSend(JSON.stringify(i))}}safeSend(e){try{this.log({message:`[send] ${e}`});let t=this.presentationConnection$.getValue();t?.state==="connected"&&t?.send(e)}catch(t){this.errorEvent$.next({category:zl.WTF,id:"ChromecastPresentationApiConnector",message:"PresentationConnection send error",data:{message:e},thrown:t})}}handleMessage(e){switch(e.type){case"new_session":case"update_session":{this.sessionId$.next(e.message.sessionId),this.friendlyName$.next(e.message.receiver.friendlyName||"Chromecast Device");break}case"receiver_action":e.message?.action==="stop"&&this.disconnect();break}}createCastUrl(){return`cast:${this.params.appId}?clientId=${this.clientId}&autoJoinPolicy=tab_and_origin_scoped&defaultActionPolicy=create_session&launchTimeout=60000&supportedAppTypes=${this.capabilities}&appParams=%7B%22launchCheckerParams%22%3A%7B%7D%7D`}getSequenceNumber(){let e=this.sequenceNumber;return this.sequenceNumber=(this.sequenceNumber+1)%Number.MAX_SAFE_INTEGER,e}resetSequenceNumber(){this.sequenceNumber=0}getClientId(){let e="__vk_player_chromecast_id";return window[e]=window[e]||Gm()}resetSubscriptionEvents(){this.subscriptionEvents.unsubscribe(),this.subscriptionEvents=new Ql}handleConnection(e){this.log({message:"connection available"}),this.isDestroyed?(this.log({message:"connected on already destroyed component"}),e.close()):(this.broadcastChannel.postMessage("connection"),this.presentationConnection$.next(e))}};import{ValueSubject as Ym,Subject as fA,map as mA,Subscription as bA,combine as gA,filterChanged as Km,assertNonNullable as SA}from"@vkontakte/videoplayer-shared/es2024";var _t=class s{constructor(e){this.subscription=new bA;this.connection$=new Ym(void 0);this.castState$=new Ym("NOT_AVAILABLE");this.errorEvent$=new fA;let t=s.isSupported();this.log=e.dependencies.logger.createComponentLog("ChromecastPresentationApiInitializer"),this.log({message:`[constructor] receiverApplicationId: ${e.receiverApplicationId}, isDisabled: ${e.isDisabled}, isSupported: ${t}`}),!(!t||e.isDisabled||!e.receiverApplicationId)&&(this.chromecastConnector=new Fs({appId:e.receiverApplicationId,logger:e.dependencies.logger}),this.subscribe())}static isSupported(){return"chrome"in window&&"presentation"in navigator&&"BroadcastChannel"in window}subscribe(){SA(this.chromecastConnector,"subscribe with null chromecastConnector"),this.subscription.add(this.chromecastConnector.errorEvent$.subscribe(this.errorEvent$));let e=gA({connection:this.chromecastConnector.presentationConnection$,available:this.chromecastConnector.presentationAvailable$,friendlyName:this.chromecastConnector.friendlyName$.pipe(Km())});this.subscription.add(e.pipe(mA(({connection:t,friendlyName:i})=>!!(t&&i)),Km()).subscribe(t=>{let i=this.chromecastConnector?.friendlyName$.getValue()??"";this.connection$.next(t?Wm(i):void 0)})).add(e.subscribe(({available:t,connection:i})=>{t?i?this.castState$.next("CONNECTED"):this.castState$.next("AVAILABLE"):this.castState$.next("NOT_AVAILABLE")}))}connect(){this.log({message:"connect"}),this.chromecastConnector?.connect()}disconnect(){this.log({message:"disconnect"}),this.chromecastConnector?.disconnect()}async stopMedia(){this.log({message:"stopMedia"}),this.chromecastConnector?.stopMedia()}toggleConnection(){let e=!!this.chromecastConnector?.presentationConnection$.getValue();this.log({message:`toggleConnection: isConnected - ${e}`}),e?this.disconnect():this.connect()}setVolume(e){}setMuted(e){}destroy(){this.log({message:"destroy"}),this.chromecastConnector?.destroy(),this.subscription.unsubscribe()}};var Jp=D(ke(),1),Zp=D(ni(),1),mw=D(fc(),1);var Dv=D(Ro(),1);import{isNonNullable as sD,Subject as $o,merge as Av}from"@vkontakte/videoplayer-shared/es2024";var O=class{constructor(e){this.transitionStarted$=new $o;this.transitionEnded$=new $o;this.transitionUpdated$=new $o;this.forceChanged$=new $o;this.stateChangeStarted$=Av(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=Av(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||sD(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 Zs,debounce as Rv,ErrorCategory as aD,fromEvent as Ui,map as $v,merge as Mv,observableFrom as nD,Subject as oD,Subscription as ed,timeout as uD}from"@vkontakte/videoplayer-shared/es2024";var lD=5,cD=5,dD=500,Lv=7e3,ea=class{constructor(e){this.subscription=new ed;this.loadMediaTimeoutSubscription=new ed;this.videoState=new O("stopped");this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(a)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.stop());return}if(!t){if(r?.to!=="paused"&&a.state==="requested"&&e!=="stopped"){this.seek(a.position/1e3);return}switch(i){case"ready":{switch(e){case"playing":case"paused":case"ready":break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:Zs(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:Zs(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:Zs(e)}break}default:Zs(i)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(_s(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 ed;this.subscription.add(e),this.subscription.add(Mv(this.videoState.stateChangeStarted$.pipe($v(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe($v(r=>`stateChangeEnded$ ${JSON.stringify(r)}`))).subscribe(r=>this.log({message:`[videoState] ${r}`})));let t=(r,a)=>this.subscription.add(r.subscribe(a));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{let r=new oD;e.add(r.pipe(Rv(dD)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let a=NaN;e.add(Ui(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(n=>{this.logRemoteEvent(n);let o=n.value;this.params.output.position$.next(o),(this.params.desiredState.seekState.getState().state==="applying"||Math.abs(o-a)>lD)&&r.next(o),a=o})),e.add(Ui(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(Ui(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(Ui(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t(Ui(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),r=>{this.logRemoteEvent(r);let{remotePlayer:a}=this.params.connection,n=r.value,o=this.params.output.isBuffering$.getValue(),u=n===chrome.cast.media.PlayerState.BUFFERING;switch(o!==u&&this.params.output.isBuffering$.next(u),n){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&a.duration-a.currentTime<cD&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),P(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:Zs(n)}}),t(Ui(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t(Ui(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});let i=Mv(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,nD(["init"])).pipe(Rv(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"),P(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),P(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=Xn(this.params),i=this.createLoadRequest(t);this.loadMedia(i)}handleRemotePause(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="paused"||e==="playing")&&(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="playing"||e==="paused")&&(this.videoState.setState("playing"),P(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.params.desiredState.playbackState.getTransition()?.to==="ready"&&P(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){let t=this.params.output.volume$.getValue(),i={volume:e.volume??t.volume,muted:e.muted??t.muted};(i.volume!==t.volume||i.muted!==i.muted)&&this.params.output.volume$.next(i)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:i}=this.params.connection;t.currentTime=e,i.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createLoadRequest(e){let t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;let i=this.params.desiredState.seekState.getState();return i.state==="applying"||i.state==="requested"?t.currentTime=this.params.output.isLive$.getValue()?0:i.position/1e3:t.currentTime=0,t}loadMedia(e){let t=this.params.connection.session.loadMedia(e),i=new Promise((r,a)=>{this.loadMediaTimeoutSubscription.add(uD(Lv).subscribe(()=>a(`timeout(${Lv})`)))});(0,Dv.default)(Promise.race([t,i]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},r=>{let a=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${r}`;this.log({message:a}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:aD.VIDEO_PIPELINE,message:a,thrown:r})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var vd=D(ke(),1);import{clearVideoElement as Cv}from"@vkontakte/videoplayer-shared/es2024";import{clearVideoElement as pD}from"@vkontakte/videoplayer-shared/es2024";var Bv=s=>{try{s.pause(),s.playbackRate=0,pD(s),s.remove()}catch(e){console.error(e)}};import{fromEvent as hD,Subscription as fD}from"@vkontakte/videoplayer-shared/es2024";var td=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)}},id=window.WeakMap?new WeakMap:new td,rd=window.WeakMap?new WeakMap:new Map,mD=(s,e=20)=>{let t=0;return hD(s,"ratechange").subscribe(i=>{t++,t>=e&&(s.currentTime=s.currentTime,t=0)})},Pe=(s,{audioVideoSyncRate:e,disableYandexPiP:t})=>{let i=s.querySelector("video"),r=!!i;i?Cv(i):(i=document.createElement("video"),s.appendChild(i)),id.set(i,r);let a=new fD;return a.add(mD(i,e)),rd.set(i,a),i.setAttribute("crossorigin","anonymous"),i.setAttribute("playsinline","playsinline"),t&&i.setAttribute("x-yandex-pip","false"),i.controls=!1,i.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),i},Ae=s=>{rd.get(s)?.unsubscribe(),rd.delete(s);let t=id.get(s);id.delete(s),t?Cv(s):Bv(s)};var ad=D(Di(),1);import{assertNonNullable as ia,isNonNullable as At,isNullable as SD,fromEvent as Br,merge as Vv,observableFrom as _v,filterChanged as Ov,map as ra,Subject as Nv,Subscription as vD,ValueSubject as yD,ErrorCategory as TD}from"@vkontakte/videoplayer-shared/es2024";import{isNonNullable as sd,isNullable as bD,Subscription as gD}from"@vkontakte/videoplayer-shared/es2024";var Mo=(s,e,t,{equal:i=(n,o)=>n===o,changed$:r,onError:a}={})=>{let n=s.getState(),o=e(),u=bD(r),l=new gD;return r&&l.add(r.subscribe(p=>{let c=s.getState();i(p,c)&&s.setState(p)},a)),i(o,n)||(t(n),u&&s.setState(n)),l.add(s.stateChangeStarted$.subscribe(p=>{t(p.to),u&&s.setState(p.to)},a)),l},ot=(s,e,t)=>Mo(e,()=>s.loop,i=>{sd(i)&&(s.loop=i)},{onError:t}),Re=(s,e,t,i)=>Mo(e,()=>({muted:s.muted,volume:s.volume}),r=>{sd(r)&&(s.muted=r.muted,s.volume=r.volume)},{equal:(r,a)=>r===a||r?.muted===a?.muted&&r?.volume===a?.volume,changed$:t,onError:i}),Qe=(s,e,t,i)=>Mo(e,()=>s.playbackRate,r=>{sd(r)&&(s.playbackRate=r)},{changed$:t,onError:i}),ta=Mo;var ID=s=>["__",s.language,s.label].join("|"),ED=(s,e)=>{if(s.id===e)return!0;let[t,i,r]=e.split("|");return s.language===i&&s.label===r},nd=class s{constructor(e){this.available$=new Nv;this.current$=new yD(void 0);this.error$=new Nv;this.subscription=new vD;this.externalTracks=new Map;this.internalTracks=new Map;this.baseURL=e}connect(e,t,i){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();let r=a=>{this.error$.next({id:"TextTracksManager",category:TD.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:a})};this.subscription.add(this.available$.subscribe(i.availableTextTracks$)),this.subscription.add(this.current$.subscribe(i.currentTextTrack$)),this.subscription.add(this.error$.subscribe(i.error$)),this.subscription.add(ta(t.internalTextTracks,()=>(0,ad.default)(this.internalTracks),a=>{At(a)&&this.setInternal(a)},{equal:(a,n)=>At(a)&&At(n)&&a.length===n.length&&a.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(ra(a=>a.filter(({type:n})=>n==="internal"))),onError:r})),this.subscription.add(ta(t.externalTextTracks,()=>(0,ad.default)(this.externalTracks),a=>{At(a)&&this.setExternal(a)},{equal:(a,n)=>At(a)&&At(n)&&a.length===n.length&&a.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(ra(a=>a.filter(({type:n})=>n==="external"))),onError:r})),this.subscription.add(ta(t.currentTextTrack,()=>{if(this.video)return;let a=this.htmlTextTracksAsArray().find(({mode:n})=>n==="showing");return a&&this.htmlTextTrackToITextTrack(a).id},a=>this.select(a),{changed$:this.current$,onError:r})),this.subscription.add(ta(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let a of this.htmlTextTracksAsArray())this.applyCueSettings(a.cues),this.applyCueSettings(a.activeCues)}))}subscribe(){ia(this.video);let{textTracks:e}=this.video;this.subscription.add(Br(e,"addtrack").subscribe(()=>{let i=this.current$.getValue();i&&this.select(i)})),this.subscription.add(Vv(Br(e,"addtrack"),Br(e,"removetrack"),_v(["init"])).pipe(ra(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),Ov((i,r)=>i.length===r.length&&i.every(({id:a},n)=>a===r[n].id))).subscribe(this.available$)),this.subscription.add(Vv(Br(e,"change"),_v(["init"])).pipe(ra(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),ra(i=>i&&this.htmlTextTrackToITextTrack(i).id),Ov()).subscribe(this.current$));let t=i=>this.applyCueSettings(i.target?.activeCues??null);this.subscription.add(Br(e,"addtrack").subscribe(i=>{i.track?.addEventListener("cuechange",t);let r=a=>{let n=a.target?.cues??null;n&&n.length&&(this.applyCueSettings(a.target?.cues??null),a.target?.removeEventListener("cuechange",r))};i.track?.addEventListener("cuechange",r)})),this.subscription.add(Br(e,"removetrack").subscribe(i=>{i.track?.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;let t=this.cueSettings.getState();for(let i of Array.from(e)){let r=i;At(t.align)&&(r.align=t.align),At(t.position)&&(r.position=t.position),At(t.size)&&(r.size=t.size),At(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){ia(this.video);let t=[...this.video.textTracks];return e?t:t.filter(s.isHealthyTrack)}htmlTextTrackToITextTrack(e){let{language:t,label:i}=e,r=e.id?e.id:ID(e),a=this.externalTracks.has(r),n=(a?this.externalTracks.get(r)?.isAuto:this.internalTracks.get(r)?.isAuto)??r.includes("auto");return a?{id:r,type:"external",isAuto:n,language:t,label:i,url:this.externalTracks.get(r)?.url}:{id:r,type:"internal",isAuto:n,language:t,label:i,url:this.internalTracks.get(r)?.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(i=>i.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){let t=[...this.externalTracks];e.filter(({id:i,language:r,isAuto:a})=>!this.internalTracks.has(i)&&!t.some(([,n])=>n.language===r&&n.isAuto===a)).forEach(i=>this.attach(i)),Array.from(this.internalTracks).filter(([i])=>!e.find(r=>r.id===i)).forEach(([,i])=>this.detach(i))}select(e){ia(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(SD(e)||!ED(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){ia(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){ia(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)}},We=nd;var qi=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 Fv=s=>{let e=s;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e?.parentNode;return e??void 0},od=s=>{let e=Fv(s);return!!(e&&e.fullscreenElement&&e.fullscreenElement===s)},Uv=s=>{let e=Fv(s);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===s)};import{fromEvent as _e,map as Rt,merge as Lo,filterChanged as jv,isNonNullable as Hv,Subject as xD,filter as ud,mapTo as ld,combine as kD,once as PD,shareReplay as Oe,throttle as AD,ErrorCategory as RD,ValueSubject as zv,Subscription as $D}from"@vkontakte/videoplayer-shared/es2024";var wD=3,qv=(s,e,t=wD)=>{let i=0,r=0;for(let a=0;a<s.length;a++){let n=s.start(a),o=s.end(a);if(n<=e&&e<=o){if(i=n,r=o,!t)return{from:i,to:r};for(let u=a-1;u>=0;u--)s.end(u)+t>=i&&(i=s.start(u));for(let u=a+1;u<s.length;u++)s.start(u)-t<=r&&(r=s.end(u))}}return{from:i,to:r}};var $e=s=>{let e=k=>_e(s,k).pipe(ld(void 0),Oe(1)),t=new $D,i=()=>t.unsubscribe(),r=Lo(_e(s,"progress"),_e(s,"timeupdate")).pipe(Rt(()=>qv(s.buffered,s.currentTime)),Oe(1)),a=$.browser.isSafari?kD({play:e("play").pipe(PD()),playing:e("playing")}).pipe(ld(void 0),Oe(1)):e("playing"),n=_e(s,"volumechange").pipe(Rt(()=>({muted:s.muted,volume:s.volume})),Oe(1)),o=_e(s,"ratechange").pipe(Rt(()=>s.playbackRate),Oe(1)),u=_e(s,"error").pipe(ud(()=>!!(s.error||s.played.length)),Rt(()=>{let k=s.error;return{id:k?`MediaError#${k.code}`:"HtmlVideoError",category:RD.VIDEO_PIPELINE,message:k?k.message:"Error event from HTML video element",thrown:s.error??void 0}}),Oe(1)),l=_e(s,"timeupdate").pipe(Rt(()=>s.currentTime),Oe(1)),p=["waiting","seeking","seeked","timeupdate"],c=new xD,d=.3,h;t.add(Lo(...p.map(k=>_e(s,k))).subscribe(k=>{let F=s.currentTime;s.loop&&Hv(h)&&Hv(F)&&h>=s.duration-d&&F<=d&&c.next(h),h=F}));let f=e("pause").pipe(ud(()=>!s.error&&h!==s.duration),Oe(1)),m=_e(s,"enterpictureinpicture").pipe(Oe(1)),S=_e(s,"leavepictureinpicture").pipe(Oe(1)),g=new zv(Uv(s));t.add(m.subscribe(()=>g.next(!0))),t.add(S.subscribe(()=>g.next(!1)));let v=new zv(od(s)),T=_e(s,"fullscreenchange").pipe(Oe(1));t.add(T.pipe(Rt(()=>od(s))).subscribe(v));let y=.1,x=1e3,A=_e(s,"timeupdate").pipe(Rt(k=>s.duration-s.currentTime<y),jv(),Oe(1)),R=Lo(A.pipe(ud(k=>!s.loop&&k)),_e(s,"ended")).pipe(AD(x),ld(void 0),Oe(1)),B=Lo(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(k=>_e(s,k)),A.pipe(Rt(k=>({type:k?"ended":"unknown"})))).pipe(Rt(k=>$.browser.isFirefox&&k.type==="ended"?s.readyState<2:s.readyState<3),jv(),Oe(1));return{playing$:a,pause$:f,canplay$:e("canplay"),ended$:R,looped$:c,error$:u,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:l,durationChange$:_e(s,"durationchange").pipe(Rt(()=>s.duration),Oe(1)),isBuffering$:B,currentBuffer$:r,volumeState$:n,playbackRateState$:o,inPiP$:g,inFullscreen$:v,enterPip$:m,leavePip$:S,destroy:i}};import{VideoQuality as ui}from"@vkontakte/videoplayer-shared/es2024";var $t=s=>{switch(s){case"mobile":return ui.Q_144P;case"lowest":return ui.Q_240P;case"low":return ui.Q_360P;case"sd":case"medium":return ui.Q_480P;case"hd":case"high":return ui.Q_720P;case"fullhd":case"full":return ui.Q_1080P;case"quadhd":case"quad":return ui.Q_1440P;case"ultrahd":case"ultra":return ui.Q_2160P}};var Fe=D(Ge(),1),dd=D(ke(),1),Hi=D(ni(),1);import{isNonNullable as K,isNullable as Vo,now as uy,isHigher as _o,isHigherOrEqual as ji,isInvariantQuality as Oo,isLowerOrEqual as Vr,videoSizeToQuality as ly,assertNotEmptyArray as No,assertNonNullable as cy}from"@vkontakte/videoplayer-shared/es2024";var cd=!1,Nt={},Jv=s=>{cd=s},Zv=()=>{Nt={}},ey=s=>{s(Nt)},sa=(s,e)=>{cd&&(Nt.meta=Nt.meta??{},Nt.meta[s]=e)},Ne=class{constructor(e){this.name=e}next(e){if(!cd)return;Nt.series=Nt.series??{};let t=Nt.series[this.name]??[];t.push([Date.now(),e]),Nt.series[this.name]=t}};import{isHigher as ND,isHigherOrEqual as fH,isLower as ty,isLowerOrEqual as mH,isNonNullable as Do,isNullable as FD,videoHeightToQuality as Bo}from"@vkontakte/videoplayer-shared/es2024";function iy(s,e,t){return!s.max&&s.min===e?"high_quality":!s.min&&s.max===t?"traffic_saving":"unknown"}function Cr(s,e,t){return FD(s)||Do(s.min)&&Do(s.max)&&ty(s.max,s.min)||Do(s.min)&&e&&ND(s.min,e)||Do(s.max)&&t&&ty(s.max,t)}function ry({limits:s,highestAvailableHeight:e,lowestAvailableHeight:t}){return Cr({max:s?.max?Bo(s.max):void 0,min:s?.min?Bo(s.min):void 0},e?Bo(e):void 0,t?Bo(t):void 0)}var dy=new Ne("best_bitrate"),Fo=(s,e,t)=>(e-t)*Math.pow(2,-10*s)+t;var _r=s=>(e,t)=>s*(Number(e.bitrate)-Number(t.bitrate)),yt=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=uy()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},Uo='Assertion "ABR Tracks is empty array" failed',Co=new WeakMap,sy=new WeakMap,ay=new WeakMap,zi=(s,e,t,i)=>{let r=[...e].sort(_r(1)),a=[...t].sort(_r(1)),n=a.filter(u=>K(u.bitrate)&&K(s.bitrate)?s.bitrate/u.bitrate>i:!0),o=(0,Fe.default)(a,Math.round(a.length*r.indexOf(s)/(r.length+1)))??(0,Fe.default)(a,-1);return o&&(0,dd.default)(n,o)?o:n.length?(0,Fe.default)(n,-1):(0,Fe.default)(a,0)},Qi=(s,e,t,i)=>{let r=Co.get(e);r||(r=[...e].sort(_r(1)),Co.set(e,r));let a=Co.get(t);a||(a=[...t].sort(_r(1)),Co.set(t,a));let n=ay.get(s);n||(n=a.filter(u=>K(u.bitrate)&&K(s.bitrate)?s.bitrate/u.bitrate>i:!0),ay.set(s,n));let o=(0,Fe.default)(a,Math.round(a.length*r.indexOf(s)/(r.length+1)))??(0,Fe.default)(a,-1);return o&&(0,dd.default)(n,o)?o:n.length?(0,Fe.default)(n,-1):(0,Fe.default)(a,0)},ny=s=>"quality"in s,qo=(s,e,t,i)=>{let r=K(i?.last?.bitrate)&&K(t?.bitrate)&&i.last.bitrate<t.bitrate?s.trackCooldownIncreaseQuality:s.trackCooldownDecreaseQuality,a=t&&i&&i.history[t.id]&&uy()-i.history[t.id]<=r&&(!i.last||t.id!==i.last.id);if(t?.id&&i&&!a&&i.recordSelection(t),a&&i?.last){let n=i.last;i?.recordSwitch(n);let o=ny(n)?"video":"audio",u=ny(n)?n.quality:n.bitrate;return e({message:`
|
|
8
|
+
[last ${o} selected] ${u}
|
|
9
|
+
`}),n}return i?.recordSwitch(t),t},UD=(s,e)=>Math.log(e)/Math.log(s),py=({tuning:s,container:e,limits:t,panelSize:i})=>{let r=s.containerSizeFactor;if(i)return{containerSizeLimit:i,containerSizeFactor:r};if(s.usePixelRatio&&$.display.pixelRatio){let a=$.display.pixelRatio;if(s.pixelRatioMultiplier)r*=s.pixelRatioMultiplier*(a-1)+1;else{let n=s.pixelRatioLogBase,[o=0,u=0,l=0]=s.pixelRatioLogCoefficients,p=UD(n,o*a+u)+l;Number.isFinite(p)&&(r*=p)}}return K(t?.min)&&ji(t.min,s.highQualityLimit)&&(r*=2),{containerSizeLimit:s.limitByContainer&&e&&e.width>0&&e.height>0?{width:e.width*r,height:e.height*r}:void 0,containerSizeFactor:r}},oy=new WeakMap,ut=(s,{container:e,estimatedThroughput:t,tuning:i,limits:r,reserve:a=0,forwardBufferHealth:n,playbackRate:o,current:u,history:l,visible:p,droppedVideoMaxQualityLimit:c,stallsVideoMaxQualityLimit:d,stallsPredictedThroughput:h,abrLogger:f,panelSize:m})=>{No(s,Uo);let{containerSizeFactor:S,containerSizeLimit:g}=py({container:e,tuning:i,limits:r,panelSize:m}),v=i.considerPlaybackRate&&K(o)?o:1,T=oy.get(s);T||(T=s.filter(E=>!Oo(E.quality)).sort((E,I)=>_o(E.quality,I.quality)?-1:1),oy.set(s,T));let y=(0,Fe.default)(T,-1)?.quality,x=(0,Fe.default)(T,0)?.quality,A=Cr(r,x,y),R=v*Fo(n??.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),w={},B=null;for(let E of T){let I=!0;if(g)if(E.size)I=E.size.width<=g.width&&E.size.height<=g.height;else{let z=g&&ly(g);I=z?Vr(E.quality,z):!0}if(!I){w[E.quality]="FitsContainer";continue}let N=h||t,L=K(N)&&isFinite(N)&&K(E.bitrate)?N-a>=E.bitrate*R:!0,H=r?.min===E.quality;if(!L&&!H){w[E.quality]="FitsThroughput";continue}if(i.lazyQualitySwitch&&K(i.minBufferToSwitchUp)&&u&&!Oo(u.quality)&&(n??0)<i.minBufferToSwitchUp&&_o(E.quality,u.quality)){w[E.quality]="Buffer";continue}if(!!c&&ji(E.quality,c)&&!H){w[E.quality]="DroppedFramesLimit";continue}if(!!d&&ji(E.quality,d)&&!H){w[E.quality]="StallsLimit";continue}let Te=A||(Vo(r?.max)||Vr(E.quality,r.max))&&(Vo(r?.min)||ji(E.quality,r.min)),Ie=K(p)&&!p?Vr(E.quality,i.backgroundVideoQualityLimit):!0;if(!Te||!Ie){w[E.quality]="FitsQualityLimits";continue}B||(B=E)}B&&B.bitrate&&dy.next(B.bitrate);let k=B??(0,Fe.default)(T,-1)??s[0],F=l?.last,C=qo(i,f,k,l);return K(l)&&C.quality!==F?.quality&&f({message:`
|
|
10
10
|
[VIDEO TRACKS ABR]
|
|
11
11
|
[available video tracks]
|
|
12
|
-
${
|
|
12
|
+
${s.map(E=>`{ id: ${E.id}, quality: ${E.quality}, bitrate: ${E.bitrate}, size: ${E.size?.width}:${E.size?.height} }`).join(`
|
|
13
13
|
`)}
|
|
14
14
|
|
|
15
15
|
[tuning]
|
|
16
|
-
${(0,
|
|
16
|
+
${(0,Hi.default)(i??{}).map(([E,I])=>`${E}: ${I}`).join(`
|
|
17
17
|
`)}
|
|
18
18
|
|
|
19
19
|
[limit params]
|
|
20
|
-
containerSizeFactor: ${
|
|
21
|
-
containerSizeLimit: ${
|
|
20
|
+
containerSizeFactor: ${S},
|
|
21
|
+
containerSizeLimit: ${g?.width??0} x ${g?.height??0},
|
|
22
22
|
estimatedThroughput: ${t},
|
|
23
23
|
stallsPredictedThroughput: ${h},
|
|
24
|
-
reserve: ${
|
|
25
|
-
playbackRate: ${
|
|
26
|
-
playbackRateFactor: ${
|
|
24
|
+
reserve: ${a},
|
|
25
|
+
playbackRate: ${o},
|
|
26
|
+
playbackRateFactor: ${v},
|
|
27
27
|
forwardBufferHealth: ${n},
|
|
28
|
-
bitrateFactor: ${
|
|
28
|
+
bitrateFactor: ${R},
|
|
29
29
|
minBufferToSwitchUp: ${i.minBufferToSwitchUp},
|
|
30
30
|
droppedVideoMaxQualityLimit: ${c},
|
|
31
31
|
stallsVideoMaxQualityLimit: ${d},
|
|
32
|
-
limitsAreInvalid: ${
|
|
32
|
+
limitsAreInvalid: ${A},
|
|
33
33
|
maxQualityLimit: ${r?.max},
|
|
34
34
|
minQualityLimit: ${r?.min},
|
|
35
35
|
|
|
36
36
|
[limited video tracks]
|
|
37
|
-
${(0,
|
|
37
|
+
${(0,Hi.default)(w).map(([E,I])=>`${E}: ${I}`).join(`
|
|
38
38
|
`)||"All tracks are available"}
|
|
39
39
|
|
|
40
|
-
[best video track] ${
|
|
41
|
-
[selected video track] ${
|
|
42
|
-
`}),
|
|
40
|
+
[best video track] ${B?.quality}
|
|
41
|
+
[selected video track] ${C?.quality}
|
|
42
|
+
`}),C},Or=(s,{container:e,estimatedThroughput:t,tuning:i,limits:r,reserve:a=0,forwardBufferHealth:n,playbackRate:o,current:u,history:l,visible:p,droppedVideoMaxQualityLimit:c,stallsVideoMaxQualityLimit:d,stallsPredictedThroughput:h,abrLogger:f,panelSize:m})=>{No(s,Uo);let{containerSizeFactor:S,containerSizeLimit:g}=py({container:e,tuning:i,limits:r,panelSize:m}),v=i.considerPlaybackRate&&K(o)?o:1,T=s.filter(I=>!Oo(I.quality)).sort((I,N)=>_o(I.quality,N.quality)?-1:1),y=(0,Fe.default)(T,-1)?.quality,x=(0,Fe.default)(T,0)?.quality,A=Cr(r,x,y),R=v*Fo(n??.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),w={},k=T.filter(I=>{let N=!0;if(g)if(I.size)N=I.size.width<=g.width&&I.size.height<=g.height;else{let q=g&&ly(g);N=q?Vr(I.quality,q):!0}if(!N)return w[I.quality]="FitsContainer",!1;let L=h||t,H=K(L)&&isFinite(L)&&K(I.bitrate)?L-a>=I.bitrate*R:!0,X=r?.min===I.quality;if(!H&&!X)return w[I.quality]="FitsThroughput",!1;if(i.lazyQualitySwitch&&K(i.minBufferToSwitchUp)&&u&&!Oo(u.quality)&&(n??0)<i.minBufferToSwitchUp&&_o(I.quality,u.quality))return w[I.quality]="Buffer",!1;if(!!c&&ji(I.quality,c)&&!X)return w[I.quality]="DroppedFramesLimit",!1;if(!!d&&ji(I.quality,d)&&!X)return w[I.quality]="StallsLimit",!1;let Ie=A||(Vo(r?.max)||Vr(I.quality,r.max))&&(Vo(r?.min)||ji(I.quality,r.min)),z=K(p)&&!p?Vr(I.quality,i.backgroundVideoQualityLimit):!0;return!Ie||!z?(w[I.quality]="FitsQualityLimits",!1):!0})[0];k&&k.bitrate&&dy.next(k.bitrate);let F=k??(0,Fe.default)(T,-1)??s[0],C=l?.last,E=qo(i,f,F,l);return K(l)&&E.quality!==C?.quality&&f({message:`
|
|
43
43
|
[VIDEO TRACKS ABR]
|
|
44
44
|
[available video tracks]
|
|
45
|
-
${
|
|
45
|
+
${s.map(I=>`{ id: ${I.id}, quality: ${I.quality}, bitrate: ${I.bitrate}, size: ${I.size?.width}:${I.size?.height} }`).join(`
|
|
46
46
|
`)}
|
|
47
47
|
|
|
48
48
|
[tuning]
|
|
49
|
-
${(0,
|
|
49
|
+
${(0,Hi.default)(i??{}).map(([I,N])=>`${I}: ${N}`).join(`
|
|
50
50
|
`)}
|
|
51
51
|
|
|
52
52
|
[limit params]
|
|
53
|
-
containerSizeFactor: ${
|
|
54
|
-
containerSizeLimit: ${
|
|
53
|
+
containerSizeFactor: ${S},
|
|
54
|
+
containerSizeLimit: ${g?.width??0} x ${g?.height??0},
|
|
55
55
|
estimatedThroughput: ${t},
|
|
56
56
|
stallsPredictedThroughput: ${h},
|
|
57
|
-
reserve: ${
|
|
58
|
-
playbackRate: ${
|
|
59
|
-
playbackRateFactor: ${
|
|
57
|
+
reserve: ${a},
|
|
58
|
+
playbackRate: ${o},
|
|
59
|
+
playbackRateFactor: ${v},
|
|
60
60
|
forwardBufferHealth: ${n},
|
|
61
|
-
bitrateFactor: ${
|
|
61
|
+
bitrateFactor: ${R},
|
|
62
62
|
minBufferToSwitchUp: ${i.minBufferToSwitchUp},
|
|
63
63
|
droppedVideoMaxQualityLimit: ${c},
|
|
64
64
|
stallsVideoMaxQualityLimit: ${d},
|
|
65
|
-
limitsAreInvalid: ${
|
|
65
|
+
limitsAreInvalid: ${A},
|
|
66
66
|
maxQualityLimit: ${r?.max},
|
|
67
67
|
minQualityLimit: ${r?.min},
|
|
68
68
|
|
|
69
69
|
[limited video tracks]
|
|
70
|
-
${(0,
|
|
70
|
+
${(0,Hi.default)(w).map(([I,N])=>`${I}: ${N}`).join(`
|
|
71
71
|
`)||"All tracks are available"}
|
|
72
72
|
|
|
73
|
-
[best video track] ${
|
|
73
|
+
[best video track] ${k?.quality}
|
|
74
74
|
[selected video track] ${E?.quality}
|
|
75
|
-
`}),E},
|
|
75
|
+
`}),E},Nr=(s,e,t,{estimatedThroughput:i,tuning:r,playbackRate:a,forwardBufferHealth:n,history:o,abrLogger:u,stallsPredictedThroughput:l})=>{No(t,Uo);let p=r.considerPlaybackRate&&K(a)?a:1,c=[...t].sort(_r(-1)),d=s.bitrate;cy(d);let h=p*Fo(n??.5,r.bitrateAudioFactorAtEmptyBuffer,r.bitrateAudioFactorAtFullBuffer),f,m=zi(s,e,t,r.minVideoAudioRatio),S=l||i;K(S)&&isFinite(S)&&(f=c.find(T=>K(T.bitrate)&&K(m?.bitrate)?S-d>=T.bitrate*h&&T.bitrate>=m.bitrate:!1)),f||(f=m);let g=o?.last,v=f&&qo(r,u,f,o);return K(o)&&v?.bitrate!==g?.bitrate&&u({message:`
|
|
76
76
|
[AUDIO TRACKS ABR]
|
|
77
77
|
[available audio tracks]
|
|
78
78
|
${t.map(T=>`{ id: ${T.id}, bitrate: ${T.bitrate} }`).join(`
|
|
79
79
|
`)}
|
|
80
80
|
|
|
81
81
|
[tuning]
|
|
82
|
-
${(0,
|
|
82
|
+
${(0,Hi.default)(r??{}).map(([T,y])=>`${T}: ${y}`).join(`
|
|
83
83
|
`)}
|
|
84
84
|
|
|
85
85
|
[limit params]
|
|
86
86
|
estimatedThroughput: ${i},
|
|
87
87
|
stallsPredictedThroughput: ${l},
|
|
88
88
|
reserve: ${d},
|
|
89
|
-
playbackRate: ${
|
|
89
|
+
playbackRate: ${a},
|
|
90
90
|
playbackRateFactor: ${p},
|
|
91
91
|
forwardBufferHealth: ${n},
|
|
92
92
|
bitrateFactor: ${h},
|
|
93
93
|
minBufferToSwitchUp: ${r.minBufferToSwitchUp},
|
|
94
94
|
|
|
95
|
-
[selected audio track] ${
|
|
96
|
-
`}),
|
|
95
|
+
[selected audio track] ${v?.id}
|
|
96
|
+
`}),v},Fr=(s,e,t,{estimatedThroughput:i,tuning:r,playbackRate:a,forwardBufferHealth:n,history:o,abrLogger:u,stallsPredictedThroughput:l})=>{No(t,Uo);let p=r.considerPlaybackRate&&K(a)?a:1,c=sy.get(t);c||(c=[...t].sort(_r(-1)),sy.set(t,c));let d=s.bitrate;cy(d);let h=p*Fo(n??.5,r.bitrateAudioFactorAtEmptyBuffer,r.bitrateAudioFactorAtFullBuffer),f,m=Qi(s,e,t,r.minVideoAudioRatio),S=l||i;K(S)&&isFinite(S)&&(f=c.find(T=>K(T.bitrate)&&K(m?.bitrate)?S-d>=T.bitrate*h&&T.bitrate>=m.bitrate:!1)),f||(f=m);let g=o?.last,v=f&&qo(r,u,f,o);return K(o)&&v?.bitrate!==g?.bitrate&&u({message:`
|
|
97
97
|
[AUDIO TRACKS ABR]
|
|
98
98
|
[available audio tracks]
|
|
99
99
|
${t.map(T=>`{ id: ${T.id}, bitrate: ${T.bitrate} }`).join(`
|
|
100
100
|
`)}
|
|
101
101
|
|
|
102
102
|
[tuning]
|
|
103
|
-
${(0,
|
|
103
|
+
${(0,Hi.default)(r??{}).map(([T,y])=>`${T}: ${y}`).join(`
|
|
104
104
|
`)}
|
|
105
105
|
|
|
106
106
|
[limit params]
|
|
107
107
|
estimatedThroughput: ${i},
|
|
108
108
|
stallsPredictedThroughput: ${l},
|
|
109
109
|
reserve: ${d},
|
|
110
|
-
playbackRate: ${
|
|
110
|
+
playbackRate: ${a},
|
|
111
111
|
playbackRateFactor: ${p},
|
|
112
112
|
forwardBufferHealth: ${n},
|
|
113
113
|
bitrateFactor: ${h},
|
|
114
114
|
minBufferToSwitchUp: ${r.minBufferToSwitchUp},
|
|
115
115
|
|
|
116
|
-
[selected audio track] ${
|
|
117
|
-
`}),S};var Se=a=>new URL(a).hostname;import{assertNever as zv,assertNonNullable as Yv,combine as YL,debounce as KL,ErrorCategory as Kv,filter as Xv,filterChanged as XL,isNonNullable as hc,map as Jn,merge as Jv,observableFrom as JL,once as ZL,Subscription as eM,ValueSubject as fc,videoQualityToHeight as Zv,videoSizeToQuality as tM}from"@vkontakte/videoplayer-shared/es2024";var Hv=C(nt(),1);var Fv=C(xe(),1),Ov=a=>{if(a instanceof DOMException&&(0,Fv.default)(["Failed to load because no supported source was found.","The element has no supported sources."],a.message))throw a;return!(a instanceof DOMException&&(a.code===20||a.name==="AbortError"))},_e=async(a,e)=>{let t=a.muted;try{await a.play()}catch(i){if(!Ov(i))return!1;if(e&&e(),t)return console.warn(i),!1;a.muted=!0;try{await a.play()}catch(r){return Ov(r)&&(a.muted=!1,console.warn(r)),!1}}return!0};import{isNonNullable as Kn,isNullable as LL,assertNonNullable as ya}from"@vkontakte/videoplayer-shared/es2024";var qv=C(hi(),1);import{isNonNullable as Nv,assertNonNullable as Yn,now as RL}from"@vkontakte/videoplayer-shared/es2024";function he(){return RL()}function lc(a){return he()-a}function cc(a){let e=a.split("/"),t=e.slice(0,e.length-1).join("/"),i=/^([a-z]+:)?\/\//i,r=n=>i.test(n);return{resolve:(n,u,o=!1)=>{r(n)||(n.startsWith("/")||(n="/"+n),n=t+n);let l=n.indexOf("?")>-1?"&":"?";return o&&(n+=l+"lowLat=1",l="&"),u&&(n+=l+"_rnd="+Math.floor(999999999*Math.random())),n}}}function Uv(a,e,t){let i=(...r)=>{t.apply(null,r),a.removeEventListener(e,i)};a.addEventListener(e,i)}function fr(a,e,t,i){let r=window.XMLHttpRequest,s,n,u,o=!1,l=0,p,c,d=!1,h="arraybuffer",f=7e3,m=2e3,g=()=>{if(o)return;Yn(p);let B=lc(p),E;if(B<m){E=m-B,setTimeout(g,E);return}m*=2,m>f&&(m=f),n&&n.abort(),n=new r,P()},v=B=>(s=B,F),S=B=>(c=B,F),T=()=>(h="json",F),y=()=>{if(!o){if(--l>=0){g(),i&&i();return}o=!0,c&&c(),t&&t()}},A=B=>(d=B,F),P=()=>{p=he(),n=new r,n.open("get",a);let B=0,E,I=0,N=()=>(Yn(p),Math.max(p,Math.max(E||0,I||0)));if(s&&n.addEventListener("progress",$=>{let U=he();s.updateChunk&&$.loaded>B&&(s.updateChunk(N(),$.loaded-B),B=$.loaded,E=U)}),u&&(n.timeout=u,n.addEventListener("timeout",()=>y())),n.addEventListener("load",()=>{if(o)return;Yn(n);let $=n.status;if($>=200&&$<300){let{response:U,responseType:K}=n,te=U?.byteLength;if(typeof te=="number"&&s){let ne=te-B;ne&&s.updateChunk&&s.updateChunk(N(),ne)}K==="json"&&(!U||!(0,qv.default)(U).length)?y():(c&&c(),e(U))}else y()}),n.addEventListener("error",()=>{y()}),d){let $=()=>{Yn(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(I=he(),n.removeEventListener("readystatechange",$))};n.addEventListener("readystatechange",$)}return n.responseType=h,n.send(),F},F={withBitrateReporting:v,withParallel:A,withJSONResponse:T,withRetryCount:B=>(l=B,F),withRetryInterval:(B,E)=>(Nv(B)&&(m=B),Nv(E)&&(f=E),F),withTimeout:B=>(u=B,F),withFinally:S,send:P,abort:()=>{n&&(n.abort(),n=void 0),o=!0,c&&c()}};return F}var va=class{constructor(e){this.intervals=[];this.currentRate=0;this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,i){return{start:e,end:t,bytes:i}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;let e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-500;if(t-e>2e3){let i=0,r=0;for(;this.intervals.length>0;){let s=this.intervals[0];if(s.end<=t)i+=s.end-s.start,r+=s.bytes,this.intervals.splice(0,1);else{if(s.start>=t)break;{let n=t-s.start,u=s.end-s.start;i+=n;let o=s.bytes*n/u;r+=o,s.start=t,s.bytes-=o}}}if(r>0&&i>0){let s=r*8/(i/1e3);return this._updateRate(s),this.logger(`rate updated, new=${Math.round(s/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(r)}/${Math.round(i)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,i){return this.intervals.push(this._createInterval(e,t,i)),this._joinIntervals(),this.intervals.length>100&&(this.logger(`too many intervals (${this.intervals.length}); will merge`,{type:"warn"}),this._doMergeIntervals(this.intervals[1],this.intervals[0]),this.intervals.splice(0,1)),this._flushIntervals()}getBitRate(){return this.currentRate}};var jv=C(hi(),1);var Sa=class{constructor(e,t,i,r,s){this.pendingQueue=[];this.activeRequests={};this.completeRequests={};this.averageSegmentDuration=2e3;this.lastPrefetchStart=0;this.throttleTimeout=null;this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=i,this.MAX_PARALLEL_REQUESTS=r,this.logger=s}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){let t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){let i=he(),r=o=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=o,e._errorCB?e._errorCB(o):(this.limitCompleteCount(),this.completeRequests[t]=e)},s=o=>{e._complete=1,e._responseData=o,e._downloadTime=he()-i,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(o,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=()=>{e._finallyCB&&e._finallyCB()},u=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=fr(t,s,()=>r("error"),u),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(n),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=he()}_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=he();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,jv.default)(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,i,r){let s={};return s.send=()=>{let n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=i,n._retryCB=r,n._finallyCB=s._finallyCB,n._error||n._complete?(this._removeFromActive(e),setTimeout(()=>{n._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(n._responseData,n._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),i(n._errorMsg)),s._finallyCB&&s._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{let u=this.pendingQueue.indexOf(e);u!==-1&&this.pendingQueue.splice(u,1),this.logger(`Request not prefetched, starting new request, url=${e}${u===-1?"":"; removed pending"}`),this._sendRequest(s,e)}},s._cb=t,s._errorCB=i,s._retryCB=r,s.abort=function(){s.request&&s.request.abort()},s.withFinally=n=>(s._finallyCB=n,s),s}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}};import{Subject as ML}from"@vkontakte/videoplayer-shared/es2024";var Xn=1e4,dc=3;var DL=6e4,CL=10,BL=1,VL=500,Ta=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 ML,this.chunkRateEstimator=new va(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=cc(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setAutoQualityLimits(e){this.autoQualityLimits=e}switchByName(e){let t;for(let i=0;i<this.manifest.length;++i)if(t=this.manifest[i],t.name===e){this._switchToQuality(t);return}}catchUp(){if(this.rep&&this.rep.stop(),this.currentManifestEntry){let e=this.params.playbackState.getState();this.paused=e==="paused",this._initPlayerWith(this.currentManifestEntry),this._notifyBuffering(!0)}}stop(){this.params.videoElement.pause(),this.rep&&(this.rep.stop(),this.rep=null)}pause(){this.paused=!0,this.params.videoElement.pause(),this.videoPlayStarted=!1,this._notifyBuffering(!1)}play(){this.paused=!1;let e=this.lowLatency&&this._getBufferSizeSec()>this.sourceJitter+5;this.rep&&!e?(this.bufferStates=[],this.videoPlayStarted=!1,this.shouldPlay()?this._playVideoElement():this._notifyBuffering(!0)):this.catchUp()}startPlay(e,t){this.autoQuality=t,this._initPlayerWith(e)}destroy(){this.destroyed=!0,this.rep&&(this.rep.stop(),this.rep=null),this.manifestRequest&&this.manifestRequest.abort(),this.manifestRefetchTimer&&(clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=void 0)}reinit(e){this.manifestUrl=e,this.urlResolver=cc(e),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){let e=this.params.videoElement,t=0,i=e.buffered.length;return i!==0&&(t=e.buffered.end(i-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){let{videoElement:e,logger:t}=this.params;e.addEventListener("error",()=>{!!e.error&&!this.destroyed&&(t(`Video element error: ${e.error?.code}, details: ${e.error?.message}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{let i=this._getBufferSizeSec();!this.paused&&i<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(i+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){let{logger:e,videoElement:t}=this.params,i=t.buffered.length,r;i!==0&&!this.waitingForFirstBufferAfterSrcChange&&(r=t.buffered.start(i-1),t.currentTime<r&&(e("Fixup stall"),t.currentTime=r))}_selectQuality(e){let{videoElement:t}=this.params,i,r,s,n=t&&1.62*(D.display.pixelRatio||1)*t.offsetHeight||520;for(let u=0;u<this.manifest.length;++u){s=this.manifest[u];let{max:o,min:l}=this.autoQualityLimits||{};!Pv({limits:this.autoQualityLimits,highestAvailableHeight:this.manifest[0].video.height,lowestAvailableHeight:(0,Hv.default)(this.manifest,-1).video.height})&&(o&&s.video.height>o||l&&s.video.height<l)||(s.bitrate<e&&n>Math.min(s.video.height,s.video.width)?(!r||s.bitrate>r.bitrate)&&(r=s):(!i||i.bitrate>s.bitrate)&&(i=s))}return r||i}shouldPlay(){if(this.paused)return!1;let t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||Kn(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){let{logger:i,videoElement:r,playerCallback:s}=this.params;this.mediaSource=new window.MediaSource,i("setting video src"),r.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,r.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});let n=()=>{Uv(r,"progress",()=>{r.buffered.length?(r.currentTime=r.buffered.start(0),this.waitingForFirstBufferAfterSrcChange=!1,s({name:"playing"})):n()})};this.waitingForFirstBufferAfterSrcChange=!0,n()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new Sa(dc,Xn,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:i,playerCallback:r}=this.params,s=!1,n=null,u=null,o=null,l=null,p=!1,c=()=>{let y=s&&(!p||p===this.rep);return y||t("Not running!"),y},d=(y,A,P)=>{o&&o.abort(),o=fr(this.urlResolver.resolve(y,!1),A,P,()=>this._retryCallback()).withTimeout(Xn).withBitrateReporting(this.bitrateSwitcher).withRetryCount(dc).withFinally(()=>{o=null}).send()},h=(y,A,P)=>{ya(this.filesFetcher),u?.abort(),u=this.filesFetcher.requestData(this.urlResolver.resolve(y,!1),A,P,()=>this._retryCallback()).withFinally(()=>{u=null}).send()},f=y=>{let A=i.playbackRate;i.playbackRate!==y&&(t(`Playback rate switch: ${A}=>${y}`),i.playbackRate=y)},m=y=>{this.lowLatency=y,t(`lowLatency changed to ${y}`),g()},g=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)f(1);else{let y=this._getBufferSizeSec();if(this.bufferStates.length<5){f(1);return}let P=he()-1e4,L=0;for(let M=0;M<this.bufferStates.length;M++){let x=this.bufferStates[M];y=Math.min(y,x.buf),x.ts<P&&L++}this.bufferStates.splice(0,L),t(`update playback rate; minBuffer=${y} drop=${L} jitter=${this.sourceJitter}`);let w=y-BL;this.sourceJitter>=0?w-=this.sourceJitter/2:this.sourceJitter-=1,w>3?f(1.15):w>1?f(1.1):w>.3?f(1.05):f(1)}},v=y=>{let A,P=()=>A&&A.start?A.start.length:0,L=$=>A.start[$]/1e3,w=$=>A.dur[$]/1e3,M=$=>A.fragIndex+$,x=($,U)=>({chunkIdx:M($),startTS:L($),dur:w($),discontinuity:U}),F=()=>{let $=0;if(A&&A.dur){let U=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,K=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,te=U;this.sourceJitter>1&&(te+=this.sourceJitter-1);let ne=A.dur.length-1;for(;ne>=0&&(te-=A.dur[ne],!(te<=0));--ne);$=Math.min(ne,A.dur.length-1-K),$=Math.max($,0)}return x($,!0)},B=$=>{let U=P();if(!(U<=0)){if(Kn($)){for(let K=0;K<U;K++)if(L(K)>$)return x(K)}return F()}},E=$=>{let U=P(),K=$?$.chunkIdx+1:0,te=K-A.fragIndex;if(!(U<=0)){if(!$||te<0||te-U>CL)return t(`Resync: offset=${te} bChunks=${U} chunk=`+JSON.stringify($)),F();if(!(te>=U))return x(K-A.fragIndex,!1)}},I=($,U,K)=>{l&&l.abort(),l=fr(this.urlResolver.resolve($,!0,this.lowLatency),U,K,()=>this._retryCallback()).withTimeout(Xn).withRetryCount(dc).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:($,U)=>{I(y,K=>{if(!c())return;A=K;let te=!!A.lowLatency;te!==this.lowLatency&&m(te);let ne=0;for(let me=0;me<A.dur.length;++me)ne+=A.dur[me];ne>0&&(ya(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(ne/A.dur.length)),r({name:"index",zeroTime:A.zeroTime,shiftDuration:A.shiftDuration}),this.sourceJitter=A.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,A.jitter/1e3)):1,$(B(U))},()=>this._handleNetworkError())},nextChunk:E}},S=()=>{s=!1,u&&u.abort(),o&&o.abort(),l&&l.abort(),ya(this.filesFetcher),this.filesFetcher.abortAll()};return p={start:y=>{let{videoElement:A,logger:P}=this.params,L=v(e.jidxUrl),w,M,x,F,B=0,E,I,N,$=()=>{E&&(clearTimeout(E),E=void 0);let q=Math.max(VL,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),ge=B+q,Ie=he(),ce=Math.min(1e4,ge-Ie);B=Ie;let Qe=()=>{l||c()&&L.seek(()=>{c()&&(B=he(),U(),$())})};ce>0?E=window.setTimeout(()=>{this.paused?$():Qe()},ce):Qe()},U=()=>{let q;for(;q=L.nextChunk(F);)F=q,be(q);let ge=L.nextChunk(x);if(ge){if(x&&ge.discontinuity){P("Detected discontinuity; restarting playback"),this.paused?$():(S(),this._initPlayerWith(e));return}me(ge)}else $()},K=(q,ge)=>{if(!c()||!this.sourceBuffer)return;let Ie,ce,Qe,_t=ct=>{window.setTimeout(()=>{c()&&K(q,ge)},ct)};if(this.sourceBuffer.updating)P("Source buffer is updating; delaying appendBuffer"),_t(100);else{let ct=he(),Oe=A.currentTime;!this.paused&&A.buffered.length>1&&I===Oe&&ct-N>500&&(P("Stall suspected; trying to fix"),this._fixupStall()),I!==Oe&&(I=Oe,N=ct);let Ot=this._getBufferSizeSec();if(Ot>30)P(`Buffered ${Ot} seconds; delaying appendBuffer`),_t(2e3);else try{this.sourceBuffer.appendBuffer(q),this.videoPlayStarted?(this.bufferStates.push({ts:ct,buf:Ot}),g(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),ge&&ge()}catch(dt){if(dt.name==="QuotaExceededError")P("QuotaExceededError; delaying appendBuffer"),Qe=this.sourceBuffer.buffered.length,Qe!==0&&(Ie=this.sourceBuffer.buffered.start(0),ce=Oe,ce-Ie>4&&this.sourceBuffer.remove(Ie,ce-3)),_t(1e3);else throw dt}}},te=()=>{M&&w&&(P([`Appending chunk, sz=${M.byteLength}:`,JSON.stringify(x)]),K(M,function(){M=null,U()}))},ne=q=>e.fragUrlTemplate.replace("%%id%%",q.chunkIdx),me=q=>{c()&&h(ne(q),(ge,Ie)=>{if(c()){if(Ie/=1e3,M=ge,x=q,n=q.startTS,Ie){let ce=Math.min(10,q.dur/Ie);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*ce:ce}te()}},()=>this._handleNetworkError())},be=q=>{c()&&(ya(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(ne(q),!1)))},j=q=>{c()&&(e.cachedHeader=q,K(q,()=>{w=!0,te()}))};s=!0,L.seek(q=>{if(c()){if(B=he(),!q){$();return}F=q,!LL(y)||q.startTS>y?me(q):(x=q,U())}},y),e.cachedHeader?j(e.cachedHeader):d(e.headerUrl,j,()=>this._handleNetworkError())},stop:S,getTimestampSec:()=>n},p}_switchToQuality(e){let{logger:t,playerCallback:i}=this.params,r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),Kn(r)&&(r+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,ya(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return Kn(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,i=c=>{if(!this.autoQuality)return;let d,h,f;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&c<this.bitrate&&(h=this._getBufferSizeSec(),f=c/this.bitrate,h>10&&f>.8||h>15&&f>.5||h>20&&f>.3)){e(`Not switching: buffer=${Math.floor(h)}; bitrate=${this.bitrate}; newRate=${Math.floor(c)}`);return}d=this._selectQuality(c),d?this._switchToQuality(d):e(`Could not find quality by bitrate ${c}`)},s={updateChunk:(d,h)=>{let f=he();if(this.chunkRateEstimator.addInterval(d,f,h)){let g=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:h,duration:f-d,speed:g}),!0}},get:()=>{let d=this.chunkRateEstimator.getBitRate();return d?d*.85:0}},n=-1/0,u,o=!0,l=()=>{let c=s.get();if(c&&u&&this.autoQuality){if(o&&c>u&&lc(n)<3e4)return;i(c)}o=this.autoQuality};return{updateChunk:(c,d)=>{let h=s.updateChunk(c,d);return h&&l(),h},notifySwitch:c=>{let d=he();c<u&&(n=d),u=c}}}_fetchManifest(e,t,i){this.manifestRequest=fr(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(Xn).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;_e(e,()=>{this.soundProhibitedEvent$.next()}).then(t=>{t||(this.params.liveOffset.pause(),this.params.videoState.setState("paused"))})}_handleManifestUpdate(e){let{logger:t,playerCallback:i,videoElement:r}=this.params,s=n=>{let u=[];return n?.length?(n.forEach((o,l)=>{o.video&&r.canPlayType(o.codecs).replace(/no/,"")&&window.MediaSource?.isTypeSupported?.(o.codecs)&&(o.index=l,u.push(o))}),u.sort(function(o,l){return o.video&&l.video?l.video.height-o.video.height:l.bitrate-o.bitrate}),u):(i({name:"error",type:"empty_manifest"}),[])};this.manifest=s(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),i({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},DL))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var Gv=C(fi(),1);import{debounce as _L,filter as Wv,fromEvent as OL,interval as FL,isHigher as NL,isInvariantQuality as qL,isLower as UL,merge as jL,Subject as Qv,Subscription as HL}from"@vkontakte/videoplayer-shared/es2024";var pc=class{constructor(){this.onDroopedVideoFramesLimit$=new Qv;this.subscription=new HL;this.playing=!1;this.tracks=[];this.forceChecker$=new Qv;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&&!qL(e.quality)&&this.onChangeQuality(e.quality)};this.checkDroppedFrames=()=>{let{totalVideoFrames:e,droppedVideoFrames:t}=this.video.getVideoPlaybackQuality(),i=e-this.prevTotalVideoFrames,r=t-this.prevDroppedVideoFrames,s=1-(i-r)/i;!isNaN(s)&&s>0&&this.log({message:`[dropped]. current dropped percent: ${s}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(s)&&s>=this.droppedFramesChecker.percentLimit&&NL(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(OL(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=FL(this.droppedFramesChecker.checkTime).pipe(Wv(()=>this.playing),Wv(()=>{let r=!!this.isForceCheckCounter;return r&&(this.isForceCheckCounter-=1),!r})),t=this.forceChecker$.pipe(_L(this.droppedFramesChecker.checkTime)),i=jL(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,Gv.default)(this.limitCounts).filter(([,i])=>i>=this.droppedFramesChecker.countLimit).sort(([i],[r])=>UL(i,r)?-1:1)?.[0]?.[0];return e??t}get isEnabled(){return this.droppedFramesChecker.enabled&&this.isDroppedFramesCheckerSupport}get isDroppedFramesCheckerSupport(){return!!this.video&&typeof this.video.getVideoPlaybackQuality=="function"}savePrevFrameCounts(e,t){this.prevTotalVideoFrames=e,this.prevDroppedVideoFrames=t}},mr=pc;import{map as WL,Observable as QL}from"@vkontakte/videoplayer-shared/es2024";import{fromEvent as GL}from"@vkontakte/videoplayer-shared/es2024";var Ia=()=>!!window.documentPictureInPicture?.window||!!document.pictureInPictureElement;var zL=(a,e)=>new QL(t=>{if(!window.IntersectionObserver)return;let i={root:null},r=new IntersectionObserver((n,u)=>{n.forEach(o=>t.next(o.isIntersecting||Ia()))},{...i,...e});r.observe(a);let s=GL(document,"visibilitychange").pipe(WL(n=>!document.hidden||Ia())).subscribe(n=>t.next(n));return()=>{r.unobserve(a),s.unsubscribe()}}),Ke=zL;var iM=["paused","playing","ready"],rM=["paused","playing","ready"],Ea=class{constructor(e){this.subscription=new eM;this.videoState=new O("stopped");this.representations$=new fc([]);this.droppedFramesManager=new mr;this.maxSeekBackTime$=new fc(1/0);this.zeroTime$=new fc(void 0);this.liveOffset=new Ii;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:Kv.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{let t=e.manifest,i=[];for(let r of t){let s=r.name??r.index.toString(10),n=Qt(r.name)??tM(r.video),u=r.bitrate/1e3,o={...r.video};if(!n)continue;let l={id:s,quality:n,bitrate:u,size:o};i.push({track:l,representation:r})}this.representations$.next(i),this.params.output.availableVideoTracks$.next(i.map(({track:r})=>r)),this.videoState.getTransition()?.to==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let t=e.quality,i=this.representations$.getValue().find(({representation:r})=>r===t)?.track;this.params.output.hostname$.next(new URL(t.headerUrl,this.params.source.url).hostname),hc(i)&&this.params.output.currentVideoTrack$.next(i);break}case"bandwidth":{let{size:t,duration:i}=e;this.params.dependencies.throughputEstimator.addRawSpeed(t,i);break}case"index":{this.maxSeekBackTime$.next(e.shiftDuration||0),this.zeroTime$.next(e.zeroTime);break}}};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; seekState: ${JSON.stringify(s)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"));return}if(t)return;let n=this.params.desiredState.videoTrack.getTransition(),u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if((0,mc.default)(rM,e)&&(n||u)){this.prepare();return}if(r?.to!=="paused"&&s.state==="requested"&&(0,mc.default)(iM,e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(ae(this.params.source.url));return;case"manifest_ready":this.videoState.startTransitionTo("ready"),this.prepare();break;case"ready":if(i==="paused")this.videoState.setState("paused");else if(i==="playing"){this.videoState.startTransitionTo("playing");let o=r?.from;o&&o==="ready"&&this.dash.catchUp(),this.dash.play()}return;case"playing":i==="paused"&&(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.dash.pause());return;case"paused":if(i==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.dash.play(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let o=this.liveOffset.getTotalOffset();o>=this.maxSeekBackTime$.getValue()&&(o=0,this.liveOffset.resetTo(o)),this.liveOffset.resume(),this.params.output.position$.next(-o/1e3),this.dash.reinit(ae(this.params.source.url,o))}return;default:return zv(e)}};this.textTracksManager=new Ye(e.source.url),this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=r=>{e.output.error$.next({id:"DashLiveProvider",category:Kv.WTF,message:"DashLiveProvider internal logic error",thrown:r})};this.subscription.add(Jv(this.videoState.stateChangeStarted$.pipe(Jn(r=>({transition:r,type:"start"}))),this.videoState.stateChangeEnded$.pipe(Jn(r=>({transition:r,type:"end"})))).subscribe(({transition:r,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(r)}`})})),this.video=De(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(Se(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=Ve(this.video);this.subscription.add(()=>i.destroy()),this.subscription.add(this.representations$.pipe(Jn(r=>r.map(({track:s})=>s)),Xv(r=>!!r.length),ZL()).subscribe(r=>this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:r}))),this.subscription.add(i.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready")},t)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused")},t)).add(i.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.videoState.setState("playing")},t)).add(i.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(XL(),Jn(r=>-r/1e3)).subscribe(this.params.output.duration$)).add(YL({zeroTime:this.zeroTime$.pipe(Xv(hc)),position:i.timeUpdate$}).subscribe(({zeroTime:r,position:s})=>this.params.output.liveTime$.next(r+s*1e3),t)).add(bt(this.video,this.params.desiredState.isLooped,t)).add(Be(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(ze(this.video,this.params.desiredState.playbackRate,i.playbackRateState$,t)).add(i.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(i.loadedMetadata$.subscribe(this.params.output.loadedMetadataEvent$)).add(i.playing$.subscribe(this.params.output.firstFrameEvent$)).add(i.canplay$.subscribe(this.params.output.canplay$)).add(i.inPiP$.subscribe(this.params.output.inPiP$)).add(i.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(Ke(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:r,min:s}})=>{this.dash.setAutoQualityLimits({max:r&&Zv(r),min:s&&Zv(s)}),this.params.output.autoVideoTrackLimits$.next({max:r,min:s})})).add(this.videoState.stateChangeEnded$.subscribe(r=>{switch(r.to){case"stopped":this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState("stopped");break;case"manifest_ready":case"ready":this.params.desiredState.playbackState.getTransition()?.to==="ready"&&this.params.desiredState.playbackState.setState("ready");break;case"paused":this.params.desiredState.playbackState.setState("paused");break;case"playing":this.params.desiredState.playbackState.setState("playing");break;default:return zv(r.to)}},t)).add(Jv(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,JL(["init"])).pipe(KL(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),Ce(this.video)}createLiveDashPlayer(){let e=new Ta({videoElement:this.video,videoState:this.videoState,playbackState:this.params.desiredState.playbackState,liveOffset:this.liveOffset,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode,manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){let e=this.representations$.getValue(),t=this.params.desiredState.videoTrack.getTransition()?.to??this.params.desiredState.videoTrack.getState(),i=this.params.desiredState.autoVideoTrackSwitching.getTransition()?.to??this.params.desiredState.autoVideoTrackSwitching.getState(),r=!i&&hc(t)?t:St(e.map(({track:l})=>l),{container:this.video.getBoundingClientRect(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),s=r?.id,n=this.params.desiredState.videoTrack.getTransition(),u=this.params.desiredState.videoTrack.getState()?.id,o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(r&&(n||s!==u)&&this.setVideoTrack(r),o&&this.setAutoQuality(i),n||o||s!==u){let l=e.find(({track:p})=>p.id===s)?.representation;Yv(l,"Representations missing"),this.dash.startPlay(l,i)}}setVideoTrack(e){let t=this.representations$.getValue().find(({track:i})=>i.id===e.id)?.representation;Yv(t,`No such representation ${e.id}`),this.dash.switchByName(t.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),r=t==="paused"&&i==="paused",s=-e,n=s<=this.maxSeekBackTime$.getValue()?s:0;this.params.output.position$.next(e/1e3),this.dash.reinit(ae(this.params.source.url,n)),r&&this.dash.pause(),this.liveOffset.resetTo(n,r)}};var eS=Ea;var ye=(a,e)=>{let t=0;for(let i=0;i<a.length;i++){let r=a.start(i)*1e3,s=a.end(i)*1e3;r<=e&&e<=s&&(t=s)}return Math.max(t-e,0)};import{assertNever as YC,assertNonNullable as KC,combine as XC,debounce as JC,ErrorCategory as gT,filter as Xc,filterChanged as cs,fromEvent as ZC,isNonNullable as vT,isNullable as eB,map as ds,merge as ps,observableFrom as Po,once as ST,Subscription as tB,throttle as iB}from"@vkontakte/videoplayer-shared/es2024";var{NativeAbortSignal:qU,NativeAbortController:UU}=function(a){return{NativeAbortSignal:a.AbortSignal,NativeAbortController:a.AbortController}}(typeof self<"u"?self:global);function tS(a){let e;try{e=new Event("abort")}catch{typeof document<"u"?document.createEvent?(e=document.createEvent("Event"),e.initEvent("abort",!1,!1)):(e=document.createEventObject(),e.type="abort"):e={type:"abort",bubbles:!1,cancelable:!1}}return e.reason=a,e}function iS(a){if(a===void 0)if(typeof document>"u")a=new Error("This operation was aborted"),a.name="AbortError";else try{a=new DOMException("signal is aborted without reason"),Object.defineProperty(a,"name",{value:"AbortError"})}catch{a=new Error("This operation was aborted"),a.name="AbortError"}return a}var Zn=class{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,i){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:i})}removeEventListener(e,t){if(!(e in this.listeners))return;let i=this.listeners[e];for(let r=0,s=i.length;r<s;r++)if(i[r].callback===t){i.splice(r,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;let i=this.listeners[e.type].slice();for(let r=0,s=i.length;r<s;r++){let n=i[r];try{n.callback.call(this,e)}catch(u){Promise.resolve().then(()=>{throw u})}n.options&&n.options.once&&this.removeEventListener(e.type,n.callback)}return!e.defaultPrevented}},br=class extends Zn{constructor(){super(),this.listeners||Zn.call(this),Object.defineProperty(this,"aborted",{value:!1,writable:!0,configurable:!0}),Object.defineProperty(this,"onabort",{value:null,writable:!0,configurable:!0}),Object.defineProperty(this,"reason",{value:void 0,writable:!0,configurable:!0})}toString(){return"[object AbortSignal]"}dispatchEvent(e){e.type==="abort"&&(this.aborted=!0,typeof this.onabort=="function"&&this.onabort.call(this,e)),super.dispatchEvent(e)}throwIfAborted(){let{aborted:e,reason:t="Aborted"}=this;if(e)throw t}static timeout(e){let t=new wi;return setTimeout(()=>t.abort(new DOMException(`This signal is timeout in ${e}ms`,"TimeoutError")),e),t.signal}static any(e){let t=new wi;function i(){t.abort(this.reason),r()}function r(){for(let s of e)s.removeEventListener("abort",i)}for(let s of e)if(s.aborted){t.abort(s.reason);break}else s.addEventListener("abort",i);return t.signal}},wi=class{constructor(){Object.defineProperty(this,"signal",{value:new br,writable:!0,configurable:!0})}abort(e){let t=iS(e),i=tS(t);this.signal.reason=t,this.signal.dispatchEvent(i)}toString(){return"[object AbortController]"}};typeof Symbol<"u"&&Symbol.toStringTag&&(wi.prototype[Symbol.toStringTag]="AbortController",br.prototype[Symbol.toStringTag]="AbortSignal");function eo(a){return a.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof a.Request=="function"&&!a.Request.prototype.hasOwnProperty("signal")||!a.AbortController}function bc(a){typeof a=="function"&&(a={fetch:a});let{fetch:e,Request:t=e.Request,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r=!1}=a;if(!eo({fetch:e,Request:t,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r}))return{fetch:e,Request:s};let s=t;(s&&!s.prototype.hasOwnProperty("signal")||r)&&(s=function(l,p){let c;p&&p.signal&&(c=p.signal,delete p.signal);let d=new t(l,p);return c&&Object.defineProperty(d,"signal",{writable:!1,enumerable:!1,configurable:!0,value:c}),d},s.prototype=t.prototype);let n=e;return{fetch:(o,l)=>{let p=s&&s.prototype.isPrototypeOf(o)?o.signal:l?l.signal:void 0;if(p){let c;try{c=new DOMException("Aborted","AbortError")}catch{c=new Error("Aborted"),c.name="AbortError"}if(p.aborted)return Promise.reject(c);let d=new Promise((h,f)=>{p.addEventListener("abort",()=>f(c),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([d,n(o,l)])}return n(o,l)},Request:s}}var aM=()=>"fetch"in window,xa=aM()&&eo({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),rS=xa?bc({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,Xe=xa?rS.fetch:window.fetch,JU=xa?rS.Request:window.Request,Y=xa?wi:window.AbortController,ZU=xa?br:window.AbortSignal;var dT=C(xe(),1),Wc=C(wa(),1);var jS=C(US(),1);import{ErrorCategory as ka}from"@vkontakte/videoplayer-shared/es2024";var to=a=>{if(!a)return{id:"EmptyResponse",category:ka.PARSER,message:"Empty response"};if(a.length<=2&&a.match(/^\d+$/))return{id:`UVError#${a}`,category:ka.NETWORK,message:`UV Error ${a}`};let e=(0,jS.default)(a).substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:ka.NETWORK,message:"Received unexpected HTML, possibly a ISP block"};if(e.startsWith("<?xml"))return new DOMParser().parseFromString(a,"text/xml").querySelector("parsererror")?{id:"InvalidXML",category:ka.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:ka.PARSER,message:"Response is valid XML, but parser failed"}};var Te=(a,e,t=0)=>{for(let i=0;i<a.length;i++)if(a.start(i)*1e3-t<=e&&a.end(i)*1e3+t>e)return!0;return!1};import{abortable as Uc,assertNonNullable as wr,combine as Ar,ErrorCategory as Ze,filter as To,filterChanged as ns,flattenObject as os,fromEvent as Dt,getTraceSubscriptionMethod as RC,interval as jc,isNonNullable as us,isNullable as uT,map as kr,merge as Li,now as Hc,Subject as Ct,Subscription as lT,SubscriptionRemovable as $C,tap as LC,throttle as MC,ValueSubject as J}from"@vkontakte/videoplayer-shared/es2024";var so=C(xe(),1),Ri=C(nt(),1),no=C(wa(),1);var jM=(a,e={})=>{let i=e.timeout||1,r=performance.now();return window.setTimeout(()=>{a({get didTimeout(){return e.timeout?!1:performance.now()-r-1>i},timeRemaining(){return Math.max(0,1+(performance.now()-r))}})},1)},HM=a=>window.clearTimeout(a),HS=a=>typeof a=="function"&&a?.toString().endsWith("{ [native code] }"),WS=!HS(window.requestIdleCallback)||!HS(window.cancelIdleCallback),zt=WS?jM:window.requestIdleCallback,Je=WS?HM:window.cancelIdleCallback;var tT=C(An(),1);import{assertNever as WM,ErrorCategory as QS,Subject as GS}from"@vkontakte/videoplayer-shared/es2024";var QM=18,zS=!1;try{zS=D.browser.isSafari&&!!D.browser.safariVersion&&D.browser.safariVersion<=QM}catch(a){console.error(a)}var Ic=class{constructor(e){this.bufferFull$=new GS;this.error$=new GS;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:QS.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:e})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(i=>{let r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(r=>{let s={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(s),this.pull()})}async abort(e){return new Promise(t=>{let i,r=s=>{this.abortRequested=!1,t(s)};zS&&e?i={operation:"safariAbort",init:e,callback:r}:i={operation:"abort",callback:r};for(let{callback:s}of this.queue)s(!1);this.abortRequested=!0,i&&(this.queue=[i]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){if((this.buffer.updating||this.currentTask||this.destroyed)&&!this.abortRequested)return;let e=this.queue.shift();if(!e)return;if(e.signal?.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(r){r instanceof DOMException&&r.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):r instanceof DOMException&&r.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:QS.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:r}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){let{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:WM(t)}}},YS=Ic;var gr=a=>{let e=0;for(let t=0;t<a.length;t++)e+=a.end(t)-a.start(t);return e*1e3};import{abortable as Kt,assertNonNullable as Re,ErrorCategory as $t,fromEvent as Vc,getExponentialDelay as _c,isHigher as fC,isNonNullable as Xt,isNullable as oe,now as ao,once as mC,Subject as bC,Subscription as gC,ValueSubject as Pi}from"@vkontakte/videoplayer-shared/es2024";var KS=C(nt(),1);var io=a=>a.valid,W=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let i=this.readUint32();this.type=this.readString(4),i===1&&(this.cursor+=8);let r=e.byteOffset+this.cursor,s;i===0?(this.size=void 0,this.valid=!1,s=void 0):i===1?(this.size=void 0,this.valid=!1,s=void 0):i>e.byteLength?(this.size=i,this.valid=!1,s=Math.min(i-this.cursor,e.byteLength-this.cursor)):(this.size=i,this.valid=!0,s=i-this.cursor),this.content=new DataView(e.buffer,r,s)}get id(){return this.type}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t="ascii"){let r=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,r}readUint8(){let e=this.source.getUint8(this.cursor);return this.cursor+=1,e}readUint16(){let e=this.source.getUint16(this.cursor);return this.cursor+=2,e}readUint32(){let e=this.source.getUint32(this.cursor);return this.cursor+=4,e}readUint64(){let e=this.source.getBigInt64(this.cursor);return this.cursor+=8,e}};var vr=class extends W{};import{assertNever as GM}from"@vkontakte/videoplayer-shared/es2024";var Pa=class extends W{constructor(e,t){if(super(e,t),!this.valid)return;let i=this.readString(16),r=new DataView(this.content.buffer,this.content.byteOffset+16,this.content.byteLength-16);this.userData=this.parseData(i,r)}parseData(e,t){switch(e){case"ondemandlivejson":{let i=new TextDecoder("ascii").decode(t),r=JSON.parse(i);return{received:r["t-in"],prepared:r["t-out"]}}default:GM(e)}}};var Ra=class extends W{constructor(e,t){if(super(e,t),!this.valid)return;this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let i=new DataView(this.content.buffer,this.content.byteOffset+8,this.content.byteLength-8);for(let r=0;r<i.byteLength;r+=4){let s=this.readString(4);this.compatibleBrands.push(s)}}};var $a=class extends W{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var X=class extends W{constructor(e,t){if(super(e,t),!this.valid)return;let i=this.readUint32();this.version=i>>>24,this.flags=i&16777215,this.content=new DataView(this.content.buffer,this.content.byteOffset+4,this.content.byteLength-4)}};var La=class extends X{constructor(e,t){super(e,t),this.valid&&(this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.timescale=this.readUint32(),this.duration=this.readUint32(),this.rate=this.readUint32(),this.volume=this.readUint16())}};var Ma=class extends W{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Da=class extends W{constructor(e,t){super(e,t),this.data=this.content}};var Ai=class extends X{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e,t){if(super(e,t),!!this.valid){this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let i=0;i<this.referenceCount;i++){let r=this.readUint32(),s=r>>>31,n=r<<1>>>1,u=this.readUint32();r=this.readUint32();let o=r>>>28,l=r<<3>>>3;this.segments.push({referenceType:s,referencedSize:n,subsegmentDuration:u,SAPType:o,SAPDeltaTime:l})}}}};var Ca=class extends W{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ba=class extends W{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Va=class extends X{constructor(e,t){if(super(e,t),!this.valid)return;switch(this.readUint8()){case 0:this.stereoMode=0;break;case 1:this.stereoMode=1;break;case 2:this.stereoMode=2;break;case 3:this.stereoMode=3;break;case 4:this.stereoMode=4;break}this.cursor+=1}};var _a=class extends X{constructor(e,t){super(e,t),this.valid&&(this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32())}};var Oa=class extends X{constructor(e,t){super(e,t),this.valid&&(this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32())}};var Fa=class extends W{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Na=class extends X{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 qa=class extends W{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ua=class extends W{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ja=class extends X{constructor(e,t){super(e,t),this.valid&&(this.sequenceNumber=this.readUint32())}};var Ha=class extends W{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Wa=class extends X{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 Qa=class extends X{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 Ga=class extends X{constructor(t,i){super(t,i);this.sampleDuration=[];this.sampleSize=[];this.sampleFlags=[];this.sampleCompositionTimeOffset=[];this.optionalFields=0;this.sampleCount=this.readUint32(),this.flags&1&&(this.dataOffset=this.readUint32()),this.flags&4&&(this.firstSampleFlags=this.readUint32());for(let r=0;r<this.sampleCount;r++)this.flags&256&&this.sampleDuration.push(this.readUint32()),this.flags&512&&this.sampleSize.push(this.readUint32()),this.flags&1024&&this.sampleFlags.push(this.readUint32()),this.flags&2048&&this.sampleCompositionTimeOffset.push(this.readUint32())}};var za=class extends W{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ya=class extends X{constructor(e,t){super(e,t),this.valid&&(this.entryCount=this.readUint32(),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+4,this.content.byteLength-4)))}};var Ka=class extends W{constructor(e,t){super(e,t),this.valid&&(this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+78,this.content.byteLength-78)))}};var YM={ftyp:Ra,moov:$a,mvhd:La,moof:Ma,mdat:Da,sidx:Ai,trak:Ca,mdia:Fa,mfhd:ja,tkhd:Na,traf:Ha,tfhd:Wa,tfdt:Qa,trun:Ga,minf:qa,sv3d:Ba,st3d:Va,prhd:_a,proj:Ua,equi:Oa,uuid:Pa,stbl:za,stsd:Ya,avc1:Ka,unknown:vr},Rt=class a{constructor(e={}){this.options={offset:0,...e}}parse(e){let t=[],i=this.options.offset;for(;i<e.byteLength;){let s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+i+4,4)),n;try{n=this.createBox(s,new DataView(e.buffer,e.byteOffset+i,e.byteLength-i))}catch(u){if(!(u instanceof RangeError))throw u}if(!n||!io(n))break;t.push(n),i+=n.size}return t}createBox(e,t){let i=YM[e];return i?new i(t,new a):new vr(t,new a)}};var Yt=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{io(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 XM=new TextDecoder("ascii"),JM=a=>XM.decode(new DataView(a.buffer,a.byteOffset+4,4))==="ftyp",ZM=a=>{let e=new Ai(a,new Rt),t=e.earliestPresentationTime/e.timescale*1e3,i=a.byteOffset+a.byteLength+e.firstOffset;return e.segments.map(s=>{if(s.referenceType!==0)throw new Error("Unsupported multilevel sidx");let n=s.subsegmentDuration/e.timescale*1e3,u={status:"none",time:{from:t,to:t+n},byte:{from:i,to:i+s.referencedSize-1}};return t+=n,i+=s.referencedSize,u})},eD=(a,e)=>{let i=new Rt().parse(a),r=new Yt(i),s=r.findAll("moof"),n=e?r.findAll("uuid"):r.findAll("mdat");if(!(n.length&&s.length))return null;let u=s[0],o=n[n.length-1],l=u.source.byteOffset,c=o.source.byteOffset-u.source.byteOffset+o.size;return new DataView(a.buffer,l,c)},tD=a=>{let t=new Rt().parse(a),i=new Yt(t),r={},s=i.findAll("uuid"),n=(0,KS.default)(s,-1);return n?{serverDataReceivedTimestamp:n.userData.received,serverDataPreparedTime:n.userData.received}:r},iD=a=>{let t=new Rt().parse(a);return new Yt(t).find("sidx")?.timescale},rD=(a,e)=>{let i=new Rt().parse(a),s=new Yt(i).findAll("traf"),n=s[s.length-1].children.find(c=>c.type==="tfhd"),u=s[s.length-1].children.find(c=>c.type==="tfdt"),o=s[s.length-1].children.find(c=>c.type==="trun"),l=0;return o.sampleDuration.length?l=o.sampleDuration.reduce((c,d)=>c+d,0):l=n.defaultSampleDuration*o.sampleCount,(Number(u.baseMediaDecodeTime)+l)/e*1e3},aD=a=>{let e={is3dVideo:!1,stereoMode:0,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}},i=new Rt().parse(a),r=new Yt(i);if(r.find("sv3d")){e.is3dVideo=!0;let n=r.find("st3d");n&&(e.stereoMode=n.stereoMode);let u=r.find("prhd");u&&(e.projectionData.pose.yaw=u.poseYawDegrees,e.projectionData.pose.pitch=u.posePitchDegrees,e.projectionData.pose.roll=u.poseRollDegrees);let o=r.find("equi");o&&(e.projectionData.bounds.top=o.projectionBoundsTop,e.projectionData.bounds.right=o.projectionBoundsRight,e.projectionData.bounds.bottom=o.projectionBoundsBottom,e.projectionData.bounds.left=o.projectionBoundsLeft)}return e},XS={validateData:JM,parseInit:aD,getIndexRange:()=>{},parseSegments:ZM,parseFeedableSegmentChunk:eD,getChunkEndTime:rD,getServerLatencyTimestamps:tD,getTimescaleFromIndex:iD};var Za=C(xe(),1);import{assertNonNullable as Ec,isNonNullable as ty,isNullable as nD}from"@vkontakte/videoplayer-shared/es2024";import{assertNever as sD}from"@vkontakte/videoplayer-shared/es2024";var JS={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"}},ZS=a=>{let e=a.getUint8(0),t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);let i=Ja(a,t),r=i in JS,s=r?JS[i].type:"binary",n=a.getUint8(t),u=0;n&128?u=1:n&64?u=2:n&32?u=3:n&16?u=4:n&8?u=5:n&4?u=6:n&2?u=7:n&1&&(u=8);let o=new DataView(a.buffer,a.byteOffset+t+1,u-1),l=n&255>>u,p=Ja(o),c=l*2**((u-1)*8)+p,d=t+u,h;return d+c>a.byteLength?h=new DataView(a.buffer,a.byteOffset+d):h=new DataView(a.buffer,a.byteOffset+d,c),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:s,tagHeaderSize:d,tagSize:d+c,value:h,valueSize:c}},Ja=(a,e=a.byteLength)=>{switch(e){case 1:return a.getUint8(0);case 2:return a.getUint16(0);case 3:return a.getUint8(0)*2**16+a.getUint16(1);case 4:return a.getUint32(0);case 5:return a.getUint8(0)*2**32+a.getUint32(1);case 6:return a.getUint16(0)*2**32+a.getUint32(2);case 7:{let t=a.getUint8(0)*281474976710656+a.getUint16(1)*4294967296+a.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},ot=(a,e)=>{switch(e){case"int":return a.getInt8(0);case"uint":return Ja(a);case"float":return a.byteLength===4?a.getFloat32(0):a.getFloat64(0);case"string":return new TextDecoder("ascii").decode(a);case"utf8":return new TextDecoder("utf-8").decode(a);case"date":return new Date(Date.UTC(2001,0)+a.getInt8(0)).getTime();case"master":return a;case"binary":return a;default:sD(e)}},ki=(a,e)=>{let t=0;for(;t<a.byteLength;){let i=new DataView(a.buffer,a.byteOffset+t),r=ZS(i);if(!e(r))return;r.type==="master"&&ki(r.value,e),t=r.value.byteOffset-a.byteOffset+r.valueSize}},ey=a=>{if(a.getUint32(0)!==440786851)return!1;let e,t,i,r=ZS(a);return ki(r.value,({tag:s,type:n,value:u})=>(s===17143?e=ot(u,n):s===17026?t=ot(u,n):s===17029&&(i=ot(u,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)};var iy=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],oD=[231,22612,22743,167,171,163,160,175],uD=a=>{let e,t,i,r,s=!1,n=!1,u=!1,o,l,p=!1,c=0;return ki(a,({tag:d,type:h,value:f,valueSize:m})=>{if(d===21419){let g=ot(f,h);l=Ja(g)}else d!==21420&&(l=void 0);return d===408125543?(e=f.byteOffset,t=f.byteOffset+m):d===357149030?s=!0:d===290298740?n=!0:d===2807729?i=ot(f,h):d===17545?r=ot(f,h):d===21420&&l===475249515?o=ot(f,h):d===374648427?ki(f,({tag:g,type:v,value:S})=>g===30321?(p=ot(S,v)===1,!1):!0):s&&n&&(0,Za.default)(iy,d)&&(u=!0),!u}),Ec(e,"Failed to parse webm Segment start"),Ec(t,"Failed to parse webm Segment end"),Ec(r,"Failed to parse webm Segment duration"),i=i??1e6,{segmentStart:Math.round(e/1e9*i*1e3),segmentEnd:Math.round(t/1e9*i*1e3),timeScale:i,segmentDuration:Math.round(r/1e9*i*1e3),cuesSeekPosition:o,is3dVideo:p,stereoMode:c,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},lD=a=>{if(nD(a.cuesSeekPosition))return;let e=a.segmentStart+a.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},cD=(a,e)=>{let t=!1,i=!1,r=u=>ty(u.time)&&ty(u.position),s=[],n;return ki(a,({tag:u,type:o,value:l})=>{switch(u){case 475249515:t=!0;break;case 187:n&&r(n)&&s.push(n),n={};break;case 179:n&&(n.time=ot(l,o));break;case 183:break;case 241:n&&(n.position=ot(l,o));break;default:t&&(0,Za.default)(iy,u)&&(i=!0)}return!(t&&i)}),n&&r(n)&&s.push(n),s.map((u,o)=>{let{time:l,position:p}=u,c=s[o+1];return{status:"none",time:{from:l,to:c?c.time:e.segmentDuration},byte:{from:e.segmentStart+p,to:c?e.segmentStart+c.position-1:e.segmentEnd-1}}})},dD=a=>{let e=0,t=!1;try{ki(a,i=>i.tag===524531317?i.tagSize<=a.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):(0,Za.default)(oD,i.tag)?(e+i.tagSize<=a.byteLength&&(e+=i.tagSize,t||=(0,Za.default)([163,160,175],i.tag)),!0):!1)}catch{}return e>0&&e<=a.byteLength&&t?new DataView(a.buffer,a.byteOffset,e):null},ry={validateData:ey,parseInit:uD,getIndexRange:lD,parseSegments:cD,parseFeedableSegmentChunk:dD};var yt=a=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(a);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return ry;case"mp4":return XS}}throw new ReferenceError(`Unsupported mime type ${a}`)};var Tt=a=>a instanceof DOMException&&(a.name==="AbortError"||a.code===20);var $c=C(Ay(),1),zy=C(fi(),1),Yy=C(Uy(),1),Ky=C(nt(),1),Lc=C(hi(),1);var jy=C(xe(),1),Rc=a=>{let e=a.split("."),[t,...i]=e;if(!t)return!1;switch(t){case"av01":{let[r,s,n]=i;return!!(n&&parseInt(n,10)>8)}case"vp09":{let[r,s,n]=i;return!!(r&&parseInt(r,10)>=2&&n&&parseInt(n,10)>8)}case"avc1":{let r=i[0];if(!r||r.length!==6)return!1;let[s,n]=r.toUpperCase(),u=s+n;return(0,jy.default)(["6E","7A","F4"],u)}}return!1};import{isNonNullable as dC,isNullable as Qy}from"@vkontakte/videoplayer-shared/es2024";var Hy=a=>{if(a.includes("/")){let e=a.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(a)};var Wy=a=>{try{let e=cC(),t=a.match(e),{groups:i}=t??{};if(i){let r={};if(i.extensions){let u=i.extensions.toLowerCase().match(/(?:[0-9a-wy-z](?:-[a-z0-9]{2,8})+)/g);Array.from(u||[]).forEach(o=>{r[o[0]]=o.slice(2)})}let s=i.variants?.split(/-/).filter(u=>u!==""),n={extlang:i.extlang,langtag:i.langtag,language:i.language,privateuse:i.privateuse||i.privateuse2,region:i.region,script:i.script,extensions:r,variants:s};return Object.keys(n).forEach(u=>{let o=n[u];(typeof o>"u"||o==="")&&delete n[u]}),n}return null}catch{return null}};function cC(){let a="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",p=`^(?:(?<langtag>${`
|
|
118
|
-
(?<language>${`(?:[a-z]{2,3}(?:-${a})?|[a-z]{4}|[a-z]{5,8})`})
|
|
119
|
-
(-(?<script>[a-z]{4}))?
|
|
120
|
-
(-(?<region>(?:[a-z]{2}|[0-9]{3})))?
|
|
121
|
-
(?<variants>(?:-(?:[a-z0-9]{5,8}|[0-9][a-z0-9]{3}))*)
|
|
122
|
-
(?<extensions>(?:-[0-9a-wy-z](?:-[a-z0-9]{2,8})+)*)
|
|
123
|
-
(?:-(?<privateuse>(?:${e})))?
|
|
124
|
-
`})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(p,"i")}var Gy=a=>{if(!a?.startsWith("P"))return;let e=(n,u)=>{let o=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(o)?0:o)*u},i=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(a),r=i?.[1]==="-"?-1:1,s={days:e(i?.[5],r),hours:e(i?.[6],r),minutes:e(i?.[7],r),seconds:e(i?.[8],r)};return s.days*24*60*60*1e3+s.hours*60*60*1e3+s.minutes*60*1e3+s.seconds*1e3},ut=(a,e)=>{let t=a;t=(0,$c.default)(t,"$$","$");let i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[r,s]of(0,zy.default)(i)){let n=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=(0,$c.default)(t,n,(u,o)=>Qy(s)?u:Qy(o)?s:(0,Yy.default)(s,parseInt(o,10),"0"))}return t},ro=(a,e)=>{let i=new DOMParser().parseFromString(a,"application/xml"),r={video:[],audio:[],text:[]},s=i.children[0],n=Array.from(s.querySelectorAll("MPD > BaseURL").values()).map(M=>M.textContent?.trim()??""),u=(0,Ky.default)(n,0)??"",o=s.getAttribute("type")==="dynamic",l=s.getAttribute("availabilityStartTime"),p=s.getAttribute("publishTime"),c=s.getElementsByTagName("vk:Attrs")[0],d=c?.getElementsByTagName("vk:XLatestSegmentPublishTime")[0].textContent,h=c?.getElementsByTagName("vk:XStreamIsLive")[0].textContent,f=c?.getElementsByTagName("vk:XStreamIsUnpublished")[0].textContent,m=c?.getElementsByTagName("vk:XPlaybackDuration")[0].textContent,g;o&&(g={availabilityStartTime:l?new Date(l).getTime():0,publishTime:p?new Date(p).getTime():0,latestSegmentPublishTime:d?new Date(d).getTime():0,streamIsAlive:h==="yes",streamIsUnpublished:f==="yes"});let v,S=s.getAttribute("mediaPresentationDuration"),T=[...s.getElementsByTagName("Period")],y=T.reduce((M,x)=>({...M,[x.id]:x.children}),{}),A=T.reduce((M,x)=>({...M,[x.id]:x.getAttribute("duration")}),{});S?v=Gy(S):(0,Lc.default)(A).filter(M=>M).length&&!o?v=(0,Lc.default)(A).reduce((M,x)=>M+(Gy(x)??0),0):m&&(v=parseInt(m,10));let P=0,L=s.getAttribute("profiles")?.split(",")??[];for(let M of T.map(x=>x.id))for(let x of y[M]){let F=x.getAttribute("id")??"id"+(P++).toString(10),B=x.getAttribute("mimeType")??"",E=x.getAttribute("codecs")??"",I=x.getAttribute("contentType")??B?.split("/")[0],N=x.getAttribute("profiles")?.split(",")??[],$=Wy(x.getAttribute("lang")??"")??{},U=x.querySelector("Label")?.textContent?.trim()??void 0,K=x.querySelectorAll("Representation"),te=x.querySelector("SegmentTemplate"),ne=x.querySelector("Role")?.getAttribute("value")??void 0,me=I,be={id:F,language:$.language,isDefault:ne==="main",label:U,codecs:E,hdr:me==="video"&&Rc(E),mime:B,representations:[]};for(let j of K){let q=j.getAttribute("lang")??void 0,ge=U??x.getAttribute("label")??j.getAttribute("label")??void 0,Ie=j.querySelector("BaseURL")?.textContent?.trim()??"",ce=new URL(Ie||u,e).toString(),Qe=j.getAttribute("mimeType")??B,_t=j.getAttribute("codecs")??E??"",ct;if(I==="text"){let Oe=j.getAttribute("id")||"",Ot=$.privateuse?.includes("x-auto")||Oe.includes("_auto"),dt=j.querySelector("SegmentTemplate");if(dt){let Vr={representationId:j.getAttribute("id")??void 0,bandwidth:j.getAttribute("bandwidth")??void 0},Vs=parseInt(j.getAttribute("bandwidth")??"",10)/1e3,_s=parseInt(dt.getAttribute("startNumber")??"",10)??1,Ni=parseInt(dt.getAttribute("timescale")??"",10),Zo=dt.querySelectorAll("SegmentTimeline S")??[],qi=dt.getAttribute("media");if(!qi)continue;let Os=[],Fs=0,Ns="",Ui=0,_r=_s,Ee=0;for(let et of Zo){let si=parseInt(et.getAttribute("d")??"",10),Ge=parseInt(et.getAttribute("r")??"",10)||0,Ft=parseInt(et.getAttribute("t")??"",10);Ee=Number.isFinite(Ft)?Ft:Ee;let ni=si/Ni*1e3,ji=Ee/Ni*1e3;for(let pt=0;pt<Ge+1;pt++){let Nt=ut(qi,{...Vr,segmentNumber:_r.toString(10),segmentTime:(Ee+pt*si).toString(10)}),Hi=(ji??0)+pt*ni,Fr=Hi+ni;_r++,Os.push({time:{from:Hi,to:Fr},url:Nt})}Ee+=(Ge+1)*si,Fs+=(Ge+1)*ni}Ui=Ee/Ni*1e3,Ns=ut(qi,{...Vr,segmentNumber:_r.toString(10),segmentTime:Ee.toString(10)});let Or={time:{from:Ui,to:1/0},url:Ns},Et={type:"template",baseUrl:ce,segmentTemplateUrl:qi,initUrl:"",totalSegmentsDurationMs:Fs,segments:Os,nextSegmentBeyondManifest:Or,timescale:Ni};ct={id:Oe,kind:"text",segmentReference:Et,profiles:[],duration:v,bitrate:Vs,mime:"",codecs:"",width:0,height:0,isAuto:Ot}}else ct={id:Oe,isAuto:Ot,kind:"text",url:ce}}else{let Oe=j.getAttribute("contentType")??Qe?.split("/")[0]??I,Ot=x.getAttribute("profiles")?.split(",")??[],dt=parseInt(j.getAttribute("width")??"",10),Vr=parseInt(j.getAttribute("height")??"",10),Vs=parseInt(j.getAttribute("bandwidth")??"",10)/1e3,_s=j.getAttribute("frameRate")??"",Ni=j.getAttribute("quality")??void 0,Zo=_s?Hy(_s):void 0,qi=j.getAttribute("id")??"id"+(P++).toString(10),Os=Oe==="video"?`${Vr}p`:Oe==="audio"?`${Vs}Kbps`:_t,Fs=`${qi}@${Os}`,Ns=[...L,...N,...Ot],Ui,_r=j.querySelector("SegmentBase"),Ee=j.querySelector("SegmentTemplate")??te;if(_r){let Et=j.querySelector("SegmentBase Initialization")?.getAttribute("range")??"",[et,si]=Et.split("-").map(Nt=>parseInt(Nt,10)),Ge={from:et,to:si},Ft=j.querySelector("SegmentBase")?.getAttribute("indexRange"),[ni,ji]=Ft?Ft.split("-").map(Nt=>parseInt(Nt,10)):[],pt=Ft?{from:ni,to:ji}:void 0;Ui={type:"byteRange",url:ce,initRange:Ge,indexRange:pt}}else if(Ee){let Et={representationId:j.getAttribute("id")??void 0,bandwidth:j.getAttribute("bandwidth")??void 0},et=parseInt(Ee.getAttribute("timescale")??"",10),si=Ee.getAttribute("initialization")??"",Ge=Ee.getAttribute("media"),Ft=parseInt(Ee.getAttribute("startNumber")??"",10)??1,ni=ut(si,Et);if(!Ge)throw new ReferenceError("No media attribute in SegmentTemplate");let ji=Ee.querySelectorAll("SegmentTimeline S")??[],pt=[],Nt=0,Hi="",Fr=0;if(ji.length){let qs=Ft,tt=0;for(let Wi of ji){let ht=parseInt(Wi.getAttribute("d")??"",10),oi=parseInt(Wi.getAttribute("r")??"",10)||0,Us=parseInt(Wi.getAttribute("t")??"",10);tt=Number.isFinite(Us)?Us:tt;let eu=ht/et*1e3,UI=tt/et*1e3;for(let js=0;js<oi+1;js++){let jI=ut(Ge,{...Et,segmentNumber:qs.toString(10),segmentTime:(tt+js*ht).toString(10)}),Nd=(UI??0)+js*eu,HI=Nd+eu;qs++,pt.push({time:{from:Nd,to:HI},url:jI})}tt+=(oi+1)*ht,Nt+=(oi+1)*eu}Fr=tt/et*1e3,Hi=ut(Ge,{...Et,segmentNumber:qs.toString(10),segmentTime:tt.toString(10)})}else if(dC(v)){let tt=parseInt(Ee.getAttribute("duration")??"",10)/et*1e3,Wi=Math.ceil(v/tt),ht=0;for(let oi=1;oi<Wi;oi++){let Us=ut(Ge,{...Et,segmentNumber:oi.toString(10),segmentTime:ht.toString(10)});pt.push({time:{from:ht,to:ht+tt},url:Us}),ht+=tt}Fr=ht,Hi=ut(Ge,{...Et,segmentNumber:Wi.toString(10),segmentTime:ht.toString(10)})}let qI={time:{from:Fr,to:1/0},url:Hi};Ui={type:"template",baseUrl:ce,segmentTemplateUrl:Ge,initUrl:ni,totalSegmentsDurationMs:Nt,segments:pt,nextSegmentBeyondManifest:qI,timescale:et}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Oe||!Qe)continue;let Or={video:"video",audio:"audio",text:"text"}[Oe];if(!Or)continue;me||=Or,ct={id:Fs,kind:Or,segmentReference:Ui,profiles:Ns,duration:v,bitrate:Vs,mime:Qe,codecs:_t,width:dt,height:Vr,fps:Zo,quality:Ni}}be.language||=q,be.label||=ge,be.mime||=Qe,be.codecs||=_t,be.hdr||=me==="video"&&Rc(_t),be.representations.push(ct)}if(me){let j=r[me].find(q=>q.id===be.id);if(j&&be.representations.every(q=>q.segmentReference.type==="template"))for(let q of j.representations){let ge=be.representations.find(Qe=>Qe.id===q.id);if(!ge)continue;let Ie=ge.segmentReference,ce=q.segmentReference;ce.segments.push(...Ie.segments),ce.nextSegmentBeyondManifest=Ie.nextSegmentBeyondManifest}else r[me].push(be)}}return{duration:v,streams:r,baseUrls:n,live:g}};var Mc=C(nt(),1);import{videoSizeToQuality as pC}from"@vkontakte/videoplayer-shared/es2024";var es=({id:a,width:e,height:t,bitrate:i,fps:r,quality:s,streamId:n})=>{let u=(s?Qt(s):void 0)??pC({width:e,height:t});return u&&{id:a,quality:u,bitrate:i,size:{width:e,height:t},fps:r,streamId:n}},Xy=({id:a,bitrate:e})=>({id:a,bitrate:e}),Jy=({language:a,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),Zy=({language:a,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),Dc=({id:a,language:e,label:t,codecs:i,isDefault:r})=>({id:a,language:e,label:t,codec:(0,Mc.default)(i.split("."),0),isDefault:r}),Cc=({id:a,language:e,label:t,hdr:i,codecs:r})=>({id:a,language:e,hdr:i,label:t,codec:(0,Mc.default)(r.split("."),0)}),Bc=a=>"url"in a,je=a=>a.type==="template";import{isNonNullable as eT}from"@vkontakte/videoplayer-shared/es2024";var V=(a,e)=>eT(a)&&eT(e)&&a.readyState==="open"&&hC(a,e);function hC(a,e){for(let t=0;t<a.activeSourceBuffers.length;++t)if(a.activeSourceBuffers[t]===e)return!0;return!1}var ts=class{constructor(e,t,i,{fetcher:r,tuning:s,getCurrentPosition:n,isActiveLowLatency:u,compatibilityMode:o=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new Pi(0);this.currentLowLatencySegmentLength$=new Pi(0);this.currentSegmentLength$=new Pi(0);this.onLastSegment$=new Pi(!1);this.fullyBuffered$=new Pi(!1);this.playingRepresentation$=new Pi(void 0);this.playingRepresentationInit$=new Pi(void 0);this.error$=new bC;this.gaps=[];this.subscription=new gC;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new Y;this.switchAbortController=new Y;this.destroyAbortController=new Y;this.useSmartRepresentationSwitch=!1;this.bufferLimit=1/0;this.failedDownloads=0;this.baseUrls=[];this.baseUrlsIndex=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.lastDataObtainedTimestampMs=0;this.loadByteRangeSegmentsTimeoutId=0;this.startWith=Kt(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);Re(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new YS(this.sourceBuffer),this.subscription.add(Vc(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let u,o=this.mediaSource.readyState;o!=="open"&&(u={id:`SegmentEjection_source_${o}`,category:$t.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),u??={id:"SegmentEjection",category:$t.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n},this.error$.next(u)})),this.subscription.add(Vc(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:$t.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let u=this.getCurrentPosition();if(!this.sourceBuffer||!u||!V(this.mediaSource,this.sourceBuffer))return;let o=Math.min(this.bufferLimit,gr(this.sourceBuffer.buffered)*.8);this.bufferLimit=o;let l=this.getForwardBufferDuration(u),p=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(u,n*2,l<p).catch(c=>{this.handleAsyncError(c,"pruneBuffer")})})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);let i=this.initData.get(t.id),r=this.segments.get(t.id),s=this.parsedInitData.get(t.id);Re(i,"No init buffer for starting representation"),Re(r,"No segments for starting representation"),i instanceof ArrayBuffer&&(this.searchGaps(r,t),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s))}.bind(this));this.switchTo=Kt(this.destroyAbortController.signal,async function*(e,t=!1){if(!V(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);Re(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if(oe(s)||oe(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),Re(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!V(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();Xt(n)&&!this.isLive&&(this.bufferLimit=1/0,await this.pruneBuffer(n,1/0,!0)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}this.maintain()}}.bind(this));this.switchToOld=Kt(this.destroyAbortController.signal,async function*(e,t=!1){if(!V(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);Re(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if(oe(s)||oe(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),Re(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!V(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();Xt(n)&&(this.isLive||(this.bufferLimit=1/0,await this.pruneBuffer(n,1/0,!0)),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}}.bind(this));this.seekLive=Kt(this.destroyAbortController.signal,async function*(e){let t=(0,no.default)(e,o=>o.representations);if(!this.downloadingRepresentationId||!t.length)return;this.isSeekingLive=!0;for(let o of this.representations.keys()){let l=t.find(d=>d.id===o);l&&this.representations.set(o,l);let p=this.representations.get(o);if(!p||!je(p.segmentReference)){this.isSeekingLive=!1;return}let c=this.getActualLiveStartingSegments(p.segmentReference);this.segments.set(p.id,c)}let i=this.switchingToRepresentationId??this.downloadingRepresentationId,r=this.representations.get(i);Re(r,`Representation not found by id ${i}`);let s=this.segments.get(i);Re(s,"No segments for starting representation");let n=this.initData.get(i);if(Re(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer)){this.isSeekingLive=!1;return}let u=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),u&&(yield this.sourceBufferTaskQueue.remove(u.from*1e3,u.to*1e3,this.destroyAbortController.signal)),this.searchGaps(s,r),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));this.fetcher=r,this.tuning=s,this.compatibilityMode=o,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=u,this.isLive=!!l?.live,this.baseUrls=l?.baseUrls??[],this.initData=new Map(i.map(p=>[p.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(p=>[p.id,p])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchToWithPreviousAbort(e,t=!1){!V(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new Y,Kt(this.switchAbortController.signal,async function*(i,r=!1){this.switchingToRepresentationId=i;let s=this.representations.get(i);Re(s,`No such representation ${i}`);let n=this.segments.get(i),u=this.initData.get(i);if(oe(u)||oe(n)?yield this.loadInit(s,"high",!1):u instanceof Promise&&(yield u),n=this.segments.get(i),Re(n,"No segments for starting representation"),u=this.initData.get(i),!(!(u instanceof ArrayBuffer)||!this.sourceBuffer||!V(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(u,this.downloadAbortController.signal),r)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=i,yield this.dropBuffer();else{let o=this.getCurrentPosition();Xt(o)&&!this.isLive&&(this.bufferLimit=this.forwardBufferTarget,yield this.pruneBuffer(o,1/0,!0)),this.downloadingRepresentationId=i,this.switchingToRepresentationId=void 0}this.maintain()}}.bind(this))(e,t))}warmUpMediaSource(){!oe(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 Y,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(oe(e)||oe(this.downloadingRepresentationId)||oe(this.playingRepresentationId)||oe(this.sourceBuffer)||!V(this.mediaSource,this.sourceBuffer)||Xt(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.representations.get(this.playingRepresentationId),r=this.segments.get(this.downloadingRepresentationId),s=this.segments.get(this.playingRepresentationId);if(Re(t,`No such representation ${this.downloadingRepresentationId}`),Re(i,`No such representation ${this.playingRepresentationId}`),oe(r)||oe(s))return;let n=r.find(d=>e>=d.time.from&&e<d.time.to);Xt(n)&&isFinite(n.time.from)&&isFinite(n.time.to)&&this.currentSegmentLength$.next(n?.time.to-n.time.from);let u=e,o=100;if(this.playingRepresentationId!==this.downloadingRepresentationId){let d=this.getForwardBufferDuration(e),h=es(i),f=es(t),m=this.useSmartRepresentationSwitch&&this.tuning.dash.useNewRepresentationSwitch&&this.tuning.dash.useSmartRepresentationSwitch&&Xt(h)&&Xt(f)&&fC(h.quality,f.quality),g=this.useSmartRepresentationSwitch&&this.tuning.dash.useNewRepresentationSwitch&&this.tuning.dash.useDelayedRepresentationSwitch;if(m||g?u+=Math.min(d,this.tuning.dash.representationSwitchForwardBufferGap):n&&n.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&d>=n.time.to-e+o&&(u=n?n.time.to+o:-1/0),this.tuning.dash.useNewRepresentationSwitch){let S=[...this.segments.entries()].map(([T,y])=>{let A=y.find(P=>e>=P.time.from&&e<P.time.to);return{representationId:T,status:A?.status}}).find(T=>T.status==="fed")?.representationId;S&&(this.playingRepresentationId=S,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)))}}if(isFinite(this.bufferLimit)&&gr(this.sourceBuffer.buffered)>=this.bufferLimit){let d=this.getForwardBufferDuration(e),h=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,d<h).catch(f=>{this.handleAsyncError(f,"pruneBuffer")});return}let p=[];if(!this.activeSegments.size&&(p=this.selectForwardBufferSegments(r,t.segmentReference.type,u),p.length)){let d="auto";if(this.tuning.dash.useFetchPriorityHints&&n)if((0,so.default)(p,n))d="high";else{let h=(0,Ri.default)(p,0);h&&h.time.from-n.time.to>=this.forwardBufferTarget/2&&(d="low")}this.loadSegments(p,t,d).catch(h=>{this.handleAsyncError(h,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&n&&n.status==="fed"&&!p.length&&this.getForwardBufferDuration(e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let c=(0,Ri.default)(r,-1);!this.isLive&&c&&(this.fullyBuffered$.next(c.time.to-e-this.getForwardBufferDuration(e)<o),this.onLastSegment$.next(e-c.time.from>0))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let i=0,r=this.isLive?this.liveInitialAdditionalOffset:0;for(let s of e)Math.trunc(s.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:s.time.from+r,persistent:!0}),i=s.time.to;Xt(t.duration)&&t.duration-i>0&&!this.isLive&&this.gaps.push({representation:t.id,from:i,to:t.duration,persistent:!0})}getActualLiveStartingSegments(e){let t=e.segments,i=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,r=[],s=0,n=t.length-1;do r.unshift(t[n]),s+=t[n].time.to-t[n].time.from,n--;while(s<i&&n>=0);return this.liveInitialAdditionalOffset=s-i,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){let t=e?.streams[this.kind];if(!t)return;let i=(0,no.default)(t,s=>s.representations).find(s=>s.id===this.downloadingRepresentationId);if(!i)return;let r=this.segments.get(i.id);if(r?.length)return{from:r[0].time.from,to:r[r.length-1].time.to}}updateLive(e){if(!e||[...this.segments.values()].every(i=>!i.length))return;let t=(0,no.default)(e.streams[this.kind],i=>i.representations);for(let i of t){if(!i||!je(i.segmentReference))return;let r=i.segmentReference.segments.map(l=>({...l,status:"none",size:void 0})),s=100,n=this.segments.get(i.id)??[],u=(0,Ri.default)(n,-1)?.time.to??0,o=r?.findIndex(l=>u>=l.time.from+s&&u<=l.time.to+s);if(o===-1){this.liveUpdateSegmentIndex=0;let l=this.getActualLiveStartingSegments(i.segmentReference);this.segments.set(i.id,l)}else{let l=r.slice(o+1);this.segments.set(i.id,[...n,...l])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;Re(e);let t=this.segments.get(e);if(t?.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}calculateDurationFromSegments(){if(!this.playingRepresentationId)return 0;let e=this.segments.get(this.playingRepresentationId);return(e?(0,Ri.default)(e,-1)?.time.to:0)||0}setSmartRepresentationSwitch(e){this.useSmartRepresentationSwitch=e}updateLowLatencyLiveIfNeeded(e){let t=0;for(let i of this.representations.values()){let r=i.segmentReference;if(!je(r))return;let s=this.segments.get(i.id)??[],n=s.find(o=>Math.floor(o.time.from)===Math.floor(e.time.from));if(n&&!isFinite(n.time.to)&&(n.time.to=e.time.to,t=n.time.to-n.time.from),!!!s.find(o=>Math.floor(o.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let o=Math.round(e.time.to*r.timescale/1e3).toString(10),l=ut(r.segmentTemplateUrl,{segmentTime:o});s.push({status:"none",time:{from:e.time.to,to:1/0},url:l})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){let t=this.switchingToRepresentationId??this.downloadingRepresentationId??this.playingRepresentationId;if(!t)return;let i=this.segments.get(t);return i?i.find(s=>s.time.from<=e&&s.time.to>=e)?.time.from??void 0:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),this.sourceBufferTaskQueue?.destroy(),this.gapDetectionIdleCallback&&Je&&Je(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&Je&&Je(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(e){if(!(e instanceof DOMException&&e.name==="NotFoundError"))throw e}this.sourceBuffer=null,this.downloadAbortController.abort(),this.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,i){return this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){let i=e.findIndex(r=>t>=r.time.from&&t<r.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=i),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,i){let r=this.getForwardBufferDuration(i),s=e.findIndex(({status:d,time:{from:h,to:f}},m)=>{let g=h<=i&&f>=i,v=h>i||g||m===0&&i===0,S=Math.min(this.forwardBufferTarget,this.bufferLimit),T=this.preloadOnly&&h<=i+S||r<S&&f-h>=S||f<=i+S;return(d==="none"||d==="partially_ejected"&&v&&T&&this.sourceBuffer&&V(this.mediaSource,this.sourceBuffer)&&!(Te(this.sourceBuffer.buffered,h)&&Te(this.sourceBuffer.buffered,f)))&&v&&T});if(s===-1)return[];if(t!=="byteRange")return e.slice(s,s+1);let n=e,u=0,o=0,l=[],p=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,c=this.preloadOnly?this.forwardBufferTarget:0;for(let d=s;d<n.length&&(u<=p||o<=c);d++){let h=n[d];if(u+=h.byte.to+1-h.byte.from,o+=h.time.to+1-h.time.from,h.status==="none"||h.status==="partially_ejected")l.push(h);else break}return l}async loadSegments(e,t,i="auto"){je(t.segmentReference)?await this.loadTemplateSegment(e[0],t,i):await this.loadByteRangeSegments(e,t,i)}async loadTemplateSegment(e,t,i="auto"){e.status="downloading";let r={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(r);let{range:s,url:n,signal:u,onProgress:o,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&u&&(await Kt(u,async function*(){let p=_c(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,p))}.bind(this))(),u.aborted&&this.abortActiveSegments([e]));try{let p=await this.fetcher.fetch(n,{range:s,signal:u,onProgress:o,priority:i,isLowLatency:this.isActiveLowLatency(),bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation});if(this.lastDataObtainedTimestampMs=ao(),!p)return;let c=new DataView(p),d=yt(t.mime);if(!isFinite(r.segment.time.to)){let m=t.segmentReference.timescale;r.segment.time.to=d.getChunkEndTime(c,m)}o&&r.feedingBytes&&l?await Promise.all(l):await this.sourceBufferTaskQueue.append(c,u);let{serverDataReceivedTimestamp:h,serverDataPreparedTime:f}=d.getServerLatencyTimestamps(c);h&&f&&this.currentLiveSegmentServerLatency$.next(f-h),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(p){this.abortActiveSegments([e]),Tt(p)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}updateRepresentationsBaseUrlIfNeeded(){if(!this.tuning.dash.enableBaseUrlSupport||!this.baseUrls.length||this.failedDownloads<=this.tuning.dash.maxSegmentRetryCount)return;this.baseUrlsIndex=(this.baseUrlsIndex+1)%this.baseUrls.length;let e=this.baseUrls[this.baseUrlsIndex];for(let t of this.representations.values())je(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}async loadByteRangeSegments(e,t,i="auto"){if(!e.length)return;for(let o of e)o.status="downloading",this.activeSegments.add({segment:o,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:r,url:s,signal:n,onProgress:u}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(await Kt(n,async function*(){let o=_c(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,o),Vc(window,"online").pipe(mC()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(s,{range:r,onProgress:u,signal:n,priority:i,bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation}),this.lastDataObtainedTimestampMs=ao(),this.failedDownloads=0}catch(o){this.abortActiveSegments(e),Tt(o)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(je(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:(0,Ri.default)(e,0).byte.from,to:(0,Ri.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:i,range:r,signal:s,onProgress:async(u,o)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=ao(),await this.onSomeByteRangesDataLoaded({dataView:u,loaded:o,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:$t.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!je(t.segmentReference))throw new Error("Representation is not template type");let i=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&i.searchParams.set("low-latency","yes");let r=i.toString(),{signal:s}=this.downloadAbortController,n=[],o=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,p)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=ao();let c=this.onSomeTemplateDataLoaded({dataView:l,loaded:p,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(c)}catch(c){this.error$.next({id:"SegmentFeeding",category:$t.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}}:void 0;return{url:r,signal:s,onProgress:o,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,so.default)(e,t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:s}){if(!this.activeSegments.size||!V(this.mediaSource,this.sourceBuffer))return;let n=this.representations.get(t);if(n)for(let u of this.activeSegments){let{segment:o}=u;if(u.representationId===t){if(s.aborted){r();continue}if(u.loadedBytes=i,u.loadedBytes>u.feedingBytes){let l=new DataView(e.buffer,e.byteOffset+u.feedingBytes,u.loadedBytes-u.feedingBytes),p=yt(n.mime).parseFeedableSegmentChunk(l,this.isLive);p?.byteLength&&(o.status="partially_fed",u.feedingBytes+=p.byteLength,await this.sourceBufferTaskQueue.append(p),u.fedBytes+=p.byteLength)}}}}async onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size||!V(this.mediaSource,this.sourceBuffer))return;let u=this.representations.get(t);if(u)for(let o of this.activeSegments){let{segment:l}=o;if(o.representationId!==t)continue;if(s.aborted){await n();continue}let p=l.byte.from-i,c=l.byte.to-i,d=c-p+1,h=p<r,f=c<=r;if(!h)continue;let m=yt(u.mime);if(l.status==="downloading"&&f){l.status="downloaded";let g=new DataView(e.buffer,e.byteOffset+p,d);await this.sourceBufferTaskQueue.append(g,s)&&!s.aborted?this.onSegmentFullyAppended(o,t):await n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(l.status==="downloading"||l.status==="partially_fed")&&(o.loadedBytes=Math.min(d,r-p),o.loadedBytes>o.feedingBytes)){let g=new DataView(e.buffer,e.byteOffset+p+o.feedingBytes,o.loadedBytes-o.feedingBytes),v=o.loadedBytes===d?g:m.parseFeedableSegmentChunk(g);v?.byteLength&&(l.status="partially_fed",o.feedingBytes+=v.byteLength,await this.sourceBufferTaskQueue.append(v,s)&&!s.aborted?(o.fedBytes+=v.byteLength,o.fedBytes===d&&this.onSegmentFullyAppended(o,t)):await n())}}}onSegmentFullyAppended(e,t){if(!(oe(this.sourceBuffer)||!V(this.mediaSource,this.sourceBuffer))){!this.isLive&&D.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(Te(this.sourceBuffer.buffered,e.segment.time.from,100)&&Te(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:$t.VIDEO_PIPELINE,message:"Browser stuck on empty result of adding segment to source buffer"})),this.tuning.dash.useNewRepresentationSwitch||(this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId))),e.segment.status="fed",Bc(e.segment)&&(e.segment.size=e.fedBytes);for(let i of this.representations.values())if(i.id!==t)for(let r of this.segments.get(i.id)??[])r.status==="fed"&&Math.round(r.time.from)===Math.round(e.segment.time.from)&&Math.round(r.time.to)===Math.round(e.segment.time.to)&&(r.status="none");this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}}abortSegment(e){e.status==="partially_fed"?e.status="partially_ejected":e.status!=="partially_ejected"&&(e.status="none");for(let t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[r,s]of this.initData.entries()){let n=s instanceof Promise;t||=n,s===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let i=this.representations.get(e);i&&(this.initLoadIdleCallback=zt(()=>(0,tT.default)(this.loadInit(i,"low",!1),()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",i=!1){let r=this.tuning.dash.useFetchPriorityHints?t:"auto",s=!i&&this.tuning.dash.ignoreNetworkErrorsOnLoadInit,u=(!i&&this.failedDownloads>0?Kt(this.destroyAbortController.signal,async function*(){let o=_c(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>setTimeout(l,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,yt(e.mime),{priority:r,ignoreNetworkErrors:s})).then(async o=>{if(!o)return;let{init:l,dataView:p,segments:c}=o,d=p.buffer.slice(p.byteOffset,p.byteOffset+p.byteLength);this.initData.set(e.id,d);let h=c;this.isLive&&je(e.segmentReference)&&(h=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,h),l&&this.parsedInitData.set(e.id,l)}).then(()=>this.failedDownloads=0,o=>{s||this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:$t.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,u),u}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||!V(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||oe(e))return!1;let r=[],s=0,n=o=>{o.sort((p,c)=>p.from-c.from);let l=[o[0]];for(let p=1;p<o.length;p++){let{from:c,to:d}=o[p],h=l[l.length-1];h.to>=c?h.to=Math.max(h.to,d):l.push(o[p])}return l},u=o=>{if(s>=t)return r;r.push({...o.time}),r=n(r);let l=Bc(o)?o.size??0:o.byte.to-o.byte.from;s+=l};for(let o of this.segments.values())for(let l of o){let p=l.time.to<=e-this.tuning.dash.bufferPruningSafeZone,c=l.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(p||c)&&l.status==="fed"&&u(l)}for(let o=0;o<this.sourceBuffer.buffered.length;o++){let l=this.sourceBuffer.buffered.start(o)*1e3,p=this.sourceBuffer.buffered.end(o)*1e3,c=0;for(let d of this.segments.values())for(let h of d)(0,so.default)(["none","partially_ejected"],h.status)&&Math.round(h.time.from)<=Math.round(l)&&Math.round(h.time.to)>=Math.round(p)&&c++;if(c===this.segments.size){let d={time:{from:l,to:p},url:"",status:"none"};u(d)}}if(r.length&&i){let o=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let l of this.segments.values())for(let p of l)p.time.from>=e+o&&p.status==="fed"&&u(p)}return r.length?(await Promise.all(r.map(l=>this.sourceBufferTaskQueue.remove(l.from,l.to)))).reduce((l,p)=>l||p,!1):!1}async abortBuffer(){if(!this.sourceBuffer||!V(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||!V(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||!V(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||oe(e)?0:ye(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!(!this.sourceBuffer||!V(this.mediaSource,this.sourceBuffer)))for(let i of t){let r={representation:e,from:i.time.from,to:i.time.to,persistent:!1},{buffered:s}=this.sourceBuffer;for(let n=0;n<s.length;n++){let u=s.start(n)*1e3,o=s.end(n)*1e3;if(!(o<=i.time.from||u>=i.time.to)){if(u<=i.time.from&&o>=i.time.to){r=void 0;break}o>i.time.from&&o<i.time.to&&(r.from=o),u<i.time.to&&u>i.time.from&&(r.to=u)}}r&&r.to-r.from>1&&!this.gaps.some(n=>r&&n.from===r.from&&n.to===r.to)&&this.gaps.push(r)}}detectGapsWhenIdle(e,t){if(this.gapDetectionIdleCallback||!this.sourceBuffer||!V(this.mediaSource,this.sourceBuffer))return;let{buffered:i}=this.sourceBuffer,{usePersistentGaps:r}=this.tuning.dash;this.gaps=this.gaps.filter(s=>{if(r&&s.persistent)return!0;let n=Math.round(s.from),u=Math.round(s.to);for(let o=0;o<i.length;o++)if(n>=Math.round(i.start(o)*1e3)&&u<=Math.round(i.end(o)*1e3))return!1;return!0}),this.gapDetectionIdleCallback=zt(()=>{try{this.detectGaps(e,t)}catch(s){this.error$.next({id:"GapDetection",category:$t.WTF,message:"detectGaps threw",thrown:s})}finally{this.gapDetectionIdleCallback=null}})}checkEjectedSegments(){if(oe(this.sourceBuffer)||!V(this.mediaSource,this.sourceBuffer)||oe(this.playingRepresentationId))return;let e=[];for(let i=0;i<this.sourceBuffer.buffered.length;i++){let r=Math.floor(this.sourceBuffer.buffered.start(i)*1e3),s=Math.ceil(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:r,to:s})}let t=100;for(let i of this.segments.values())for(let r of i){let{status:s}=r;if(s!=="fed"&&s!=="partially_ejected")continue;let n=Math.floor(r.time.from),u=Math.ceil(r.time.to),o=e.some(p=>p.from-t<=n&&p.to+t>=u),l=e.filter(p=>n>=p.from&&n<p.to-t||u>p.from+t&&u<=p.to);o||(l.length===1?r.status="partially_ejected":this.gaps.some(p=>p.from===r.time.from||p.to===r.time.to)?r.status="partially_ejected":r.status="none")}}handleAsyncError(e,t){this.error$.next({id:t,category:$t.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}};var Jt=a=>{let e=new URL(a);return e.searchParams.set("quic","1"),e.toString()};var oo=a=>{let e=a.get("X-Delivery-Type"),t=a.get("X-Reused"),i=e===null?"http1":e??void 0,r=t===null?void 0:{1:!0,0:!1}[t]??void 0;return{type:i,reused:r}};import{abortable as is,assertNever as iT,fromEvent as rT,merge as vC,now as rs,Subject as $i,ValueSubject as Oc,flattenObject as Ir,ErrorCategory as as,SubscriptionRemovable as SC}from"@vkontakte/videoplayer-shared/es2024";var uo=a=>{let e=new URL(a);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var co=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:s=!1}){this.manifestRequested$=new $i;this.firstBytesManifest$=new $i;this.manifestReceived$=new $i;this.firstBytesRequested$=new $i;this.firstBytesReceived$=new $i;this.lastConnectionType$=new Oc(void 0);this.lastConnectionReused$=new Oc(void 0);this.lastRequestFirstBytes$=new Oc(void 0);this.recoverableError$=new $i;this.error$=new $i;this.abortAllController=new Y;this.subscription=new SC;this.fetchManifest=is(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=Jt(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=uo(i)),this.manifestRequested$.next();let r=yield this.doFetch(i,{signal:this.abortAllController.signal},{type:"manifest"}).catch(lo);return r?(t.log("success",Ir({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(r.headers),this.manifestReceived$.next(),r.text()):(t.error("error",Ir({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=is(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:s="auto",signal:n,measureThroughput:u=!0,isLowLatency:o=!1,bufferOptimisation:l=!1,ignoreNetworkErrors:p=!1}={}){let c=e,d=new Headers,h=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{d.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let I=new URL(c,location.href);I.searchParams.append("bytes",`${i.from}-${i.to}`),c=I.toString();break}default:iT(t)}this.requestQuic&&(c=Jt(c));let f=this.abortAllController.signal,m;if(n){let I=new Y;if(m=vC(rT(this.abortAllController.signal,"abort"),rT(n,"abort")).subscribe(()=>{try{I.abort()}catch(N){lo(N)}}),this.subscription.add(m),this.abortAllController.signal.aborted||n.aborted)try{I.abort()}catch(N){lo(N)}f=I.signal}let g=0,v=rs();h.log("startRequest",Ir({url:c,priority:s,rangeMethod:t,range:i,isLowLatency:o,requestStartedAt:v})),this.firstBytesRequested$.next();let S=yield this.doFetch(c,{priority:s,headers:d,signal:f},{ignoreNetworkErrors:p}),T=rs();if(!S)return h.error("error",{message:"No response in request"}),h.end(),this.unsubscribeAbortSubscription(m),null;if(this.throughputEstimator?.addRawRtt(T-v),!S.ok||!S.body){this.unsubscribeAbortSubscription(m);let I=`Fetch error ${S.status}: ${S.statusText}`;return h.error("error",{message:I}),h.end(),Promise.reject(new Error(`Fetch error ${S.status}: ${S.statusText}`))}if(this.onHeadersReceived(S.headers),!r&&!u){this.unsubscribeAbortSubscription(m);let I=rs(),N={requestStartedAt:v,requestEndedAt:I,duration:I-v};return h.log("endRequest",Ir(N)),h.end(),S.arrayBuffer()}let y=S.body;if(u){let I;[y,I]=S.body.tee(),this.throughputEstimator?.trackStream(I,o)}let A=y.getReader(),P,L=parseInt(S.headers.get("content-length")??"",10);Number.isFinite(L)&&(P=L),!P&&i&&(P=i.to-i.from+1);let w=P?new Uint8Array(P):new Uint8Array(0),M=!1,x=I=>{this.unsubscribeAbortSubscription(m),M=!0,lo(I)},F=is(f,async function*({done:I,value:N}){if(g===0&&(this.lastRequestFirstBytes$.next(rs()-v),this.firstBytesReceived$.next()),f.aborted){this.unsubscribeAbortSubscription(m);return}if(!I&&N){if(l&&P)w.set(N,g),g+=N.byteLength;else{let $=new Uint8Array(w.length+N.length);$.set(w),$.set(N,w.length),w=$,g+=N.byteLength}r?.(new DataView(w.buffer),g),yield A?.read().then(F,x)}}.bind(this));yield A?.read().then(F,x),this.unsubscribeAbortSubscription(m);let B=rs(),E={failed:M,requestStartedAt:v,requestEndedAt:B,duration:B-v};return M?(h.error("endRequest",Ir(E)),h.end(),null):(h.log("endRequest",Ir(E)),h.end(),w.buffer)}.bind(this));this.fetchByteRangeRepresentation=is(this.abortAllController.signal,async function*(e,t,i){if(e.type!=="byteRange")return null;let{from:r,to:s}=e.initRange,n=r,u=s,o=!1,l,p;e.indexRange&&(l=e.indexRange.from,p=e.indexRange.to,o=s+1===l,o&&(n=Math.min(l,r),u=Math.max(p,s))),n=Math.min(n,0);let c=yield this.fetch(e.url,{range:{from:n,to:u},measureThroughput:!1,...i});if(!c)return null;let d=new DataView(c,r-n,s-n+1);if(!t.validateData(d))throw new Error("Invalid media file");let h=t.parseInit(d),f=e.indexRange??t.getIndexRange(h);if(!f)throw new ReferenceError("No way to load representation index");let m;if(o)m=new DataView(c,f.from-n,f.to-f.from+1);else{let v=yield this.fetch(e.url,{range:f,measureThroughput:!1});if(!v)return null;m=new DataView(v)}let g=t.parseSegments(m,h,f);return{init:h,dataView:new DataView(c),segments:g}}.bind(this));this.fetchTemplateRepresentation=is(this.abortAllController.signal,async function*(e,t){if(e.type!=="template")return null;let i=new URL(e.initUrl,e.baseUrl).toString(),r=yield this.fetch(i,{measureThroughput:!1,...t});return r?{init:null,segments:e.segments.map(n=>({...n,status:"none",size:void 0})),dataView:new DataView(r)}:null}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=r,this.tracer=i.createComponentTracer("Fetcher"),this.useEnableSubtitlesParam=s}onHeadersReceived(e){let{type:t,reused:i}=oo(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,t,i){let{type:r}=e;switch(r){case"byteRange":return await this.fetchByteRangeRepresentation(e,t,i)??null;case"template":return await this.fetchTemplateRepresentation(e,i)??null;default:iT(r)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}async doFetch(e,t,i){let r=await Xe(e,t);if(r.ok)return i?.type==="manifest"&&this.firstBytesManifest$.next(),r;if(i?.ignoreNetworkErrors)return;let s=await r.text(),n=parseInt(s);if(!isNaN(n))switch(n){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:as.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:as.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:as.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:as.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${n})`,category:as.FATAL})}}unsubscribeAbortSubscription(e){e&&(e.unsubscribe(),this.subscription.remove(e))}},lo=a=>{if(!Tt(a))throw a};var Lt=(a,e,t)=>t*e+(1-t)*a,Fc=(a,e)=>a.reduce((t,i)=>t+i,0)/e,aT=(a,e,t,i)=>{let r=0,s=t,n=Fc(a,e),u=e<i?e:i;for(let o=0;o<u;o++)a[s]>n?r++:r--,s=(a.length+s-1)%a.length;return Math.abs(r)===u};import{isNullable as yC,ValueSubject as sT}from"@vkontakte/videoplayer-shared/es2024";var Zt=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 sT(e.initial),this.debounced$=new sT(e.initial);let t=e.label??"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new ke(`raw_${t}`),this.smoothedSeries$=new ke(`smoothed_${t}`),this.reportedSeries$=new ke(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,i=0;for(let u=0;u<this.pastMeasures.length;u++)this.pastMeasures[u]!==void 0&&(t+=(this.pastMeasures[u]-this.smoothed)**2,i++);this.takenMeasures=i,t/=i;let r=Math.sqrt(t),s=this.smoothed+this.params.deviationFactor*r,n=this.smoothed-this.params.deviationFactor*r;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>s||this.smoothed<n)&&(yC(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 po=class extends Zt{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=Lt(this.slow,e,this.params.emaAlphaSlow),this.fast=Lt(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var ho=class extends Zt{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=Fc(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Lt(this.emaSmoothed,e,this.params.emaAlpha);let i=aT(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}};var fo=class extends Zt{constructor(t){super(t);this.furtherValues=[];this.currentTopExtremumValue=0;this.extremumInterval=t.extremumInterval}next(t){this.currentTopExtremumValue<=t?(this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.length===this.extremumInterval?(super.next(this.currentTopExtremumValue),this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.push(t)}updateSmoothedValue(t){this.smoothed=this.smoothed?Lt(this.smoothed,t,this.params.emaAlpha):t}};var Mt=class{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new po({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new ho({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 fo({initial:e,label:"liveEdgeDelay",...t})}};var Er=(a,e)=>{a&&a.playbackRate!==e&&(a.playbackRate=e)};import{isNullable as TC,ValueSubject as IC}from"@vkontakte/videoplayer-shared/es2024";var ss=class a{constructor(e,t){this.currentRepresentation$=new IC(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(!TC(e))for(let t of this.representations)for(let i of t){let r=i.segmentReference,s=r.segments.length,n=r.segments[0].time.from,u=r.segments[s-1].time.to;if(e<n||e>u)continue;let o=r.segments.find(l=>l.time.from<=e&&l.time.to>=e);!o||this.currentSegment?.time.from===o.time.from&&this.currentSegment.time.to===o.time.to||(this.currentSegment=o,this.currentRepresentation$.next({...i,label:"Live Text",language:"ru",isAuto:!0,url:new URL(o.url,r.baseUrl).toString()}))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e??[]){let i=a.filterRepresentations(t.representations);if(i){this.representations[this.representationsCursor]=i,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!e?.some(t=>a.filterRepresentations(t.representations))}static filterRepresentations(e){return e?.filter(t=>t.kind==="text"&&"segmentReference"in t&&je(t.segmentReference))}};var bo=C(nt(),1),Nc=C(xe(),1);import{assertNever as go}from"@vkontakte/videoplayer-shared/es2024";var mo=a=>{let{webmDecodingInfo:e}=D.video,t="DASH_WEBM",i="DASH_WEBM_AV1";switch(a){case"vp9":return[t,i];case"av1":return[i,t];case"none":return[];case"smooth":return e?e[i].smooth?[i,t]:e[t].smooth?[t,i]:[i,t]:[t,i];case"power_efficient":return e?e[i].powerEfficient?[i,t]:e[t].powerEfficient?[t,i]:[i,t]:[t,i];default:go(a)}},nT=({webmCodec:a,androidPreferredFormat:e,iosPreferredFormat:t,preferMultiStream:i})=>{let r=[...i?["DASH_STREAMS"]:[],...mo(a),"DASH_SEP","DASH_ONDEMAND",...i?[]:["DASH_STREAMS"]],s=[...i?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...i?[]:["DASH_STREAMS"]];if(D.device.isAndroid)switch(e){case"mpeg":return["MPEG",...r,"HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...r,"MPEG"];case"dash":return[...r,"HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return[...s,"MPEG",...mo(a),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...mo(a),"MPEG",...s,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...mo(a),...s,"HLS","HLS_ONDEMAND"];default:go(e)}if(D.video.nativeHlsSupported)switch(t){case"hls":return[...r,"HLS","HLS_FMP4","HLS_ONDEMAND","MPEG"];case"hls_fmp4":return[...r,"HLS_FMP4","HLS","HLS_ONDEMAND","MPEG"];default:go(t)}return[...r,"HLS","HLS_ONDEMAND","MPEG"]},oT=({androidPreferredFormat:a,preferCMAF:e,preferWebRTC:t})=>{let i=e?["DASH_LIVE_CMAF","DASH_LIVE"]:["DASH_LIVE","DASH_LIVE_CMAF"],r=e?["HLS_LIVE_CMAF","HLS_LIVE"]:["HLS_LIVE","HLS_LIVE_CMAF"],s=[...i,...r],n=[...r,...i],u,o=D.device.isMac&&D.browser.isSafari;if(D.device.isAndroid)switch(a){case"dash":case"dash_any_mpeg":case"dash_any_webm":case"dash_sep":{u=s;break}case"hls":case"mpeg":{u=n;break}default:go(a)}else D.video.nativeHlsSupported&&!o&&!D.browser.isChromiumBased?u=n:o?u=e?["DASH_LIVE_CMAF","HLS_LIVE_CMAF","HLS_LIVE","DASH_LIVE"]:["HLS_LIVE","DASH_LIVE","DASH_LIVE_CMAF","HLS_LIVE_CMAF"]:u=s;return t?["WEB_RTC_LIVE",...u]:[...u,"WEB_RTC_LIVE"]},qc=a=>a?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],vo=a=>{if(a.size===0)return;if(a.size===1){let t=a.values().next();return(0,bo.default)(t.value.split("."),0)}for(let t of a){let i=(0,bo.default)(t.split("."),0);if(i==="opus"||i==="vp09"||i==="av01")return i}let e=a.values().next();return(0,bo.default)(e.value.split("."),0)},So=a=>{let e=a.map(i=>xr(i)),{codecs:t}=D.video;return AC().filter(i=>{if((0,Nc.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})},yo=a=>{let e=a.map(i=>xr(i)),{codecs:t}=D.video;return kC().filter(i=>{if((0,Nc.default)(e,i))switch(i){case"opus":return t.opus;case"mp4a":return t.aac;default:return!1}else return!1})},xr=a=>a.split(".")[0].replace("0",""),AC=()=>["av1","vp9","hev1","avc1"],kC=()=>["opus","mp4a"];var DC=["timeupdate","progress","play","seeked","stalled","waiting"],CC=["timeupdate","progress","loadeddata","playing","seeked"];var Io=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.bufferManagers=[];this.subscription=new lT;this.subscriptionRemovable=new $C;this.representationSubscription=new lT;this.state$=new O("none");this.currentVideoRepresentation$=new J(void 0);this.currentVideoRepresentationInit$=new J(void 0);this.currentAudioRepresentation$=new J(void 0);this.currentVideoSegmentLength$=new J(0);this.currentAudioSegmentLength$=new J(0);this.error$=new Ct;this.manifestRequested$=new Ct;this.firstBytesManifest$=new Ct;this.manifestReceived$=new Ct;this.firstBytesRequested$=new Ct;this.firstBytesReceived$=new Ct;this.lastConnectionType$=new J(void 0);this.lastConnectionReused$=new J(void 0);this.lastRequestFirstBytes$=new J(void 0);this.currentLiveTextRepresentation$=new J(null);this.isLive$=new J(!1);this.isActiveLive$=new J(!1);this.isLowLatency$=new J(!1);this.liveDuration$=new J(0);this.liveSeekableDuration$=new J(0);this.liveAvailabilityStartTime$=new J(0);this.liveStreamStatus$=new J(void 0);this.bufferLength$=new J(0);this.liveLatency$=new J(void 0);this.liveLoadBufferLength$=new J(0);this.livePositionFromPlayer$=new J(0);this.currentStallDuration$=new J(0);this.videoLastDataObtainedTimestamp$=new J(0);this.fetcherRecoverableError$=new Ct;this.fetcherError$=new Ct;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new Ct;this.gapWatchdogActive=!1;this.liveWasInterrupted=!1;this.destroyController=new Y;this.initManifest=Uc(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=ae(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:Ze.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=Uc(this.destroyController.signal,async function*(){this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(o=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:Ze.NETWORK,message:"Failed to load manifest",thrown:o})});if(!e)return null;let t=null;try{t=ro(e??"",this.manifestUrlString)}catch(o){let l=to(e)??{id:"ManifestParsing",category:Ze.PARSER,message:"Failed to parse MPD manifest",thrown:o};this.error$.next(l)}if(!t)return null;let i=(o,l,p)=>!!(this.element?.canPlayType?.(l)&&Ue()?.isTypeSupported?.(`${l}; codecs="${p}"`)||o==="text");if(t.live){this.isLive$.next(!0);let{availabilityStartTime:o,latestSegmentPublishTime:l,streamIsUnpublished:p,streamIsAlive:c}=t.live,d=(t.duration??0)/1e3;this.liveSeekableDuration$.next(-1*d),this.liveDuration$.next((l-o)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let h="active";if(c||(h=p?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(h),c&&this.liveWasInterrupted){this.liveWasInterrupted=!1,this.stopStallWatchdogSubscription();let f=this.normalizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(f).catch(m=>{this.error$.next({id:"updateManifest",category:Ze.VIDEO_PIPELINE,message:"seekLive after stream restore failed",thrown:m})})}}let r={text:t.streams.text,video:[],audio:[]},s,n;for(let o of["video","audio"]){let p=t.streams[o].filter(({mime:d,codecs:h})=>i(o,d,h));r[o]=p;let c;if(this.tuning.dash.codecsPrioritizeEnabled){let d=p.map(({codecs:h})=>h);o==="audio"&&(n=yo(d),c=n[0]),o==="video"&&(s=So(d),this.forceVideoCodec&&(0,dT.default)(s,this.forceVideoCodec)?c=this.forceVideoCodec:c=s[0]),c&&(r[o]=p.filter(({codecs:h})=>xr(h)===c))}else{let d=new Set(p.map(({codecs:h})=>h));c=vo(d),c&&(r[o]=p.filter(({codecs:h})=>h.startsWith(c)))}if(o==="video"){let d=this.tuning.preferHDR,h=r.video.some(m=>m.hdr),f=r.video.some(m=>!m.hdr);D.display.isHDR&&d&&h?r.video=r.video.filter(m=>m.hdr):f&&(r.video=r.video.filter(m=>!m.hdr))}}let u={...t,streams:r};return this.tuning.dash.codecsPrioritizeEnabled&&(u.codecs={video:s,audio:n}),this.tracer.log("updateManifestEnd",os(u)),u}.bind(this));this.initRepresentations=Uc(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initRepresentationsStart",os({initialVideo:e,initialAudio:t,sourceHls:i})),wr(this.manifest),wr(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let r=c=>{this.representationSubscription.add(Dt(c,"error").pipe(To(d=>!!this.element?.played.length)).subscribe(d=>{this.error$.next({id:"VideoSource",category:Ze.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:d})}))};this.source=Ln();let s=document.createElement("source");if(r(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),ur())if(i){let c=document.createElement("source");r(c),c.type="application/x-mpegurl",c.src=i.url,this.element.appendChild(c)}else this.element.disableRemotePlayback=!0;this.isActiveLive$.next(this.isLive$.getValue());let n={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),manifest:this.manifest},u=this.manifest.streams.video.reduce((c,d)=>[...c,...d.representations],[]);if(this.videoBufferManager=new ts("video",this.source,u,n),this.bufferManagers=[this.videoBufferManager],us(t)){let c=this.manifest.streams.audio.reduce((d,h)=>[...d,...h.representations],[]);this.audioBufferManager=new ts("audio",this.source,c,n),this.bufferManagers.push(this.audioBufferManager)}if(ss.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new ss(this.manifest.streams.text,n)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add(Li(...CC.map(c=>Dt(this.element,c))).pipe(kr(c=>this.element?ye(this.element.buffered,this.element.currentTime*1e3):0),ns(),LC(c=>{c>this.tuning.dash.bufferEmptinessTolerance&&this.stopStallWatchdogSubscription()})).subscribe(this.bufferLength$)),this.representationSubscription.add(Li(Dt(this.element,"ended"),this.forceEnded$).subscribe(()=>{this.stopStallWatchdogSubscription()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe(ns()).subscribe(d=>this.liveStreamEndTimestamp=Hc())),this.subscription.add(Dt(this.element,"pause").subscribe(()=>{let{liveUpdateInterval:d}=this.tuning.dash;this.livePauseWatchdogSubscription=jc(d).subscribe(h=>{let f=Ht(this.manifestUrlString,2);this.manifestUrlString=ae(this.manifestUrlString,f+d,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add(Dt(this.element,"play").subscribe(d=>this.livePauseWatchdogSubscription?.unsubscribe())),this.representationSubscription.add(Ar({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(kr(({isActiveLive:d,isLowLatency:h})=>d&&h),ns()).subscribe(d=>{this.isManualDecreasePlaybackInLive()||Er(this.element,1)})),this.representationSubscription.add(Ar({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(To(({bufferLength:d,isActiveLive:h,isLowLatency:f})=>h&&f&&!!d)).subscribe(({bufferLength:d})=>this.liveBuffer.next(d))),this.representationSubscription.add(this.videoBufferManager.currentLowLatencySegmentLength$.subscribe(d=>{if(!this.isActiveLive$.getValue()&&!this.isLowLatency$.getValue()&&!d)return;let h=this.liveSeekableDuration$.getValue()-d/1e3;this.liveSeekableDuration$.next(Math.max(h,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+d/1e3)})),this.representationSubscription.add(Ar({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(To(({isLive:d})=>d),ns((d,h)=>h.bufferLength<d.bufferLength),kr(({rtt:d,bufferLength:h,segmentServerLatency:f})=>{let m=Ht(this.manifestUrlString,2);return(d/2+h+f+m)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(Ar({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:d,isActiveLive:h,isLowLatency:f})=>{if(!f||!h)return;let m=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,g=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,v=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,S=d-m;if(this.isManualDecreasePlaybackInLive())return;let T=1;Math.abs(S)>g&&(T=1+Math.sign(S)*v),Er(this.element,T)})),this.representationSubscription.add(this.bufferLength$.subscribe(d=>{let h=0;if(d){let f=(this.element?.currentTime??0)*1e3;h=Math.min(...this.bufferManagers.map(g=>g.getLiveSegmentsToLoadState(this.manifest)?.to??f))-f}this.liveLoadBufferLength$.getValue()!==h&&this.liveLoadBufferLength$.next(h)}));let c=0;this.representationSubscription.add(Ar({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(MC(this.tuning.dash.liveUpdateInterval)).subscribe(async({liveLoadBufferLength:d,bufferLength:h})=>{if(!this.element||this.isUpdatingLive)return;let f=this.element.playbackRate,m=Ht(this.manifestUrlString,2),g=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,v=Math.min(g,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*f),S=this.tuning.dashCmafLive.normalizedActualBufferOffset*f,T=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*f,y=isFinite(d)?d:h,A=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),P=g<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(P);let L="none";if(A?L="active_low_latency":this.isLowLatency$.getValue()&&P?(this.bufferManagers.forEach(w=>w.proceedLowLatencyLive()),L="active_low_latency"):m!==0&&y<v?L="live_forward_buffering":y<v+T&&(L="live_with_target_offset"),isFinite(d)&&(c=d>c?d:c),L==="live_forward_buffering"||L==="live_with_target_offset"){let w=c-(v+S),M=this.normalizeLiveOffset(Math.trunc(m+w/f)),x=Math.abs(M-m),F=0;!d||x<=this.tuning.dashCmafLive.offsetCalculationError?F=m:M>0&&x>this.tuning.dashCmafLive.offsetCalculationError&&(F=M),this.manifestUrlString=ae(this.manifestUrlString,F,2)}(L==="live_with_target_offset"||L==="live_forward_buffering")&&(c=0,await this.updateLive())},d=>{this.error$.next({id:"updateLive",category:Ze.VIDEO_PIPELINE,thrown:d,message:"Failed to update live with subscription"})}))}let o=Li(...this.bufferManagers.map(c=>c.fullyBuffered$)).pipe(kr(()=>this.bufferManagers.every(c=>c.fullyBuffered$.getValue()))),l=Li(...this.bufferManagers.map(c=>c.onLastSegment$)).pipe(kr(()=>this.bufferManagers.some(c=>c.onLastSegment$.getValue()))),p=Ar({allBuffersFull:o,someBufferEnded:l}).pipe(ns(),kr(({allBuffersFull:c,someBufferEnded:d})=>c&&d),To(c=>c));if(this.representationSubscription.add(Li(this.forceEnded$,p).subscribe(()=>{if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(c=>!c.updating))try{this.source?.endOfStream()}catch(c){this.error$.next({id:"EndOfStream",category:Ze.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:c})}})),this.representationSubscription.add(Li(...this.bufferManagers.map(c=>c.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 c=this.tuning.dash.sourceOpenTimeout>=0;yield new Promise(d=>{c&&(this.timeoutSourceOpenId=setTimeout(()=>{if(this.source?.readyState==="open"){d();return}this.error$.next({id:"OpenOfStream",category:Ze.VIDEO_PIPELINE,message:"Failed to open MediaSource",thrown:new Error("Timeout reject when wait sourceopen event"),traceAsLog:!0})},this.tuning.dash.sourceOpenTimeout)),this.source?.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),d()},{once:!0})})}if(!this.isLive$.getValue()){let c=[this.manifest.duration??0,...(0,Wc.default)((0,Wc.default)([...this.manifest.streams.audio,...this.manifest.streams.video],d=>d.representations),d=>{let h=[];return d.duration&&h.push(d.duration),je(d.segmentReference)&&d.segmentReference.totalSegmentsDurationMs&&h.push(d.segmentReference.totalSegmentsDurationMs),h})];this.source.duration=Math.max(...c)/1e3}this.audioBufferManager&&us(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=jc(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:Ze.WTF,message:"Error handling gaps",thrown:t})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.forceVideoCodec=e.forceVideoCodec,this.fetcher=new co({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.subscription.add(this.fetcher.recoverableError$.subscribe(this.fetcherRecoverableError$)),this.subscription.add(this.fetcher.error$.subscribe(this.fetcherError$)),this.subscription.add(this.fetcher.manifestRequested$.subscribe(this.manifestRequested$)),this.subscription.add(this.fetcher.firstBytesManifest$.subscribe(this.firstBytesManifest$)),this.subscription.add(this.fetcher.manifestReceived$.subscribe(this.manifestReceived$)),this.subscription.add(this.fetcher.firstBytesRequested$.subscribe(this.firstBytesRequested$)),this.subscription.add(this.fetcher.firstBytesReceived$.subscribe(this.firstBytesReceived$)),this.subscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.subscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.liveBuffer=Mt.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator}),this.initTracerSubscription()}setSmartRepresentationSwitch(e){this.bufferManagers.forEach(t=>t.setSmartRepresentationSwitch(e))}async seekLive(e){wr(this.element),this.updateManifestUrlWithTimeOffset(e),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await this.updateLiveBuffersFromManifest(this.manifest))}updateManifestUrlWithTimeOffset(e){let t=this.liveStreamStatus$.getValue()!=="active"?Hc()-this.liveStreamEndTimestamp:0,i=this.normalizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=ae(this.manifestUrlString,i,2)}async updateLiveBuffersFromManifest(e){await this.videoBufferManager?.seekLive(e.streams.video),await this.audioBufferManager?.seekLive(e.streams.audio),this.liveTextManager?.seekLive(e.streams.text)}stopStallWatchdogSubscription(){this.stallWatchdogSubscription?.unsubscribe(),this.currentStallDuration$.next(0)}initBuffer(){wr(this.element),this.state$.setState("running"),this.subscription.add(Li(...DC.map(e=>Dt(this.element,e)),Dt(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:Ze.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(Dt(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(Dt(this.element,"waiting").subscribe(()=>{this.tuning.dash.useVideoElementWaitingCurrentTimeReassign&&this.element&&this.element.readyState===2&&!this.element.seeking&&Te(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{let{keepSilentStallWatchdogWhenNotActive:t}=this.tuning.dashCmafLive,{crashOnStallTimeout:i,crashOnStallTWithoutDataTimeout:r,liveStallReinitInterval:s,stallWatchdogInterval:n}=this.tuning.dash,u=this.isLive$.getValue(),l=this.liveStreamStatus$.getValue()==="active";if(!this.element||this.source?.readyState!=="open")return;let p=this.currentStallDuration$.getValue();p+=n,this.currentStallDuration$.next(p);let c={timeInWaiting:p},d=Hc(),h=100,f=this.videoBufferManager?.lastDataObtainedTimestamp??0;this.videoLastDataObtainedTimestamp$.next(f);let m=this.audioBufferManager?.lastDataObtainedTimestamp??0,g=this.videoBufferManager?.getForwardBufferDuration()??0,v=this.audioBufferManager?.getForwardBufferDuration()??0,S=g<h&&d-f>r,T=this.audioBufferManager&&v<h&&d-m>r;if((!t||l)&&((S||T)&&p>r||p>=i))throw new Error(`Stall timeout exceeded: ${p} ms`);if(u&&p%s===0){let y=this.normalizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);!l&&t?(this.liveWasInterrupted=!0,this.updateManifestUrlWithTimeOffset(y),this.updateManifest()):this.seekLive(y).catch(A=>{this.error$.next({id:"stallIntervalCallback",category:Ze.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:A})}),c.liveLastOffset=y}else{let y=this.element.currentTime*1e3;this.videoBufferManager?.maintain(y),this.audioBufferManager?.maintain(y),c.position=y}this.tracer.log("stallIntervalCallback",os(c))};this.stallWatchdogSubscription&&(this.stallWatchdogSubscription.unsubscribe(),this.subscriptionRemovable.remove(this.stallWatchdogSubscription)),this.stallWatchdogSubscription=jc(this.tuning.dash.stallWatchdogInterval).subscribe(e,t=>{this.error$.next({id:"StallWatchdogCallback",category:Ze.NETWORK,message:"Can't restore DASH after stall.",thrown:t})}),this.subscriptionRemovable.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,i=!1){let r={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return this.tuning.useNewSwitchTo?this.currentStallDuration$.getValue()>0?r?.switchToWithPreviousAbort(t,i):r?.switchTo(t,i):r?.switchToOld(t,i)}async seek(e,t){wr(this.element),wr(this.videoBufferManager);let i;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?i=e:i=Math.max(this.videoBufferManager.findSegmentStartTime(e)??e,this.audioBufferManager?.findSegmentStartTime(e)??e),this.warmUpMediaSourceIfNeeded(i),Te(this.element.buffered,i)||await Promise.all([this.videoBufferManager.abort(),this.audioBufferManager?.abort()]),!(uT(this.element)||uT(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),this.audioBufferManager?.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",os({requestedPosition:e,forcePrecise:t,position:i})))}warmUpMediaSourceIfNeeded(e=this.element?.currentTime){us(this.element)&&us(this.source)&&us(e)&&this.source?.readyState==="ended"&&this.element.duration*1e3-e>this.tuning.dash.seekBiasInTheEnd&&this.bufferManagers.forEach(t=>t.warmUpMediaSource())}get isStreamEnded(){return this.source?.readyState==="ended"}stop(){this.tracer.log("stop"),this.element?.querySelectorAll("source").forEach(e=>{URL.revokeObjectURL(e.src),e.remove()}),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),this.videoBufferManager?.destroy(),this.videoBufferManager=null,this.audioBufferManager?.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){return this.manifest?.streams}getCodecs(){return this.manifest?.codecs}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){this.subscription.unsubscribe(),this.subscriptionRemovable.unsubscribe(),this.representationSubscription.unsubscribe(),this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),this.source?.readyState==="open"&&Array.from(this.source.sourceBuffers).every(e=>!e.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=RC(this.tracer.error.bind(this.tracer));this.subscription.add(this.error$.subscribe(e("error")))}isManualDecreasePlaybackInLive(){if(!this.element||!this.isLive$.getValue())return!1;let e=1-this.element.playbackRate;return Number(e.toFixed(2))>Number(this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup.toFixed(2))}normalizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&(this.bufferManagers.forEach(e=>e.updateLive(this.manifest)),this.liveTextManager?.updateLive(this.manifest)),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getDebugBufferState();if(!e)return;let t=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),i={isJumpGapAfterSeekLive:this.isJumpGapAfterSeekLive,isActiveLowLatency:t,initialCurrentTime:this.element.currentTime},{usePersistentGaps:r}=this.tuning.dash;this.isJumpGapAfterSeekLive&&!t&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let s=this.element.currentTime*1e3,n=[],u=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let o of this.bufferManagers)for(let l of o.gaps)(r&&l.persistent||o.playingRepresentation$.getValue()===l.representation)&&l.from-u<=s&&l.to+u>s&&(this.element.duration*1e3-l.to<this.tuning.endGapTolerance?n.push(1/0):n.push(l.to));if(n.length){let o=Math.max(...n)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,o===1/0?this.forceEnded$.next():(this.element.currentTime=o/1e3,i={...i,gapEnds:n,jumpTo:o,resultCurrentTime:this.element.currentTime},this.tracer.log("jumpGap",os(i)))}}calculateDurationFromSegments(){return Math.max(this.videoBufferManager?.calculateDurationFromSegments()||0,this.audioBufferManager?.calculateDurationFromSegments()||0)}};var Eo=class{constructor(e,t){this.fov=e,this.orientation=t}};var xo=class{constructor(e,t){this.rotating=!1;this.fading=!1;this.lastTickTS=0;this.lastCameraTurnTS=0;this.fadeStartSpeed=null;this.fadeTime=0;this.camera=e,this.options=t,this.rotationSpeed={x:0,y:0,z:0},this.fadeCorrection=1/(this.options.speedFadeTime/1e3)**2}turnCamera(e=0,t=0,i=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+i)}pointCameraTo(e=0,t=0,i=0){t=this.limitCameraRotationY(t);let r=e-this.camera.orientation.x,s=t-this.camera.orientation.y,n=i-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=i,this.lastCameraTurn={x:r,y:s,z:n},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,i){this.rotationSpeed.x=e??this.rotationSpeed.x,this.rotationSpeed.y=t??this.rotationSpeed.y,this.rotationSpeed.z=i??this.rotationSpeed.z}startRotation(){this.rotating=!0}stopRotation(e=!1){e?(this.setRotationSpeed(0,0,0),this.fadeStartSpeed=null):this.startFading(this.rotationSpeed.x,this.rotationSpeed.y,this.rotationSpeed.z),this.rotating=!1}onCameraRelease(){if(this.lastCameraTurn&&this.lastCameraTurnTS){let e=Date.now()-this.lastCameraTurnTS;if(e<this.options.speedFadeThreshold){let t=(1-e/this.options.speedFadeThreshold)*this.options.rotationSpeedCorrection;this.startFading(this.lastCameraTurn.x*t,this.lastCameraTurn.y*t,this.lastCameraTurn.z*t)}}}startFading(e,t,i){this.setRotationSpeed(e,t,i),this.fadeStartSpeed={...this.rotationSpeed},this.fading=!0}stopFading(){this.fadeStartSpeed=null,this.fading=!0,this.fadeTime=0}limitCameraRotationY(e){return Math.max(-this.options.maxYawAngle,Math.min(e,this.options.maxYawAngle))}tick(e){if(!this.lastTickTS){this.lastTickTS=e,this.lastCameraTurnTS=Date.now();return}let t=e-this.lastTickTS,i=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i);else if(this.fading&&this.fadeStartSpeed){let r=-this.fadeCorrection*(this.fadeTime/1e3)**2+1;this.setRotationSpeed(this.fadeStartSpeed.x*r,this.fadeStartSpeed.y*r,this.fadeStartSpeed.z*r),r>0?this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}};var pT=`attribute vec2 a_vertex;
|
|
116
|
+
[selected audio track] ${v?.id}
|
|
117
|
+
`}),v};var ce=s=>new URL(s).hostname;import{assertNever as xy,assertNonNullable as ky,combine as cB,debounce as dB,ErrorCategory as Py,filter as Ay,filterChanged as pB,isNonNullable as gd,map as Qo,merge as Ry,observableFrom as hB,once as fB,Subscription as mB,ValueSubject as Sd,videoQualityToHeight as $y,videoSizeToQuality as bB}from"@vkontakte/videoplayer-shared/es2024";var Ty=D(Ge(),1);var fy=D(ke(),1),hy=s=>{if(s instanceof DOMException&&(0,fy.default)(["Failed to load because no supported source was found.","The element has no supported sources."],s.message))throw s;return!(s instanceof DOMException&&(s.code===20||s.name==="AbortError"))},Me=async(s,e)=>{let t=s.muted;try{await s.play()}catch(i){if(!hy(i))return!1;if(e&&e(),t)return console.warn(i),!1;s.muted=!0;try{await s.play()}catch(r){return hy(r)&&(s.muted=!1,console.warn(r)),!1}}return!0};import{isNonNullable as Ho,isNullable as QD,assertNonNullable as oa}from"@vkontakte/videoplayer-shared/es2024";var by=D(Di(),1);import{isNonNullable as my,assertNonNullable as jo,now as qD}from"@vkontakte/videoplayer-shared/es2024";function Se(){return qD()}function pd(s){return Se()-s}function hd(s){let e=s.split("/"),t=e.slice(0,e.length-1).join("/"),i=/^([a-z]+:)?\/\//i,r=n=>i.test(n);return{resolve:(n,o,u=!1)=>{r(n)||(n.startsWith("/")||(n="/"+n),n=t+n);let l=n.indexOf("?")>-1?"&":"?";return u&&(n+=l+"lowLat=1",l="&"),o&&(n+=l+"_rnd="+Math.floor(999999999*Math.random())),n}}}function gy(s,e,t){let i=(...r)=>{t.apply(null,r),s.removeEventListener(e,i)};s.addEventListener(e,i)}function Ur(s,e,t,i){let r=window.XMLHttpRequest,a,n,o,u=!1,l=0,p,c,d=!1,h="arraybuffer",f=7e3,m=2e3,S=()=>{if(u)return;jo(p);let C=pd(p),E;if(C<m){E=m-C,setTimeout(S,E);return}m*=2,m>f&&(m=f),n&&n.abort(),n=new r,A()},g=C=>(a=C,F),v=C=>(c=C,F),T=()=>(h="json",F),y=()=>{if(!u){if(--l>=0){S(),i&&i();return}u=!0,c&&c(),t&&t()}},x=C=>(d=C,F),A=()=>{p=Se(),n=new r,n.open("get",s);let C=0,E,I=0,N=()=>(jo(p),Math.max(p,Math.max(E||0,I||0)));if(a&&n.addEventListener("progress",L=>{let H=Se();a.updateChunk&&L.loaded>C&&(a.updateChunk(N(),L.loaded-C),C=L.loaded,E=H)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>y())),n.addEventListener("load",()=>{if(u)return;jo(n);let L=n.status;if(L>=200&&L<300){let{response:H,responseType:X}=n,re=H?.byteLength;if(typeof re=="number"&&a){let le=re-C;le&&a.updateChunk&&a.updateChunk(N(),le)}X==="json"&&(!H||!(0,by.default)(H).length)?y():(c&&c(),e(H))}else y()}),n.addEventListener("error",()=>{y()}),d){let L=()=>{jo(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(I=Se(),n.removeEventListener("readystatechange",L))};n.addEventListener("readystatechange",L)}return n.responseType=h,n.send(),F},F={withBitrateReporting:g,withParallel:x,withJSONResponse:T,withRetryCount:C=>(l=C,F),withRetryInterval:(C,E)=>(my(C)&&(m=C),my(E)&&(f=E),F),withTimeout:C=>(o=C,F),withFinally:v,send:A,abort:()=>{n&&(n.abort(),n=void 0),u=!0,c&&c()}};return F}var aa=class{constructor(e){this.intervals=[];this.currentRate=0;this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,i){return{start:e,end:t,bytes:i}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;let e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-500;if(t-e>2e3){let i=0,r=0;for(;this.intervals.length>0;){let a=this.intervals[0];if(a.end<=t)i+=a.end-a.start,r+=a.bytes,this.intervals.splice(0,1);else{if(a.start>=t)break;{let n=t-a.start,o=a.end-a.start;i+=n;let u=a.bytes*n/o;r+=u,a.start=t,a.bytes-=u}}}if(r>0&&i>0){let a=r*8/(i/1e3);return this._updateRate(a),this.logger(`rate updated, new=${Math.round(a/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(r)}/${Math.round(i)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,i){return this.intervals.push(this._createInterval(e,t,i)),this._joinIntervals(),this.intervals.length>100&&(this.logger(`too many intervals (${this.intervals.length}); will merge`,{type:"warn"}),this._doMergeIntervals(this.intervals[1],this.intervals[0]),this.intervals.splice(0,1)),this._flushIntervals()}getBitRate(){return this.currentRate}};var Sy=D(Di(),1);var na=class{constructor(e,t,i,r,a){this.pendingQueue=[];this.activeRequests={};this.completeRequests={};this.averageSegmentDuration=2e3;this.lastPrefetchStart=0;this.throttleTimeout=null;this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=i,this.MAX_PARALLEL_REQUESTS=r,this.logger=a}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){let t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){let i=Se(),r=u=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=u,e._errorCB?e._errorCB(u):(this.limitCompleteCount(),this.completeRequests[t]=e)},a=u=>{e._complete=1,e._responseData=u,e._downloadTime=Se()-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=Ur(t,a,()=>r("error"),o),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(n),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=Se()}_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=Se();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,Sy.default)(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,i,r){let a={};return a.send=()=>{let n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=i,n._retryCB=r,n._finallyCB=a._finallyCB,n._error||n._complete?(this._removeFromActive(e),setTimeout(()=>{n._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(n._responseData,n._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),i(n._errorMsg)),a._finallyCB&&a._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{let o=this.pendingQueue.indexOf(e);o!==-1&&this.pendingQueue.splice(o,1),this.logger(`Request not prefetched, starting new request, url=${e}${o===-1?"":"; removed pending"}`),this._sendRequest(a,e)}},a._cb=t,a._errorCB=i,a._retryCB=r,a.abort=function(){a.request&&a.request.abort()},a.withFinally=n=>(a._finallyCB=n,a),a}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}};import{Subject as WD}from"@vkontakte/videoplayer-shared/es2024";import{isNonNullable as vy}from"@vkontakte/videoplayer-shared/es2024";var V=(s,e)=>vy(s)&&vy(e)&&s.readyState==="open"&&jD(s,e);function jD(s,e){for(let t=0;t<s.activeSourceBuffers.length;++t)if(s.activeSourceBuffers[t]===e)return!0;return!1}var yy=D(ni(),1),fd=class{constructor(e,t,i,r){this.tag=e;this.time=t;this.data=i;this.stack=r}toString(){return`${this.tag}: ${this.time}: ${JSON.stringify(this.data)}${this.stack?`, stack: ${this.stack}`:""}`}toDevNullEntry(){let e=(0,yy.default)(this.data).map(([t,i])=>`${t}:${i}`).join(",");return{key:this.tag,strings:[e,this.stack??""],numbers:[this.time]}}},HD=(s,e="warn")=>{let t=[];function i(r,a=!1){let n=window.performance?.timing?.navigationStart??0,o=new fd(s,Math.round((Date.now()-n)/1e3),r,a?new Error().stack:void 0);t.push(o),e&&window.console[e](o.toString())}return i.reset=()=>{t=[]},i.drain=()=>{let r=t;return t=[],r},i},_=HD("vp_dash_live_debug",!1);var zo=1e4,md=3;var GD=6e4,YD=10,KD=1,XD=500,ua=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 WD,this.chunkRateEstimator=new aa(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=hd(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setAutoQualityLimits(e){this.autoQualityLimits=e}switchByName(e){let t;for(let i=0;i<this.manifest.length;++i)if(t=this.manifest[i],t.name===e){this._switchToQuality(t);return}}catchUp(){if(this.rep&&(_({m:"ldp.catchUp.1"}),this.rep.stop()),this.currentManifestEntry){let e=this.params.playbackState.getState();this.paused=e==="paused",_({m:"ldp.catchUp.2"}),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()?(_({m:"ldp.play.1"}),this._playVideoElement()):(_({m:"ldp.play.2"}),this._notifyBuffering(!0))):(_({m:"ldp.play.3"}),this.catchUp())}startPlay(e,t){this.autoQuality=t,_({m:"startPlay",url:e.jidxUrl}),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=hd(e),_({m:"ldp.reinit",url: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;_({m:"iv"}),e.addEventListener("error",()=>{!!e.error&&!this.destroyed&&(_({m:"iv.err",e:e.error?.code+":"+e.error?.message}),t(`Video element error: ${e.error?.code}, details: ${e.error?.message}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{let i=this._getBufferSizeSec();!this.paused&&i<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(i+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){let{logger:e,videoElement:t}=this.params,i=t.buffered.length,r;i!==0&&!this.waitingForFirstBufferAfterSrcChange&&(r=t.buffered.start(i-1),t.currentTime<r&&(e("Fixup stall"),_({m:"ldp.fs",t:r}),t.currentTime=r))}_selectQuality(e){let{videoElement:t}=this.params,i,r,a,n=t&&1.62*($.display.pixelRatio||1)*t.offsetHeight||520;for(let o=0;o<this.manifest.length;++o){a=this.manifest[o];let{max:u,min:l}=this.autoQualityLimits||{};!ry({limits:this.autoQualityLimits,highestAvailableHeight:this.manifest[0].video.height,lowestAvailableHeight:(0,Ty.default)(this.manifest,-1).video.height})&&(u&&a.video.height>u||l&&a.video.height<l)||(a.bitrate<e&&n>Math.min(a.video.height,a.video.width)?(!r||a.bitrate>r.bitrate)&&(r=a):(!i||i.bitrate>a.bitrate)&&(i=a))}return r||i}shouldPlay(){if(this.paused)return!1;let t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||Ho(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){let{logger:i,videoElement:r,playerCallback:a}=this.params;this.mediaSource=new window.MediaSource,i("setting video src"),r.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(_({m:"sourceopen",c:e.codecs}),this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.mediaSource?.addEventListener("sourceclose",o=>{_({m:"sourceclose"})}),this.videoPlayStarted=!1,r.addEventListener("canplay",()=>{_({m:"canplay"}),this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});let n=()=>{gy(r,"progress",()=>{r.buffered.length?(r.currentTime=r.buffered.start(0),this.waitingForFirstBufferAfterSrcChange=!1,a({name:"playing"})):n()})};this.waitingForFirstBufferAfterSrcChange=!0,n()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new na(md,zo,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:i,playerCallback:r}=this.params,a=!1,n=null,o=null,u=null,l=null,p=!1,c=()=>{let y=a&&(!p||p===this.rep);return y||t("Not running!"),y},d=(y,x,A)=>{u&&u.abort(),u=Ur(this.urlResolver.resolve(y,!1),x,A,()=>this._retryCallback()).withTimeout(zo).withBitrateReporting(this.bitrateSwitcher).withRetryCount(md).withFinally(()=>{u=null}).send()},h=(y,x,A)=>{oa(this.filesFetcher),o?.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(y,!1),x,A,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},f=y=>{let x=i.playbackRate;i.playbackRate!==y&&(t(`Playback rate switch: ${x}=>${y}`),i.playbackRate=y)},m=y=>{this.lowLatency=y,t(`lowLatency changed to ${y}`),S()},S=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)f(1);else{let y=this._getBufferSizeSec();if(this.bufferStates.length<5){f(1);return}let A=Se()-1e4,R=0;for(let B=0;B<this.bufferStates.length;B++){let k=this.bufferStates[B];y=Math.min(y,k.buf),k.ts<A&&R++}this.bufferStates.splice(0,R),t(`update playback rate; minBuffer=${y} drop=${R} jitter=${this.sourceJitter}`);let w=y-KD;this.sourceJitter>=0?w-=this.sourceJitter/2:this.sourceJitter-=1,w>3?f(1.15):w>1?f(1.1):w>.3?f(1.05):f(1)}},g=y=>{let x,A=()=>x&&x.start?x.start.length:0,R=L=>x.start[L]/1e3,w=L=>x.dur[L]/1e3,B=L=>x.fragIndex+L,k=(L,H)=>({chunkIdx:B(L),startTS:R(L),dur:w(L),discontinuity:H}),F=()=>{let L=0;if(x&&x.dur){let H=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,X=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,re=H;this.sourceJitter>1&&(re+=this.sourceJitter-1);let le=x.dur.length-1;for(;le>=0&&(re-=x.dur[le],!(re<=0));--le);L=Math.min(le,x.dur.length-1-X),L=Math.max(L,0)}return k(L,!0)},C=L=>{let H=A();if(!(H<=0)){if(Ho(L)){for(let X=0;X<H;X++)if(R(X)>L)return k(X)}return F()}},E=L=>{let H=A(),X=L?L.chunkIdx+1:0,re=X-x.fragIndex;if(!(H<=0)){if(!L||re<0||re-H>YD)return t(`Resync: offset=${re} bChunks=${H} chunk=`+JSON.stringify(L)),F();if(!(re>=H))return k(X-x.fragIndex,!1)}},I=(L,H,X)=>{l&&l.abort(),l=Ur(this.urlResolver.resolve(L,!0,this.lowLatency),H,X,()=>this._retryCallback()).withTimeout(zo).withRetryCount(md).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(L,H)=>{I(y,X=>{if(!c())return;x=X;let re=!!x.lowLatency;re!==this.lowLatency&&m(re);let le=0;for(let Te=0;Te<x.dur.length;++Te)le+=x.dur[Te];le>0&&(oa(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(le/x.dur.length)),r({name:"index",zeroTime:x.zeroTime,shiftDuration:x.shiftDuration}),this.sourceJitter=x.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,x.jitter/1e3)):1,L(C(H))},()=>this._handleNetworkError())},nextChunk:E}},v=()=>{a=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),oa(this.filesFetcher),this.filesFetcher.abortAll()};return p={start:y=>{let{videoElement:x,logger:A}=this.params,R=g(e.jidxUrl),w,B,k,F,C=0,E,I,N,L=()=>{E&&(clearTimeout(E),E=void 0);let q=Math.max(XD,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),Ee=C+q,Be=Se(),me=Math.min(1e4,Ee-Be);C=Be;let at=()=>{l||c()&&R.seek(()=>{c()&&(C=Se(),H(),L())})};me>0?E=window.setTimeout(()=>{this.paused?L():at()},me):at()},H=()=>{let q;for(;q=R.nextChunk(F);)F=q,Ie(q);let Ee=R.nextChunk(k);if(Ee){if(k&&Ee.discontinuity){A("Detected discontinuity; restarting playback"),this.paused?L():(v(),_({m:"ldp.fetchChunkIdx.0"}),this._initPlayerWith(e));return}Te(Ee)}else L()},X=(q,Ee)=>{if(!c()||!this.sourceBuffer){_({m:"ab.0",c:[!c(),!this.sourceBuffer]});return}let Be,me,at,Jt=dt=>{_({m:"ldp.postpone",t:dt}),window.setTimeout(()=>{c()&&X(q,Ee)},dt)};if(this.sourceBuffer.updating)A("Source buffer is updating; delaying appendBuffer"),_({m:"ldp.ab.1"}),Jt(100);else{let dt=Se(),Xe=x.currentTime;!this.paused&&x.buffered.length>1&&I===Xe&&dt-N>500&&(A("Stall suspected; trying to fix"),this._fixupStall()),I!==Xe&&(I=Xe,N=dt);let Zt=this._getBufferSizeSec();if(Zt>30)_({m:"ldp.ab.3"}),A(`Buffered ${Zt} seconds; delaying appendBuffer`),Jt(2e3);else try{if(this.params.config.useInvalidBufferFix&&V(this.mediaSource,this.sourceBuffer))return;this.sourceBuffer.appendBuffer(q),this.videoPlayStarted?(_({m:"ldp.ab.5"}),this.bufferStates.push({ts:dt,buf:Zt}),S(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(_({m:"ldp.ab.4"}),this.videoPlayStarted=!0,this._playVideoElement()),Ee&&Ee()}catch(pt){if(_({m:"ldp.ab.err",e:pt.name}),pt.name==="QuotaExceededError")A("QuotaExceededError; delaying appendBuffer"),at=this.sourceBuffer.buffered.length,at!==0&&(Be=this.sourceBuffer.buffered.start(0),me=Xe,me-Be>4&&this.sourceBuffer.remove(Be,me-3)),Jt(1e3);else throw pt}}},re=()=>{B&&w&&(A([`Appending chunk, sz=${B.byteLength}:`,JSON.stringify(k)]),X(B,function(){B=null,H()}))},le=q=>e.fragUrlTemplate.replace("%%id%%",q.chunkIdx),Te=q=>{c()&&h(le(q),(Ee,Be)=>{if(c()){if(Be/=1e3,B=Ee,k=q,n=q.startTS,Be){let me=Math.min(10,q.dur/Be);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*me:me}re()}},()=>this._handleNetworkError())},Ie=q=>{c()&&(oa(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(le(q),!1)))},z=q=>{c()&&(e.cachedHeader=q,X(q,()=>{w=!0,re()}))};a=!0,R.seek(q=>{if(c()){if(C=Se(),!q){L();return}F=q,!QD(y)||q.startTS>y?Te(q):(k=q,H())}},y),e.cachedHeader?z(e.cachedHeader):d(e.headerUrl,z,()=>this._handleNetworkError())},stop:v,getTimestampSec:()=>n},p}_switchToQuality(e){let{logger:t,playerCallback:i}=this.params,r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),Ho(r)&&(r+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,oa(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return Ho(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,i=c=>{if(!this.autoQuality)return;let d,h,f;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&c<this.bitrate&&(h=this._getBufferSizeSec(),f=c/this.bitrate,h>10&&f>.8||h>15&&f>.5||h>20&&f>.3)){e(`Not switching: buffer=${Math.floor(h)}; bitrate=${this.bitrate}; newRate=${Math.floor(c)}`);return}d=this._selectQuality(c),d?this._switchToQuality(d):e(`Could not find quality by bitrate ${c}`)},a={updateChunk:(d,h)=>{let f=Se();if(this.chunkRateEstimator.addInterval(d,f,h)){let S=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:h,duration:f-d,speed:S}),!0}},get:()=>{let d=this.chunkRateEstimator.getBitRate();return d?d*.85:0}},n=-1/0,o,u=!0,l=()=>{let c=a.get();if(c&&o&&this.autoQuality){if(u&&c>o&&pd(n)<3e4)return;i(c)}u=this.autoQuality};return{updateChunk:(c,d)=>{let h=a.updateChunk(c,d);return h&&l(),h},notifySwitch:c=>{let d=Se();c<o&&(n=d),o=c}}}_fetchManifest(e,t,i){this.manifestRequest=Ur(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(zo).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;Me(e,()=>{this.soundProhibitedEvent$.next()}).then(t=>{_({m:"ldp.pve.1"}),t||(_({m:"ldp.pve.2"}),this.params.liveOffset.pause(),this.params.videoState.setState("paused"))})}_handleManifestUpdate(e){let{logger:t,playerCallback:i,videoElement:r}=this.params,a=n=>{let o=[];return n?.length?(n.forEach((u,l)=>{u.video&&r.canPlayType(u.codecs).replace(/no/,"")&&window.MediaSource?.isTypeSupported?.(u.codecs)&&(u.index=l,o.push(u))}),o.sort(function(u,l){return u.video&&l.video?l.video.height-u.video.height:l.bitrate-u.bitrate}),o):(i({name:"error",type:"empty_manifest"}),[])};this.manifest=a(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),i({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},GD))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var wy=D(ni(),1);import{debounce as JD,filter as Iy,fromEvent as ZD,interval as eB,isHigher as tB,isInvariantQuality as iB,isLower as rB,merge as sB,Subject as Ey,Subscription as aB}from"@vkontakte/videoplayer-shared/es2024";var bd=class{constructor(){this.onDroopedVideoFramesLimit$=new Ey;this.subscription=new aB;this.playing=!1;this.tracks=[];this.forceChecker$=new Ey;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&&!iB(e.quality)&&this.onChangeQuality(e.quality)};this.checkDroppedFrames=()=>{let{totalVideoFrames:e,droppedVideoFrames:t}=this.video.getVideoPlaybackQuality(),i=e-this.prevTotalVideoFrames,r=t-this.prevDroppedVideoFrames,a=1-(i-r)/i;!isNaN(a)&&a>0&&this.log({message:`[dropped]. current dropped percent: ${a}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(a)&&a>=this.droppedFramesChecker.percentLimit&&tB(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(ZD(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=eB(this.droppedFramesChecker.checkTime).pipe(Iy(()=>this.playing),Iy(()=>{let r=!!this.isForceCheckCounter;return r&&(this.isForceCheckCounter-=1),!r})),t=this.forceChecker$.pipe(JD(this.droppedFramesChecker.checkTime)),i=sB(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,wy.default)(this.limitCounts).filter(([,i])=>i>=this.droppedFramesChecker.countLimit).sort(([i],[r])=>rB(i,r)?-1:1)?.[0]?.[0];return e??t}get isEnabled(){return this.droppedFramesChecker.enabled&&this.isDroppedFramesCheckerSupport}get isDroppedFramesCheckerSupport(){return!!this.video&&typeof this.video.getVideoPlaybackQuality=="function"}savePrevFrameCounts(e,t){this.prevTotalVideoFrames=e,this.prevDroppedVideoFrames=t}},li=bd;import{map as nB,Observable as oB}from"@vkontakte/videoplayer-shared/es2024";import{fromEvent as uB}from"@vkontakte/videoplayer-shared/es2024";var la=()=>!!window.documentPictureInPicture?.window||!!document.pictureInPictureElement;var lB=(s,e)=>new oB(t=>{if(!window.IntersectionObserver)return;let i={root:null},r=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||la()))},{...i,...e});r.observe(s);let a=uB(document,"visibilitychange").pipe(nB(n=>!document.hidden||la())).subscribe(n=>t.next(n));return()=>{r.unobserve(s),a.unsubscribe()}}),Ye=lB;var gB=["paused","playing","ready"],SB=["paused","playing","ready"],ca=class{constructor(e){this.subscription=new mB;this.videoState=new O("stopped");this.representations$=new Sd([]);this.droppedFramesManager=new li;this.maxSeekBackTime$=new Sd(1/0);this.zeroTime$=new Sd(void 0);this.liveOffset=new qi;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:Py.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{let t=e.manifest,i=[];for(let r of t){let a=r.name??r.index.toString(10),n=$t(r.name)??bB(r.video),o=r.bitrate/1e3,u={...r.video};if(!n)continue;let l={id:a,quality:n,bitrate:o,size:u};i.push({track:l,representation:r})}this.representations$.next(i),this.params.output.availableVideoTracks$.next(i.map(({track:r})=>r)),this.videoState.getTransition()?.to==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let t=e.quality,i=this.representations$.getValue().find(({representation:r})=>r===t)?.track;this.params.output.hostname$.next(new URL(t.headerUrl,this.params.source.url).hostname),gd(i)&&this.params.output.currentVideoTrack$.next(i);break}case"bandwidth":{let{size:t,duration:i}=e;this.params.dependencies.throughputEstimator.addRawSpeed(t,i);break}case"index":{this.maxSeekBackTime$.next(e.shiftDuration||0),this.zeroTime$.next(e.zeroTime);break}}};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; seekState: ${JSON.stringify(a)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"));return}if(t)return;let n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if((0,vd.default)(SB,e)&&(n||o)){this.prepare();return}if(r?.to!=="paused"&&a.state==="requested"&&(0,vd.default)(gB,e)){this.seek(a.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(ne(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"){_({m:"dlp.sync.1"}),this.videoState.startTransitionTo("playing");let u=r?.from;u&&u==="ready"&&(_({m:"dlp.sync.2"}),this.dash.catchUp()),_({m:"dlp.sync.3"}),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(ne(this.params.source.url,u))}return;default:return xy(e)}};this.textTracksManager=new We(e.source.url),this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=r=>{e.output.error$.next({id:"DashLiveProvider",category:Py.WTF,message:"DashLiveProvider internal logic error",thrown:r})};this.subscription.add(Ry(this.videoState.stateChangeStarted$.pipe(Qo(r=>({transition:r,type:"start"}))),this.videoState.stateChangeEnded$.pipe(Qo(r=>({transition:r,type:"end"})))).subscribe(({transition:r,type:a})=>{_({m:"dlp.s.1",t:a+`:${r.from}-${r.to}`}),this.log({message:`[videoState change] ${a}: ${JSON.stringify(r)}`})})),this.video=Pe(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(ce(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);let i=$e(this.video);this.subscription.add(()=>i.destroy()),this.subscription.add(this.representations$.pipe(Qo(r=>r.map(({track:a})=>a)),Ay(r=>!!r.length),fB()).subscribe(r=>this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:r}))),this.subscription.add(i.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready")},t)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused")},t)).add(i.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.videoState.setState("playing")},t)).add(i.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(pB(),Qo(r=>-r/1e3)).subscribe(this.params.output.duration$)).add(cB({zeroTime:this.zeroTime$.pipe(Ay(gd)),position:i.timeUpdate$}).subscribe(({zeroTime:r,position:a})=>this.params.output.liveTime$.next(r+a*1e3),t)).add(ot(this.video,this.params.desiredState.isLooped,t)).add(Re(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(Qe(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(Ye(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:r,min:a}})=>{this.dash.setAutoQualityLimits({max:r&&$y(r),min:a&&$y(a)}),this.params.output.autoVideoTrackLimits$.next({max:r,min:a})})).add(this.videoState.stateChangeEnded$.subscribe(r=>{switch(r.to){case"stopped":this.params.output.position$.next(0),this.params.output.duration$.next(1/0),_({m:"dlp.vse.s"}),this.params.desiredState.playbackState.setState("stopped");break;case"manifest_ready":case"ready":this.params.desiredState.playbackState.getTransition()?.to==="ready"&&(_({m:"dlp.vse.r"}),this.params.desiredState.playbackState.setState("ready"));break;case"paused":_({m:"dlp.vse.pa"}),this.params.desiredState.playbackState.setState("paused");break;case"playing":_({m:"dlp.vse.pl"}),this.params.desiredState.playbackState.setState("playing");break;default:return xy(r.to)}},t)).add(Ry(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,hB(["init"])).pipe(dB(0)).subscribe(this.syncPlayback,t))}destroy(){_({m:"dlp.destroy"}),this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),Ae(this.video)}createLiveDashPlayer(){let e=new ua({videoElement:this.video,videoState:this.videoState,playbackState:this.params.desiredState.playbackState,liveOffset:this.liveOffset,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode,manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount,useInvalidBufferFix:this.params.tuning.useInvalidBufferFix||!1},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){let e=this.representations$.getValue(),t=this.params.desiredState.videoTrack.getTransition()?.to??this.params.desiredState.videoTrack.getState(),i=this.params.desiredState.autoVideoTrackSwitching.getTransition()?.to??this.params.desiredState.autoVideoTrackSwitching.getState(),r=!i&&gd(t)?t:ut(e.map(({track:l})=>l),{container:this.video.getBoundingClientRect(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),a=r?.id,n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.videoTrack.getState()?.id,u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(r&&(n||a!==o)&&this.setVideoTrack(r),u&&this.setAutoQuality(i),n||u||a!==o){let l=e.find(({track:p})=>p.id===a)?.representation;ky(l,"Representations missing"),this.dash.startPlay(l,i)}}setVideoTrack(e){let t=this.representations$.getValue().find(({track:i})=>i.id===e.id)?.representation;ky(t,`No such representation ${e.id}`),this.dash.switchByName(t.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),r=t==="paused"&&i==="paused",a=-e,n=a<=this.maxSeekBackTime$.getValue()?a:0;this.params.output.position$.next(e/1e3),_({m:"dlp.seek",p:e,no:n,url:this.params.source.url}),this.dash.reinit(ne(this.params.source.url,n)),r&&this.dash.pause(),this.liveOffset.resetTo(n,r)}};var My=ca;import{filterChanged as $0}from"@vkontakte/videoplayer-shared/es2024";import{assertNever as BB,assertNonNullable as CB,debounce as VB,ErrorCategory as Uy,filter as Ad,filterChanged as Rd,fromEvent as _B,isNonNullable as qy,isNullable as OB,map as $d,merge as Jo,observableFrom as Md,once as jy,Subscription as NB,throttle as FB}from"@vkontakte/videoplayer-shared/es2024";var yd=D(Ge(),1);import{videoSizeToQuality as vB}from"@vkontakte/videoplayer-shared/es2024";var Ly=({id:s,width:e,height:t,bitrate:i,fps:r,quality:a,streamId:n})=>{let o=(a?$t(a):void 0)??vB({width:e,height:t});return o&&{id:s,quality:o,bitrate:i,size:{width:e,height:t},fps:r,streamId:n}},Dy=({id:s,bitrate:e})=>({id:s,bitrate:e}),By=({language:s,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:s,label:e});var Td=({id:s,language:e,label:t,codecs:i,isDefault:r})=>({id:s,language:e,label:t,codec:(0,yd.default)(i.split("."),0),isDefault:r}),Wo=({id:s,language:e,label:t,hdr:i,codecs:r})=>({id:s,language:e,hdr:i,label:t,codec:(0,yd.default)(r.split("."),0)});var Ue=s=>s.type==="template";var Go=class{constructor(e,t){this.fov=e,this.orientation=t}};var Yo=class{constructor(e,t){this.rotating=!1;this.fading=!1;this.lastTickTS=0;this.lastCameraTurnTS=0;this.fadeStartSpeed=null;this.fadeTime=0;this.camera=e,this.options=t,this.rotationSpeed={x:0,y:0,z:0},this.fadeCorrection=1/(this.options.speedFadeTime/1e3)**2}turnCamera(e=0,t=0,i=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+i)}pointCameraTo(e=0,t=0,i=0){t=this.limitCameraRotationY(t);let r=e-this.camera.orientation.x,a=t-this.camera.orientation.y,n=i-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=i,this.lastCameraTurn={x:r,y:a,z:n},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,i){this.rotationSpeed.x=e??this.rotationSpeed.x,this.rotationSpeed.y=t??this.rotationSpeed.y,this.rotationSpeed.z=i??this.rotationSpeed.z}startRotation(){this.rotating=!0}stopRotation(e=!1){e?(this.setRotationSpeed(0,0,0),this.fadeStartSpeed=null):this.startFading(this.rotationSpeed.x,this.rotationSpeed.y,this.rotationSpeed.z),this.rotating=!1}onCameraRelease(){if(this.lastCameraTurn&&this.lastCameraTurnTS){let e=Date.now()-this.lastCameraTurnTS;if(e<this.options.speedFadeThreshold){let t=(1-e/this.options.speedFadeThreshold)*this.options.rotationSpeedCorrection;this.startFading(this.lastCameraTurn.x*t,this.lastCameraTurn.y*t,this.lastCameraTurn.z*t)}}}startFading(e,t,i){this.setRotationSpeed(e,t,i),this.fadeStartSpeed={...this.rotationSpeed},this.fading=!0}stopFading(){this.fadeStartSpeed=null,this.fading=!0,this.fadeTime=0}limitCameraRotationY(e){return Math.max(-this.options.maxYawAngle,Math.min(e,this.options.maxYawAngle))}tick(e){if(!this.lastTickTS){this.lastTickTS=e,this.lastCameraTurnTS=Date.now();return}let t=e-this.lastTickTS,i=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i);else if(this.fading&&this.fadeStartSpeed){let r=-this.fadeCorrection*(this.fadeTime/1e3)**2+1;this.setRotationSpeed(this.fadeStartSpeed.x*r,this.fadeStartSpeed.y*r,this.fadeStartSpeed.z*r),r>0?this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}};var Cy=`attribute vec2 a_vertex;
|
|
125
118
|
attribute vec2 a_texel;
|
|
126
119
|
|
|
127
120
|
varying vec2 v_texel;
|
|
@@ -132,7 +125,7 @@ void main(void) {
|
|
|
132
125
|
// save texel vector to pass to fragment shader
|
|
133
126
|
v_texel = a_texel;
|
|
134
127
|
}
|
|
135
|
-
`;var
|
|
128
|
+
`;var Vy=`#ifdef GL_ES
|
|
136
129
|
precision highp float;
|
|
137
130
|
precision highp int;
|
|
138
131
|
#else
|
|
@@ -175,6 +168,17 @@ void main(void) {
|
|
|
175
168
|
// sample using new coordinates
|
|
176
169
|
gl_FragColor = texture2D(u_texture, tc);
|
|
177
170
|
}
|
|
178
|
-
`;var Pr=class{constructor(e,t,i){this.videoInitialized=!1;this.active=!1;this.container=e,this.sourceVideoElement=t,this.params=i,this.canvas=this.createCanvas();let r=this.canvas.getContext("webgl");if(!r)throw new Error("Could not initialize WebGL context");this.gl=r,this.container.appendChild(this.canvas),this.camera=new Eo(this.params.fov,this.params.orientation),this.cameraRotationManager=new xo(this.camera,{rotationSpeed:this.params.rotationSpeed,maxYawAngle:this.params.maxYawAngle,rotationSpeedCorrection:this.params.rotationSpeedCorrection,degreeToPixelCorrection:this.params.degreeToPixelCorrection,speedFadeTime:this.params.speedFadeTime,speedFadeThreshold:this.params.speedFadeThreshold}),this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.textureMappingBuffer=this.createTextureMappingBuffer(),this.updateTextureMappingBuffer(),this.program=this.createProgram(),this.videoTexture=this.createTexture(),this.gl.useProgram(this.program),this.videoElementDataLoadedFn=this.onDataLoadedHandler.bind(this),this.renderFn=this.render.bind(this)}play(){this.active||(this.videoInitialized?this.doPlay():this.sourceVideoElement.readyState>=2?(this.videoInitialized=!0,this.doPlay()):this.sourceVideoElement.addEventListener("loadeddata",this.videoElementDataLoadedFn))}stop(){this.active=!1}startCameraManualRotation(e,t){this.cameraRotationManager.setRotationSpeed(e*this.params.rotationSpeed,t*this.params.rotationSpeed,0),this.cameraRotationManager.startRotation()}stopCameraManualRotation(e=!1){this.cameraRotationManager.stopRotation(e)}turnCamera(e,t){this.cameraRotationManager.turnCamera(e,t)}pointCameraTo(e,t){this.cameraRotationManager.pointCameraTo(e,t)}pixelToDegree(e){return{x:this.params.degreeToPixelCorrection*this.params.fov.x*-e.x/this.viewportWidth,y:this.params.degreeToPixelCorrection*this.params.fov.y*e.y/this.viewportHeight}}getCameraRotation(){return this.camera.orientation}holdCamera(){this.cameraRotationManager.stopRotation(!0)}releaseCamera(){this.cameraRotationManager.onCameraRelease()}destroy(){this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),this.stop(),this.canvas.remove()}setViewportSize(e,t){this.viewportWidth=e,this.viewportHeight=t,this.canvas.width=this.viewportWidth,this.canvas.height=this.viewportHeight,this.gl.viewport(0,0,this.canvas.width,this.canvas.height)}onDataLoadedHandler(){this.videoInitialized=!0,this.doPlay()}doPlay(){this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.active=!0,this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),requestAnimationFrame(this.renderFn)}render(e){this.cameraRotationManager.tick(e),this.updateTexture(),this.updateTextureMappingBuffer();let t=this.gl.getAttribLocation(this.program,"a_vertex"),i=this.gl.getAttribLocation(this.program,"a_texel"),r=this.gl.getUniformLocation(this.program,"u_texture"),s=this.gl.getUniformLocation(this.program,"u_focus");this.gl.enableVertexAttribArray(t),this.gl.enableVertexAttribArray(i),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.vertexBuffer),this.gl.vertexAttribPointer(t,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.vertexAttribPointer(i,2,this.gl.FLOAT,!1,0,0),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.uniform1i(r,0),this.gl.uniform2f(s,-this.camera.orientation.x,-this.camera.orientation.y),this.gl.drawArrays(this.gl.TRIANGLE_FAN,0,4),this.gl.bindTexture(this.gl.TEXTURE_2D,null),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),this.gl.disableVertexAttribArray(t),this.gl.disableVertexAttribArray(i),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){let i=this.gl.createShader(t);if(!i)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(i,e),this.gl.compileShader(i),!this.gl.getShaderParameter(i,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(i));return i}createProgram(){let e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");let t=this.createShader(pT,this.gl.VERTEX_SHADER),i=this.createShader(hT,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,i),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){let e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,i=1,r=this.frameHeight/(this.frameWidth/this.viewportWidth);return r>this.viewportHeight?t=this.viewportHeight/r:i=r/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-i,t,-i,t,i,-t,i]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){let e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,i=this.camera.fov.x/360/2,r=this.camera.fov.y/180/2,s=e-i,n=t-r,u=e+i,o=t-r,l=e+i,p=t+r,c=e-i,d=t+r;return[s,n,u,o,l,p,c,d]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){let e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}};import{isNullable as _C,now as ls,once as OC,Subscription as FC,ValueSubject as Qc,isNonNullable as NC,safeStorage as Gc,filterChanged as qC}from"@vkontakte/videoplayer-shared/es2024";var wo="stalls_manager_metrics",zc="stalls_manager_abr_params",fT="stalls_manager_default_tuning_abr_params",Yc=class{constructor(){this.isSeeked$=new Qc(!1);this.isBuffering$=new Qc(!1);this.maxQualityLimit=void 0;this.currentStallsCount=0;this.sumStallsDuration=0;this.lastStallDuration=0;this.providerStartWatchingTimestamp=0;this.lastUniqueVideoTrackSelectedTimestamp=0;this.predictedThroughputWithoutData=0;this.subscription=new FC;this.severeStallOccurred$=new Qc(!1)}init(e){this.currentStallDuration$=e.currentStallDuration$,this.videoLastDataObtainedTimestamp$=e.videoLastDataObtainedTimestamp$,this.throughput$=e.throughput$,this.rtt$=e.rtt$,this.tuning=e.tuning,this.abrParams=e.abrParams,this.duration=e.duration,this.resetStoredAbrParamsIfNeeded(),this.subscribe(e)}get videoMaxQualityLimit(){return this.maxQualityLimit}get predictedThroughput(){return this.predictedThroughputWithoutData}get abrTuningParams(){let t=(this.tuning.ignoreDynamicAbrForShortVideo?this.tuning.enabled&&this.duration>this.tuning.minTvtToBeCounted:this.tuning.enabled)?this.getStoredData(zc):{};return{...this.abrParams,...t}}set lastVideoTrackSelected(e){this.lastUniqueVideoTrackSelected?.id!==e.id&&(this.lastUniqueVideoTrackSelected=e,this.lastUniqueVideoTrackSelectedTimestamp=ls(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe(),this.currentStallDuration$.getValue()!==0&&this.updateStallData();let e=(ls()-this.providerStartWatchingTimestamp-this.sumStallsDuration)/1e3,t=this.sumStallsDuration;this.addStallInfoToHistory(e,t),this.updateStoredAbrParams()}resetStoredAbrParamsIfNeeded(){let{bitrateFactorAtEmptyBuffer:e,bitrateFactorAtFullBuffer:t,containerSizeFactor:i}={...this.getStoredData(fT)},{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:s,containerSizeFactor:n}={...this.abrParams};this.tuning.enabled&&e===r&&t===s&&i===n||(this.removeStoredData(zc),this.setStoredData(fT,{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:s,containerSizeFactor:n}))}updateStoredAbrParams(){let e=[],t=this.getStoredData(wo,"[]");if(!this.tuning.enabled||t.length<this.tuning.stallsMetricsHistoryLength)return;let i=t.reduce((s,n)=>s+n.tvt,0);if(this.tuning.useTotalStallsDurationPerTvt){let n=t.reduce((u,o)=>u+o.stallsDuration,0)/i;e.push(this.calculateOptimalAbrParams(n,i))}if(this.tuning.useAverageStallsDurationPerTvt){let s=t.reduce((n,u)=>n+u.stallsDurationPerTvt,0)/t.length;e.push(this.calculateOptimalAbrParams(s,i))}this.tuning.useEmaStallsDurationPerTvt&&e.push(this.calculateOptimalAbrParams(t[t.length-1].stallsDurationPerTvtSmoothed,i));let r={bitrateFactorAtEmptyBuffer:Math.max(...e.map(s=>s.bitrateFactorAtEmptyBuffer)),bitrateFactorAtFullBuffer:Math.max(...e.map(s=>s.bitrateFactorAtFullBuffer)),containerSizeFactor:Math.min(...e.map(s=>s.containerSizeFactor))};this.setStoredData(wo,[]),this.setStoredData(zc,r)}calculateOptimalAbrParams(e,t){let{targetStallsDurationPerTvt:i,deviationStallsDurationPerTvt:r,criticalStallsDurationPerTvt:s,abrAdjustingSpeed:n,significantTvt:u}=this.tuning,o=n*Math.min(t/u,1),l=this.abrTuningParams;return e<i-r?l={bitrateFactorAtEmptyBuffer:Math.max(l.bitrateFactorAtEmptyBuffer-o,this.abrParams.minBitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.max(l.bitrateFactorAtFullBuffer-o,this.abrParams.minBitrateFactorAtFullBuffer),containerSizeFactor:Math.min(l.containerSizeFactor+o,this.abrParams.maxContainerSizeFactor)}:e>i+r&&(l={bitrateFactorAtEmptyBuffer:Math.min(l.bitrateFactorAtEmptyBuffer+o,this.abrParams.maxBitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.min(l.bitrateFactorAtFullBuffer+o,this.abrParams.maxBitrateFactorAtFullBuffer),containerSizeFactor:Math.max(l.containerSizeFactor-o,this.abrParams.minContainerSizeFactor)}),e>s&&(l={bitrateFactorAtEmptyBuffer:Math.max(l.bitrateFactorAtEmptyBuffer,this.abrParams.bitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.max(l.bitrateFactorAtFullBuffer,this.abrParams.bitrateFactorAtFullBuffer),containerSizeFactor:Math.min(l.containerSizeFactor,this.abrParams.containerSizeFactor)}),l}getStoredData(e,t="{}"){return JSON.parse(Gc.get(e)??t)}setStoredData(e,t){Gc.set(e,JSON.stringify(t))}removeStoredData(e){Gc.remove(e)}addStallInfoToHistory(e,t){if(e<this.tuning.minTvtToBeCounted||e>this.tuning.maxTvtToBeCounted||e*1e3<t)return;let i=this.getStoredData(wo,"[]"),r=t/e,s=i.length?Lt(i[i.length-1].stallsDurationPerTvtSmoothed,t/e,this.tuning.emaAlpha):r,n={tvt:e,stallsDuration:t,stallsDurationPerTvt:r,stallsDurationPerTvtSmoothed:s};i.push(n),i.length>this.tuning.stallsMetricsHistoryLength&&i.shift(),this.setStoredData(wo,i)}updateStallData(){this.providerStartWatchingTimestamp&&!this.isSeeked$.getValue()&&(this.sumStallsDuration+=Math.min(this.lastStallDuration,this.tuning.maxPossibleStallDuration),this.currentStallsCount++)}subscribe(e){this.subscription.add(e.isSeeked$.subscribe(this.isSeeked$)),this.subscription.add(e.isBuffering$.subscribe(this.isBuffering$)),this.subscription.add(e.looped$.subscribe(t=>this.currentStallsCount=0)),this.subscription.add(e.playing$.pipe(OC()).subscribe(t=>this.providerStartWatchingTimestamp=ls())),this.subscription.add(this.currentStallDuration$.pipe(qC()).subscribe(t=>{let{stallDurationNoDataBeforeQualityDecrease:i,stallCountBeforeQualityDecrease:r,resetQualityRestrictionTimeout:s,ignoreStallsOnSeek:n}=this.tuning;if(_C(this.lastUniqueVideoTrackSelected)||n&&this.isSeeked$.getValue())return;let u=this.rtt$.getValue(),o=this.throughput$.getValue(),l=this.videoLastDataObtainedTimestamp$.getValue(),p=ls(),c=r&&this.currentStallsCount>=r,d=i&&p-this.lastUniqueVideoTrackSelectedTimestamp>=i+u&&p-l>=i+u&&t>=i;(c||d)&&(this.severeStallOccurred$.next(!0),window.clearTimeout(this.qualityRestrictionTimer),this.maxQualityLimit=this.lastUniqueVideoTrackSelected.quality,NC(this.lastUniqueVideoTrackSelected.bitrate)&&o>this.lastUniqueVideoTrackSelected.bitrate&&(this.predictedThroughputWithoutData=this.lastUniqueVideoTrackSelected.bitrate)),!t&&ls()-this.providerStartWatchingTimestamp>this.lastStallDuration&&(this.updateStallData(),this.severeStallOccurred$.next(!1),window.clearTimeout(this.qualityRestrictionTimer),this.qualityRestrictionTimer=window.setTimeout(()=>{this.maxQualityLimit=void 0,this.predictedThroughputWithoutData=0},s)),this.lastStallDuration=t}))}},Ao=Yc;import{combine as UC,map as jC,observeElementSize as HC,Subscription as WC,ValueSubject as Kc,noop as QC}from"@vkontakte/videoplayer-shared/es2024";var ko=class{constructor(){this.subscription=new WC;this.pipSize$=new Kc(void 0);this.videoSize$=new Kc(void 0);this.elementSize$=new Kc(void 0);this.pictureInPictureWindowRemoveEventListener=QC}connect({observableVideo:e,video:t}){let i=r=>{let s=r.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add(HC(t).subscribe(this.videoSize$)).add(e.enterPip$.subscribe(({pictureInPictureWindow:r})=>{this.pipSize$.next({width:r.width,height:r.height}),r.addEventListener("resize",i),this.pictureInPictureWindowRemoveEventListener=()=>{r.removeEventListener("resize",i)}})).add(e.leavePip$.subscribe(()=>{this.pictureInPictureWindowRemoveEventListener()})).add(UC({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(jC(({videoSize:r,inPip:s,pipSize:n})=>s?n:r)).subscribe(this.elementSize$))}getValue(){return this.elementSize$.getValue()}subscribe(e,t){return this.elementSize$.subscribe(e,t)}getObservable(){return this.elementSize$}destroy(){this.pictureInPictureWindowRemoveEventListener(),this.subscription.unsubscribe()}};import{filter as mT,map as GC,once as bT}from"@vkontakte/videoplayer-shared/es2024";var Rr=({subscription:a,desiredState:e,videoElement$:t,observableVideo:i})=>{if(!D.browser.isSafari)return;let r=0,s=!1;a.add(e.volume.stateChangeStarted$.pipe(GC(()=>{let n=e.volume.getTransition(),u=t.getValue();return!u||!n?!1:!n.to.muted&&u.muted}),mT(n=>!!n),bT()).subscribe(()=>{r=performance.now(),s=!0})),a.add(i.playbackRateState$.pipe(mT(()=>s),bT()).subscribe(()=>{let n=t.getValue(),u=e.playbackRate.getState();n&&u!==n.playbackRate&&performance.now()-r<1e3&&(n.playbackRate=u)}))};var Mi=class{constructor(e){this.subscription=new tB;this.videoState=new O("stopped");this.observableVideo=null;this.droppedFramesManager=new mr;this.stallsManager=new Ao;this.elementSizeManager=new ko;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Gt;this.audioTrackSwitchHistory=new Gt;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(r.state==="requested"&&i?.to!=="paused"&&e!=="stopped"&&t!=="stopped"&&this.seek(r.position,r.forcePrecise),t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),k(this.params.desiredState.playbackState,"stopped",!0));return}switch(e){case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();return;case"ready":t==="paused"?(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="ready"&&k(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):t==="playing"&&this.video.paused?this.playIfAllowed():i?.to==="playing"&&k(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&k(this.params.desiredState.playbackState,"paused");return;default:return YC(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new Pr(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:e.projectionData?.pose.yaw||0,y:e.projectionData?.pose.pitch||0,z:e.projectionData?.pose.roll||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSizeManager.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.textTracksManager=new Ye(e.source.url),this.params=e,this.video=De(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(Se(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 Io({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;eB(this.observableVideo)&&(this.observableVideo=Ve(this.video),this.subscription.add(()=>this.observableVideo?.destroy()));let i=this.constructor.name,r=n=>{e.error$.next({id:i,category:gT.WTF,message:`${i} internal logic error`,thrown:n})},s=(n,u)=>this.subscription.add(n.subscribe(u,r));return{output:e,desiredState:t,observableVideo:this.observableVideo,genericErrorListener:r,connect:s}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:s}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(Xc(c=>!!c.length),ST()).subscribe(c=>{this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:c})}));let n=this.params.desiredState.seekState.stateChangeEnded$.pipe(ds(c=>c.to.state!=="none"),cs());this.stallsManager.init({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$,videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,tuning:this.params.tuning.stallsManager,abrParams:this.params.tuning.autoTrackSelection,isBuffering$:i.isBuffering$,looped$:i.looped$,playing$:i.playing$,duration:this.video.duration}),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(this.player.error$,e.error$),s(this.player.fetcherRecoverableError$,e.fetcherRecoverableError$),s(this.player.fetcherError$,e.fetcherError$),s(this.player.manifestRequested$,e.manifestRequested$),s(this.player.firstBytesManifest$,e.firstBytesManifest$),s(this.player.manifestReceived$,e.manifestReceived$),s(this.player.firstBytesRequested$,e.firstBytesRequested$),s(this.player.firstBytesReceived$,e.firstBytesReceived$),s(this.player.lastConnectionType$,e.httpConnectionType$),s(this.player.lastConnectionReused$,e.httpConnectionReused$),s(this.player.isLive$,e.isLive$),s(this.player.lastRequestFirstBytes$.pipe(Xc(vT),ST()),e.firstBytesEvent$),s(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),s(this.videoState.stateChangeEnded$.pipe(ds(c=>c.to)),this.params.output.playbackState$),this.subscription.add(i.looped$.subscribe(()=>this.player.warmUpMediaSourceIfNeeded(),r)),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(bt(this.video,t.isLooped,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),Rr({subscription:this.subscription,desiredState:t,videoElement$:this.params.output.element$,observableVideo:i}),this.subscription.add(Be(this.video,t.volume,i.volumeState$,r)),this.subscription.add(ze(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),s(Ke(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),k(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),k(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(i.ended$.subscribe(()=>{this.videoState.setState("paused"),k(t.playbackState,"paused")})),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 d=this.player.getStreams(),h=this.player.getCodecs();if(KC(d,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let m=[];for(let g of d.audio){m.push(Dc(g));let v=[];for(let S of g.representations){let T=Xy(S);v.push(T),this.audioTracksMap.set(T,{stream:g,representation:S})}this.audioStreamsMap.set(g,v)}this.params.output.availableAudioStreams$.next(m)}let f=[];for(let m of d.video){f.push(Cc(m));let g=[];for(let v of m.representations){let S=es({...v,streamId:m.id});S&&(g.push(S),this.videoTracksMap.set(S,{stream:m,representation:v}))}this.videoStreamsMap.set(m,g)}this.params.output.availableVideoStreams$.next(f);for(let m of d.text)for(let g of m.representations){let v=Jy(m,g);this.textTracksMap.set(v,{stream:m,representation:g})}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),h?.video&&this.params.output.availableVideoCodecs$.next(h.video),h?.audio&&this.params.output.availableAudioCodecs$.next(h.audio),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else c==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r));let u=ps(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$,ZC(this.video,"progress")).pipe(Xc(()=>this.videoTracksMap.size>0)),{abrThrottle:o}=this.params.tuning.dash;o&&(u=u.pipe(iB(o))),this.subscription.add(u.subscribe(async()=>{let c=this.player.state$.getState(),d=this.player.state$.getTransition();if(c!=="manifest_ready"&&c!=="running"||d)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let h=this.selectVideoAudioRepresentations();if(!h)return;let[f,m]=h,g=[...this.videoTracksMap.keys()].find(S=>this.videoTracksMap.get(S)?.representation.id===f.id);vT(g)&&(this.stallsManager.lastVideoTrackSelected=g);let v=this.params.desiredState.autoVideoTrackLimits.getTransition();if(v&&this.params.output.autoVideoTrackLimits$.next(v.to),c==="manifest_ready")await this.player.initRepresentations(f.id,m?.id,this.params.sourceHls);else if(await this.player.switchRepresentation("video",f.id),m){let S=!!t.audioStream.getTransition();await this.player.switchRepresentation("audio",m.id,S)}},r)),this.subscription.add(XC({videoState:this.videoState.stateChangeEnded$,autoVideoTrackState:ps(Po([t.autoVideoTrackSwitching.getState()]),t.autoVideoTrackSwitching.stateChangeEnded$.pipe(ds(c=>c.to)))}).pipe(ds(({videoState:c,autoVideoTrackState:d})=>c.to!=="stopped"&&d),cs()).subscribe(c=>this.player.setSmartRepresentationSwitch(c))),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(cs()).subscribe(c=>{let d=[...this.videoTracksMap.entries()].find(([,{representation:v}])=>v.id===c);if(!d){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[h,{stream:f}]=d,m=this.params.desiredState.videoStream.getTransition();m&&m.to&&m.to.id===f.id&&this.params.desiredState.videoStream.setState(m.to),e.currentVideoTrack$.next(h),e.currentVideoStream$.next(Cc(f));let g=this.player.calculateDurationFromSegments();g&&this.params.output.duration$.next(g/1e3)},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(cs()).subscribe(c=>{let d=[...this.audioTracksMap.entries()].find(([,{representation:g}])=>g.id===c);if(!d){e.currentAudioStream$.next(void 0);return}let[h,{stream:f}]=d,m=this.params.desiredState.audioStream.getTransition();m&&m.to&&m.to.id===f.id&&this.params.desiredState.audioStream.setState(m.to),e.currentAudioStream$.next(Dc(f))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(c=>{if(c?.is3dVideo&&this.params.tuning.spherical?.enabled)try{this.init3DScene(c),e.is3DVideo$.next(!0)}catch(d){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${d}`})}else this.destroy3DScene(),this.params.tuning.spherical?.enabled&&e.is3DVideo$.next(!1)},r)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,r)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,r)),this.textTracksManager.connect(this.video,t,e);let l=t.playbackState.stateChangeStarted$.pipe(ds(({to:c})=>c==="ready"),cs());this.subscription.add(ps(l,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,Po(["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(ps(l,this.player.state$.stateChangeEnded$,Po(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let p=ps(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Po(["init"])).pipe(JC(0));this.subscription.add(p.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?ga:ba,t=this.params.tuning.useNewAutoSelectVideoTrack?zn:Gn,i=this.params.tuning.useNewAutoSelectVideoTrack?St:Qn,{desiredState:r,output:s}=this.params,n=r.autoVideoTrackSwitching.getState(),u=r.videoTrack.getState()?.id,o=[...this.videoTracksMap.keys()].find(({id:w})=>w===u),l=s.currentVideoTrack$.getValue(),p=r.videoStream.getState()??(o&&this.videoTracksMap.get(o)?.stream)??this.videoStreamsMap.size===1?this.videoStreamsMap.keys().next().value:void 0;if(!p)return;let c=[...this.videoStreamsMap.keys()].find(({id:w})=>w===p.id),d=c&&this.videoStreamsMap.get(c);if(!d)return;let h=ye(this.video.buffered,this.video.currentTime*1e3),f;this.player.isActiveLive$.getValue()?f=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?f=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:f=n?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let m=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,g=Math.min(h/Math.min(f,m||1/0),1),v=r.audioStream.getState()??(this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0),S=[...this.audioStreamsMap.keys()].find(({id:w})=>w===v?.id)??this.audioStreamsMap.keys().next().value,T=0;if(S){if(o&&!n){let w=e(o,d,this.audioStreamsMap.get(S)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);T=Math.max(T,w?.bitrate??-1/0)}if(l){let w=e(l,d,this.audioStreamsMap.get(S)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);T=Math.max(T,w?.bitrate??-1/0)}}let y=o;(n||!y)&&(y=i(d,{container:this.elementSizeManager.getValue(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.stallsManager.abrTuningParams,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:T,forwardBufferHealth:g,current:l,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,stallsVideoMaxQualityLimit:this.stallsManager.videoMaxQualityLimit,stallsPredictedThroughput:this.stallsManager.predictedThroughput,abrLogger:this.params.dependencies.abrLogger}));let A=S&&t(y,d,this.audioStreamsMap.get(S)??[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.stallsManager.abrTuningParams,forwardBufferHealth:g,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),P=this.videoTracksMap.get(y)?.representation,L=A&&this.audioTracksMap.get(A)?.representation;if(P&&L)return[P,L];if(P&&!L&&this.audioTracksMap.size===0)return[P,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){_e(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:gT.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),Ce(this.video),this.tracer.end()}};var hs=class extends Mi{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 Jc,merge as yT,filter as TT,filterChanged as IT,isNullable as Zc,map as ET,ValueSubject as ed,isNonNullable as rB}from"@vkontakte/videoplayer-shared/es2024";var fs=class extends Mi{constructor(e){super(e),this.textTracksManager.destroy()}subscribe(){super.subscribe();let e=!1,t=-1,{output:i,observableVideo:r,desiredState:s,connect:n}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canPlayLiveTailBuffer$.next(!0),n(r.timeUpdate$,i.liveBufferTime$),n(this.player.liveSeekableDuration$,i.duration$),n(this.player.liveLatency$,i.liveLatency$);let u=new ed(1);n(r.playbackRateState$,u),this.params.tuning.dashCmafLive.catchupLiveForMutedInactiveTab&&this.subscription.add(i.elementVisible$.pipe(IT()).subscribe(o=>{let l=i.position$.getValue(),p=i.volume$.getValue(),c=!p.volume||p.muted;!o&&!l&&c?e=!0:o&&e&&(this.seek(0),e=!1)})),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(s.isLowLatency.stateChangeEnded$.pipe(ET(o=>o.to)).subscribe(this.player.isLowLatency$)).add(Jc({liveBufferTime:i.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(ET(({liveBufferTime:o,liveAvailabilityStartTime:l})=>o&&l?o*1e3+l+t:void 0)).subscribe(i.liveTime$)).add(Jc({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:yT(r.playbackRateState$,new ed(1))}).pipe(TT(({liveStreamStatus:o,liveDuration:l})=>o==="active"&&!!l)).subscribe(({liveDuration:o,playbackRate:l})=>{let p=i.liveBufferTime$.getValue(),c=i.position$.getValue(),{playbackCatchupSpeedup:d}=this.params.tuning.dashCmafLive.lowLatency;c||l<1-d||this.video.paused||Zc(p)||(t=o-p)})).add(Jc({time:i.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:yT(r.playbackRateState$,new ed(1))}).pipe(IT((o,l)=>this.player.liveStreamStatus$.getValue()==="active"?o.liveDuration===l.liveDuration:o.time===l.time)).subscribe(({time:o,liveDuration:l,playbackRate:p})=>{let c=i.position$.getValue(),{playbackCatchupSpeedup:d}=this.params.tuning.dashCmafLive.lowLatency;if(!c&&!this.video.paused&&p>=1-d||Zc(o)||Zc(l))return;let h=-1*(l-o-t);i.position$.next(Math.min(h,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(o=>{if(o){let l=Zy(o);this.params.output.availableTextTracks$.next([l])}})),this.params.tuning.dashCmafLive.externalStopControl||this.subscription.add(this.player.liveStreamStatus$.pipe(TT(o=>rB(o))).subscribe(o=>i.isLiveEnded$.next(o==="unpublished"&&i.position$.getValue()===0)))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=Math.trunc(t/1e3<=Math.abs(this.params.output.duration$.getValue())?t:0);this.player.seekLive(i).then(()=>{this.params.output.position$.next(e/1e3)})}};import{assertNever as LB,assertNonNullable as MB,combine as DB,debounce as CB,ErrorCategory as NT,filter as bd,filterChanged as xs,fromEvent as BB,isNonNullable as qT,isNullable as VB,map as ws,merge as As,observableFrom as Fo,once as UT,Subscription as _B}from"@vkontakte/videoplayer-shared/es2024";var FT=C(xe(),1),fd=C(wa(),1);import{abortable as cd,assertNonNullable as Lr,combine as Mr,ErrorCategory as lt,filter as Vo,filterChanged as Ts,flattenObject as Is,fromEvent as It,getTraceSubscriptionMethod as yB,interval as dd,isNonNullable as Es,isNullable as _T,map as Dr,merge as Oi,now as pd,Subject as Bt,Subscription as hd,SubscriptionRemovable as TB,tap as IB,throttle as OT,ValueSubject as Z}from"@vkontakte/videoplayer-shared/es2024";var Mo=C(xe(),1),Vi=C(nt(),1),Do=C(wa(),1);var DT=C(An(),1);import{assertNever as aB,ErrorCategory as xT,Subject as wT}from"@vkontakte/videoplayer-shared/es2024";var sB=18,AT=!1;try{AT=D.browser.isSafari&&!!D.browser.safariVersion&&D.browser.safariVersion<=sB}catch(a){console.error(a)}var td=class{constructor(e){this.bufferFull$=new wT;this.error$=new wT;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:xT.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:e})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(i=>{let r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(r=>{let s={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(s),this.pull()})}async abort(e){return new Promise(t=>{let i,r=s=>{this.abortRequested=!1,t(s)};AT&&e?i={operation:"safariAbort",init:e,callback:r}:i={operation:"abort",callback:r};for(let{callback:s}of this.queue)s(!1);this.abortRequested=!0,i&&(this.queue=[i]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){if((this.buffer.updating||this.currentTask||this.destroyed)&&!this.abortRequested)return;let e=this.queue.shift();if(!e)return;if(e.signal?.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(r){r instanceof DOMException&&r.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):r instanceof DOMException&&r.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:xT.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:r}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){let{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:aB(t)}}},kT=td;import{abortable as ei,assertNonNullable as $e,ErrorCategory as Ci,fromEvent as nd,getExponentialDelay as od,isHigher as cB,isNonNullable as ti,isNullable as ue,now as Lo,once as dB,Subject as pB,Subscription as hB,ValueSubject as Bi}from"@vkontakte/videoplayer-shared/es2024";var id=C(nt(),1);import{videoSizeToQuality as nB,throttleFn as oB}from"@vkontakte/videoplayer-shared/es2024";var ms=({id:a,width:e,height:t,bitrate:i,fps:r,quality:s,streamId:n})=>{let u=(s?Qt(s):void 0)??nB({width:e,height:t});return u&&{id:a,quality:u,bitrate:i,size:{width:e,height:t},fps:r,streamId:n}},PT=({id:a,bitrate:e})=>({id:a,bitrate:e}),RT=({language:a,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),$T=({language:a,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),rd=({id:a,language:e,label:t,codecs:i,isDefault:r})=>({id:a,language:e,label:t,codec:(0,id.default)(i.split("."),0),isDefault:r}),ad=({id:a,language:e,label:t,hdr:i,codecs:r})=>({id:a,language:e,hdr:i,label:t,codec:(0,id.default)(r.split("."),0)}),sd=a=>"url"in a,He=a=>a.type==="template";var LT=a=>{a.sort((t,i)=>t.from-i.from);let e=[a[0]];for(let t=1;t<a.length;t++){let{from:i,to:r}=a[t],s=e[e.length-1];s.to>=i?s.to=Math.max(s.to,r):e.push(a[t])}return e},Di=(a,e)=>{for(let t of a)if(e(t))return t;return null},MT=a=>{let e=!1,t=oB(()=>{e=!0},a);return()=>{try{return t(),e}finally{e=!1}}};import{fromEvent as uB,Subscription as lB}from"@vkontakte/videoplayer-shared/es2024";var Ro=a=>{let e=[];for(let t=0;t<a.length;t++){let i=Math.floor(a.start(t)*1e3),r=Math.ceil(a.end(t)*1e3);e.push(i,r)}return e};var $o=class{constructor(e,t){this.lastUpdateTs=0;this.lastCallTs=0;this.prevRanges=[];this.subscription=new lB;this.mediaSource=e,this.sourceBuffer=t,this.subscription.add(uB(this.sourceBuffer,"updateend").subscribe(()=>this.updateend()))}updateend(){if(!V(this.mediaSource,this.sourceBuffer))return;let{prevRanges:e}=this,t=Ro(this.sourceBuffer.buffered);this.prevRanges=t,this.isRangesRemoved(e,t)&&(this.lastUpdateTs=Date.now())}isRangesRemoved(e,t){if(e.length!==t.length)return!0;for(let i=0;i<e.length;i+=2){let r=e[i],s=e[i+1],n=t[i],u=t[i+1];if(n>r||u<s)return!0}return!1}wasUpdated(){let{lastCallTs:e,lastUpdateTs:t}=this;return this.lastCallTs=Date.now(),e<=t}destroy(){this.subscription.unsubscribe()}};var bs=class{constructor(e,t,i,{fetcher:r,tuning:s,getCurrentPosition:n,isActiveLowLatency:u,compatibilityMode:o=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new Bi(0);this.currentLowLatencySegmentLength$=new Bi(0);this.currentSegmentLength$=new Bi(0);this.onLastSegment$=new Bi(!1);this.fullyBuffered$=new Bi(!1);this.playingRepresentation$=new Bi(void 0);this.playingRepresentationInit$=new Bi(void 0);this.error$=new pB;this.gaps=[];this.subscription=new hB;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new Y;this.switchAbortController=new Y;this.destroyAbortController=new Y;this.useSmartRepresentationSwitch=!1;this.bufferLimit=1/0;this.failedDownloads=0;this.baseUrls=[];this.baseUrlsIndex=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.lastDataObtainedTimestampMs=0;this.loadByteRangeSegmentsTimeoutId=0;this.sourceBufferBufferedDiff=null;this.startWith=ei(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);$e(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new kT(this.sourceBuffer),this.sourceBufferBufferedDiff=new $o(this.mediaSource,this.sourceBuffer),this.subscription.add(nd(this.sourceBuffer,"updateend").subscribe(()=>{this.maintain()})),this.subscription.add(nd(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:Ci.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let u=this.getCurrentPosition();if(!this.sourceBuffer||!u||!V(this.mediaSource,this.sourceBuffer))return;let o=Math.min(this.bufferLimit,gr(this.sourceBuffer.buffered)*.8);this.bufferLimit=o;let l=ye(this.sourceBuffer.buffered,u),p=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(u,n*2,l<p).catch(c=>{this.handleAsyncError(c,"pruneBuffer")})})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);let i=this.initData.get(t.id),r=this.segments.get(t.id),s=this.parsedInitData.get(t.id);$e(i,"No init buffer for starting representation"),$e(r,"No segments for starting representation"),i instanceof ArrayBuffer&&(this.searchGaps(r,t),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s))}.bind(this));this.switchTo=ei(this.destroyAbortController.signal,async function*(e,t=!1){if(!V(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);$e(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if(ue(s)||ue(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),$e(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!V(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();ti(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=ei(this.destroyAbortController.signal,async function*(e,t=!1){if(!V(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);$e(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if(ue(s)||ue(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),$e(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!V(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();ti(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=ei(this.destroyAbortController.signal,async function*(e){let t=(0,Do.default)(e,o=>o.representations);if(!this.downloadingRepresentationId||!t.length)return;this.isSeekingLive=!0;for(let o of this.representations.keys()){let l=t.find(d=>d.id===o);l&&this.representations.set(o,l);let p=this.representations.get(o);if(!p||!He(p.segmentReference)){this.isSeekingLive=!1;return}let c=this.getActualLiveStartingSegments(p.segmentReference);this.segments.set(p.id,c)}let i=this.switchingToRepresentationId??this.downloadingRepresentationId,r=this.representations.get(i);$e(r,`Representation not found by id ${i}`);let s=this.segments.get(i);$e(s,"No segments for starting representation");let n=this.initData.get(i);if($e(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer)){this.isSeekingLive=!1;return}let u=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),u&&(yield this.sourceBufferTaskQueue.remove(u.from*1e3,u.to*1e3,this.destroyAbortController.signal)),this.searchGaps(s,r),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));this.fetcher=r,this.tuning=s,this.compatibilityMode=o,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=u,this.isLive=!!l?.live,this.baseUrls=l?.baseUrls??[],this.initData=new Map(i.map(p=>[p.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(p=>[p.id,p])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchToWithPreviousAbort(e,t=!1){!V(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new Y,ei(this.switchAbortController.signal,async function*(i,r=!1){this.switchingToRepresentationId=i;let s=this.representations.get(i);$e(s,`No such representation ${i}`);let n=this.segments.get(i),u=this.initData.get(i);if(ue(u)||ue(n)?yield this.loadInit(s,"high",!1):u instanceof Promise&&(yield u),n=this.segments.get(i),$e(n,"No segments for starting representation"),u=this.initData.get(i),!(!(u instanceof ArrayBuffer)||!this.sourceBuffer||!V(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(u,this.downloadAbortController.signal),r)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=i,yield this.dropBuffer();else{let o=this.getCurrentPosition();ti(o)&&!this.isLive&&(this.bufferLimit=this.forwardBufferTarget,yield this.pruneBuffer(o,1/0,!0)),this.downloadingRepresentationId=i,this.switchingToRepresentationId=void 0}this.maintain()}}.bind(this))(e,t))}warmUpMediaSource(){!ue(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 Y,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(ue(e)||ue(this.downloadingRepresentationId)||ue(this.playingRepresentationId)||ue(this.sourceBuffer)||!V(this.mediaSource,this.sourceBuffer)||ti(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.representations.get(this.playingRepresentationId),r=this.segments.get(this.downloadingRepresentationId),s=this.segments.get(this.playingRepresentationId);if($e(t,`No such representation ${this.downloadingRepresentationId}`),$e(i,`No such representation ${this.playingRepresentationId}`),ue(r)||ue(s))return;let n=r.find(d=>e>=d.time.from&&e<d.time.to);ti(n)&&isFinite(n.time.from)&&isFinite(n.time.to)&&this.currentSegmentLength$.next(n?.time.to-n.time.from);let u=e,o=100;if(this.playingRepresentationId!==this.downloadingRepresentationId){let d=this.getForwardBufferDuration(e),h=ms(i),f=ms(t),m=this.useSmartRepresentationSwitch&&this.tuning.dash.useNewRepresentationSwitch&&this.tuning.dash.useSmartRepresentationSwitch&&ti(h)&&ti(f)&&cB(h.quality,f.quality),g=this.useSmartRepresentationSwitch&&this.tuning.dash.useNewRepresentationSwitch&&this.tuning.dash.useDelayedRepresentationSwitch;if(m||g?u+=Math.min(d,this.tuning.dash.representationSwitchForwardBufferGap):n&&n.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&d>=n.time.to-e+o&&(u=n?n.time.to+o:-1/0),this.tuning.dash.useNewRepresentationSwitch){let S=[...this.segments.entries()].map(([T,y])=>{let A=y.find(P=>e>=P.time.from&&e<P.time.to);return{representationId:T,status:A?.status}}).find(T=>T.status==="fed")?.representationId;S&&(this.playingRepresentationId=S,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)))}}if(isFinite(this.bufferLimit)&&gr(this.sourceBuffer.buffered)>=this.bufferLimit){let d=ye(this.sourceBuffer.buffered,e),h=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,d<h).catch(f=>{this.handleAsyncError(f,"pruneBuffer")});return}let p=null;if(!this.activeSegments.size&&(p=this.selectForwardBufferSegments(r,t.segmentReference.type,u),p?.length)){let d="auto";if(this.tuning.dash.useFetchPriorityHints&&n)if((0,Mo.default)(p,n))d="high";else{let h=(0,Vi.default)(p,0);h&&h.time.from-n.time.to>=this.forwardBufferTarget/2&&(d="low")}this.loadSegments(p,t,d).catch(h=>{this.handleAsyncError(h,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&n&&n.status==="fed"&&!p?.length&&ye(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let c=(0,Vi.default)(r,-1);!this.isLive&&c&&(this.fullyBuffered$.next(c.time.to-e-ye(this.sourceBuffer.buffered,e)<o),this.onLastSegment$.next(e-c.time.from>0))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let i=0,r=this.isLive?this.liveInitialAdditionalOffset:0;for(let s of e)Math.trunc(s.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:s.time.from+r,persistent:!0}),i=s.time.to;ti(t.duration)&&t.duration-i>0&&!this.isLive&&this.gaps.push({representation:t.id,from:i,to:t.duration,persistent:!0})}getActualLiveStartingSegments(e){let t=e.segments,i=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,r=[],s=0,n=t.length-1;do r.unshift(t[n]),s+=t[n].time.to-t[n].time.from,n--;while(s<i&&n>=0);return this.liveInitialAdditionalOffset=s-i,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){let t=e?.streams[this.kind];if(!t)return;let i=(0,Do.default)(t,s=>s.representations).find(s=>s.id===this.downloadingRepresentationId);if(!i)return;let r=this.segments.get(i.id);if(r?.length)return{from:r[0].time.from,to:r[r.length-1].time.to}}updateLive(e){if(!e||[...this.segments.values()].every(i=>!i.length))return;let t=(0,Do.default)(e.streams[this.kind],i=>i.representations)??[];for(let i of t){if(!i||!He(i.segmentReference))return;let r=i.segmentReference.segments.map(l=>({...l,status:"none",size:void 0})),s=100,n=this.segments.get(i.id)??[],u=(0,Vi.default)(n,-1)?.time.to??0,o=r?.findIndex(l=>u>=l.time.from+s&&u<=l.time.to+s);if(o===-1){this.liveUpdateSegmentIndex=0;let l=this.getActualLiveStartingSegments(i.segmentReference);this.segments.set(i.id,l)}else{let l=r.slice(o+1);this.segments.set(i.id,[...n,...l])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;$e(e);let t=this.segments.get(e);if(t?.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}setSmartRepresentationSwitch(e){this.useSmartRepresentationSwitch=e}updateLowLatencyLiveIfNeeded(e){let t=0;for(let i of this.representations.values()){let r=i.segmentReference;if(!He(r))return;let s=this.segments.get(i.id);if(!s)continue;let n=s.find(o=>Math.floor(o.time.from)===Math.floor(e.time.from));if(n&&!isFinite(n.time.to)&&(n.time.to=e.time.to,t=n.time.to-n.time.from),!!!s.find(o=>Math.floor(o.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let o=Math.round(e.time.to*r.timescale/1e3).toString(10),l=ut(r.segmentTemplateUrl,{segmentTime:o});s.push({status:"none",time:{from:e.time.to,to:1/0},url:l})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){let t=this.switchingToRepresentationId??this.downloadingRepresentationId??this.playingRepresentationId;if(!t)return;let i=this.segments.get(t);return i?i.find(s=>s.time.from<=e&&s.time.to>=e)?.time.from??void 0:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),this.sourceBufferTaskQueue?.destroy(),this.sourceBufferBufferedDiff?.destroy(),this.gapDetectionIdleCallback&&Je&&Je(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&Je&&Je(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(e){if(!(e instanceof DOMException&&e.name==="NotFoundError"))throw e}this.sourceBuffer=null,this.downloadAbortController.abort(),this.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,i){return this.checkEjectedSegments(),this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){if(this.playingRepresentationId!==this.downloadingRepresentationId){let i=e.findIndex(r=>t>=r.time.from&&t<r.time.to);this.liveUpdateSegmentIndex=i}return this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):null}selectForwardBufferSegmentsRecord(e,t,i){let r=this.getForwardBufferDuration(i),s=e.findIndex(({status:d,time:{from:h,to:f}},m)=>{let g=h<=i&&f>=i,v=h>i||g||m===0&&i===0,S=Math.min(this.forwardBufferTarget,this.bufferLimit),T=this.preloadOnly&&h<=i+S||r<S&&f-h>=S||f<=i+S;return(d==="none"||d==="partially_ejected"&&v&&T&&this.sourceBuffer&&V(this.mediaSource,this.sourceBuffer)&&!(Te(this.sourceBuffer.buffered,h)&&Te(this.sourceBuffer.buffered,f)))&&v&&T});if(s===-1)return null;if(t!=="byteRange")return e.slice(s,s+1);let n=e,u=0,o=0,l=[],p=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,c=this.preloadOnly?this.forwardBufferTarget:0;for(let d=s;d<n.length&&(u<=p||o<=c);d++){let h=n[d];if(u+=h.byte.to+1-h.byte.from,o+=h.time.to+1-h.time.from,h.status==="none"||h.status==="partially_ejected")l.push(h);else break}return l}async loadSegments(e,t,i="auto"){He(t.segmentReference)?await this.loadTemplateSegment(e[0],t,i):await this.loadByteRangeSegments(e,t,i)}async loadTemplateSegment(e,t,i="auto"){e.status="downloading";let r={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(r);let{range:s,url:n,signal:u,onProgress:o,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&u&&(await ei(u,async function*(){let p=od(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,p))}.bind(this))(),u.aborted&&this.abortActiveSegments([e]));try{let p=await this.fetcher.fetch(n,{range:s,signal:u,onProgress:o,priority:i,isLowLatency:this.isActiveLowLatency(),bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation});if(this.lastDataObtainedTimestampMs=Lo(),!p)return;let c=new DataView(p),d=yt(t.mime);if(!isFinite(r.segment.time.to)){let m=t.segmentReference.timescale;r.segment.time.to=d.getChunkEndTime(c,m)}o&&r.feedingBytes&&l?await Promise.all(l):await this.sourceBufferTaskQueue.append(c,u);let{serverDataReceivedTimestamp:h,serverDataPreparedTime:f}=d.getServerLatencyTimestamps(c);h&&f&&this.currentLiveSegmentServerLatency$.next(f-h),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(p){this.abortActiveSegments([e]),Tt(p)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}updateRepresentationsBaseUrlIfNeeded(){if(!this.tuning.dash.enableBaseUrlSupport||!this.baseUrls.length||this.failedDownloads<=this.tuning.dash.maxSegmentRetryCount)return;this.baseUrlsIndex=(this.baseUrlsIndex+1)%this.baseUrls.length;let e=this.baseUrls[this.baseUrlsIndex];for(let t of this.representations.values())He(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}async loadByteRangeSegments(e,t,i="auto"){if(!e.length)return;for(let o of e)o.status="downloading",this.activeSegments.add({segment:o,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:r,url:s,signal:n,onProgress:u}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(await ei(n,async function*(){let o=od(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,o),nd(window,"online").pipe(dB()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(s,{range:r,onProgress:u,signal:n,priority:i,bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation}),this.lastDataObtainedTimestampMs=Lo(),this.failedDownloads=0}catch(o){this.abortActiveSegments(e),Tt(o)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(He(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:(0,Vi.default)(e,0).byte.from,to:(0,Vi.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:i,range:r,signal:s,onProgress:async(u,o)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=Lo(),await this.onSomeByteRangesDataLoaded({dataView:u,loaded:o,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:Ci.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!He(t.segmentReference))throw new Error("Representation is not template type");let i=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&i.searchParams.set("low-latency","yes");let r=i.toString(),{signal:s}=this.downloadAbortController,n=[],o=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,p)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=Lo();let c=this.onSomeTemplateDataLoaded({dataView:l,loaded:p,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(c)}catch(c){this.error$.next({id:"SegmentFeeding",category:Ci.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}}:void 0;return{url:r,signal:s,onProgress:o,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,Mo.default)(e,t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:s}){if(!this.activeSegments.size||!V(this.mediaSource,this.sourceBuffer))return;let n=this.representations.get(t);if(n)for(let u of this.activeSegments){let{segment:o}=u;if(u.representationId===t){if(s.aborted){r();continue}if(u.loadedBytes=i,u.loadedBytes>u.feedingBytes){let l=new DataView(e.buffer,e.byteOffset+u.feedingBytes,u.loadedBytes-u.feedingBytes),p=yt(n.mime).parseFeedableSegmentChunk(l,this.isLive);p?.byteLength&&(o.status="partially_fed",u.feedingBytes+=p.byteLength,await this.sourceBufferTaskQueue.append(p),u.fedBytes+=p.byteLength)}}}}async onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size||!V(this.mediaSource,this.sourceBuffer))return;let u=this.representations.get(t);if(u)for(let o of this.activeSegments){if(o.representationId!==t)continue;if(s.aborted){await n();continue}let{segment:l}=o,p=l.byte.from-i,c=l.byte.to-i,d=c-p+1,h=p<r,f=c<=r;if(h){if(l.status==="downloading"&&f){l.status="downloaded";let m=new DataView(e.buffer,e.byteOffset+p,d);await this.sourceBufferTaskQueue.append(m,s)&&!s.aborted?this.onSegmentFullyAppended(o,t):await n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(l.status==="downloading"||l.status==="partially_fed")&&(o.loadedBytes=Math.min(d,r-p),o.loadedBytes>o.feedingBytes)){let m=new DataView(e.buffer,e.byteOffset+p+o.feedingBytes,o.loadedBytes-o.feedingBytes),g=o.loadedBytes===d?m:yt(u.mime).parseFeedableSegmentChunk(m);g?.byteLength&&(l.status="partially_fed",o.feedingBytes+=g.byteLength,await this.sourceBufferTaskQueue.append(g,s)&&!s.aborted?(o.fedBytes+=g.byteLength,o.fedBytes===d&&this.onSegmentFullyAppended(o,t)):await n())}}}}onSegmentFullyAppended(e,t){if(!(ue(this.sourceBuffer)||!V(this.mediaSource,this.sourceBuffer))){!this.isLive&&D.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(Te(this.sourceBuffer.buffered,e.segment.time.from,100)&&Te(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:Ci.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",sd(e.segment)&&(e.segment.size=e.fedBytes);for(let i of this.representations.values()){if(i.id===t)continue;let r=this.segments.get(i.id);if(r)for(let s of r)s.status==="fed"&&Math.round(s.time.from)===Math.round(e.segment.time.from)&&Math.round(s.time.to)===Math.round(e.segment.time.to)&&(s.status="none")}this.isActiveLowLatency()&&this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,e.segment)}}abortSegment(e){e.status==="partially_fed"?e.status="partially_ejected":e.status!=="partially_ejected"&&(e.status="none");for(let t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[r,s]of this.initData.entries()){let n=s instanceof Promise;t||=n,s===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let i=this.representations.get(e);i&&(this.initLoadIdleCallback=zt(()=>(0,DT.default)(this.loadInit(i,"low",!1),()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",i=!1){let r=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!i&&this.failedDownloads>0?ei(this.destroyAbortController.signal,async function*(){let u=od(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(o=>setTimeout(o,u))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,yt(e.mime),r)).then(u=>{if(!u)return;let{init:o,dataView:l,segments:p}=u,c=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,c);let d=p;this.isLive&&He(e.segmentReference)&&(d=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,d),o&&this.parsedInitData.set(e.id,o)}).then(()=>this.failedDownloads=0,u=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:Ci.WTF,message:"loadInit threw",thrown:u})});return this.initData.set(e.id,n),n}async dropBuffer(){for(let e of this.segments.values())for(let t of e)t.status="none";await this.pruneBuffer(0,1/0,!0)}async pruneBuffer(e,t,i=!1){if(!this.sourceBuffer||!V(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||ue(e))return!1;this.checkEjectedSegments();let r=[],s=0,n=u=>{if(s>=t)return;r.push({...u.time});let o=sd(u)?u.size??0:u.byte.to-u.byte.from;s+=o};for(let u of this.segments.values())for(let o of u){let l=o.time.to<=e-this.tuning.dash.bufferPruningSafeZone,p=o.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(l||p)&&o.status==="fed"&&n(o)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let o=this.sourceBuffer.buffered.start(u)*1e3,l=this.sourceBuffer.buffered.end(u)*1e3,p=0;for(let c of this.segments.values())for(let d of c)(0,Mo.default)(["none","partially_ejected"],d.status)&&Math.round(d.time.from)<=Math.round(o)&&Math.round(d.time.to)>=Math.round(l)&&p++;if(p===this.segments.size){let c={time:{from:o,to:l},url:"",status:"none"};n(c)}}if(r.length&&i){let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let o of this.segments.values())for(let l of o)l.time.from>=e+u&&l.status==="fed"&&n(l)}return r.length?(r=LT(r),(await Promise.all(r.map(o=>this.sourceBufferTaskQueue.remove(o.from,o.to)))).reduce((o,l)=>o||l,!1)):!1}async abortBuffer(){if(!this.sourceBuffer||!V(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||!V(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||!V(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||!V(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||ue(e)?0:ye(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!this.sourceBuffer||!V(this.mediaSource,this.sourceBuffer))return;let{buffered:i}=this.sourceBuffer,r={representation:e,from:t.time.from,to:t.time.to,persistent:!1};for(let s=0;s<i.length;s++){let n=i.start(s)*1e3,u=i.end(s)*1e3;if(!(u<=t.time.from||n>=t.time.to)){if(n<=t.time.from&&u>=t.time.to){r=void 0;break}u>t.time.from&&u<t.time.to&&(r.from=u),n<t.time.to&&n>t.time.from&&(r.to=n)}}r&&r.to-r.from>1&&!this.gaps.some(s=>r&&s.from===r.from&&s.to===r.to)&&this.gaps.push(r)}detectGapsWhenIdle(e,t){if(this.gapDetectionIdleCallback||!this.sourceBuffer||!V(this.mediaSource,this.sourceBuffer))return;let{buffered:i}=this.sourceBuffer;this.gaps=this.gaps.filter(r=>{if(r.persistent)return!0;let s=Math.round(r.from),n=Math.round(r.to);for(let u=0;u<i.length;u++)if(s>=Math.round(i.start(u)*1e3)&&n<=Math.round(i.end(u)*1e3))return!1;return!0}),this.gapDetectionIdleCallback=zt(()=>{try{this.detectGaps(e,t)}catch(r){this.error$.next({id:"GapDetection",category:Ci.WTF,message:"detectGaps threw",thrown:r})}finally{this.gapDetectionIdleCallback=null}})}checkEjectedSegments(){if(ue(this.sourceBuffer)||!V(this.mediaSource,this.sourceBuffer)||ue(this.playingRepresentationId)||this.sourceBufferBufferedDiff&&!this.sourceBufferBufferedDiff.wasUpdated())return;let e=Ro(this.sourceBuffer.buffered),t=100;for(let i of this.segments.values())for(let r of i){let{status:s}=r;if(s!=="fed"&&s!=="partially_ejected")continue;let n=Math.floor(r.time.from),u=Math.ceil(r.time.to),o=!1,l=0;for(let p=0;p<e.length;p+=2){let c=e[p],d=e[p+1];o||(o=c-t<=n&&d+t>=u),(n>=c&&n<d-t||u>c+t&&u<=d)&&(l+=1)}o||(l===1?r.status="partially_ejected":this.gaps.some(p=>p.from===r.time.from||p.to===r.time.to)?r.status="partially_ejected":r.status="none")}}handleAsyncError(e,t){this.error$.next({id:t,category:Ci.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}calculateDurationFromSegments(){if(!this.playingRepresentationId)return 0;let e=this.segments.get(this.playingRepresentationId);return(e?(0,Vi.default)(e,-1)?.time.to:0)||0}};import{abortable as gs,assertNever as CT,fromEvent as BT,merge as fB,now as vs,Subject as _i,ValueSubject as ud,flattenObject as $r,ErrorCategory as Ss,SubscriptionRemovable as mB}from"@vkontakte/videoplayer-shared/es2024";var Bo=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:s=!1}){this.manifestRequested$=new _i;this.firstBytesManifest$=new _i;this.manifestReceived$=new _i;this.firstBytesRequested$=new _i;this.firstBytesReceived$=new _i;this.lastConnectionType$=new ud(void 0);this.lastConnectionReused$=new ud(void 0);this.lastRequestFirstBytes$=new ud(void 0);this.recoverableError$=new _i;this.error$=new _i;this.abortAllController=new Y;this.subscription=new mB;this.fetchManifest=gs(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=Jt(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=uo(i)),this.manifestRequested$.next();let r=yield this.doFetch(i,{signal:this.abortAllController.signal},"manifest").catch(Co);return r?(t.log("success",$r({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(r.headers),this.manifestReceived$.next(),r.text()):(t.error("error",$r({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=gs(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:s="auto",signal:n,measureThroughput:u=!0,isLowLatency:o=!1,bufferOptimisation:l=!1}={}){let p=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 E=new URL(p,location.href);E.searchParams.append("bytes",`${i.from}-${i.to}`),p=E.toString();break}default:CT(t)}this.requestQuic&&(p=Jt(p));let h=this.abortAllController.signal,f;if(n){let E=new Y;if(f=fB(BT(this.abortAllController.signal,"abort"),BT(n,"abort")).subscribe(()=>{try{E.abort()}catch(I){Co(I)}}),this.subscription.add(f),this.abortAllController.signal.aborted||n.aborted)try{E.abort()}catch(I){Co(I)}h=E.signal}let m=0,g=vs();d.log("startRequest",$r({url:p,priority:s,rangeMethod:t,range:i,isLowLatency:o,requestStartedAt:g})),this.firstBytesRequested$.next();let v=yield this.doFetch(p,{priority:s,headers:c,signal:h}),S=vs();if(!v)return d.error("error",{message:"No response in request"}),d.end(),this.unsubscribeAbortSubscription(f),null;if(this.throughputEstimator?.addRawRtt(S-g),!v.ok||!v.body){this.unsubscribeAbortSubscription(f);let E=`Fetch error ${v.status}: ${v.statusText}`;return d.error("error",{message:E}),d.end(),Promise.reject(new Error(`Fetch error ${v.status}: ${v.statusText}`))}if(this.onHeadersReceived(v.headers),!r&&!u){this.unsubscribeAbortSubscription(f);let E=vs(),I={requestStartedAt:g,requestEndedAt:E,duration:E-g};return d.log("endRequest",$r(I)),d.end(),v.arrayBuffer()}let T=v.body;if(u){let E;[T,E]=v.body.tee(),this.throughputEstimator?.trackStream(E,o)}let y=T.getReader(),A,P=parseInt(v.headers.get("content-length")??"",10);Number.isFinite(P)&&(A=P),!A&&i&&(A=i.to-i.from+1);let L=A?new Uint8Array(A):new Uint8Array(0),w=!1,M=E=>{this.unsubscribeAbortSubscription(f),w=!0,Co(E)},x=gs(h,async function*({done:E,value:I}){if(m===0&&(this.lastRequestFirstBytes$.next(vs()-g),this.firstBytesReceived$.next()),h.aborted){this.unsubscribeAbortSubscription(f);return}if(!E&&I){if(l&&A)L.set(I,m),m+=I.byteLength;else{let N=new Uint8Array(L.length+I.length);N.set(L),N.set(I,L.length),L=N,m+=I.byteLength}r?.(new DataView(L.buffer),m),yield y?.read().then(x,M)}}.bind(this));yield y?.read().then(x,M),this.unsubscribeAbortSubscription(f);let F=vs(),B={failed:w,requestStartedAt:g,requestEndedAt:F,duration:F-g};return w?(d.error("endRequest",$r(B)),d.end(),null):(d.log("endRequest",$r(B)),d.end(),L.buffer)}.bind(this));this.fetchByteRangeRepresentation=gs(this.abortAllController.signal,async function*(e,t,i){if(e.type!=="byteRange")return null;let{from:r,to:s}=e.initRange,n=r,u=s,o=!1,l,p;e.indexRange&&(l=e.indexRange.from,p=e.indexRange.to,o=s+1===l,o&&(n=Math.min(l,r),u=Math.max(p,s))),n=Math.min(n,0);let c=yield this.fetch(e.url,{range:{from:n,to:u},priority:i,measureThroughput:!1});if(!c)return null;let d=new DataView(c,r-n,s-n+1);if(!t.validateData(d))throw new Error("Invalid media file");let h=t.parseInit(d),f=e.indexRange??t.getIndexRange(h);if(!f)throw new ReferenceError("No way to load representation index");let m;if(o)m=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;m=new DataView(v)}let g=t.parseSegments(m,h,f);return{init:h,dataView:new DataView(c),segments:g}}.bind(this));this.fetchTemplateRepresentation=gs(this.abortAllController.signal,async function*(e,t){if(e.type!=="template")return null;let i=new URL(e.initUrl,e.baseUrl).toString(),r=yield this.fetch(i,{priority:t,measureThroughput:!1});return r?{init:null,segments:e.segments.map(n=>({...n,status:"none",size:void 0})),dataView:new DataView(r)}:null}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=r,this.tracer=i.createComponentTracer("Fetcher"),this.useEnableSubtitlesParam=s}onHeadersReceived(e){let{type:t,reused:i}=oo(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,t,i="auto"){let{type:r}=e;switch(r){case"byteRange":return await this.fetchByteRangeRepresentation(e,t,i)??null;case"template":return await this.fetchTemplateRepresentation(e,i)??null;default:CT(r)}}destroy(){this.abortAllController.abort(),this.tracer.end(),this.subscription.unsubscribe()}async doFetch(e,t,i){let r=await Xe(e,t);if(r.ok)return i==="manifest"&&this.firstBytesManifest$.next(),r;let s=await r.text(),n=parseInt(s);if(!isNaN(n))switch(n){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:Ss.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:Ss.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:Ss.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:Ss.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${n})`,category:Ss.FATAL})}}unsubscribeAbortSubscription(e){e&&(e.unsubscribe(),this.subscription.remove(e))}},Co=a=>{if(!Tt(a))throw a};import{isNullable as bB,ValueSubject as gB}from"@vkontakte/videoplayer-shared/es2024";var ys=class a{constructor(e,t){this.currentRepresentation$=new gB(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(!bB(e))for(let t of this.representations)for(let i of t){let r=i.segmentReference,s=r.segments.length,n=r.segments[0].time.from,u=r.segments[s-1].time.to;if(e<n||e>u)continue;let o=r.segments.find(l=>l.time.from<=e&&l.time.to>=e);!o||this.currentSegment?.time.from===o.time.from&&this.currentSegment.time.to===o.time.to||(this.currentSegment=o,this.currentRepresentation$.next({...i,label:"Live Text",language:"ru",isAuto:!0,url:new URL(o.url,r.baseUrl).toString()}))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e??[]){let i=a.filterRepresentations(t.representations);if(i){this.representations[this.representationsCursor]=i,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!e?.some(t=>a.filterRepresentations(t.representations))}static filterRepresentations(e){return e?.filter(t=>t.kind==="text"&&"segmentReference"in t&&He(t.segmentReference))}};var EB=["progress","play","seeked","stalled","waiting"],xB=["timeupdate","progress","loadeddata","playing","seeked"];var _o=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.bufferManagers=[];this.subscription=new hd;this.subscriptionRemovable=new TB;this.representationSubscription=new hd;this.state$=new O("none");this.currentVideoRepresentation$=new Z(void 0);this.currentVideoRepresentationInit$=new Z(void 0);this.currentAudioRepresentation$=new Z(void 0);this.currentVideoSegmentLength$=new Z(0);this.currentAudioSegmentLength$=new Z(0);this.error$=new Bt;this.manifestRequested$=new Bt;this.firstBytesManifest$=new Bt;this.manifestReceived$=new Bt;this.firstBytesRequested$=new Bt;this.firstBytesReceived$=new Bt;this.lastConnectionType$=new Z(void 0);this.lastConnectionReused$=new Z(void 0);this.lastRequestFirstBytes$=new Z(void 0);this.currentLiveTextRepresentation$=new Z(null);this.isLive$=new Z(!1);this.isActiveLive$=new Z(!1);this.isLowLatency$=new Z(!1);this.liveDuration$=new Z(0);this.liveSeekableDuration$=new Z(0);this.liveAvailabilityStartTime$=new Z(0);this.liveStreamStatus$=new Z(void 0);this.bufferLength$=new Z(0);this.liveLatency$=new Z(void 0);this.liveLoadBufferLength$=new Z(0);this.livePositionFromPlayer$=new Z(0);this.currentStallDuration$=new Z(0);this.videoLastDataObtainedTimestamp$=new Z(0);this.fetcherRecoverableError$=new Bt;this.fetcherError$=new Bt;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new Bt;this.gapWatchdogActive=!1;this.destroyController=new Y;this.initManifest=cd(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=ae(t,i,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),this.manifest?.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:lt.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=cd(this.destroyController.signal,async function*(){this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(o=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:lt.NETWORK,message:"Failed to load manifest",thrown:o})});if(!e)return null;let t=null;try{t=ro(e??"",this.manifestUrlString)}catch(o){let l=to(e)??{id:"ManifestParsing",category:lt.PARSER,message:"Failed to parse MPD manifest",thrown:o};this.error$.next(l)}if(!t)return null;let i=(o,l,p)=>!!(this.element?.canPlayType?.(l)&&Ue()?.isTypeSupported?.(`${l}; codecs="${p}"`)||o==="text");if(t.live){this.isLive$.next(!!t.live);let{availabilityStartTime:o,latestSegmentPublishTime:l,streamIsUnpublished:p,streamIsAlive:c}=t.live,d=(t.duration??0)/1e3;this.liveSeekableDuration$.next(-1*d),this.liveDuration$.next((l-o)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let h="active";c||(h=p?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(h)}let r={text:t.streams.text,video:[],audio:[]},s,n;for(let o of["video","audio"]){let p=t.streams[o].filter(({mime:d,codecs:h})=>i(o,d,h));r[o]=p;let c;if(this.tuning.dash.codecsPrioritizeEnabled){let d=p.map(({codecs:h})=>h);o==="audio"&&(n=yo(d),c=n[0]),o==="video"&&(s=So(d),this.forceVideoCodec&&(0,FT.default)(s,this.forceVideoCodec)?c=this.forceVideoCodec:c=s[0]),c&&(r[o]=p.filter(({codecs:h})=>xr(h)===c))}else{let d=new Set(p.map(({codecs:h})=>h));c=vo(d),c&&(r[o]=p.filter(({codecs:h})=>h.startsWith(c)))}if(o==="video"){let d=this.tuning.preferHDR,h=r.video.some(m=>m.hdr),f=r.video.some(m=>!m.hdr);D.display.isHDR&&d&&h?r.video=r.video.filter(m=>m.hdr):f&&(r.video=r.video.filter(m=>!m.hdr))}}let u={...t,streams:r};return this.tuning.dash.codecsPrioritizeEnabled&&(u.codecs={video:s,audio:n}),this.tracer.log("updateManifestEnd",Is(u)),u}.bind(this));this.initRepresentations=cd(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initRepresentationsStart",Is({initialVideo:e,initialAudio:t,sourceHls:i})),Lr(this.manifest),Lr(this.element),this.representationSubscription.unsubscribe(),this.representationSubscription=new hd,this.state$.startTransitionTo("representations_ready");let r=d=>{this.representationSubscription.add(It(d,"error").pipe(Vo(h=>!!this.element?.played.length)).subscribe(h=>{this.error$.next({id:"VideoSource",category:lt.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=Ln();let s=document.createElement("source");if(r(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),ur())if(i){let d=document.createElement("source");r(d),d.type="application/x-mpegurl",d.src=i.url,this.element.appendChild(d)}else this.element.disableRemotePlayback=!0;this.isActiveLive$.next(this.isLive$.getValue());let n={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),manifest:this.manifest},u=this.manifest.streams.video.reduce((d,h)=>[...d,...h.representations],[]);if(this.videoBufferManager=new bs("video",this.source,u,n),this.bufferManagers=[this.videoBufferManager],Es(t)){let d=this.manifest.streams.audio.reduce((h,f)=>[...h,...f.representations],[]);this.audioBufferManager=new bs("audio",this.source,d,n),this.bufferManagers.push(this.audioBufferManager)}ys.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new ys(this.manifest.streams.text,n)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$));let o=()=>{this.stallWatchdogSubscription?.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add(Oi(...xB.map(d=>It(this.element,d))).pipe(Dr(d=>this.element?ye(this.element.buffered,this.element.currentTime*1e3):0),Ts(),IB(d=>{d>this.tuning.dash.bufferEmptinessTolerance&&o()})).subscribe(this.bufferLength$)),this.representationSubscription.add(Oi(It(this.element,"ended"),this.forceEnded$).subscribe(()=>{o()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe(Ts()).subscribe(h=>this.liveStreamEndTimestamp=pd())),this.subscription.add(It(this.element,"pause").subscribe(()=>{this.livePauseWatchdogSubscription=dd(1e3).subscribe(h=>{let f=Ht(this.manifestUrlString,2);this.manifestUrlString=ae(this.manifestUrlString,f+1e3,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add(It(this.element,"play").subscribe(h=>this.livePauseWatchdogSubscription?.unsubscribe())),this.representationSubscription.add(Mr({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(Dr(({isActiveLive:h,isLowLatency:f})=>h&&f),Ts()).subscribe(h=>{this.isManualDecreasePlaybackInLive()||Er(this.element,1)})),this.representationSubscription.add(Mr({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(Vo(({bufferLength:h,isActiveLive:f,isLowLatency:m})=>f&&m&&!!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(Mr({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(Vo(({isLive:h})=>h),Ts((h,f)=>f.bufferLength<h.bufferLength),Dr(({rtt:h,bufferLength:f,segmentServerLatency:m})=>{let g=Ht(this.manifestUrlString,2);return(h/2+f+m+g)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(Mr({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:h,isActiveLive:f,isLowLatency:m})=>{if(!m||!f)return;let g=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,v=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,S=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,T=h-g;if(this.isManualDecreasePlaybackInLive())return;let y=1;Math.abs(T)>v&&(y=1+Math.sign(T)*S),Er(this.element,y)})),this.representationSubscription.add(this.bufferLength$.subscribe(h=>{let f=0;if(h){let m=(this.element?.currentTime??0)*1e3;f=Math.min(...this.bufferManagers.map(v=>v.getLiveSegmentsToLoadState(this.manifest)?.to??m))-m}this.liveLoadBufferLength$.getValue()!==f&&this.liveLoadBufferLength$.next(f)}));let d=0;this.representationSubscription.add(Mr({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(OT(1e3)).subscribe(async({liveLoadBufferLength:h,bufferLength:f})=>{if(!this.element||this.isUpdatingLive)return;let m=this.element.playbackRate,g=Ht(this.manifestUrlString,2),v=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,S=Math.min(v,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*m),T=this.tuning.dashCmafLive.normalizedActualBufferOffset*m,y=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*m,A=isFinite(h)?h:f,P=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),L=v<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(L);let w="none";if(P?w="active_low_latency":this.isLowLatency$.getValue()&&L?(this.bufferManagers.forEach(M=>M.proceedLowLatencyLive()),w="active_low_latency"):g!==0&&A<S?w="live_forward_buffering":A<S+y&&(w="live_with_target_offset"),isFinite(h)&&(d=h>d?h:d),w==="live_forward_buffering"||w==="live_with_target_offset"){let M=d-(S+T),x=this.normolizeLiveOffset(Math.trunc(g+M/m)),F=Math.abs(x-g),B=0;!h||F<=this.tuning.dashCmafLive.offsetCalculationError?B=g:x>0&&F>this.tuning.dashCmafLive.offsetCalculationError&&(B=x),this.manifestUrlString=ae(this.manifestUrlString,B,2)}(w==="live_with_target_offset"||w==="live_forward_buffering")&&(d=0,await this.updateLive())},h=>{this.error$.next({id:"updateLive",category:lt.VIDEO_PIPELINE,thrown:h,message:"Failed to update live with subscription"})}))}let l=Oi(...this.bufferManagers.map(d=>d.fullyBuffered$)).pipe(Dr(()=>this.bufferManagers.every(d=>d.fullyBuffered$.getValue()))),p=Oi(...this.bufferManagers.map(d=>d.onLastSegment$)).pipe(Dr(()=>this.bufferManagers.some(d=>d.onLastSegment$.getValue()))),c=Mr({allBuffersFull:l,someBufferEnded:p}).pipe(Ts(),Dr(({allBuffersFull:d,someBufferEnded:h})=>d&&h),Vo(d=>d));if(this.representationSubscription.add(Oi(this.forceEnded$,c).subscribe(()=>{if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(d=>!d.updating))try{this.source?.endOfStream()}catch(d){this.error$.next({id:"EndOfStream",category:lt.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:d})}})),this.representationSubscription.add(Oi(...this.bufferManagers.map(d=>d.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.representationSubscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.representationSubscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.liveTextManager&&this.representationSubscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$)),this.source.readyState!=="open"){let d=this.tuning.dash.sourceOpenTimeout>=0;yield new Promise(h=>{d&&(this.timeoutSourceOpenId=setTimeout(()=>{if(this.source?.readyState==="open"){h();return}this.error$.next({id:"OpenOfStream",category:lt.VIDEO_PIPELINE,message:"Failed to open MediaSource",thrown:new Error("Timeout reject when wait sourceopen event"),traceAsLog:!0})},this.tuning.dash.sourceOpenTimeout)),this.source?.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),h()},{once:!0})})}if(!this.isLive$.getValue()){let d=[this.manifest.duration??0,...(0,fd.default)((0,fd.default)([...this.manifest.streams.audio,...this.manifest.streams.video],h=>h.representations),h=>{let f=[];return h.duration&&f.push(h.duration),He(h.segmentReference)&&h.segmentReference.totalSegmentsDurationMs&&f.push(h.segmentReference.totalSegmentsDurationMs),f})];this.source.duration=Math.max(...d)/1e3}this.audioBufferManager&&Es(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")}.bind(this));this.tick=()=>{if(!this.element||!this.videoBufferManager||this.source?.readyState!=="open")return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),this.audioBufferManager?.maintain(e),this.liveTextManager?.maintain(e),(this.videoBufferManager.gaps.length||this.audioBufferManager?.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=dd(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:lt.WTF,message:"Error handling gaps",thrown:t})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.forceVideoCodec=e.forceVideoCodec,this.fetcher=new Bo({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.subscription.add(this.fetcher.recoverableError$.subscribe(this.fetcherRecoverableError$)),this.subscription.add(this.fetcher.error$.subscribe(this.fetcherError$)),this.subscription.add(this.fetcher.manifestRequested$.subscribe(this.manifestRequested$)),this.subscription.add(this.fetcher.firstBytesManifest$.subscribe(this.firstBytesManifest$)),this.subscription.add(this.fetcher.manifestReceived$.subscribe(this.manifestReceived$)),this.subscription.add(this.fetcher.firstBytesRequested$.subscribe(this.firstBytesRequested$)),this.subscription.add(this.fetcher.firstBytesReceived$.subscribe(this.firstBytesReceived$)),this.subscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.subscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.liveBuffer=Mt.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator}),this.initTracerSubscription()}setSmartRepresentationSwitch(e){this.bufferManagers.forEach(t=>t.setSmartRepresentationSwitch(e))}async seekLive(e){Lr(this.element);let t=this.liveStreamStatus$.getValue()!=="active"?pd()-this.liveStreamEndTimestamp:0,i=this.normolizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=ae(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(){Lr(this.element),this.state$.setState("running");let e=It(this.element,"timeupdate");this.tuning.dash.timeupdateEventTickThrottle&&(e=e.pipe(OT(this.tuning.dash.timeupdateEventTickThrottle))),this.subscription.add(Oi(...EB.map(t=>It(this.element,t)),It(window,"online"),e).subscribe(()=>this.tick(),t=>{this.error$.next({id:"DashVKPlayer",category:lt.WTF,message:"Internal logic error",thrown:t})})),this.subscription.add(It(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===HTMLMediaElement.HAVE_CURRENT_DATA&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(It(this.element,"waiting").subscribe(()=>{this.tuning.dash.useVideoElementWaitingCurrentTimeReassign&&this.element&&this.element.readyState===HTMLMediaElement.HAVE_CURRENT_DATA&&!this.element.seeking&&Te(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let t=()=>{if(!this.element||this.source?.readyState!=="open")return;let i=this.currentStallDuration$.getValue();i+=50,this.currentStallDuration$.next(i);let r={timeInWaiting:i},s=pd(),n=100,u=this.videoBufferManager?.lastDataObtainedTimestamp??0;this.videoLastDataObtainedTimestamp$.next(u);let o=this.audioBufferManager?.lastDataObtainedTimestamp??0,l=this.videoBufferManager?.getForwardBufferDuration()??0,p=this.audioBufferManager?.getForwardBufferDuration()??0,c=l<n&&s-u>this.tuning.dash.crashOnStallTWithoutDataTimeout,d=this.audioBufferManager&&p<n&&s-o>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((c||d)&&i>this.tuning.dash.crashOnStallTWithoutDataTimeout||i>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${i} ms`);if(this.isLive$.getValue()&&i%2e3===0){let h=this.normolizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(h).catch(f=>{this.error$.next({id:"stallIntervalCallback",category:lt.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:f})}),r.liveLastOffset=h}else{let h=this.element.currentTime*1e3;this.videoBufferManager?.maintain(h),this.audioBufferManager?.maintain(h),r.position=h}this.tracer.log("stallIntervalCallback",Is(r))};this.stallWatchdogSubscription&&(this.stallWatchdogSubscription.unsubscribe(),this.subscriptionRemovable.remove(this.stallWatchdogSubscription)),this.stallWatchdogSubscription=dd(50).subscribe(t,i=>{this.error$.next({id:"StallWatchdogCallback",category:lt.NETWORK,message:"Can't restore DASH after stall.",thrown:i})}),this.subscriptionRemovable.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,i=!1){let r={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return this.tuning.useNewSwitchTo?this.currentStallDuration$.getValue()>0?r?.switchToWithPreviousAbort(t,i):r?.switchTo(t,i):r?.switchToOld(t,i)}async seek(e,t){Lr(this.element),Lr(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),Te(this.element.buffered,i)||await Promise.all([this.videoBufferManager.abort(),this.audioBufferManager?.abort()]),!(_T(this.element)||_T(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),this.audioBufferManager?.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",Is({requestedPosition:e,forcePrecise:t,position:i})))}warmUpMediaSourceIfNeeded(e=this.element?.currentTime){Es(this.element)&&Es(this.source)&&Es(e)&&this.source?.readyState==="ended"&&this.element.duration*1e3-e>this.tuning.dash.seekBiasInTheEnd&&this.bufferManagers.forEach(t=>t.warmUpMediaSource())}get isStreamEnded(){return this.source?.readyState==="ended"}stop(){this.tracer.log("stop"),this.element?.querySelectorAll("source").forEach(e=>{URL.revokeObjectURL(e.src),e.remove()}),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),this.videoBufferManager?.destroy(),this.videoBufferManager=null,this.audioBufferManager?.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){return this.manifest?.streams}getCodecs(){return this.manifest?.codecs}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){this.subscription.unsubscribe(),this.subscriptionRemovable.unsubscribe(),this.representationSubscription.unsubscribe(),this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),this.source?.readyState==="open"&&Array.from(this.source.sourceBuffers).every(e=>!e.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=yB(this.tracer.error.bind(this.tracer));this.subscription.add(this.error$.subscribe(e("error")))}isManualDecreasePlaybackInLive(){return!this.element||!this.isLive$.getValue()?!1:1-this.element.playbackRate>this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&(this.bufferManagers.forEach(e=>e.updateLive(this.manifest)),this.liveTextManager?.updateLive(this.manifest)),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getBufferedTo();if(e===null)return;let t=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),i=this.isJumpGapAfterSeekLive,r=this.element.currentTime;this.isJumpGapAfterSeekLive&&!t&&this.element.currentTime>e&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let s=this.element.currentTime*1e3,n=null,u=this.element.readyState===HTMLMediaElement.HAVE_METADATA?this.tuning.endGapTolerance:0;for(let o of this.bufferManagers)for(let l of o.gaps)(l.persistent||o.playingRepresentation$.getValue()===l.representation)&&l.from-u<=s&&l.to+u>s&&(this.element.duration*1e3-l.to<this.tuning.endGapTolerance?n=1/0:(n===null||l.to>n)&&(n=l.to));if(n!==null){let o=n+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,o===1/0?this.forceEnded$.next():(this.element.currentTime=o/1e3,this.tracer.log("jumpGap",Is({isJumpGapAfterSeekLive:i,isActiveLowLatency:t,initialCurrentTime:r,jumpTo:o,resultCurrentTime:this.element.currentTime})))}}calculateDurationFromSegments(){return Math.max(this.videoBufferManager?.calculateDurationFromSegments()||0,this.audioBufferManager?.calculateDurationFromSegments()||0)}};import{combine as wB,map as AB,observeElementSize as kB,Subscription as PB,ValueSubject as md,noop as RB}from"@vkontakte/videoplayer-shared/es2024";var Oo=class{constructor(){this.subscription=new PB;this.pipSize$=new md(void 0);this.videoSize$=new md(void 0);this.elementSize$=new md(void 0);this.pictureInPictureWindowRemoveEventListener=RB}connect({observableVideo:e,video:t}){let i=r=>{let s=r.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add(kB(t).subscribe(this.videoSize$)).add(e.enterPip$.subscribe(({pictureInPictureWindow:r})=>{this.pipSize$.next({width:r.width,height:r.height}),r.addEventListener("resize",i),this.pictureInPictureWindowRemoveEventListener=()=>{r.removeEventListener("resize",i)}})).add(e.leavePip$.subscribe(()=>{this.pictureInPictureWindowRemoveEventListener()})).add(wB({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(AB(({videoSize:r,inPip:s,pipSize:n})=>s?n:r)).subscribe(this.elementSize$))}getValue(){return this.elementSize$.getValue()}subscribe(e,t){return this.elementSize$.subscribe(e,t)}getObservable(){return this.elementSize$}destroy(){this.pictureInPictureWindowRemoveEventListener(),this.subscription.unsubscribe()}};var Fi=class{constructor(e){this.subscription=new _B;this.videoState=new O("stopped");this.observableVideo=null;this.droppedFramesManager=new mr;this.stallsManager=new Ao;this.elementSizeManager=new Oo;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Gt;this.audioTrackSwitchHistory=new Gt;this.selectedRepresentations={audio:null,video:null};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(r.state==="requested"&&i?.to!=="paused"&&e!=="stopped"&&t!=="stopped"&&this.seek(r.position,r.forcePrecise),t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),k(this.params.desiredState.playbackState,"stopped",!0));return}switch(e){case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();return;case"ready":t==="paused"?(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="ready"&&k(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):t==="playing"&&this.video.paused?this.playIfAllowed():i?.to==="playing"&&k(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&k(this.params.desiredState.playbackState,"paused");return;default:return LB(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new Pr(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:e.projectionData?.pose.yaw||0,y:e.projectionData?.pose.pitch||0,z:e.projectionData?.pose.roll||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSizeManager.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.textTracksManager=new Ye(e.source.url),this.params=e,this.video=De(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(Se(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 _o({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;VB(this.observableVideo)&&(this.observableVideo=Ve(this.video),this.subscription.add(()=>this.observableVideo?.destroy()));let i=this.constructor.name,r=n=>{e.error$.next({id:i,category:NT.WTF,message:`${i} internal logic error`,thrown:n})},s=(n,u)=>this.subscription.add(n.subscribe(u,r));return{output:e,desiredState:t,observableVideo:this.observableVideo,genericErrorListener:r,connect:s}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:s}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(bd(c=>!!c.length),UT()).subscribe(c=>{this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:c})}));let n=this.params.desiredState.seekState.stateChangeEnded$.pipe(ws(c=>c.to.state!=="none"),xs());this.stallsManager.init({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$,videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,tuning:this.params.tuning.stallsManager,abrParams:this.params.tuning.autoTrackSelection,isBuffering$:i.isBuffering$,looped$:i.looped$,playing$:i.playing$,duration:this.video.duration}),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(this.player.error$,e.error$),s(this.player.fetcherRecoverableError$,e.fetcherRecoverableError$),s(this.player.fetcherError$,e.fetcherError$),s(this.player.manifestRequested$,e.manifestRequested$),s(this.player.firstBytesManifest$,e.firstBytesManifest$),s(this.player.manifestReceived$,e.manifestReceived$),s(this.player.firstBytesRequested$,e.firstBytesRequested$),s(this.player.firstBytesReceived$,e.firstBytesReceived$),s(this.player.lastConnectionType$,e.httpConnectionType$),s(this.player.lastConnectionReused$,e.httpConnectionReused$),s(this.player.isLive$,e.isLive$),s(this.player.lastRequestFirstBytes$.pipe(bd(qT),UT()),e.firstBytesEvent$),s(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),s(this.videoState.stateChangeEnded$.pipe(ws(c=>c.to)),this.params.output.playbackState$),this.subscription.add(i.looped$.subscribe(()=>this.player.warmUpMediaSourceIfNeeded(),r)),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(bt(this.video,t.isLooped,r)),this.subscription.add(Be(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(ze(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),s(Ke(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),k(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),k(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(i.ended$.subscribe(()=>{this.videoState.setState("paused"),k(t.playbackState,"paused")})),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 d=this.player.getStreams(),h=this.player.getCodecs();if(MB(d,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let m=[];for(let g of d.audio){m.push(rd(g));let v=[];for(let S of g.representations){let T=PT(S);v.push(T),this.audioTracksMap.set(T,{stream:g,representation:S})}this.audioStreamsMap.set(g,v)}this.params.output.availableAudioStreams$.next(m)}let f=[];for(let m of d.video){f.push(ad(m));let g=[];for(let v of m.representations){let S=ms({...v,streamId:m.id});S&&(g.push(S),this.videoTracksMap.set(S,{stream:m,representation:v}))}this.videoStreamsMap.set(m,g)}this.params.output.availableVideoStreams$.next(f);for(let m of d.text)for(let g of m.representations){let v=RT(m,g);this.textTracksMap.set(v,{stream:m,representation:g})}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),h?.video&&this.params.output.availableVideoCodecs$.next(h.video),h?.audio&&this.params.output.availableAudioCodecs$.next(h.audio),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else c==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r));let{vktvAbrThrottle:u}=this.params.tuning.dash,o=u&&MT(u)||null;this.subscription.add(As(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$,BB(this.video,"progress")).pipe(bd(()=>this.videoTracksMap.size>0)).subscribe(async()=>{let c=this.player.state$.getState(),d=this.player.state$.getTransition();if(c!=="manifest_ready"&&c!=="running"||d||c==="running"&&o&&!o())return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState()),this.selectVideoAudioRepresentations();let{video:h,audio:f}=this.selectedRepresentations;if(!h)return;let m=Di(this.videoTracksMap.keys(),v=>this.videoTracksMap.get(v)?.representation.id===h.id);qT(m)&&(this.stallsManager.lastVideoTrackSelected=m);let g=this.params.desiredState.autoVideoTrackLimits.getTransition();if(g&&this.params.output.autoVideoTrackLimits$.next(g.to),c==="manifest_ready")await this.player.initRepresentations(h.id,f?.id,this.params.sourceHls);else if(await this.player.switchRepresentation("video",h.id),f){let v=!!t.audioStream.getTransition();await this.player.switchRepresentation("audio",f.id,v)}},r)),this.subscription.add(DB({videoState:this.videoState.stateChangeEnded$,autoVideoTrackState:As(Fo([t.autoVideoTrackSwitching.getState()]),t.autoVideoTrackSwitching.stateChangeEnded$.pipe(ws(c=>c.to)))}).pipe(ws(({videoState:c,autoVideoTrackState:d})=>c.to!=="stopped"&&d),xs()).subscribe(c=>this.player.setSmartRepresentationSwitch(c))),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(xs()).subscribe(c=>{let d=Di(this.videoTracksMap.entries(),([,{representation:v}])=>v.id===c);if(!d){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[h,{stream:f}]=d,m=this.params.desiredState.videoStream.getTransition();m&&m.to&&m.to.id===f.id&&this.params.desiredState.videoStream.setState(m.to),e.currentVideoTrack$.next(h),e.currentVideoStream$.next(ad(f));let g=this.player.calculateDurationFromSegments();g&&this.params.output.duration$.next(g/1e3)},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(xs()).subscribe(c=>{let d=Di(this.audioTracksMap.entries(),([,{representation:g}])=>g.id===c);if(!d){e.currentAudioStream$.next(void 0);return}let[h,{stream:f}]=d,m=this.params.desiredState.audioStream.getTransition();m&&m.to&&m.to.id===f.id&&this.params.desiredState.audioStream.setState(m.to),e.currentAudioStream$.next(rd(f))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(c=>{if(c?.is3dVideo&&this.params.tuning.spherical?.enabled)try{this.init3DScene(c),e.is3DVideo$.next(!0)}catch(d){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${d}`})}else this.destroy3DScene(),this.params.tuning.spherical?.enabled&&e.is3DVideo$.next(!1)},r)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,r)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,r)),this.textTracksManager.connect(this.video,t,e);let l=t.playbackState.stateChangeStarted$.pipe(ws(({to:c})=>c==="ready"),xs());this.subscription.add(As(l,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,Fo(["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(As(l,this.player.state$.stateChangeEnded$,Fo(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let p=As(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Fo(["init"])).pipe(CB(0));this.subscription.add(p.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?ga:ba,t=this.params.tuning.useNewAutoSelectVideoTrack?zn:Gn,i=this.params.tuning.useNewAutoSelectVideoTrack?St:Qn,{desiredState:r,output:s}=this.params,n=r.autoVideoTrackSwitching.getState(),u=r.videoTrack.getState()?.id,o=Di(this.videoTracksMap.keys(),w=>w.id===u),l=s.currentVideoTrack$.getValue(),p=r.videoStream.getState()??(o&&this.videoTracksMap.get(o)?.stream)??this.videoStreamsMap.size===1?this.videoStreamsMap.keys().next().value:void 0;if(!p)return;let c=Di(this.videoStreamsMap.keys(),w=>w.id===p.id),d=c&&this.videoStreamsMap.get(c);if(!d)return;let h=ye(this.video.buffered,this.video.currentTime*1e3),f;this.player.isActiveLive$.getValue()?f=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?f=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:f=n?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let m=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,g=Math.min(h/Math.min(f,m||1/0),1),v=r.audioStream.getState()??(this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0),S=v?.id&&Di(this.audioStreamsMap.keys(),w=>w.id===v.id)||this.audioStreamsMap.keys().next().value,T=0;if(S){if(o&&!n){let w=e(o,d,this.audioStreamsMap.get(S)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);T=Math.max(T,w?.bitrate??-1/0)}if(l){let w=e(l,d,this.audioStreamsMap.get(S)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);T=Math.max(T,w?.bitrate??-1/0)}}let y=o;(n||!y)&&(y=i(d,{container:this.elementSizeManager.getValue(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.stallsManager.abrTuningParams,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:T,forwardBufferHealth:g,current:l,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,stallsVideoMaxQualityLimit:this.stallsManager.videoMaxQualityLimit,stallsPredictedThroughput:this.stallsManager.predictedThroughput,abrLogger:this.params.dependencies.abrLogger}));let A=S&&t(y,d,this.audioStreamsMap.get(S)??[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.stallsManager.abrTuningParams,forwardBufferHealth:g,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),P=this.videoTracksMap.get(y)?.representation,L=A&&this.audioTracksMap.get(A)?.representation;P&&L?(this.selectedRepresentations.video=P,this.selectedRepresentations.audio=L):P&&!L&&this.audioTracksMap.size===0&&(this.selectedRepresentations.video=P,this.selectedRepresentations.audio=null)}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){_e(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:NT.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.stallsManager.destroy(),this.elementSizeManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),this.params.output.currentVideoStream$.next(void 0),Ce(this.video),this.tracer.end()}};var ks=class extends Fi{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 gd,merge as jT,filter as HT,filterChanged as WT,isNullable as vd,map as QT,ValueSubject as Sd,isNonNullable as OB}from"@vkontakte/videoplayer-shared/es2024";var Ps=class extends Fi{constructor(e){super(e),this.textTracksManager.destroy()}subscribe(){super.subscribe();let e=!1,t=-1,{output:i,observableVideo:r,desiredState:s,connect:n}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canPlayLiveTailBuffer$.next(!0),n(r.timeUpdate$,i.liveBufferTime$),n(this.player.liveSeekableDuration$,i.duration$),n(this.player.liveLatency$,i.liveLatency$);let u=new Sd(1);n(r.playbackRateState$,u),this.params.tuning.dashCmafLive.catchupLiveForMutedInactiveTab&&this.subscription.add(i.elementVisible$.pipe(WT()).subscribe(o=>{let l=i.position$.getValue(),p=i.volume$.getValue(),c=!p.volume||p.muted;!o&&!l&&c?e=!0:o&&e&&(this.seek(0),e=!1)})),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(s.isLowLatency.stateChangeEnded$.pipe(QT(o=>o.to)).subscribe(this.player.isLowLatency$)).add(gd({liveBufferTime:i.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(QT(({liveBufferTime:o,liveAvailabilityStartTime:l})=>o&&l?o+l:void 0)).subscribe(i.liveTime$)).add(this.player.liveStreamStatus$.pipe(HT(o=>OB(o))).subscribe(o=>i.isLiveEnded$.next(o!=="active"&&i.position$.getValue()===0))).add(gd({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:jT(r.playbackRateState$,new Sd(1))}).pipe(HT(({liveStreamStatus:o,liveDuration:l})=>o==="active"&&!!l)).subscribe(({liveDuration:o,playbackRate:l})=>{let p=i.liveBufferTime$.getValue(),c=i.position$.getValue(),{playbackCatchupSpeedup:d}=this.params.tuning.dashCmafLive.lowLatency;c||l<1-d||this.video.paused||vd(p)||(t=o-p)})).add(gd({time:i.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:jT(r.playbackRateState$,new Sd(1))}).pipe(WT((o,l)=>this.player.liveStreamStatus$.getValue()==="active"?o.liveDuration===l.liveDuration:o.time===l.time)).subscribe(({time:o,liveDuration:l,playbackRate:p})=>{let c=i.position$.getValue(),{playbackCatchupSpeedup:d}=this.params.tuning.dashCmafLive.lowLatency;if(!c&&!this.video.paused&&p>=1-d||vd(o)||vd(l))return;let h=-1*(l-o-t);i.position$.next(Math.min(h,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(o=>{if(o){let l=$T(o);this.params.output.availableTextTracks$.next([l])}}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=Math.trunc(t/1e3<=Math.abs(this.params.output.duration$.getValue())?t:0);this.player.seekLive(i).then(()=>{this.params.output.position$.next(e/1e3)})}};var GT="X-Playback-Duration",yd=async a=>{let e=await Xe(a),t=await e.text(),i=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t)?.[1];return i?parseInt(i,10):e.headers.has(GT)?parseInt(e.headers.get(GT),10):void 0};import{assertNever as YB,combine as KB,debounce as XB,ErrorCategory as Uo,filter as JB,filterChanged as ZB,isNonNullable as KT,isNullable as jo,map as XT,merge as e0,observableFrom as t0,Subscription as i0,ValueSubject as Ed,VideoQuality as r0}from"@vkontakte/videoplayer-shared/es2024";var Id=C(ul(),1);import{videoSizeToQuality as FB,getExponentialDelay as NB}from"@vkontakte/videoplayer-shared/es2024";var qB=a=>{let e=null;if(a.QUALITY&&(e=Qt(a.QUALITY)),!e&&a.RESOLUTION){let[t,i]=a.RESOLUTION.split("x").map(r=>parseInt(r,10));e=FB({width:t,height:i})}return e??null},UB=(a,e)=>{let t=a.split(`
|
|
179
|
-
|
|
180
|
-
`),s=0;for(let n=0;n<r.length;++n){let u=r[n];switch(!0){case u.startsWith("#EXTINF:"):{let o=r[++n],l=new URL(o,t).toString(),p=Number(this.extractPlaylistRowValue("#EXTINF:",u))*1e3;if(i.segments.push({time:{from:s,to:s+p},url:l}),s=s+p,!i.segmentStartTime){let c=new Date(i.vkStartTime).valueOf(),d=new Date(i.programDateTime).valueOf();i.segmentStartTime=d-c}break}case u.startsWith("#EXT-X-TARGETDURATION:"):i.targetDuration=Number(this.extractPlaylistRowValue("#EXT-X-TARGETDURATION:",u));break;case u.startsWith("#EXT-X-MEDIA-SEQUENCE:"):i.mediaSequence=Number(this.extractPlaylistRowValue("#EXT-X-MEDIA-SEQUENCE:",u));break;case u.startsWith("#EXT-X-VK-PLAYBACK-DURATION:"):i.vkPlaybackDuration=Number(this.extractPlaylistRowValue("#EXT-X-VK-PLAYBACK-DURATION:",u));break;case u.startsWith("#EXT-X-PROGRAM-DATE-TIME:"):{let o=this.extractPlaylistRowValue("#EXT-X-PROGRAM-DATE-TIME:",u);i.programDateTime=o;let l=new Date(o);l.setMilliseconds(0),s=l.valueOf();break}case u.startsWith("#EXT-X-VK-START-TIME:"):i.vkStartTime=this.extractPlaylistRowValue("#EXT-X-VK-START-TIME:",u);break}}return i}extractPlaylistRowValue(e,t){switch(e){case"#EXTINF:":return t.substring(e.length,t.length-1);default:return t.substring(e.length)}}processLiveTime(e){if(HB(e)&&this.currentTextTrackData){let{segments:t}=this.currentTextTrackData.playlist,{from:i}=t[0].time,{to:r}=t[t.length-1].time;if(e<i||e>r)return;r-e<this.params.downloadThreshold&&this.fetchNextManifestData();for(let n of t)if(n.time.from<=e&&n.time.to>=e){this.availableTextTracks$.next([{...this.currentTextTrackData.textTrack,url:n.url,isAuto:!0}]);break}}}async fetchNextManifestData(){try{if(this.abortControllers.nextManifest)return;this.abortControllers.nextManifest=new Y;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:zB.WTF,thrown:t,message:e})}};var Rs=class{constructor(e){this.subscription=new i0;this.videoState=new O("stopped");this.textTracksManager=null;this.liveTextManager=null;this.manifests$=new Ed([]);this.liveOffset=new Ii;this.manifestStartTime$=new Ed(void 0);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),u=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),k(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||u){let p=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(p),this.prepare(),u&&this.params.output.autoVideoTrackLimits$.next(u.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if(r?.to!=="paused"&&l.state==="requested"){this.videoState.startTransitionTo("ready"),this.seek(l.position&&l.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":i==="ready"?k(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),k(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):r?.to==="playing"&&k(this.params.desiredState.playbackState,"playing");return;case"paused":if(i==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let p=this.liveOffset.getTotalOffset();p>=this.maxSeekBackTime$.getValue()&&(p=0,this.liveOffset.resetTo(p)),this.liveOffset.resume(),this.params.output.position$.next(-p/1e3),this.prepare()}else r?.to==="paused"&&(k(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return YB(t)}};this.params=e,this.video=De(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:r0.INVARIANT,url:this.params.source.url};let t=(i,r)=>No(i,this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},r);this.params.tuning.useHlsLiveNewTextManager?this.liveTextManager=new qo(this.params.output.liveTime$,this.video,t,this.params.source.url,this.params.tuning.hlsLiveNewTextManagerDownloadThreshold):this.textTracksManager=new Ye(e.source.url),t(this.generateLiveUrl()).then(({qualityManifests:i,textTracks:r})=>{i.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:Uo.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.liveTextManager?.processTextTracks(r,this.params.source.url),this.manifests$.next([this.masterManifest,...i])}).catch(i=>{this.params.output.error$.next({id:"ExtractHlsQualities",category:Uo.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(Se(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new Ed(e.source.maxSeekBackTime??1/0),this.subscribe()}selectManifest(){let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),s=r?.to?.id??t.getState()?.id??"master",n=this.manifests$.getValue();if(!n.length)return;let u=i?"master":s;return i&&!r&&t.startTransitionTo(this.masterManifest),n.find(o=>o.id===u)}subscribe(){let{output:e,desiredState:t}=this.params,i=u=>{e.error$.next({id:"HlsLiveProvider",category:Uo.WTF,message:"HlsLiveProvider internal logic error",thrown:u})},r=Ve(this.video);this.subscription.add(()=>r.destroy());let s=(u,o)=>this.subscription.add(u.subscribe(o,i));s(r.ended$,e.endedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.loadedMetadata$,e.firstBytesEvent$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(Be(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(ze(this.video,t.playbackRate,r.playbackRateState$,i)),s(Ke(this.video),e.elementVisible$),this.liveTextManager?(s(this.liveTextManager.getCurrentTime$,this.params.output.getCurrentTime$),s(this.liveTextManager.error$,this.params.output.error$)):this.textTracksManager&&this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),k(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),k(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.liveTextManager&&this.subscription.add(this.liveTextManager.availableTextTracks$.subscribe(u=>{u&&this.params.output.availableTextTracks$.next(u)})),this.subscription.add(this.maxSeekBackTime$.pipe(ZB(),XT(u=>-u/1e3)).subscribe(this.params.output.duration$,i)),this.subscription.add(r.loadedMetadata$.subscribe(()=>{let u=this.params.desiredState.seekState.getState(),o=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),p=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&KT(l.to)){let c=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let d=this.manifests$.getValue().find(h=>h.id===c);d&&(this.params.output.currentVideoTrack$.next(d),this.params.output.hostname$.next(Se(d.url)))}p&&this.params.desiredState.autoVideoTrackSwitching.setState(p.to),o&&o.from==="changing_manifest"&&this.videoState.setState(o.to),u&&u.state==="requested"&&this.seek(u.position)},i)),this.subscription.add(r.loadedData$.subscribe(()=>{let u=this.video?.getStartDate?.()?.getTime();this.manifestStartTime$.next(u||void 0)},i)),this.subscription.add(KB({startTime:this.manifestStartTime$.pipe(JB(KT)),currentTime:r.timeUpdate$}).subscribe(({startTime:u,currentTime:o})=>this.params.output.liveTime$.next(u+o*1e3),i)),this.subscription.add(this.manifests$.pipe(XT(u=>u.map(({id:o,quality:l,size:p,bandwidth:c,fps:d})=>({id:o,quality:l,size:p,fps:d,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,i));let n=e0(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,t0(["init"])).pipe(XB(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),Ce(this.video)}prepare(){let e=this.selectManifest();if(jo(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:u,min:o}=t?.to??i??{};for(let[l,p]of[[u,"mq"],[o,"lq"]]){let c=String(parseFloat(l||""));p&&l&&r.searchParams.set(p,c)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,n=ae(r.toString(),this.liveOffset.getTotalOffset(),s);this.liveTextManager?.prepare(n),this.video.setAttribute("src",n),this.video.load(),yd(n).then(u=>{if(!jo(u))this.maxSeekBackTime$.next(u);else{let o=this.params.source.maxSeekBackTime??this.maxSeekBackTime$.getValue();(jo(o)||!isFinite(o))&&Xe(n).then(l=>l.text()).then(l=>{let p=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(l)?.[1];if(p){let c=new URL(p,n).toString();yd(c).then(d=>{jo(d)||this.maxSeekBackTime$.next(d)})}}).catch(()=>{})}})}playIfAllowed(){_e(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),k(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Uo.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=ae(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 a0,debounce as s0,ErrorCategory as xd,fromEvent as wd,isNonNullable as n0,isNullable as o0,map as JT,merge as ZT,observableFrom as eI,Subscription as u0,ValueSubject as tI,VideoQuality as l0}from"@vkontakte/videoplayer-shared/es2024";var $s=class{constructor(e){this.subscription=new u0;this.videoState=new O("stopped");this.manifests$=new tI([]);this.unmuteAfterBrowserResetsHappened=new tI(!1);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),u=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),k(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||u){let p=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(p);let{currentTime:c}=this.video;this.prepare(),u&&this.params.output.autoVideoTrackLimits$.next(u.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:c*1e3,forcePrecise:!0});return}switch(r?.to!=="paused"&&l.state==="requested"&&this.seek(l.position),t){case"ready":i==="ready"?k(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):r?.to==="playing"&&k(this.params.desiredState.playbackState,"playing");return;case"paused":i==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):r?.to==="paused"&&k(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return a0(t)}};this.textTracksManager=new Ye(e.source.url),this.params=e,this.video=De(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:l0.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(Se(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.manifestRequested$.next(),No(ae(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:t,textTracks:i})=>{this.params.output.firstBytesManifest$.next(),this.manifests$.next([this.masterManifest,...t]),this.params.output.manifestReceived$.next(),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(i)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:xd.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),s=r?.to?.id??t.getState()?.id??"master",n=this.manifests$.getValue();if(!n.length)return;let u=i?"master":s;return i&&(!r||!r.from)&&t.startTransitionTo(this.masterManifest),n.find(o=>o.id===u)}subscribe(){let{output:e,desiredState:t}=this.params,i=u=>{e.error$.next({id:"HlsProvider",category:xd.WTF,message:"HlsProvider internal logic error",thrown:u})},r=Ve(this.video);this.subscription.add(()=>r.destroy());let s=(u,o)=>this.subscription.add(u.subscribe(o));if(s(r.timeUpdate$,e.position$),s(r.durationChange$,e.duration$),s(r.ended$,e.endedEvent$),s(r.looped$,e.loopedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.loadedMetadata$,e.firstBytesEvent$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.seeked$,e.seekedEvent$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe(JT(u=>u.to)),this.params.output.playbackState$),this.subscription.add(bt(this.video,t.isLooped,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(ze(this.video,t.playbackRate,r.playbackRateState$,i)),Rr({subscription:this.subscription,desiredState:t,videoElement$:this.params.output.element$,observableVideo:r}),this.subscription.add(Be(this.video,t.volume,r.volumeState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),k(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),k(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i).add(r.loadedMetadata$.subscribe(()=>{let u=this.params.desiredState.seekState.getState(),o=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),p=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&n0(l.to)){let h=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let f=this.manifests$.getValue().find(m=>m.id===h);f&&(this.params.output.currentVideoTrack$.next(f),this.params.output.hostname$.next(Se(f.url)))}let c=this.params.desiredState.playbackRate.getState(),d=this.params.output.element$.getValue()?.playbackRate;if(c!==d){let h=this.params.output.element$.getValue();h&&(this.params.desiredState.playbackRate.setState(c),h.playbackRate=c)}p&&this.params.desiredState.autoVideoTrackSwitching.setState(p.to),o&&o.from==="changing_manifest"&&this.videoState.setState(o.to),u.state==="requested"&&this.seek(u.position)},i))),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(r.ended$.subscribe(()=>{this.videoState.setState("paused"),k(t.playbackState,"paused")})),this.subscription.add(this.manifests$.pipe(JT(u=>u.map(({id:o,quality:l,size:p,bandwidth:c,fps:d})=>({id:o,quality:l,size:p,fps:d,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,i)),!D.device.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:u}=this.video;this.subscription.add(ZT(wd(u,"addtrack"),wd(u,"removetrack"),wd(u,"change"),eI(["init"])).subscribe(()=>{for(let o=0;o<u.length;o++)u[o].mode="hidden"},i))}let n=ZT(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,eI(["init"])).pipe(s0(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Ce(this.video)}prepare(){let e=this.selectManifest();if(o0(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:s,min:n}=t?.to??i??{};for(let[u,o]of[[s,"mq"],[n,"lq"]]){let l=String(parseFloat(u||""));o&&u&&r.searchParams.set(o,l)}}this.video.setAttribute("src",r.toString()),this.video.load()}playIfAllowed(){_e(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:xd.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var aI=C(fi(),1),Ad=C(hi(),1),sI=C(nt(),1);import{assertNever as c0,assertNonNullable as iI,debounce as d0,ErrorCategory as rI,isHigherOrEqual as p0,isLowerOrEqual as h0,isNonNullable as f0,merge as m0,observableFrom as b0,Subscription as g0,map as v0}from"@vkontakte/videoplayer-shared/es2024";var Ls=class{constructor(e){this.subscription=new g0;this.videoState=new O("stopped");this.trackUrls={};this.textTracksManager=new Ye;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),k(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.autoVideoTrackLimits.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),u=this.params.desiredState.seekState.getState();if(s&&e!=="ready"&&!n){this.handleQualityLimitTransition(s.to);return}if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(n){let{currentTime:o}=this.video;this.prepare(),u.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:o*1e3,forcePrecise:!0});return}switch(i?.to!=="paused"&&u.state==="requested"&&this.seek(u.position),e){case"ready":t==="ready"?k(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):i?.to==="playing"&&k(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&k(this.params.desiredState.playbackState,"paused");return;default:return c0(e)}};this.params=e,this.video=De(e.container,e.tuning),this.params.output.element$.next(this.video),(0,aI.default)(this.params.source).reverse().forEach(([t,i],r)=>{let s=r.toString(10);this.trackUrls[s]={track:{quality:t,id:s},url:i}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next((0,Ad.default)(this.trackUrls).map(({track:t})=>t)),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.subscribe()}subscribe(){let{output:e,desiredState:t}=this.params,i=u=>{e.error$.next({id:"MpegProvider",category:rI.WTF,message:"MpegProvider internal logic error",thrown:u})},r=Ve(this.video);this.subscription.add(()=>r.destroy());let s=(u,o)=>this.subscription.add(u.subscribe(o,i));s(r.timeUpdate$,e.position$),s(r.durationChange$,e.duration$),s(r.ended$,e.endedEvent$),s(r.looped$,e.loopedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.loadedMetadata$,e.firstBytesEvent$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.seeked$,e.seekedEvent$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe(v0(u=>u.to)),this.params.output.playbackState$),this.subscription.add(bt(this.video,t.isLooped,i)),Rr({subscription:this.subscription,desiredState:t,videoElement$:this.params.output.element$,observableVideo:r}),this.subscription.add(Be(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(ze(this.video,t.playbackRate,r.playbackRateState$,i)),s(Ke(this.video),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),k(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),k(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready");let u=this.params.desiredState.videoTrack.getTransition();if(u&&f0(u.to)){this.params.desiredState.videoTrack.setState(u.to),this.params.output.currentVideoTrack$.next(this.trackUrls[u.to.id].track);let o=this.params.desiredState.playbackRate.getState(),l=this.params.output.element$.getValue()?.playbackRate;if(o!==l){let p=this.params.output.element$.getValue();p&&(this.params.desiredState.playbackRate.setState(o),p.playbackRate=o)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(r.ended$.subscribe(()=>{this.videoState.setState("paused"),k(t.playbackState,"paused")})),this.textTracksManager.connect(this.video,t,e);let n=m0(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,b0(["init"])).pipe(d0(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),Ce(this.video)}prepare(){let e=this.params.desiredState.videoTrack.getState()?.id;iI(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];iI(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=Jt(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(Se(t))}playIfAllowed(){_e(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:rI.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 p=St(n,{container:this.video.getBoundingClientRect(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,limits:l,abrLogger:this.params.dependencies.abrLogger});t(p)},r=this.params.output.currentVideoTrack$.getValue()?.quality,s=!!(e.max||e.min),n=(0,Ad.default)(this.trackUrls).map(l=>l.track);if(!r||!s||dr(e,n[0].quality,(0,sI.default)(n,-1)?.quality)){i();return}let u=e.max?h0(r,e.max):!0,o=e.min?p0(r,e.min):!0;u&&o||i(e)}};import{assertNever as oI,debounce as I0,merge as uI,observableFrom as E0,Subscription as x0,map as lI,ValueSubject as w0,ErrorCategory as Pd,VideoQuality as A0}from"@vkontakte/videoplayer-shared/es2024";import{ErrorCategory as S0}from"@vkontakte/videoplayer-shared/es2024";var nI=["stun:videostun.mycdn.me:80"],y0=1e3,T0=3,kd=()=>null,Ho=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=kd;this.externalStopCallback=kd;this.externalErrorCallback=kd;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:nI}]};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:S0.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),y0)}normalizeOptions(e={}){let t={stunServerList:nI,maxRetryNumber:T0,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var Ms=class{constructor(e){this.videoState=new O("stopped");this.maxSeekBackTime$=new w0(0);this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.pause(),this.video.srcObject=null,this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),k(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.videoTrack.getTransition();if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s){this.prepare();return}switch(e){case"ready":t==="paused"?(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):i?.to==="playing"&&k(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&k(this.params.desiredState.playbackState,"paused");return;default:return oI(e)}};this.subscription=new x0,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=De(e.container,e.tuning),this.liveStreamClient=new Ho(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),Ce(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,i=n=>{e.error$.next({id:"WebRTCLiveProvider",category:Pd.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};this.subscription.add(uI(this.videoState.stateChangeStarted$.pipe(lI(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(lI(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:u})=>{this.log({message:`[videoState change] ${u}: ${JSON.stringify(n)}`})}));let r=Ve(this.video);this.subscription.add(()=>r.destroy());let s=(n,u)=>this.subscription.add(n.subscribe(u,i));s(r.timeUpdate$,e.liveTime$),s(r.ended$,e.endedEvent$),s(r.looped$,e.loopedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(Ke(this.video),this.params.output.elementVisible$),this.subscription.add(r.durationChange$.subscribe(n=>{e.duration$.next(n===1/0?0:n)})).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused")},i)).add(r.playing$.subscribe(()=>{this.videoState.setState("playing")},i)).add(r.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(Be(this.video,t.volume,r.volumeState$,i)).add(r.volumeState$.subscribe(e.volume$,i)).add(this.videoState.stateChangeEnded$.subscribe(n=>{switch(n.to){case"stopped":e.position$.next(0),e.duration$.next(0),t.playbackState.setState("stopped");break;case"ready":break;case"paused":t.playbackState.setState("paused");break;case"playing":t.playbackState.setState("playing");break;default:return oI(n.to)}},i)).add(uI(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,E0(["init"])).pipe(I0(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(Se(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.currentVideoTrack$.next({id:"webrtc",quality:A0.INVARIANT}),this.video.srcObject=e,k(this.params.desiredState.playbackState,"playing")}onLiveStreamStop(){this.videoState.startTransitionTo("stopped"),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.params.output.endedEvent$.next()}onLiveStreamError(e){this.onLiveStreamStop(),this.params.output.error$.next({id:"WebRTC stream runtime error",category:Pd.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){_e(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Pd.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var Cr=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 Ds,assertNonNullable as ii,ErrorCategory as Wo,filter as mI,isNonNullable as bI,isNullable as D0,map as C0,merge as B0,once as V0,Subject as ee,Subscription as gI,ValueSubject as _,flattenObject as Rd}from"@vkontakte/videoplayer-shared/es2024";import{Observable as k0,map as cI,Subscription as P0,Subject as R0}from"@vkontakte/videoplayer-shared/es2024";var dI=a=>new k0(e=>{let t=new P0,i=a.desiredPlaybackState$.stateChangeStarted$.pipe(cI(({from:l,to:p})=>`${l}-${p}`)),r=a.desiredPlaybackState$.stateChangeEnded$,s=a.providerChanged$.pipe(cI(({type:l})=>l!==void 0)),n=new R0,u=0,o="unknown";return t.add(i.subscribe(l=>{u&&window.clearTimeout(u),o=l,u=window.setTimeout(()=>n.next(l),a.maxTransitionInterval)})),t.add(r.subscribe(()=>{window.clearTimeout(u),o="unknown",u=0})),t.add(s.subscribe(l=>{u&&(window.clearTimeout(u),u=0,l&&(u=window.setTimeout(()=>n.next(o),a.maxTransitionInterval)))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(u),t.unsubscribe()}});import{ErrorCategory as $0,Subscription as L0,combine as M0,filter as hI,once as fI}from"@vkontakte/videoplayer-shared/es2024";function pI(){return new(window.AudioContext||window.webkitAudioContext)}var Br=class a{constructor(e,t,i,r){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=i;this.volumeMultiplier=r;this.destroyController=new Y;this.subscriptions=new L0;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe(hI(s=>!!s.type),fI()).subscribe(({type:s})=>this.subscribe(s)))}static{this.errorId="VolumeMultiplierManager"}subscribe(e){D.browser.isSafari&&e!=="MPEG"||this.subscriptions.add(M0({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(hI(({playbackState:t,video:i,volume:{muted:r,volume:s}})=>t==="playing"&&!!i&&!r&&!!s),fI()).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=pI();this.audioContext=i;let r=i.createGain();if(this.gainNode=r,r.gain.value=t,r.connect(i.destination),i.state==="suspended"&&(await i.resume(),this.destroyController.signal.aborted))return!1;let s=i.createMediaElementSource(e);return this.mediaElementSource=s,s.connect(r),!0}cleanup(){this.mediaElementSource&&(this.mediaElementSource.disconnect(),this.mediaElementSource=null),this.gainNode&&(this.gainNode.disconnect(),this.gainNode=null),this.audioContext&&(this.audioContext.state!=="closed"&&this.audioContext.close(),this.audioContext=null)}destroy(){this.destroyController.abort(),this.subscriptions.unsubscribe(),this.cleanup()}handleError(e){this.volumeMultiplierError$.next({id:a.errorId,category:$0.VIDEO_PIPELINE,message:e?.message??`${a.errorId} exception`,thrown:e})}};var _0={chunkDuration:5e3,maxParallelRequests:5},Cs=class{constructor(e){this.current$=new _({type:void 0});this.providerError$=new ee;this.noAvailableProvidersError$=new ee;this.volumeMultiplierError$=new ee;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 ee,fetcherError$:new ee,fetcherRecoverableError$:new ee,warning$:new ee,willSeekEvent$:new ee,soundProhibitedEvent$:new ee,seekedEvent$:new ee,loopedEvent$:new ee,endedEvent$:new ee,manifestRequested$:new ee,firstBytesManifest$:new ee,manifestReceived$:new ee,firstBytesRequested$:new ee,firstBytesReceived$:new ee,firstBytesEvent$:new ee,loadedMetadataEvent$:new ee,firstFrameEvent$:new ee,canplay$:new ee,isLive$:new _(void 0),isLiveEnded$:new _(null),canPlayLiveTailBuffer$:new _(!1),isLowLatency$:new _(!1),canChangePlaybackSpeed$:new _(!0),liveTime$:new _(void 0),liveBufferTime$:new _(void 0),liveLatency$:new _(void 0),severeStallOccurred$:new ee,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 gI;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=Yl([...oT(this.params.tuning),...nT(this.params.tuning)]).filter(l=>bI(e.sources[l])),{forceFormat:i,formatsToAvoid:r}=this.params.tuning,s=[];i?s=[i]:r.length?s=[...t.filter(l=>!(0,$d.default)(r,l)),...t.filter(l=>(0,$d.default)(r,l))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",Rd(s)),this.screenFormatsIterator=new Cr(s);let n=[...qc(!0),...qc(!1)];this.chromecastFormatsIterator=new Cr(n.filter(l=>bI(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:u=1,tuning:{useVolumeMultiplier:o}}=this.params;o&&u!==1&&Br.isSupported()&&(this.volumeMultiplierManager=new Br(this.providerOutput,this.current$,this.volumeMultiplierError$,u))}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 Cr(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(D0(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:Wo.WTF,message:"Failed to create provider",thrown:r})}i?this.current$.next({type:t,provider:i,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.tracer.log("reinitProvider"),this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.tracer.log("switchToNextProvider",{destination:e}),this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}switchToNextVideoCodec(){this.params.tuning.dash.codecsPrioritizeEnabled&&!this.videoCodecsIterator.isLast()&&(this.tracer.log("switchToNextVideoCodec"),this.destroyProvider(),this.videoCodecsIterator.next(),this.initProvider())}destroyProvider(){let e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"}),this.tracer.log("destroyProvider"),e.destroy();let t=this.providerOutput.position$.getValue()*1e3,i=this.params.desiredState.seekState.getState(),r=i.state!=="none";if(this.params.desiredState.seekState.setState({state:"requested",position:r?i.position:t,forcePrecise:r?i.forcePrecise:!1}),e.scene3D){let n=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:n.x,y:n.y})}let s=this.providerOutput.isBuffering$;s.getValue()||s.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),this.tracer.log("createProvider",{destination:e,format:t}),e){case"SCREEN":return this.createScreenProvider(t);case"CHROMECAST":return this.createChromecastProvider(t);default:return Ds(e)}}createScreenProvider(e){let{sources:t,container:i,desiredState:r,panelSize:s}=this.params,n=this.providerOutput,u={container:i,source:null,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning,panelSize:s};switch(e){case"DASH_SEP":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_ONDEMAND":case"DASH_STREAMS":{let o=this.applyFailoverHost(t[e]),l=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return ii(o),this.params.tuning.useNewDashProvider?new ks({...u,source:o,sourceHls:l,forceVideoCodec:this.videoCodecsIterator?.getValue()}):new hs({...u,source:o,sourceHls:l,forceVideoCodec:this.videoCodecsIterator?.getValue()})}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return ii(o),this.params.tuning.useNewDashProvider?new Ps({...u,source:o}):new fs({...u,source:o})}case"HLS":case"HLS_ONDEMAND":case"HLS_FMP4":{let o=this.applyFailoverHost(t[e]);return ii(o),new $s({...u,source:o})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return ii(o),new Rs({...u,source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let o=this.applyFailoverHost(t[e]);return ii(o),new Ls({...u,source:o})}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return ii(o),new eS({...u,source:o,config:{..._0,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return ii(o),new Ms({container:i,source:o,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return Ds(e)}}createChromecastProvider(e){let{sources:t,container:i,desiredState:r,meta:s}=this.params,n=this.providerOutput,u=this.params.dependencies.chromecastInitializer.connection$.getValue();return ii(u),new da({connection:u,meta:s,container:i,source:t,format:e,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?"CHROMECAST":"SCREEN"}chooseFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case"CHROMECAST":return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return Ds(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return Ds(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 Ds(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;let t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;let i=r=>{let s=new URL(r);return s.host=t,s.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return{...e,url:i(e.url)}}return(0,SI.default)((0,vI.default)(e).map(([r,s])=>[r,i(s)]))}initProviderErrorHandling(){let e=new gI,t=!1,i=0;return e.add(B0(this.providerOutput.error$.pipe(mI(r=>!this.params.tuning.ignoreAudioRendererError||!r.message||!/AUDIO_RENDERER_ERROR/ig.test(r.message))),dI({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(C0(r=>({id:`ProviderHangup:${r}`,category:Wo.WTF,message:`A ${r} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.providerOutput.fetcherError$.subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;let r=this.params.desiredState.playbackState.transitionEnded$.pipe(mI(({to:s})=>s==="playing"),V0()).subscribe(()=>t=!0);e.add(r)})),e.add(this.providerError$.subscribe(r=>{let s=this.current$.getValue().destination,n={error:r,currentDestination:s};if(s==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("SCREEN"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let u=r.category===Wo.NETWORK,o=r.category===Wo.FATAL,l=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),p=i<this.params.tuning.providerErrorLimit&&!o,c=this.videoCodecsIterator&&!this.videoCodecsIterator.isLast()&&this.params.tuning.dash.codecsPrioritizeEnabled,d=l&&!o&&(u&&t||!p);n={...n,isNetworkError:u,isFatalError:o,haveFailoverHost:l,tryFailover:d,canReinitProvider:p},p?(i++,this.reinitProvider()):d?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):c?this.switchToNextVideoCodec():(i=0,this.switchToNextProvider(s??"SCREEN"))}r.traceAsLog?this.tracer.log("providerInfo",Rd(n)):this.tracer.error("providerError",Rd(n))})),e}};import{fromEvent as Qo,once as O0,combine as F0,Subscription as yI,ValueSubject as Ld,map as TI,filter as N0,isNonNullable as Go,now as We,safeStorage as Md}from"@vkontakte/videoplayer-shared/es2024";var q0=5e3,II="one_video_throughput",EI="one_video_rtt",Bs=window.navigator.connection,xI=()=>{let a=Bs?.downlink;if(Go(a)&&a!==10)return a*1e3},wI=()=>{let a=Bs?.rtt;if(Go(a)&&a!==3e3)return a},AI=(a,e,t)=>{let i=t*8,r=i/a;return i/(r+e)},Dd=class a{constructor(e){this.subscription=new yI;this.concurrentDownloads=new Set;this.tuningConfig=e;let t=a.load(II)||(e.useBrowserEstimation?xI():void 0)||q0,i=a.load(EI)??(e.useBrowserEstimation?wI():void 0)??0;if(this.throughput$=new Ld(t),this.rtt$=new Ld(i),this.rttAdjustedThroughput$=new Ld(AI(t,i,e.rttPenaltyRequestSize)),this.throughput=Mt.getSmoothedValue(t,-1,e),this.rtt=Mt.getSmoothedValue(i,1,e),e.useBrowserEstimation){let r=()=>{let n=xI();n&&this.throughput.next(n);let u=wI();Go(u)&&this.rtt.next(u)};Bs&&"onchange"in Bs&&this.subscription.add(Qo(Bs,"change").subscribe(r)),r()}this.subscription.add(this.throughput.smoothed$.subscribe(r=>{Md.set(II,r.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(r=>{Md.set(EI,r.toFixed(0))})),this.subscription.add(this.throughput.debounced$.pipe(TI(r=>Math.round(r))).subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(F0({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(TI(({throughput:r,rtt:s})=>AI(r,s,e.rttPenaltyRequestSize)),N0(r=>{let s=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(r-s)/s>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,i=We(),r=new yI;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add(Qo(e,"progress").pipe(O0()).subscribe(s=>{t=s.loaded,i=We()}));break;case 1:case 0:r.add(Qo(e,"loadstart").subscribe(()=>{t=0,i=We()}));break}r.add(Qo(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,u=We(),o=n-t,l=u-i;this.addRawSpeed(o,l,1)}this.concurrentDownloads.delete(e),r.unsubscribe()}))}trackStream(e,t=!1){let i=e.getReader();if(!i){e.cancel("Could not get reader");return}let r=0,s=We(),n=0,u=We(),o=p=>{this.concurrentDownloads.delete(e),i.releaseLock(),e.cancel(`Throughput Estimator error: ${p}`).catch(()=>{})},l=async({done:p,value:c})=>{if(p)!t&&this.addRawSpeed(r,We()-s,1),this.concurrentDownloads.delete(e);else if(c){if(t){let d=We();if(d-u>this.tuningConfig.lowLatency.continuesByteSequenceInterval||d-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let f=u-s;f&&this.addRawSpeed(n,f,1,t),n=c.byteLength,s=We()}else n+=c.byteLength;u=We()}else r+=c.byteLength,n+=c.byteLength,n>=this.tuningConfig.streamMinSampleSize&&We()-u>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,We()-u,this.concurrentDownloads.size),n=0,u=We());await i?.read().then(l,o)}};this.concurrentDownloads.add(e),i?.read().then(l,o)}addRawSpeed(e,t,i=1,r=!1){if(a.sanityCheck(e,t,r)){let s=e*8/t;this.throughput.next(s*i)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,i=!1){let r=e*8/t;return!(!r||!isFinite(r)||r>1e6||r<30||i&&e<1e4||!i&&e<10*1024||!i&&t<=20)}static load(e){let t=Md.get(e);if(Go(t))return parseInt(t,10)??void 0}},kI=Dd;import{fillWithDefault as U0,VideoQuality as zo}from"@vkontakte/videoplayer-shared/es2024";var PI={configName:["core"],throughputEstimator:{type:"EmaAndMa",emaAlphaSlow:.2,emaAlphaFast:.7,emaAlpha:.45,basisTrendChangeCount:10,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1*1024*1024,streamMinSampleSize:10*1024,streamMinSampleTime:300,deviationDepth:20,deviationFactor:.5,lowLatency:{continuesByteSequenceInterval:50,maxLastEvaluationTimeout:300}},autoTrackSelection:{maxBitrateFactorAtEmptyBuffer:4,bitrateFactorAtEmptyBuffer:2.8,minBitrateFactorAtEmptyBuffer:1.5,bitrateAudioFactorAtEmptyBuffer:10,maxBitrateFactorAtFullBuffer:3,bitrateFactorAtFullBuffer:2,minBitrateFactorAtFullBuffer:1,bitrateAudioFactorAtFullBuffer:7,minVideoAudioRatio:5,minAvailableThroughputAudioRatio:5,usePixelRatio:!0,pixelRatioMultiplier:void 0,pixelRatioLogBase:3,pixelRatioLogCoefficients:[1,0,1],limitByContainer:!0,maxContainerSizeFactor:2,containerSizeFactor:1.3,minContainerSizeFactor:1,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldownIncreaseQuality:15e3,trackCooldownDecreaseQuality:3e3,backgroundVideoQualityLimit:zo.Q_4320P,activeVideoAreaThreshold:.1,highQualityLimit:zo.Q_720P,trafficSavingLimit:zo.Q_480P},stallsManager:{enabled:!0,ignoreDynamicAbrForShortVideo:!1,stallDurationNoDataBeforeQualityDecrease:500,stallDurationToBeCount:100,stallCountBeforeQualityDecrease:3,resetQualityRestrictionTimeout:1e4,ignoreStallsOnSeek:!0,stallsMetricsHistoryLength:20,maxPossibleStallDuration:3e4,minTvtToBeCounted:120,maxTvtToBeCounted:10800,significantTvt:600,targetStallsDurationPerTvt:1,deviationStallsDurationPerTvt:.5,criticalStallsDurationPerTvt:6,abrAdjustingSpeed:.1,emaAlpha:.6,useTotalStallsDurationPerTvt:!0,useAverageStallsDurationPerTvt:!0,useEmaStallsDurationPerTvt:!0},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:zo.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:15e3,crashOnStallTimeout:25e3,crashOnStallTWithoutDataTimeout:5e3,enableSubSegmentBufferFeeding:!0,bufferEmptinessTolerance:100,useNewRepresentationSwitch:!1,useDelayedRepresentationSwitch:!1,useSmartRepresentationSwitch:!1,useFetchPriorityHints:!0,enableBaseUrlSupport:!0,maxSegmentRetryCount:5,sourceOpenTimeout:1e3,vktvAbrThrottle:0,timeupdateEventTickThrottle:300,fetcherBufferOptimisation:!0,codecsPrioritizeEnabled:!1,usePersistentGaps:!1,abrThrottle:0,useVideoElementWaitingCurrentTimeReassign:!0,stallWatchdogInterval:100,liveUpdateInterval:1e3,liveStallReinitInterval:3e3,ignoreNetworkErrorsOnLoadInit:!1},dashCmafLive:{externalStopControl:!1,keepSilentStallWatchdogWhenNotActive:!1,maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,maxLiveDuration:7200,catchupLiveForMutedInactiveTab:!0,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:250,playbackCatchupSpeedup:.05,isActiveOnDefault:!1,bufferEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:"07A4434E",useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"dash",iosPreferredFormat:"hls",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,useNewSwitchTo:!1,useNewDashProvider:!1,useNewAutoSelectVideoTrack:!1,useSafariEndlessRequestBugfix:!0,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,useHlsLiveNewTextManager:!1,exposeInternalsToGlobal:!1,hlsLiveNewTextManagerDownloadThreshold:4e3,disableYandexPiP:!1,asyncResolveClientChecker:!1,autostartOnlyIfVisible:!1,changePlaybackStateToPausedWhenEnded:!1,suppressExceptionsInObservables:!0,devNullLogEnabled:!1,collectingDecodingInfoEnabled:!1},RI=a=>({...U0(a,PI),configName:[...a.configName??[],...PI.configName]});import{assertNonNullable as Bd,combine as Vt,ErrorCategory as Yo,filter as le,filterChanged as G,fromEvent as Vd,isNonNullable as BI,isNullable as Z0,Logger as eV,map as Q,mapTo as VI,merge as ri,now as Ko,once as fe,Subject as H,Subscription as _I,tap as _d,ValueSubject as R,isHigher as tV,isInvariantQuality as OI,flattenObject as ai,throttle as Od,getTraceSubscriptionMethod as FI,TracerFactory as iV,InternalsExposure as rV,getPlayerId as aV,devNull as Xo}from"@vkontakte/videoplayer-shared/es2024";import{merge as j0,map as H0,filter as $I,isNonNullable as W0}from"@vkontakte/videoplayer-shared/es2024";var Cd=({seekState:a,position$:e})=>j0(a.stateChangeEnded$.pipe(H0(({to:t})=>t.state==="none"?void 0:(t.position??NaN)/1e3),$I(W0)),e.pipe($I(()=>a.getState().state==="none")));import{assertNonNullable as Q0}from"@vkontakte/videoplayer-shared/es2024";var LI=a=>{let e=typeof a.container=="string"?document.getElementById(a.container):a.container;return Q0(e,`Wrong container or containerId {${a.container}}`),e};import{filter as G0,once as z0}from"@vkontakte/videoplayer-shared/es2024";var MI=(a,e,t,i)=>{a!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&t?.getValue().length===0?t.pipe(G0(r=>r.length>0),z0()).subscribe(r=>{r.find(i)&&e.startTransitionTo(a)}):(a===void 0||t?.getValue().find(i))&&e.startTransitionTo(a)};var DI=C(fi(),1);import{devNull as Y0}from"@vkontakte/videoplayer-shared/es2024";var CI=()=>{let a="mediaCapabilities"in navigator?K0:X0,e=zt(async()=>{let t=await Promise.all((0,DI.default)(J0).map(async([r,s])=>({codec:r,supported:await a(s)}))),i=[D.browser.current,...t.map(r=>JSON.stringify(r))].slice(0,16);return Y0.push("core",{key:"videoplayer_decoding_info",strings:i}),t});return()=>Je(e)},K0=async a=>{if(!a)return Promise.resolve({supported:!1});let e={["channels"in a?"audio":"video"]:a};return await navigator.mediaCapabilities.decodingInfo({type:"media-source",...e})},X0=a=>{if(!a)return Promise.resolve({supported:!1});let e="channels"in a?document.createElement("audio"):document.createElement("video");return Promise.resolve({supported:e.canPlayType(a?.contentType??"")==="probably"})},J0={H264:{contentType:'video/mp4; codecs="avc1.4D400C"',width:720,height:720,bitrate:2886,framerate:30},H265:{contentType:'video/mp4; codecs="hvc1.1.6.L123.B0"',width:720,height:720,bitrate:2886,framerate:30},VP8:{contentType:'video/webm; codecs="vp8"',width:720,height:720,bitrate:2886,framerate:30},VP9:{contentType:'video/webm; codecs="vp09.00.10.08"',width:720,height:720,bitrate:2886,framerate:30},AV1:{contentType:'video/mp4; codecs="av01.0.01M.08"',width:720,height:720,bitrate:2886,framerate:30},OPUS:{contentType:'audio/ogg; codecs="opus"',channels:"2",bitrate:128e3},AAC_LC:{contentType:'audio/mp4; codecs="mp4a.40.2"',channels:"2",bitrate:128e3},AC3:{contentType:'audio/mp4; codecs="ac-3"',channels:"6",bitrate:128e3},EAC3:{contentType:'audio/mp4; codecs="ec-3"',channels:"6",bitrate:128e3},AAC_HE_V1:{contentType:'audio/mp4; codecs="mp4a.40.5"',channels:"2",bitrate:128e3},AAC_HE_V2:{contentType:'audio/mp4; codecs="mp4a.40.29"',channels:"2",bitrate:128e3},AAC_xHE:{contentType:'audio/mp4; codecs="mp4a.40.42"',channels:"2",bitrate:128e3}};var Jo=class{constructor(e={configName:[]},t=iV.createRootTracer(!1),i){this.subscription=new _I;this.logger=new eV;this.abrLogger=this.logger.createComponentLog("ABR");this.internalsExposure=null;this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new R(!1);this.hasLiveOffsetByPausedTimer=0;this.playerInitRequest=0;this.playerInited=new R(!1);this.wasSetStartedQuality=!1;this.desiredState={playbackState:new O("stopped"),seekState:new O({state:"none"}),volume:new O({volume:1,muted:!1}),videoTrack:new O(void 0),videoStream:new O(void 0),audioStream:new O(void 0),autoVideoTrackSwitching:new O(!0),autoVideoTrackLimits:new O({}),isLooped:new O(!1),isLowLatency:new O(!1),playbackRate:new O(1),externalTextTracks:new O([]),internalTextTracks:new O([]),currentTextTrack:new O(void 0),textTrackCuesSettings:new O({}),cameraOrientation:new O({x:0,y:0})};this.info={playbackState$:new R(void 0),position$:new R(0),duration$:new R(1/0),muted$:new R(!1),volume$:new R(1),availableVideoStreams$:new R([]),currentVideoStream$:new R(void 0),availableQualities$:new R([]),availableQualitiesFps$:new R({}),currentQuality$:new R(void 0),isAutoQualityEnabled$:new R(!0),autoQualityLimitingAvailable$:new R(!1),autoQualityLimits$:new R({}),predefinedQualityLimitType$:new R("unknown"),availableAudioStreams$:new R([]),currentAudioStream$:new R(void 0),availableAudioTracks$:new R([]),isAudioAvailable$:new R(!0),currentPlaybackRate$:new R(1),currentBuffer$:new R({start:0,end:0}),isBuffering$:new R(!0),isStalled$:new R(!1),isEnded$:new R(!1),isLooped$:new R(!1),isLive$:new R(void 0),isLiveEnded$:new R(null),canPlayLiveTailBuffer$:new R(!1),canChangePlaybackSpeed$:new R(void 0),atLiveEdge$:new R(void 0),atLiveDurationEdge$:new R(void 0),liveTime$:new R(void 0),liveBufferTime$:new R(void 0),liveLatency$:new R(void 0),currentFormat$:new R(void 0),availableTextTracks$:new R([]),currentTextTrack$:new R(void 0),throughputEstimation$:new R(void 0),rttEstimation$:new R(void 0),videoBitrate$:new R(void 0),hostname$:new R(void 0),httpConnectionType$:new R(void 0),httpConnectionReused$:new R(void 0),surface$:new R("none"),chromecastState$:new R("NOT_AVAILABLE"),chromecastDeviceName$:new R(void 0),intrinsicVideoSize$:new R(void 0),availableSources$:new R(void 0),is3DVideo$:new R(!1),currentVideoSegmentLength$:new R(0),currentAudioSegmentLength$:new R(0)};this.events={inited$:new H,ready$:new H,started$:new H,playing$:new H,paused$:new H,stopped$:new H,willReady$:new H,willStart$:new H,willResume$:new H,willPause$:new H,willStop$:new H,willDestruct$:new H,watchCoverageRecord$:new H,watchCoverageLive$:new H,managedError$:new H,fatalError$:new H,fetcherRecoverableError$:new H,ended$:new H,looped$:new H,seeked$:new H,willSeek$:new H,autoplaySoundProhibited$:new H,manifestRequested$:new H,firstBytesManifest$:new H,manifestReceived$:new H,firstBytesRequested$:new H,firstBytesReceived$:new H,firstBytes$:new H,loadedMetadata$:new H,firstFrame$:new H,canplay$:new H,log$:new H,fetcherError$:new H,severeStallOccured$:new H};this.experimental={element$:new R(void 0),tuningConfigName$:new R([]),enableDebugTelemetry$:new R(!1),dumpTelemetry:wv,getCurrentTime$:new R(null)};if(this.initLogs(),this.tuning=RI(e),this.tracer=t,this.tuning.suppressExceptionsInObservables&&((0,Fd.default)(this.info).forEach(r=>r.setSuppressErrors(!0)),(0,Fd.default)(this.events).forEach(r=>r.setSuppressErrors(!0))),this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new en({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new kI(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new rV("core",aV(i?.playerId)),this.internalsExposure.expose({player:this})),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),this.devNullLog=i?.onDevNullLog,Xo.create("core"),Proxy&&Reflect)return new Proxy(this,{get:(r,s,n)=>{let u=Reflect.get(r,s,n);return typeof u!="function"?u:(...o)=>{try{return u.apply(r,o)}catch(l){let p=o.map(h=>JSON.stringify(h,(f,m)=>{let g=typeof m;return(0,NI.default)(["number","string","boolean"],g)?m:m===null?null:`<${g}>`})),c=`Player.${String(s)}`,d=`Exception calling ${c} (${p.join(", ")})`;throw this.events.fatalError$.next({id:c,category:Yo.WTF,message:d,thrown:l}),l}}}})}initVideo(e){this.config=e,this.internalsExposure?.expose({config:e,logger:this.logger,tuning:this.tuning}),this.setMuted(this.tuning.isAudioDisabled);let t=()=>{let{container:s,...n}=e;this.tracer.log("initVideo",ai(n)),this.domContainer=LI(e),this.chromecastInitializer.contentId=e.meta?.videoId,this.providerContainer=new Cs({sources:e.sources,meta:e.meta??{},failoverHosts:e.failoverHosts??[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,tracer:this.tracer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning,volumeMultiplier:e.volumeMultiplier,panelSize:e.panelSize}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.initTracerSubscription(),this.providerContainer.init(),this.setLiveLowLatency(this.tuning.dashCmafLive.lowLatency.isActiveOnDefault),this.initDebugTelemetry(),this.initWakeLock(),this.playerInited.next(!0),this.devNullLog&&this.tuning.devNullLogEnabled?(Xo.subscribe("core",this.devNullLog),this.tuning.collectingDecodingInfoEnabled&&(this.collectDecodingInfoDestroyCb=CI())):Xo.destroy("core")},i=()=>{this.tuning.autostartOnlyIfVisible&&window.requestAnimationFrame?this.playerInitRequest=window.requestAnimationFrame(()=>t()):t()},r=()=>{this.tuning.asyncResolveClientChecker?D.isInited$.pipe(le(s=>!!s),fe()).subscribe(()=>{console.log("Core SDK async start"),i()}):i()};return this.isNotActiveTabCase()?(this.tracer.log("request play from hidden tab"),Vd(document,"visibilitychange").pipe(fe()).subscribe(r)):r(),this}destroy(){this.tracer.log("destroy"),window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.playerInitRequest&&window.cancelAnimationFrame(this.playerInitRequest),this.events.willDestruct$.next(),this.stop(),this.providerContainer?.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe(),this.tracer.end(),this.internalsExposure?.destroy(),Xo.destroy("core"),this.collectDecodingInfoDestroyCb?.()}waitInit(e){this.playerInited.getValue()?e():this.subscription.add(this.playerInited.pipe(le(t=>!!t),fe()).subscribe(e))}prepare(){return this.waitInit(()=>{let e=this.desiredState.playbackState;this.tracer.log("prepare",{currentPlayBackState:e.getState()}),e.getState()==="stopped"&&e.startTransitionTo("ready")}),this}play(){return this.waitInit(()=>{let e=this.desiredState.playbackState;this.tracer.log("play",{currentPlayBackState:e.getState()}),e.getState()!=="playing"&&e.startTransitionTo("playing")}),this}pause(){return this.waitInit(()=>{let e=this.desiredState.playbackState;this.tracer.log("pause",{currentPlayBackState:e.getState()}),e.getState()!=="paused"&&e.startTransitionTo("paused")}),this}stop(){return this.waitInit(()=>{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.waitInit(()=>{let i=this.info.duration$.getValue(),r=this.info.isLive$.getValue(),s=e;e>=i&&!r&&(s=i-this.tuning.seekNearDurationBias),this.tracer.log("seekTime",{duration:i,isLive:r,time:e,calculatedTime:s,forcePrecise:t}),Number.isFinite(s)&&(this.events.willSeek$.next({from:this.getExactTime(),to:s}),this.desiredState.seekState.setState({state:"requested",position:s*1e3,forcePrecise:t}))}),this}seekPercent(e){return this.waitInit(()=>{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.waitInit(()=>{let i=this.desiredState.volume,s=i.getTransition()?.to.muted??this.info.muted$.getValue(),n=t??(this.tuning.isAudioDisabled||s);this.tracer.log("setVolume",{volume:e,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:n}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setVolume(e):i.startTransitionTo({volume:e,muted:n})}),this}setMuted(e,t=!1){return this.waitInit(()=>{let i=this.desiredState.volume,r=this.tuning.isAudioDisabled&&!t||e,n=i.getTransition()?.to.volume??this.info.volume$.getValue();this.tracer.log("setMuted",{isMuted:e,nextMuted:r,volume:n,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue()}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setMuted(r):i.startTransitionTo({volume:n,muted:r})}),this}setVideoStream(e){return this.waitInit(()=>{this.desiredState.videoStream.startTransitionTo(e)}),this}setAudioStream(e){return this.waitInit(()=>{this.desiredState.audioStream.startTransitionTo(e)}),this}setQuality(e){return this.waitInit(()=>{Bd(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(le(i=>i.length>0),fe()).subscribe(i=>{this.setVideoTrackIdByQuality(i,e)}):this.explicitInitialQuality=e:t.length>0&&this.setVideoTrackIdByQuality(t,e)}),this}setAutoQuality(e){return this.waitInit(()=>{this.tracer.log("setAutoQuality",{enable:e}),this.desiredState.autoVideoTrackSwitching.startTransitionTo(e)}),this}setAutoQualityLimits(e){return this.waitInit(()=>{this.tracer.log("setAutoQualityLimits",ai(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e)}),this}setPredefinedQualityLimits(e){return this.waitInit(()=>{if(this.info.predefinedQualityLimitType$.getValue()===e)return this;let{highQualityLimit:t,trafficSavingLimit:i}=this.tuning.autoTrackSelection,r;switch(e){case"high_quality":r={min:t,max:void 0};break;case"traffic_saving":r={max:i,min:void 0};break;default:r={max:void 0,min:void 0}}this.setAutoQualityLimits(r)}),this}setPlaybackRate(e){return this.waitInit(()=>{this.tracer.log("setPlaybackRate",{playbackRate:e}),this.desiredState.playbackRate.startTransitionTo(e)}),this}setExternalTextTracks(e){return this.waitInit(()=>{e.length&&this.tracer.log("setExternalTextTracks",ai(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t})))}),this}selectTextTrack(e){return this.waitInit(()=>{MI(e,this.desiredState.currentTextTrack,this.providerContainer?.providerOutput.availableTextTracks$,t=>t.id===e),this.tracer.log("selectTextTrack",{textTrackId:e})}),this}setTextTrackCueSettings(e){return this.waitInit(()=>{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.waitInit(()=>{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.waitInit(()=>{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.waitInit(()=>{let t=this.getScene3D();this.tracer.log("stopCameraManualRotation",{isScene3DAvailable:!!t,immediate:e}),t&&t.stopCameraManualRotation(e)}),this}moveCameraFocusPX(e,t){return this.waitInit(()=>{let i=this.getScene3D();if(this.tracer.log("moveCameraFocusPX",{isScene3DAvailable:!!i,dxpx:e,dypx:t}),i){let r=i.getCameraRotation(),s=i.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:r.x+s.x,y:r.y+s.y})}}),this}holdCamera(){return this.waitInit(()=>{let e=this.getScene3D();e&&e.holdCamera()}),this}releaseCamera(){return this.waitInit(()=>{let e=this.getScene3D();e&&e.releaseCamera()}),this}getExactTime(){if(!this.providerContainer)return 0;let e=this.providerContainer.providerOutput.element$.getValue();if(Z0(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),i=t.state==="none"?void 0:t.position;return BI(i)?i/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){let e=this.providerContainer?.current$.getValue();if(e?.provider?.scene3D)return e.provider.scene3D}setIntrinsicVideoSize(...e){let t={width:e.reduce((i,{width:r})=>i||r||0,0),height:e.reduce((i,{height:r})=>i||r||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(ri(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(Q(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(Q(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(Q(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(Q(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(Q(e=>e.to)).subscribe(e=>{this.info.autoQualityLimits$.next(e);let{highQualityLimit:t,trafficSavingLimit:i}=this.tuning.autoTrackSelection;this.info.predefinedQualityLimitType$.next(kv(e,t,i))})),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(le(({from:e})=>e==="stopped"),fe()).subscribe(()=>{this.initedAt=Ko(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case"ready":this.events.ready$.next();break;case"playing":this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case"paused":this.events.paused$.next();break;case"stopped":this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case"ready":this.events.willReady$.next();break;case"paused":this.events.willPause$.next();break;case"playing":this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case"stopped":this.events.willStop$.next();break;default:}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("willSeekEvent",ai(n)),n.state==="requested"?this.desiredState.seekState.setState({...n,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:Yo.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe(fe()).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",ai(n)),n.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe(Q(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(Q(n=>n.destination),G()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(Vt({availableVideoTracks:e.providerOutput.availableVideoTracks$,currentVideoStream:e.providerOutput.currentVideoStream$}).pipe(Q(({availableVideoTracks:n,currentVideoStream:u})=>n.filter(o=>u?u.id===o.streamId:!0).map(({quality:o})=>o).sort((o,l)=>OI(o)?1:OI(l)?-1:tV(l,o)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(n=>{let u={};for(let o of n)o.fps&&(u[o.quality]=o.fps);this.info.availableQualitiesFps$.next(u)})).add(e.providerOutput.availableAudioStreams$.subscribe(this.info.availableAudioStreams$)).add(e.providerOutput.currentVideoStream$.subscribe(this.info.currentVideoStream$)).add(e.providerOutput.currentAudioStream$.subscribe(this.info.currentAudioStream$)).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.pipe(G()).subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.pipe(le(n=>BI(n))).subscribe(n=>{this.info.currentQuality$.next(n?.quality),this.info.videoBitrate$.next(n?.bitrate)})).add(e.providerOutput.currentVideoSegmentLength$.pipe(G((n,u)=>Math.round(n)===Math.round(u))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe(G((n,u)=>Math.round(n)===Math.round(u))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(G()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(G()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(G()).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(Q(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(_d(n=>n&&this.stop())).subscribe(this.info.isLiveEnded$)).add(e.providerOutput.canPlayLiveTailBuffer$.subscribe(this.info.canPlayLiveTailBuffer$)).add(e.providerOutput.canChangePlaybackSpeed$.subscribe(this.info.canChangePlaybackSpeed$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.liveBufferTime$.subscribe(this.info.liveBufferTime$)).add(e.providerOutput.liveLatency$.subscribe(this.info.liveLatency$)).add(Vt({hasLiveOffsetByPaused:ri(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(Q(n=>n.to),G(),Q(n=>n==="paused")),isLowLatency:e.providerOutput.isLowLatency$}).subscribe(({hasLiveOffsetByPaused:n,isLowLatency:u})=>{if(window.clearTimeout(this.hasLiveOffsetByPausedTimer),n){this.hasLiveOffsetByPausedTimer=window.setTimeout(()=>{this.hasLiveOffsetByPaused.next(!0)},this.getActiveLiveDelay(u));return}this.hasLiveOffsetByPaused.next(!1)})).add(Vt({atLiveEdge:Vt({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Cd({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(Q(({isLive:n,position:u,isLowLatency:o})=>{let l=this.getActiveLiveDelay(o);return n&&Math.abs(u)<l/1e3}),G(),_d(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(Q(({atLiveEdge:n,hasPausedTimeoutCase:u})=>n&&!u)).subscribe(this.info.atLiveEdge$)).add(Vt({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(Q(({isLive:n,position:u,duration:o})=>n&&(Math.abs(o)-Math.abs(u))*1e3<this.tuning.live.activeLiveDelay),G(),_d(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(Q(n=>n.muted),G()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(Q(n=>n.volume),G()).subscribe(this.info.volume$)).add(Cd({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(e.providerOutput.seekedEvent$.subscribe(()=>{this.info.isEnded$.getValue()&&this.tuning.changePlaybackStateToPausedWhenEnded&&this.play()})).add(ri(e.providerOutput.endedEvent$.pipe(VI(!0)),e.providerOutput.seekedEvent$.pipe(VI(!1))).pipe(G()).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(Q(n=>({id:n?`No${n}`:"NoProviders",category:Yo.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.manifestRequested$.pipe(fe()).subscribe(this.events.manifestRequested$)).add(e.providerOutput.firstBytesManifest$.pipe(fe()).subscribe(this.events.firstBytesManifest$)).add(e.providerOutput.manifestReceived$.pipe(fe()).subscribe(this.events.manifestReceived$)).add(e.providerOutput.firstBytesRequested$.pipe(fe()).subscribe(this.events.firstBytesRequested$)).add(e.providerOutput.firstBytesReceived$.pipe(fe()).subscribe(this.events.firstBytesReceived$)).add(e.providerOutput.firstBytesEvent$.pipe(fe(),Q(n=>n??Ko()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(fe(),Q(()=>Ko()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(fe(),Q(()=>Ko()-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 R(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let i=new R(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(le(({to:n})=>n==="playing"),fe()).subscribe(()=>i.next(!1)));let r=0,s=ri(e.providerOutput.isBuffering$,t,i).pipe(Q(()=>{let n=e.providerOutput.isBuffering$.getValue(),u=t.getValue()||i.getValue();return n&&!u}),G());this.subscription.add(s.subscribe(n=>{n?r=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(r),this.info.isStalled$.next(!1))})),this.subscription.add(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 u=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n?.size?.width,height:n?.size?.height},{width:u?.videoWidth,height:u?.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add(ri(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,e.providerOutput.elementVisible$,this.chromecastInitializer.castState$).subscribe(()=>{let n=e.providerOutput.inPiP$.getValue(),u=e.providerOutput.inFullscreen$.getValue(),o=e.providerOutput.element$.getValue(),l=e.providerOutput.elementVisible$.getValue(),p=this.chromecastInitializer.castState$.getValue(),c;p==="CONNECTED"?c="second_screen":o?l?n?c="pip":u?c="fullscreen":c="inline":c="invisible":c="none",this.info.surface$.getValue()!==c&&this.info.surface$.next(c)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(Q(e=>e?.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new _I;this.subscription.add(t),this.subscription.add(e.current$.pipe(G((i,r)=>i.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(le(i=>i.length>0),fe()).subscribe(i=>{this.setStartingVideoTrack(i)}))}))}setStartingVideoTrack(e){let t;this.wasSetStartedQuality=!0;let i=this.explicitInitialQuality??this.info.currentQuality$.getValue();i&&(t=e.find(({quality:r})=>r===i),t||this.setAutoQuality(!0)),t||(t=St(e,{container:this.domContainer.getBoundingClientRect(),panelSize:this.config.panelSize,estimatedThroughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),playbackRate:this.info.currentPlaybackRate$.getValue(),forwardBufferHealth:0,abrLogger:this.abrLogger})),this.desiredState.videoTrack.startTransitionTo(t),this.info.currentQuality$.next(t.quality),this.info.videoBitrate$.next(t.bitrate)}initLogs(){this.subscription.add(ri(this.desiredState.videoTrack.stateChangeStarted$.pipe(Q(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(Q(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(Q(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(Q(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(Q(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(Q(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(Q(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(Q(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(Q(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;Bd(this.providerContainer),Bd(e),xv(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(t=>Ev(t)),this.providerContainer.current$.subscribe(({type:t})=>ma("provider",t)),e.duration$.subscribe(t=>ma("duration",t)),e.availableVideoTracks$.pipe(le(t=>!!t.length),fe()).subscribe(t=>ma("tracks",t)),this.events.fatalError$.subscribe(new ke("fatalError")),this.events.managedError$.subscribe(new ke("managedError")),e.position$.subscribe(new ke("position")),e.currentVideoTrack$.pipe(Q(t=>t?.quality)).subscribe(new ke("quality")),this.info.currentBuffer$.subscribe(new ke("buffer")),e.isBuffering$.subscribe(new ke("isBuffering"))].forEach(t=>this.subscription.add(t)),ma("codecs",D.video.supportedCodecs)}initTracerSubscription(){let e=FI(this.tracer.log.bind(this.tracer)),t=FI(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(G()).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(Vt({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe(le(({currentQuality:i,videoBitrate:r})=>!!i&&!!r),G((i,r)=>i.currentQuality===r.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe(le(i=>i>0),G()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe(le(i=>i>0),G()).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(Vt({currentBuffer:this.info.currentBuffer$.pipe(le(i=>i.end>0),G((i,r)=>i.end===r.end&&i.start===r.start)),position:this.info.position$.pipe(G())}).pipe(Od(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe(G()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe(G()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe(G()).subscribe(e("canChangePlaybackSpeed"))).add(Vt({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(le(({liveTime:i,liveBufferTime:r})=>!!i&&!!r),Od(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(G(),le(i=>i===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(G(),le(i=>i===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe(G()).subscribe(e("muted"))).add(this.info.volume$.pipe(G()).subscribe(e("volume"))).add(this.info.isEnded$.pipe(G(),le(i=>i===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add(Vt({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(le(({throughputEstimation:i,rtt:r})=>!!i&&!!r),Od(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(G(),le(i=>i===!0)).subscribe(e("is3DVideo"))).add(this.info.surface$.subscribe(e("surface"))).add(this.events.ended$.subscribe(e("ended"))).add(this.events.looped$.subscribe(e("looped"))).add(this.events.managedError$.subscribe(t("managedError"))).add(this.events.fatalError$.subscribe(t("fatalError"))).add(this.events.firstBytes$.subscribe(e("firstBytes"))).add(this.events.firstFrame$.subscribe(e("firstFrame"))).add(this.events.canplay$.subscribe(e("canplay")))}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e,t=()=>{e?.release(),e=void 0},i=async()=>{t(),e=await window.navigator.wakeLock.request("screen").catch(r=>{r instanceof DOMException&&r.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:Yo.DOM,message:String(r)})})};this.subscription.add(ri(Vd(document,"visibilitychange"),Vd(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let r=document.visibilityState==="visible",s=this.desiredState.playbackState.getState()==="playing",n=!!e&&!e?.released;r&&s?n||i():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let i=e.find(r=>r.quality===t);this.tracer.log("setVideoTrackIdByQuality",ai({quality:t,availableTracks:ai(e),track:ai(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&&!Ia()}};import{Subscription as qX,Observable as UX,Subject as jX,ValueSubject as HX,VideoQuality as WX}from"@vkontakte/videoplayer-shared/es2024";var QX=`@vkontakte/videoplayer-core@${Ud}`;export{Hs as ChromecastState,tu as HttpConnectionType,UX as Observable,Le as PlaybackState,Jo as Player,Ws as PredefinedQualityLimits,QX as SDK_VERSION,jX as Subject,qX as Subscription,iu as Surface,Ud as VERSION,HX as ValueSubject,xt as VideoFormat,WX as VideoQuality,W$ as areValidLiveRecordSources,D as clientChecker,ca as isMobile};
|
|
171
|
+
`;var di=class{constructor(e,t,i){this.videoInitialized=!1;this.active=!1;this.container=e,this.sourceVideoElement=t,this.params=i,this.canvas=this.createCanvas();let r=this.canvas.getContext("webgl");if(!r)throw new Error("Could not initialize WebGL context");this.gl=r,this.container.appendChild(this.canvas),this.camera=new Go(this.params.fov,this.params.orientation),this.cameraRotationManager=new Yo(this.camera,{rotationSpeed:this.params.rotationSpeed,maxYawAngle:this.params.maxYawAngle,rotationSpeedCorrection:this.params.rotationSpeedCorrection,degreeToPixelCorrection:this.params.degreeToPixelCorrection,speedFadeTime:this.params.speedFadeTime,speedFadeThreshold:this.params.speedFadeThreshold}),this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.textureMappingBuffer=this.createTextureMappingBuffer(),this.updateTextureMappingBuffer(),this.program=this.createProgram(),this.videoTexture=this.createTexture(),this.gl.useProgram(this.program),this.videoElementDataLoadedFn=this.onDataLoadedHandler.bind(this),this.renderFn=this.render.bind(this)}play(){this.active||(this.videoInitialized?this.doPlay():this.sourceVideoElement.readyState>=2?(this.videoInitialized=!0,this.doPlay()):this.sourceVideoElement.addEventListener("loadeddata",this.videoElementDataLoadedFn))}stop(){this.active=!1}startCameraManualRotation(e,t){this.cameraRotationManager.setRotationSpeed(e*this.params.rotationSpeed,t*this.params.rotationSpeed,0),this.cameraRotationManager.startRotation()}stopCameraManualRotation(e=!1){this.cameraRotationManager.stopRotation(e)}turnCamera(e,t){this.cameraRotationManager.turnCamera(e,t)}pointCameraTo(e,t){this.cameraRotationManager.pointCameraTo(e,t)}pixelToDegree(e){return{x:this.params.degreeToPixelCorrection*this.params.fov.x*-e.x/this.viewportWidth,y:this.params.degreeToPixelCorrection*this.params.fov.y*e.y/this.viewportHeight}}getCameraRotation(){return this.camera.orientation}holdCamera(){this.cameraRotationManager.stopRotation(!0)}releaseCamera(){this.cameraRotationManager.onCameraRelease()}destroy(){this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),this.stop(),this.canvas.remove()}setViewportSize(e,t){this.viewportWidth=e,this.viewportHeight=t,this.canvas.width=this.viewportWidth,this.canvas.height=this.viewportHeight,this.gl.viewport(0,0,this.canvas.width,this.canvas.height)}onDataLoadedHandler(){this.videoInitialized=!0,this.doPlay()}doPlay(){this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.active=!0,this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),requestAnimationFrame(this.renderFn)}render(e){this.cameraRotationManager.tick(e),this.updateTexture(),this.updateTextureMappingBuffer();let t=this.gl.getAttribLocation(this.program,"a_vertex"),i=this.gl.getAttribLocation(this.program,"a_texel"),r=this.gl.getUniformLocation(this.program,"u_texture"),a=this.gl.getUniformLocation(this.program,"u_focus");this.gl.enableVertexAttribArray(t),this.gl.enableVertexAttribArray(i),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.vertexBuffer),this.gl.vertexAttribPointer(t,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.vertexAttribPointer(i,2,this.gl.FLOAT,!1,0,0),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.uniform1i(r,0),this.gl.uniform2f(a,-this.camera.orientation.x,-this.camera.orientation.y),this.gl.drawArrays(this.gl.TRIANGLE_FAN,0,4),this.gl.bindTexture(this.gl.TEXTURE_2D,null),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),this.gl.disableVertexAttribArray(t),this.gl.disableVertexAttribArray(i),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){let i=this.gl.createShader(t);if(!i)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(i,e),this.gl.compileShader(i),!this.gl.getShaderParameter(i,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(i));return i}createProgram(){let e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");let t=this.createShader(Cy,this.gl.VERTEX_SHADER),i=this.createShader(Vy,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,i),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){let e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,i=1,r=this.frameHeight/(this.frameWidth/this.viewportWidth);return r>this.viewportHeight?t=this.viewportHeight/r:i=r/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-i,t,-i,t,i,-t,i]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){let e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,i=this.camera.fov.x/360/2,r=this.camera.fov.y/180/2,a=e-i,n=t-r,o=e+i,u=t-r,l=e+i,p=t+r,c=e-i,d=t+r;return[a,n,o,u,l,p,c,d]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){let e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}};import{isNullable as IB,now as da,once as EB,Subscription as wB,ValueSubject as Ed,isNonNullable as xB,safeStorage as wd,filterChanged as kB}from"@vkontakte/videoplayer-shared/es2024";var Ft=(s,e,t)=>t*e+(1-t)*s,Id=(s,e)=>s.reduce((t,i)=>t+i,0)/e,_y=(s,e,t,i)=>{let r=0,a=t,n=Id(s,e),o=e<i?e:i;for(let u=0;u<o;u++)s[a]>n?r++:r--,a=(s.length+a-1)%s.length;return Math.abs(r)===o};var Ko="stalls_manager_metrics",xd="stalls_manager_abr_params",Oy="stalls_manager_default_tuning_abr_params",kd=class{constructor(){this.isSeeked$=new Ed(!1);this.isBuffering$=new Ed(!1);this.maxQualityLimit=void 0;this.currentStallsCount=0;this.sumStallsDuration=0;this.lastStallDuration=0;this.providerStartWatchingTimestamp=0;this.lastUniqueVideoTrackSelectedTimestamp=0;this.predictedThroughputWithoutData=0;this.subscription=new wB;this.severeStallOccurred$=new Ed(!1)}init(e){this.currentStallDuration$=e.currentStallDuration$,this.videoLastDataObtainedTimestamp$=e.videoLastDataObtainedTimestamp$,this.throughput$=e.throughput$,this.rtt$=e.rtt$,this.tuning=e.tuning,this.abrParams=e.abrParams,this.duration=e.duration,this.resetStoredAbrParamsIfNeeded(),this.subscribe(e)}get videoMaxQualityLimit(){return this.maxQualityLimit}get predictedThroughput(){return this.predictedThroughputWithoutData}get abrTuningParams(){let t=(this.tuning.ignoreDynamicAbrForShortVideo?this.tuning.enabled&&this.duration>this.tuning.minTvtToBeCounted:this.tuning.enabled)?this.getStoredData(xd):{};return{...this.abrParams,...t}}set lastVideoTrackSelected(e){this.lastUniqueVideoTrackSelected?.id!==e.id&&(this.lastUniqueVideoTrackSelected=e,this.lastUniqueVideoTrackSelectedTimestamp=da(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe(),this.currentStallDuration$.getValue()!==0&&this.updateStallData();let e=(da()-this.providerStartWatchingTimestamp-this.sumStallsDuration)/1e3,t=this.sumStallsDuration;this.addStallInfoToHistory(e,t),this.updateStoredAbrParams()}resetStoredAbrParamsIfNeeded(){let{bitrateFactorAtEmptyBuffer:e,bitrateFactorAtFullBuffer:t,containerSizeFactor:i}={...this.getStoredData(Oy)},{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:a,containerSizeFactor:n}={...this.abrParams};this.tuning.enabled&&e===r&&t===a&&i===n||(this.removeStoredData(xd),this.setStoredData(Oy,{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:a,containerSizeFactor:n}))}updateStoredAbrParams(){let e=[],t=this.getStoredData(Ko,"[]");if(!this.tuning.enabled||t.length<this.tuning.stallsMetricsHistoryLength)return;let i=t.reduce((a,n)=>a+n.tvt,0);if(this.tuning.useTotalStallsDurationPerTvt){let n=t.reduce((o,u)=>o+u.stallsDuration,0)/i;e.push(this.calculateOptimalAbrParams(n,i))}if(this.tuning.useAverageStallsDurationPerTvt){let a=t.reduce((n,o)=>n+o.stallsDurationPerTvt,0)/t.length;e.push(this.calculateOptimalAbrParams(a,i))}this.tuning.useEmaStallsDurationPerTvt&&e.push(this.calculateOptimalAbrParams(t[t.length-1].stallsDurationPerTvtSmoothed,i));let r={bitrateFactorAtEmptyBuffer:Math.max(...e.map(a=>a.bitrateFactorAtEmptyBuffer)),bitrateFactorAtFullBuffer:Math.max(...e.map(a=>a.bitrateFactorAtFullBuffer)),containerSizeFactor:Math.min(...e.map(a=>a.containerSizeFactor))};this.setStoredData(Ko,[]),this.setStoredData(xd,r)}calculateOptimalAbrParams(e,t){let{targetStallsDurationPerTvt:i,deviationStallsDurationPerTvt:r,criticalStallsDurationPerTvt:a,abrAdjustingSpeed:n,significantTvt:o}=this.tuning,u=n*Math.min(t/o,1),l=this.abrTuningParams;return e<i-r?l={bitrateFactorAtEmptyBuffer:Math.max(l.bitrateFactorAtEmptyBuffer-u,this.abrParams.minBitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.max(l.bitrateFactorAtFullBuffer-u,this.abrParams.minBitrateFactorAtFullBuffer),containerSizeFactor:Math.min(l.containerSizeFactor+u,this.abrParams.maxContainerSizeFactor)}:e>i+r&&(l={bitrateFactorAtEmptyBuffer:Math.min(l.bitrateFactorAtEmptyBuffer+u,this.abrParams.maxBitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.min(l.bitrateFactorAtFullBuffer+u,this.abrParams.maxBitrateFactorAtFullBuffer),containerSizeFactor:Math.max(l.containerSizeFactor-u,this.abrParams.minContainerSizeFactor)}),e>a&&(l={bitrateFactorAtEmptyBuffer:Math.max(l.bitrateFactorAtEmptyBuffer,this.abrParams.bitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.max(l.bitrateFactorAtFullBuffer,this.abrParams.bitrateFactorAtFullBuffer),containerSizeFactor:Math.min(l.containerSizeFactor,this.abrParams.containerSizeFactor)}),l}getStoredData(e,t="{}"){return JSON.parse(wd.get(e)??t)}setStoredData(e,t){wd.set(e,JSON.stringify(t))}removeStoredData(e){wd.remove(e)}addStallInfoToHistory(e,t){if(e<this.tuning.minTvtToBeCounted||e>this.tuning.maxTvtToBeCounted||e*1e3<t)return;let i=this.getStoredData(Ko,"[]"),r=t/e,a=i.length?Ft(i[i.length-1].stallsDurationPerTvtSmoothed,t/e,this.tuning.emaAlpha):r,n={tvt:e,stallsDuration:t,stallsDurationPerTvt:r,stallsDurationPerTvtSmoothed:a};i.push(n),i.length>this.tuning.stallsMetricsHistoryLength&&i.shift(),this.setStoredData(Ko,i)}updateStallData(){this.providerStartWatchingTimestamp&&!this.isSeeked$.getValue()&&(this.sumStallsDuration+=Math.min(this.lastStallDuration,this.tuning.maxPossibleStallDuration),this.currentStallsCount++)}subscribe(e){this.subscription.add(e.isSeeked$.subscribe(this.isSeeked$)),this.subscription.add(e.isBuffering$.subscribe(this.isBuffering$)),this.subscription.add(e.looped$.subscribe(t=>this.currentStallsCount=0)),this.subscription.add(e.playing$.pipe(EB()).subscribe(t=>this.providerStartWatchingTimestamp=da())),this.subscription.add(this.currentStallDuration$.pipe(kB()).subscribe(t=>{let{stallDurationNoDataBeforeQualityDecrease:i,stallCountBeforeQualityDecrease:r,resetQualityRestrictionTimeout:a,ignoreStallsOnSeek:n}=this.tuning;if(IB(this.lastUniqueVideoTrackSelected)||n&&this.isSeeked$.getValue())return;let o=this.rtt$.getValue(),u=this.throughput$.getValue(),l=this.videoLastDataObtainedTimestamp$.getValue(),p=da(),c=r&&this.currentStallsCount>=r,d=i&&p-this.lastUniqueVideoTrackSelectedTimestamp>=i+o&&p-l>=i+o&&t>=i;(c||d)&&(this.severeStallOccurred$.next(!0),window.clearTimeout(this.qualityRestrictionTimer),this.maxQualityLimit=this.lastUniqueVideoTrackSelected.quality,xB(this.lastUniqueVideoTrackSelected.bitrate)&&u>this.lastUniqueVideoTrackSelected.bitrate&&(this.predictedThroughputWithoutData=this.lastUniqueVideoTrackSelected.bitrate)),!t&&da()-this.providerStartWatchingTimestamp>this.lastStallDuration&&(this.updateStallData(),this.severeStallOccurred$.next(!1),window.clearTimeout(this.qualityRestrictionTimer),this.qualityRestrictionTimer=window.setTimeout(()=>{this.maxQualityLimit=void 0,this.predictedThroughputWithoutData=0},a)),this.lastStallDuration=t}))}},qr=kd;import{combine as PB,map as AB,observeElementSize as RB,Subscription as $B,ValueSubject as Pd,noop as MB}from"@vkontakte/videoplayer-shared/es2024";var Xo=class{constructor(){this.subscription=new $B;this.pipSize$=new Pd(void 0);this.videoSize$=new Pd(void 0);this.elementSize$=new Pd(void 0);this.pictureInPictureWindowRemoveEventListener=MB}connect({observableVideo:e,video:t}){let i=r=>{let a=r.target;this.pipSize$.next({width:a.width,height:a.height})};this.subscription.add(RB(t).subscribe(this.videoSize$)).add(e.enterPip$.subscribe(({pictureInPictureWindow:r})=>{this.pipSize$.next({width:r.width,height:r.height}),r.addEventListener("resize",i),this.pictureInPictureWindowRemoveEventListener=()=>{r.removeEventListener("resize",i)}})).add(e.leavePip$.subscribe(()=>{this.pictureInPictureWindowRemoveEventListener()})).add(PB({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(AB(({videoSize:r,inPip:a,pipSize:n})=>a?n:r)).subscribe(this.elementSize$))}getValue(){return this.elementSize$.getValue()}subscribe(e,t){return this.elementSize$.subscribe(e,t)}getObservable(){return this.elementSize$}destroy(){this.pictureInPictureWindowRemoveEventListener(),this.subscription.unsubscribe()}};import{filter as Ny,map as LB,once as Fy}from"@vkontakte/videoplayer-shared/es2024";var pi=({subscription:s,desiredState:e,videoElement$:t,observableVideo:i})=>{if(!$.browser.isSafari)return;let r=0,a=!1;s.add(e.volume.stateChangeStarted$.pipe(LB(()=>{let n=e.volume.getTransition(),o=t.getValue();return!o||!n?!1:!n.to.muted&&o.muted}),Ny(n=>!!n),Fy()).subscribe(()=>{r=performance.now(),a=!0})),s.add(i.playbackRateState$.pipe(Ny(()=>a),Fy()).subscribe(()=>{let n=t.getValue(),o=e.playbackRate.getState();n&&o!==n.playbackRate&&performance.now()-r<1e3&&(n.playbackRate=o)}))};var pa=class{constructor(e){this.subscription=new NB;this.videoState=new O("stopped");this.observableVideo=null;this.droppedFramesManager=new li;this.stallsManager=new qr;this.elementSizeManager=new Xo;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new yt;this.audioTrackSwitchHistory=new yt;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(r.state==="requested"&&i?.to!=="paused"&&e!=="stopped"&&t!=="stopped"&&this.seek(r.position,r.forcePrecise),t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.currentNativeBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),P(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"),P(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="ready"&&P(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"&&P(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&P(this.params.desiredState.playbackState,"paused");return;default:return BB(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new di(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 We(e.source.url),this.params=e,this.video=Pe(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(ce(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=this.getPlayer(),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params;OB(this.observableVideo)&&(this.observableVideo=$e(this.video),this.subscription.add(()=>this.observableVideo?.destroy()));let i=this.constructor.name,r=n=>{e.error$.next({id:i,category:Uy.WTF,message:`${i} internal logic error`,thrown:n})},a=(n,o)=>this.subscription.add(n.subscribe(o,r));return{output:e,desiredState:t,observableVideo:this.observableVideo,genericErrorListener:r,connect:a}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:a}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(Ad(c=>!!c.length),jy()).subscribe(c=>{this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:c})}));let n=this.params.desiredState.seekState.stateChangeEnded$.pipe($d(c=>c.to.state!=="none"),Rd());this.stallsManager.init({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$,videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,tuning:this.params.tuning.stallsManager,abrParams:this.params.tuning.autoTrackSelection,isBuffering$:i.isBuffering$,looped$:i.looped$,playing$:i.playing$,duration:this.video.duration}),a(i.ended$,e.endedEvent$),a(i.looped$,e.loopedEvent$),a(i.error$,e.error$),a(i.isBuffering$,e.isBuffering$),a(i.currentBuffer$,e.currentNativeBuffer$),a(i.playing$,e.firstFrameEvent$),a(i.canplay$,e.canplay$),a(i.inPiP$,e.inPiP$),a(i.inFullscreen$,e.inFullscreen$),a(i.loadedMetadata$,e.loadedMetadataEvent$),a(this.player.error$,e.error$),a(this.player.fetcherRecoverableError$,e.fetcherRecoverableError$),a(this.player.fetcherError$,e.fetcherError$),a(this.player.lastConnectionType$,e.httpConnectionType$),a(this.player.lastConnectionReused$,e.httpConnectionReused$),a(this.player.isLive$,e.isLive$),a(this.player.currentBuffer$,e.currentBuffer$),a(this.player.lastRequestFirstBytes$.pipe(Ad(qy),jy()),e.firstBytesEvent$),a(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),a(this.videoState.stateChangeEnded$.pipe($d(c=>c.to)),this.params.output.playbackState$),this.subscription.add(i.looped$.subscribe(()=>this.player.warmUpMediaSourceIfNeeded(),r)),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(ot(this.video,t.isLooped,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),pi({subscription:this.subscription,desiredState:t,videoElement$:this.params.output.element$,observableVideo:i}),this.subscription.add(Re(this.video,t.volume,i.volumeState$,r)),this.subscription.add(Qe(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),a(Ye(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),P(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),P(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(i.ended$.subscribe(()=>{this.videoState.setState("paused"),P(t.playbackState,"paused")})),this.subscription.add(this.player.manifestRequested.subscribe(this.params.output.manifestRequested$)).add(this.player.manifestReceived.subscribe(this.params.output.manifestReceived$)).add(this.player.firstBytesRequested.subscribe(this.params.output.firstBytesRequested$)).add(this.player.firstBytesReceived.subscribe(this.params.output.firstBytesReceived$)),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 d=this.player.getStreams(),h=this.player.getCodecs();if(CB(d,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let m=[];for(let S of d.audio){m.push(Td(S));let g=[];for(let v of S.representations){let T=Dy(v);g.push(T),this.audioTracksMap.set(T,{stream:S,representation:v})}this.audioStreamsMap.set(S,g)}this.params.output.availableAudioStreams$.next(m)}let f=[];for(let m of d.video){f.push(Wo(m));let S=[];for(let g of m.representations){let v=Ly({...g,streamId:m.id});v&&(S.push(v),this.videoTracksMap.set(v,{stream:m,representation:g}))}this.videoStreamsMap.set(m,S)}this.params.output.availableVideoStreams$.next(f);for(let m of d.text)for(let S of m.representations){let g=By(m,S);this.textTracksMap.set(g,{stream:m,representation:S})}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),h?.video&&this.params.output.availableVideoCodecs$.next(h.video),h?.audio&&this.params.output.availableAudioCodecs$.next(h.audio),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else c==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r));let o=Jo(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$,_B(this.video,"progress")).pipe(Ad(()=>this.videoTracksMap.size>0)),{abrThrottle:u}=this.params.tuning.dash;u&&(o=o.pipe(FB(u))),this.subscription.add(o.subscribe(async()=>{let c=this.player.state$.getState(),d=this.player.state$.getTransition(),h=t.autoVideoTrackSwitching.getState();if(c!=="manifest_ready"&&c!=="running"||d)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let f=this.selectVideoAudioRepresentations();if(!f)return;let[m,S]=f,g=[...this.videoTracksMap.keys()].find(T=>this.videoTracksMap.get(T)?.representation.id===m.id);qy(g)&&(this.stallsManager.lastVideoTrackSelected=g);let v=this.params.desiredState.autoVideoTrackLimits.getTransition();v&&this.params.output.autoVideoTrackLimits$.next(v.to),c==="manifest_ready"?await this.player.initRepresentations(m.id,S?.id,this.params.sourceHls):(await this.player.switchRepresentation("video",m.id,h),S&&await this.player.switchRepresentation("audio",S.id,h))},r)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:c})=>{this.scene3D&&c&&this.scene3D.pointCameraTo(c.x,c.y)})),this.subscription.add(this.elementSizeManager.subscribe(c=>{this.scene3D&&c&&this.scene3D.setViewportSize(c.width,c.height)})),this.subscription.add(this.player.currentAudioRepresentation$.pipe(Rd()).subscribe(c=>{let d=[...this.audioTracksMap.entries()].find(([,{representation:S}])=>S.id===c);if(!d){e.currentAudioStream$.next(void 0);return}let[h,{stream:f}]=d,m=this.params.desiredState.audioStream.getTransition();m&&m.to&&m.to.id===f.id&&this.params.desiredState.audioStream.setState(m.to),e.currentAudioStream$.next(Td(f))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(c=>{if(c?.is3dVideo&&this.params.tuning.spherical?.enabled)try{this.init3DScene(c),e.is3DVideo$.next(!0)}catch(d){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${d}`})}else this.destroy3DScene(),this.params.tuning.spherical?.enabled&&e.is3DVideo$.next(!1)},r)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,r)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,r)),this.textTracksManager.connect(this.video,t,e);let l=t.playbackState.stateChangeStarted$.pipe($d(({to:c})=>c==="ready"),Rd());this.subscription.add(Jo(l,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,Md(["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(Jo(l,this.player.state$.stateChangeEnded$,Md(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let p=Jo(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Md(["init"])).pipe(VB(0));this.subscription.add(p.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?Qi:zi,t=this.params.tuning.useNewAutoSelectVideoTrack?Fr:Nr,i=this.params.tuning.useNewAutoSelectVideoTrack?ut:Or,{desiredState:r,output:a}=this.params,n=r.autoVideoTrackSwitching.getState(),o=r.videoTrack.getState()?.id,u=[...this.videoTracksMap.keys()].find(({id:w})=>w===o),l=a.currentVideoTrack$.getValue(),p=r.videoStream.getState()??(u&&this.videoTracksMap.get(u)?.stream)??this.videoStreamsMap.size===1?this.videoStreamsMap.keys().next().value:void 0;if(!p)return;let c=[...this.videoStreamsMap.keys()].find(({id:w})=>w===p.id),d=c&&this.videoStreamsMap.get(c);if(!d)return;let h=this.player.bufferLength$.getValue(),f;this.player.isActiveLive$.getValue()?f=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?f=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:f=n?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let m=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,S=Math.min(h/Math.min(f,m||1/0),1),g=r.audioStream.getState()??(this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0),v=[...this.audioStreamsMap.keys()].find(({id:w})=>w===g?.id)??this.audioStreamsMap.keys().next().value,T=0;if(v){if(u&&!n){let w=e(u,d,this.audioStreamsMap.get(v)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);T=Math.max(T,w?.bitrate??-1/0)}if(l){let w=e(l,d,this.audioStreamsMap.get(v)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);T=Math.max(T,w?.bitrate??-1/0)}}let y=u;(n||!y)&&(y=i(d,{container:this.elementSizeManager.getValue(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.stallsManager.abrTuningParams,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:T,forwardBufferHealth:S,current:l,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,stallsVideoMaxQualityLimit:this.stallsManager.videoMaxQualityLimit,stallsPredictedThroughput:this.stallsManager.predictedThroughput,abrLogger:this.params.dependencies.abrLogger}));let x=v&&t(y,d,this.audioStreamsMap.get(v)??[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.stallsManager.abrTuningParams,forwardBufferHealth:S,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),A=this.videoTracksMap.get(y)?.representation,R=x&&this.audioTracksMap.get(x)?.representation;if(A&&R)return[A,R];if(A&&!R&&this.audioTracksMap.size===0)return[A,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Me(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Uy.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),Ae(this.video),this.tracer.end()}};var lp=D(Wi(),1);var{NativeAbortSignal:DW,NativeAbortController:BW}=function(s){return{NativeAbortSignal:s.AbortSignal,NativeAbortController:s.AbortController}}(typeof self<"u"?self:global);function lT(s){let e;try{e=new Event("abort")}catch{typeof document<"u"?document.createEvent?(e=document.createEvent("Event"),e.initEvent("abort",!1,!1)):(e=document.createEventObject(),e.type="abort"):e={type:"abort",bubbles:!1,cancelable:!1}}return e.reason=s,e}function cT(s){if(s===void 0)if(typeof document>"u")s=new Error("This operation was aborted"),s.name="AbortError";else try{s=new DOMException("signal is aborted without reason"),Object.defineProperty(s,"name",{value:"AbortError"})}catch{s=new Error("This operation was aborted"),s.name="AbortError"}return s}var Zo=class{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,i){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:i})}removeEventListener(e,t){if(!(e in this.listeners))return;let i=this.listeners[e];for(let r=0,a=i.length;r<a;r++)if(i[r].callback===t){i.splice(r,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;let i=this.listeners[e.type].slice();for(let r=0,a=i.length;r<a;r++){let n=i[r];try{n.callback.call(this,e)}catch(o){Promise.resolve().then(()=>{throw o})}n.options&&n.options.once&&this.removeEventListener(e.type,n.callback)}return!e.defaultPrevented}},jr=class extends Zo{constructor(){super(),this.listeners||Zo.call(this),Object.defineProperty(this,"aborted",{value:!1,writable:!0,configurable:!0}),Object.defineProperty(this,"onabort",{value:null,writable:!0,configurable:!0}),Object.defineProperty(this,"reason",{value:void 0,writable:!0,configurable:!0})}toString(){return"[object AbortSignal]"}dispatchEvent(e){e.type==="abort"&&(this.aborted=!0,typeof this.onabort=="function"&&this.onabort.call(this,e)),super.dispatchEvent(e)}throwIfAborted(){let{aborted:e,reason:t="Aborted"}=this;if(e)throw t}static timeout(e){let t=new Gi;return setTimeout(()=>t.abort(new DOMException(`This signal is timeout in ${e}ms`,"TimeoutError")),e),t.signal}static any(e){let t=new Gi;function i(){t.abort(this.reason),r()}function r(){for(let a of e)a.removeEventListener("abort",i)}for(let a of e)if(a.aborted){t.abort(a.reason);break}else a.addEventListener("abort",i);return t.signal}},Gi=class{constructor(){Object.defineProperty(this,"signal",{value:new jr,writable:!0,configurable:!0})}abort(e){let t=cT(e),i=lT(t);this.signal.reason=t,this.signal.dispatchEvent(i)}toString(){return"[object AbortController]"}};typeof Symbol<"u"&&Symbol.toStringTag&&(Gi.prototype[Symbol.toStringTag]="AbortController",jr.prototype[Symbol.toStringTag]="AbortSignal");function eu(s){return s.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof s.Request=="function"&&!s.Request.prototype.hasOwnProperty("signal")||!s.AbortController}function Dd(s){typeof s=="function"&&(s={fetch:s});let{fetch:e,Request:t=e.Request,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r=!1}=s;if(!eu({fetch:e,Request:t,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r}))return{fetch:e,Request:a};let a=t;(a&&!a.prototype.hasOwnProperty("signal")||r)&&(a=function(l,p){let c;p&&p.signal&&(c=p.signal,delete p.signal);let d=new t(l,p);return c&&Object.defineProperty(d,"signal",{writable:!1,enumerable:!1,configurable:!0,value:c}),d},a.prototype=t.prototype);let n=e;return{fetch:(u,l)=>{let p=a&&a.prototype.isPrototypeOf(u)?u.signal:l?l.signal:void 0;if(p){let c;try{c=new DOMException("Aborted","AbortError")}catch{c=new Error("Aborted"),c.name="AbortError"}if(p.aborted)return Promise.reject(c);let d=new Promise((h,f)=>{p.addEventListener("abort",()=>f(c),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([d,n(u,l)])}return n(u,l)},Request:a}}var lC=()=>"fetch"in window,ha=lC()&&eu({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),dT=ha?Dd({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,Ke=ha?dT.fetch:window.fetch,HW=ha?dT.Request:window.Request,j=ha?Gi:window.AbortController,zW=ha?jr:window.AbortSignal;var tE=D(ke(),1);var LT=D(MT(),1);import{ErrorCategory as ma}from"@vkontakte/videoplayer-shared/es2024";var Hr=s=>{if(!s)return{id:"EmptyResponse",category:ma.PARSER,message:"Empty response"};if(s.length<=2&&s.match(/^\d+$/))return{id:`UVError#${s}`,category:ma.NETWORK,message:`UV Error ${s}`};let e=(0,LT.default)(s).substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:ma.NETWORK,message:"Received unexpected HTML, possibly a ISP block"};if(e.startsWith("<?xml"))return new DOMParser().parseFromString(s,"text/xml").querySelector("parsererror")?{id:"InvalidXML",category:ma.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:ma.PARSER,message:"Response is valid XML, but parser failed"}};import{abortable as JI,assertNonNullable as Ht,ErrorCategory as Xi,filter as ap,filterChanged as v0,flattenObject as cu,fromEvent as Ji,getTraceSubscriptionMethod as y0,interval as T0,isNonNullable as bi,isNullable as Ga,map as np,merge as Ya,now as I0,Subject as gi,Subscription as ZI,SubscriptionRemovable as E0,ValueSubject as Z}from"@vkontakte/videoplayer-shared/es2024";var Tt=s=>{let e=new URL(s);return e.searchParams.set("quic","1"),e.toString()};var zr=s=>{let e=s.get("X-Delivery-Type"),t=s.get("X-Reused"),i=e===null?"http1":e??void 0,r=t===null?void 0:{1:!0,0:!1}[t]??void 0;return{type:i,reused:r}};import{abortable as ba,assertNever as DT,ErrorCategory as ga,flattenObject as Wr,fromEvent as BT,merge as kC,now as Sa,Subject as Gr,Subscription as PC,ValueSubject as Od}from"@vkontakte/videoplayer-shared/es2024";var Le=s=>s instanceof DOMException&&(s.name==="AbortError"||s.code===20);var Qr=s=>{let e=new URL(s);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var iu=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:a=!1}){this.manifestRequested=new Gr;this.manifestReceived=new Gr;this.firstBytesRequested=new Gr;this.firstBytesReceived=new Gr;this.lastConnectionType$=new Od(void 0);this.lastConnectionReused$=new Od(void 0);this.lastRequestFirstBytes$=new Od(void 0);this.recoverableError$=new Gr;this.error$=new Gr;this.abortAllController=new j;this.subscription=new PC;this.fetchManifest=ba(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=Tt(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=Qr(i)),this.manifestRequested.next();let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(tu);return r?(t.log("success",Wr({url:i,message:"Request successfully executed"})),t.end(),this.manifestReceived.next(),this.onHeadersReceived(r.headers),r.text()):(t.error("error",Wr({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:r,priority:a="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1,bufferOptimisation:l=!1}={}){let p=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 E=new URL(p,location.href);E.searchParams.append("bytes",`${i.from}-${i.to}`),p=E.toString();break}default:DT(t)}this.requestQuic&&(p=Tt(p));let h=this.abortAllController.signal,f;if(n){let E=new j;if(f=kC(BT(this.abortAllController.signal,"abort"),BT(n,"abort")).subscribe(()=>{try{E.abort()}catch(I){tu(I)}}),this.subscription.add(f),this.abortAllController.signal.aborted||n.aborted)try{E.abort()}catch(I){tu(I)}h=E.signal}let m=0,S=Sa();d.log("startRequest",Wr({url:p,priority:a,rangeMethod:t,range:i,isLowLatency:u,requestStartedAt:S})),this.firstBytesRequested.next();let g=yield this.doFetch(p,{priority:a,headers:c,signal:h}),v=Sa();if(!g)return d.error("error",{message:"No response in request"}),d.end(),f?.unsubscribe(),null;if(this.throughputEstimator?.addRawRtt(v-S),!g.ok||!g.body){f?.unsubscribe();let E=`Fetch error ${g.status}: ${g.statusText}`;return d.error("error",{message:E}),d.end(),Promise.reject(new Error(`Fetch error ${g.status}: ${g.statusText}`))}if(this.onHeadersReceived(g.headers),!r&&!o){f?.unsubscribe();let E=Sa(),I={requestStartedAt:S,requestEndedAt:E,duration:E-S};return d.log("endRequest",Wr(I)),d.end(),g.arrayBuffer()}let T=g.body;if(o){let E;[T,E]=g.body.tee(),this.throughputEstimator?.trackStream(E,u)}let y=T.getReader(),x,A=parseInt(g.headers.get("content-length")??"",10);Number.isFinite(A)&&(x=A),!x&&i&&(x=i.to-i.from+1);let R=x?new Uint8Array(x):new Uint8Array(0),w=!1,B=E=>{f?.unsubscribe(),w=!0,tu(E)},k=ba(h,async function*({done:E,value:I}){if(m===0&&(this.lastRequestFirstBytes$.next(Sa()-S),this.firstBytesReceived.next()),h.aborted){f?.unsubscribe();return}if(!E&&I){if(l&&x)R.set(I,m),m+=I.byteLength;else{let N=new Uint8Array(R.length+I.length);N.set(R),N.set(I,R.length),R=N,m+=I.byteLength}r?.(new DataView(R.buffer),m),yield y?.read().then(k,B)}}.bind(this));yield y?.read().then(k,B),f?.unsubscribe();let F=Sa(),C={failed:w,requestStartedAt:S,requestEndedAt:F,duration:F-S};return w?(d.error("endRequest",Wr(C)),d.end(),null):(d.log("endRequest",Wr(C)),d.end(),R.buffer)}.bind(this));this.fetchByteRangeRepresentation=ba(this.abortAllController.signal,async function*(e,t,i){if(e.type!=="byteRange")return null;let{from:r,to:a}=e.initRange,n=r,o=a,u=!1,l,p;e.indexRange&&(l=e.indexRange.from,p=e.indexRange.to,u=a+1===l,u&&(n=Math.min(l,r),o=Math.max(p,a))),n=Math.min(n,0);let c=yield this.fetch(e.url,{range:{from:n,to:o},priority:i,measureThroughput:!1});if(!c)return null;let d=new DataView(c,r-n,a-n+1);if(!t.validateData(d))throw new Error("Invalid media file");let h=t.parseInit(d),f=e.indexRange??t.getIndexRange(h);if(!f)throw new ReferenceError("No way to load representation index");let m;if(u)m=new DataView(c,f.from-n,f.to-f.from+1);else{let g=yield this.fetch(e.url,{range:f,priority:i,measureThroughput:!1});if(!g)return null;m=new DataView(g)}let S=t.parseSegments(m,h,f).map(g=>({networkStatus:"none",bufferStatus:"none",status:"none",time:g.time,byte:g.byte}));return{initMetadata:h,initDataView:new DataView(c),segments:S}}.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(),r=yield this.fetch(i,{priority:t,measureThroughput:!1});if(!r)return null;let a=e.segments.map(n=>({...n,networkStatus:"none",bufferStatus:"none",status:"none",size:void 0}));return{initMetadata:null,initDataView:new DataView(r),segments:a}}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=r,this.tracer=i.createComponentTracer("Fetcher"),this.useEnableSubtitlesParam=a}onHeadersReceived(e){let{type:t,reused:i}=zr(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,t,i="auto"){let{type:r}=e;switch(r){case"byteRange":return this.fetchByteRangeRepresentation(e,t,i)??null;case"template":return this.fetchTemplateRepresentation(e,i)??null;default:DT(r)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}async doFetch(e,t){let i=await Ke(e,t);if(i.ok)return i;let r=await i.text(),a=parseInt(r);if(!isNaN(a))switch(a){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:ga.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:ga.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:ga.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:ga.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${a})`,category:ga.FATAL})}}},tu=s=>{if(!Le(s))throw s};var Qd=D(rI(),1),xI=D(ni(),1),kI=D(vI(),1),PI=D(Ge(),1),Wd=D(Di(),1);var yI=D(ke(),1),zd=s=>{let e=s.split("."),[t,...i]=e;if(!t)return!1;switch(t){case"av01":{let[r,a,n]=i;return!!(n&&parseInt(n,10)>8)}case"vp09":{let[r,a,n]=i;return!!(r&&parseInt(r,10)>=2&&n&&parseInt(n,10)>8)}case"avc1":{let r=i[0];if(!r||r.length!==6)return!1;let[a,n]=r.toUpperCase(),o=a+n;return(0,yI.default)(["6E","7A","F4"],o)}}return!1};import{isNonNullable as PV,isNullable as EI}from"@vkontakte/videoplayer-shared/es2024";var TI=s=>{if(s.includes("/")){let e=s.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(s)};var II=s=>{try{let e=kV(),t=s.match(e),{groups:i}=t??{};if(i){let r={};if(i.extensions){let o=i.extensions.toLowerCase().match(/(?:[0-9a-wy-z](?:-[a-z0-9]{2,8})+)/g);Array.from(o||[]).forEach(u=>{r[u[0]]=u.slice(2)})}let a=i.variants?.split(/-/).filter(o=>o!==""),n={extlang:i.extlang,langtag:i.langtag,language:i.language,privateuse:i.privateuse||i.privateuse2,region:i.region,script:i.script,extensions:r,variants:a};return Object.keys(n).forEach(o=>{let u=n[o];(typeof u>"u"||u==="")&&delete n[o]}),n}return null}catch{return null}};function kV(){let s="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",p=`^(?:(?<langtag>${`
|
|
172
|
+
(?<language>${`(?:[a-z]{2,3}(?:-${s})?|[a-z]{4}|[a-z]{5,8})`})
|
|
173
|
+
(-(?<script>[a-z]{4}))?
|
|
174
|
+
(-(?<region>(?:[a-z]{2}|[0-9]{3})))?
|
|
175
|
+
(?<variants>(?:-(?:[a-z0-9]{5,8}|[0-9][a-z0-9]{3}))*)
|
|
176
|
+
(?<extensions>(?:-[0-9a-wy-z](?:-[a-z0-9]{2,8})+)*)
|
|
177
|
+
(?:-(?<privateuse>(?:${e})))?
|
|
178
|
+
`})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(p,"i")}var wI=s=>{if(!s?.startsWith("P"))return;let e=(n,o)=>{let u=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(u)?0:u)*o},i=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(s),r=i?.[1]==="-"?-1:1,a={days:e(i?.[5],r),hours:e(i?.[6],r),minutes:e(i?.[7],r),seconds:e(i?.[8],r)};return a.days*24*60*60*1e3+a.hours*60*60*1e3+a.minutes*60*1e3+a.seconds*1e3},tt=(s,e)=>{let t=s;t=(0,Qd.default)(t,"$$","$");let i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[r,a]of(0,xI.default)(i)){let n=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=(0,Qd.default)(t,n,(o,u)=>EI(a)?o:EI(u)?a:(0,kI.default)(a,parseInt(u,10),"0"))}return t},Xr=(s,e)=>{let i=new DOMParser().parseFromString(s,"application/xml"),r={video:[],audio:[],text:[]},a=i.children[0],n=Array.from(a.querySelectorAll("MPD > BaseURL").values()).map(B=>B.textContent?.trim()??""),o=(0,PI.default)(n,0)??"",u=a.getAttribute("type")==="dynamic",l=a.getAttribute("availabilityStartTime"),p=a.getAttribute("publishTime"),c=a.getElementsByTagName("vk:Attrs")[0],d=c?.getElementsByTagName("vk:XLatestSegmentPublishTime")[0].textContent,h=c?.getElementsByTagName("vk:XStreamIsLive")[0].textContent,f=c?.getElementsByTagName("vk:XStreamIsUnpublished")[0].textContent,m=c?.getElementsByTagName("vk:XPlaybackDuration")[0].textContent,S;u&&(S={availabilityStartTime:l?new Date(l).getTime():0,publishTime:p?new Date(p).getTime():0,latestSegmentPublishTime:d?new Date(d).getTime():0,streamIsAlive:h==="yes",streamIsUnpublished:f==="yes"});let g,v=a.getAttribute("mediaPresentationDuration"),T=[...a.getElementsByTagName("Period")],y=T.reduce((B,k)=>({...B,[k.id]:k.children}),{}),x=T.reduce((B,k)=>({...B,[k.id]:k.getAttribute("duration")}),{});v?g=wI(v):(0,Wd.default)(x).filter(B=>B).length&&!u?g=(0,Wd.default)(x).reduce((B,k)=>B+(wI(k)??0),0):m&&(g=parseInt(m,10));let A=0,R=a.getAttribute("profiles")?.split(",")??[];for(let B of T.map(k=>k.id))for(let k of y[B]){let F=k.getAttribute("id")??"id"+(A++).toString(10),C=k.getAttribute("mimeType")??"",E=k.getAttribute("codecs")??"",I=k.getAttribute("contentType")??C?.split("/")[0],N=k.getAttribute("profiles")?.split(",")??[],L=II(k.getAttribute("lang")??"")??{},H=k.querySelector("Label")?.textContent?.trim()??void 0,X=k.querySelectorAll("Representation"),re=k.querySelector("SegmentTemplate"),le=k.querySelector("Role")?.getAttribute("value")??void 0,Te=I,Ie={id:F,language:L.language,isDefault:le==="main",label:H,codecs:E,hdr:Te==="video"&&zd(E),mime:C,representations:[]};for(let z of X){let q=z.getAttribute("lang")??void 0,Ee=H??k.getAttribute("label")??z.getAttribute("label")??void 0,Be=z.querySelector("BaseURL")?.textContent?.trim()??"",me=new URL(Be||o,e).toString(),at=z.getAttribute("mimeType")??C,Jt=z.getAttribute("codecs")??E??"",dt;if(I==="text"){let Xe=z.getAttribute("id")||"",Zt=L.privateuse?.includes("x-auto")||Xe.includes("_auto"),pt=z.querySelector("SegmentTemplate");if(pt){let ys={representationId:z.getAttribute("id")??void 0,bandwidth:z.getAttribute("bandwidth")??void 0},Ln=parseInt(z.getAttribute("bandwidth")??"",10)/1e3,Dn=parseInt(pt.getAttribute("startNumber")??"",10)??1,lr=parseInt(pt.getAttribute("timescale")??"",10),Ku=pt.querySelectorAll("SegmentTimeline S")??[],cr=pt.getAttribute("media");if(!cr)continue;let Bn=[],Cn=0,Vn="",dr=0,Ts=Dn,Ce=0;for(let ht of Ku){let xi=parseInt(ht.getAttribute("d")??"",10),nt=parseInt(ht.getAttribute("r")??"",10)||0,ei=parseInt(ht.getAttribute("t")??"",10);Ce=Number.isFinite(ei)?ei:Ce;let ki=xi/lr*1e3,pr=Ce/lr*1e3;for(let wt=0;wt<nt+1;wt++){let ti=tt(cr,{...ys,segmentNumber:Ts.toString(10),segmentTime:(Ce+wt*xi).toString(10)}),hr=(pr??0)+wt*ki,Es=hr+ki;Ts++,Bn.push({time:{from:hr,to:Es},url:ti})}Ce+=(nt+1)*xi,Cn+=(nt+1)*ki}dr=Ce/lr*1e3,Vn=tt(cr,{...ys,segmentNumber:Ts.toString(10),segmentTime:Ce.toString(10)});let Is={time:{from:dr,to:1/0},url:Vn},Bt={type:"template",baseUrl:me,segmentTemplateUrl:cr,initUrl:"",totalSegmentsDurationMs:Cn,segments:Bn,nextSegmentBeyondManifest:Is,timescale:lr};dt={id:Xe,kind:"text",segmentReference:Bt,profiles:[],duration:g,bitrate:Ln,mime:"",codecs:"",width:0,height:0,isAuto:Zt}}else dt={id:Xe,isAuto:Zt,kind:"text",url:me}}else{let Xe=z.getAttribute("contentType")??at?.split("/")[0]??I,Zt=k.getAttribute("profiles")?.split(",")??[],pt=parseInt(z.getAttribute("width")??"",10),ys=parseInt(z.getAttribute("height")??"",10),Ln=parseInt(z.getAttribute("bandwidth")??"",10)/1e3,Dn=z.getAttribute("frameRate")??"",lr=z.getAttribute("quality")??void 0,Ku=Dn?TI(Dn):void 0,cr=z.getAttribute("id")??"id"+(A++).toString(10),Bn=Xe==="video"?`${ys}p`:Xe==="audio"?`${Ln}Kbps`:Jt,Cn=`${cr}@${Bn}`,Vn=[...R,...N,...Zt],dr,Ts=z.querySelector("SegmentBase"),Ce=z.querySelector("SegmentTemplate")??re;if(Ts){let Bt=z.querySelector("SegmentBase Initialization")?.getAttribute("range")??"",[ht,xi]=Bt.split("-").map(ti=>parseInt(ti,10)),nt={from:ht,to:xi},ei=z.querySelector("SegmentBase")?.getAttribute("indexRange"),[ki,pr]=ei?ei.split("-").map(ti=>parseInt(ti,10)):[],wt=ei?{from:ki,to:pr}:void 0;dr={type:"byteRange",url:me,initRange:nt,indexRange:wt}}else if(Ce){let Bt={representationId:z.getAttribute("id")??void 0,bandwidth:z.getAttribute("bandwidth")??void 0},ht=parseInt(Ce.getAttribute("timescale")??"",10),xi=Ce.getAttribute("initialization")??"",nt=Ce.getAttribute("media"),ei=parseInt(Ce.getAttribute("startNumber")??"",10)??1,ki=tt(xi,Bt);if(!nt)throw new ReferenceError("No media attribute in SegmentTemplate");let pr=Ce.querySelectorAll("SegmentTimeline S")??[],wt=[],ti=0,hr="",Es=0;if(pr.length){let _n=ei,ft=0;for(let fr of pr){let xt=parseInt(fr.getAttribute("d")??"",10),Pi=parseInt(fr.getAttribute("r")??"",10)||0,On=parseInt(fr.getAttribute("t")??"",10);ft=Number.isFinite(On)?On:ft;let Xu=xt/ht*1e3,Ow=ft/ht*1e3;for(let Nn=0;Nn<Pi+1;Nn++){let Nw=tt(nt,{...Bt,segmentNumber:_n.toString(10),segmentTime:(ft+Nn*xt).toString(10)}),lh=(Ow??0)+Nn*Xu,Fw=lh+Xu;_n++,wt.push({time:{from:lh,to:Fw},url:Nw})}ft+=(Pi+1)*xt,ti+=(Pi+1)*Xu}Es=ft/ht*1e3,hr=tt(nt,{...Bt,segmentNumber:_n.toString(10),segmentTime:ft.toString(10)})}else if(PV(g)){let ft=parseInt(Ce.getAttribute("duration")??"",10)/ht*1e3,fr=Math.ceil(g/ft),xt=0;for(let Pi=1;Pi<fr;Pi++){let On=tt(nt,{...Bt,segmentNumber:Pi.toString(10),segmentTime:xt.toString(10)});wt.push({time:{from:xt,to:xt+ft},url:On}),xt+=ft}Es=xt,hr=tt(nt,{...Bt,segmentNumber:fr.toString(10),segmentTime:xt.toString(10)})}let _w={time:{from:Es,to:1/0},url:hr};dr={type:"template",baseUrl:me,segmentTemplateUrl:nt,initUrl:ki,totalSegmentsDurationMs:ti,segments:wt,nextSegmentBeyondManifest:_w,timescale:ht}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Xe||!at)continue;let Is={video:"video",audio:"audio",text:"text"}[Xe];if(!Is)continue;Te||=Is,dt={id:Cn,kind:Is,segmentReference:dr,profiles:Vn,duration:g,bitrate:Ln,mime:at,codecs:Jt,width:pt,height:ys,fps:Ku,quality:lr}}Ie.language||=q,Ie.label||=Ee,Ie.mime||=at,Ie.codecs||=Jt,Ie.hdr||=Te==="video"&&zd(Jt),Ie.representations.push(dt)}if(Te){let z=r[Te].find(q=>q.id===Ie.id);if(z&&Ie.representations.every(q=>q.segmentReference.type==="template"))for(let q of z.representations){let Ee=Ie.representations.find(at=>at.id===q.id);if(!Ee)continue;let Be=Ee.segmentReference,me=q.segmentReference;me.segments.push(...Be.segments),me.nextSegmentBeyondManifest=Be.nextSegmentBeyondManifest}else r[Te].push(Ie)}}return{duration:g,streams:r,baseUrls:n,live:S}};var au=D(Ge(),1),Gd=D(ke(),1);import{assertNever as nu}from"@vkontakte/videoplayer-shared/es2024";var su=s=>{let{webmDecodingInfo:e}=$.video,t="DASH_WEBM",i="DASH_WEBM_AV1";switch(s){case"vp9":return[t,i];case"av1":return[i,t];case"none":return[];case"smooth":return e?e[i].smooth?[i,t]:e[t].smooth?[t,i]:[i,t]:[t,i];case"power_efficient":return e?e[i].powerEfficient?[i,t]:e[t].powerEfficient?[t,i]:[i,t]:[t,i];default:nu(s)}},AI=({webmCodec:s,androidPreferredFormat:e,iosPreferredFormat:t,preferMultiStream:i})=>{let r=[...i?["DASH_STREAMS"]:[],...su(s),"DASH_SEP","DASH_ONDEMAND",...i?[]:["DASH_STREAMS"]],a=[...i?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...i?[]:["DASH_STREAMS"]];if($.device.isAndroid)switch(e){case"mpeg":return["MPEG",...r,"HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...r,"MPEG"];case"dash":return[...r,"HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return[...a,"MPEG",...su(s),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...su(s),"MPEG",...a,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...su(s),...a,"HLS","HLS_ONDEMAND"];default:nu(e)}if($.video.nativeHlsSupported)switch(t){case"hls":return[...r,"HLS","HLS_FMP4","HLS_ONDEMAND","MPEG"];case"hls_fmp4":return[...r,"HLS_FMP4","HLS","HLS_ONDEMAND","MPEG"];default:nu(t)}return[...r,"HLS","HLS_ONDEMAND","MPEG"]},RI=({androidPreferredFormat:s,preferCMAF:e,preferWebRTC:t})=>{let i=e?["DASH_LIVE_CMAF","DASH_LIVE"]:["DASH_LIVE","DASH_LIVE_CMAF"],r=e?["HLS_LIVE_CMAF","HLS_LIVE"]:["HLS_LIVE","HLS_LIVE_CMAF"],a=[...i,...r],n=[...r,...i],o,u=$.device.isMac&&$.browser.isSafari;if($.device.isAndroid)switch(s){case"dash":case"dash_any_mpeg":case"dash_any_webm":case"dash_sep":{o=a;break}case"hls":case"mpeg":{o=n;break}default:nu(s)}else $.video.nativeHlsSupported&&!u&&!$.browser.isChromiumBased?o=n:u?o=e?["DASH_LIVE_CMAF","HLS_LIVE_CMAF","HLS_LIVE","DASH_LIVE"]:["HLS_LIVE","DASH_LIVE","DASH_LIVE_CMAF","HLS_LIVE_CMAF"]:o=a;return t?["WEB_RTC_LIVE",...o]:[...o,"WEB_RTC_LIVE"]},Yd=s=>s?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],Jr=s=>{if(s.size===0)return;if(s.size===1){let t=s.values().next();return(0,au.default)(t.value.split("."),0)}for(let t of s){let i=(0,au.default)(t.split("."),0);if(i==="opus"||i==="vp09"||i==="av01")return i}let e=s.values().next();return(0,au.default)(e.value.split("."),0)},Zr=s=>{let e=s.map(i=>hi(i)),{codecs:t}=$.video;return MV().filter(i=>{if((0,Gd.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})},es=s=>{let e=s.map(i=>hi(i)),{codecs:t}=$.video;return LV().filter(i=>{if((0,Gd.default)(e,i))switch(i){case"opus":return t.opus;case"mp4a":return t.aac;default:return!1}else return!1})},hi=s=>s.split(".")[0].replace("0",""),MV=()=>["av1","vp9","hev1","avc1"],LV=()=>["opus","mp4a"];var qI=D(Ge(),1);var DV=(s,e={})=>{let i=e.timeout||1,r=performance.now();return window.setTimeout(()=>{s({get didTimeout(){return e.timeout?!1:performance.now()-r-1>i},timeRemaining(){return Math.max(0,1+(performance.now()-r))}})},1)},BV=s=>window.clearTimeout(s),$I=s=>typeof s=="function"&&s?.toString().endsWith("{ [native code] }"),MI=!$I(window.requestIdleCallback)||!$I(window.cancelIdleCallback),Mt=MI?DV:window.requestIdleCallback,qe=MI?BV:window.cancelIdleCallback;import{abortable as tp,assertNonNullable as Lt,ErrorCategory as t0,fromEvent as i0,getExponentialDelay as r0,isHigher as s0,isNonNullable as oe,isNullable as ve,once as a0,Subject as n0,Subscription as o0,ValueSubject as za}from"@vkontakte/videoplayer-shared/es2024";var LI=D(Ge(),1);var ou=s=>s.valid,W=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let i=this.readUint32();this.type=this.readString(4),i===1&&(this.cursor+=8);let r=e.byteOffset+this.cursor,a;i===0?(this.size=void 0,this.valid=!1,a=void 0):i===1?(this.size=void 0,this.valid=!1,a=void 0):i>e.byteLength?(this.size=i,this.valid=!1,a=Math.min(i-this.cursor,e.byteLength-this.cursor)):(this.size=i,this.valid=!0,a=i-this.cursor),this.content=new DataView(e.buffer,r,a)}get id(){return this.type}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t="ascii"){let r=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,r}readUint8(){let e=this.source.getUint8(this.cursor);return this.cursor+=1,e}readUint16(){let e=this.source.getUint16(this.cursor);return this.cursor+=2,e}readUint32(){let e=this.source.getUint32(this.cursor);return this.cursor+=4,e}readUint64(){let e=this.source.getBigInt64(this.cursor);return this.cursor+=8,e}};var ts=class extends W{};import{assertNever as CV}from"@vkontakte/videoplayer-shared/es2024";var va=class extends W{constructor(e,t){if(super(e,t),!this.valid)return;let i=this.readString(16),r=new DataView(this.content.buffer,this.content.byteOffset+16,this.content.byteLength-16);this.userData=this.parseData(i,r)}parseData(e,t){switch(e){case"ondemandlivejson":{let i=new TextDecoder("ascii").decode(t),r=JSON.parse(i);return{received:r["t-in"],prepared:r["t-out"]}}default:CV(e)}}};var ya=class extends W{constructor(e,t){if(super(e,t),!this.valid)return;this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let i=new DataView(this.content.buffer,this.content.byteOffset+8,this.content.byteLength-8);for(let r=0;r<i.byteLength;r+=4){let a=this.readString(4);this.compatibleBrands.push(a)}}};var Ta=class extends W{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var J=class extends W{constructor(e,t){if(super(e,t),!this.valid)return;let i=this.readUint32();this.version=i>>>24,this.flags=i&16777215,this.content=new DataView(this.content.buffer,this.content.byteOffset+4,this.content.byteLength-4)}};var Ia=class extends J{constructor(e,t){super(e,t),this.valid&&(this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.timescale=this.readUint32(),this.duration=this.readUint32(),this.rate=this.readUint32(),this.volume=this.readUint16())}};var Ea=class extends W{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var wa=class extends W{constructor(e,t){super(e,t),this.data=this.content}};var Yi=class extends J{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e,t){if(super(e,t),!!this.valid){this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let i=0;i<this.referenceCount;i++){let r=this.readUint32(),a=r>>>31,n=r<<1>>>1,o=this.readUint32();r=this.readUint32();let u=r>>>28,l=r<<3>>>3;this.segments.push({referenceType:a,referencedSize:n,subsegmentDuration:o,SAPType:u,SAPDeltaTime:l})}}}};var xa=class extends W{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ka=class extends W{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Pa=class extends J{constructor(e,t){if(super(e,t),!this.valid)return;switch(this.readUint8()){case 0:this.stereoMode=0;break;case 1:this.stereoMode=1;break;case 2:this.stereoMode=2;break;case 3:this.stereoMode=3;break;case 4:this.stereoMode=4;break}this.cursor+=1}};var Aa=class extends J{constructor(e,t){super(e,t),this.valid&&(this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32())}};var Ra=class extends J{constructor(e,t){super(e,t),this.valid&&(this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32())}};var $a=class extends W{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ma=class extends J{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 La=class extends W{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Da=class extends W{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ba=class extends J{constructor(e,t){super(e,t),this.valid&&(this.sequenceNumber=this.readUint32())}};var Ca=class extends W{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Va=class extends J{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 _a=class extends J{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 Oa=class extends J{constructor(t,i){super(t,i);this.sampleDuration=[];this.sampleSize=[];this.sampleFlags=[];this.sampleCompositionTimeOffset=[];this.optionalFields=0;this.sampleCount=this.readUint32(),this.flags&1&&(this.dataOffset=this.readUint32()),this.flags&4&&(this.firstSampleFlags=this.readUint32());for(let r=0;r<this.sampleCount;r++)this.flags&256&&this.sampleDuration.push(this.readUint32()),this.flags&512&&this.sampleSize.push(this.readUint32()),this.flags&1024&&this.sampleFlags.push(this.readUint32()),this.flags&2048&&this.sampleCompositionTimeOffset.push(this.readUint32())}};var Na=class extends W{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Fa=class extends J{constructor(e,t){super(e,t),this.valid&&(this.entryCount=this.readUint32(),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+4,this.content.byteLength-4)))}};var Ua=class extends W{constructor(e,t){super(e,t),this.valid&&(this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+78,this.content.byteLength-78)))}};var _V={ftyp:ya,moov:Ta,mvhd:Ia,moof:Ea,mdat:wa,sidx:Yi,trak:xa,mdia:$a,mfhd:Ba,tkhd:Ma,traf:Ca,tfhd:Va,tfdt:_a,trun:Oa,minf:La,sv3d:ka,st3d:Pa,prhd:Aa,proj:Da,equi:Ra,uuid:va,stbl:Na,stsd:Fa,avc1:Ua,unknown:ts},qt=class s{constructor(e={}){this.options={offset:0,...e}}parse(e){let t=[],i=this.options.offset;for(;i<e.byteLength;){let a=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+i+4,4)),n;try{n=this.createBox(a,new DataView(e.buffer,e.byteOffset+i,e.byteLength-i))}catch(o){if(!(o instanceof RangeError))throw o}if(!n||!ou(n))break;t.push(n),i+=n.size}return t}createBox(e,t){let i=_V[e];return i?new i(t,new s):new ts(t,new s)}};var fi=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{ou(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 NV=new TextDecoder("ascii"),FV=s=>NV.decode(new DataView(s.buffer,s.byteOffset+4,4))==="ftyp",UV=s=>{let e=new Yi(s,new qt),t=e.earliestPresentationTime/e.timescale*1e3,i=s.byteOffset+s.byteLength+e.firstOffset;return e.segments.map(a=>{if(a.referenceType!==0)throw new Error("Unsupported multilevel sidx");let n=a.subsegmentDuration/e.timescale*1e3,o={status:"none",time:{from:t,to:t+n},byte:{from:i,to:i+a.referencedSize-1}};return t+=n,i+=a.referencedSize,o})},qV=(s,e)=>{let i=new qt().parse(s),r=new fi(i),a=r.findAll("moof"),n=e?r.findAll("uuid"):r.findAll("mdat");if(!(n.length&&a.length))return null;let o=a[0],u=n[n.length-1],l=o.source.byteOffset,c=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(s.buffer,l,c)},jV=s=>{let t=new qt().parse(s),i=new fi(t),r={},a=i.findAll("uuid"),n=(0,LI.default)(a,-1);return n?{serverDataReceivedTimestamp:n.userData.received,serverDataPreparedTime:n.userData.received}:r},HV=s=>{let t=new qt().parse(s);return new fi(t).find("sidx")?.timescale},zV=(s,e)=>{let i=new qt().parse(s),a=new fi(i).findAll("traf"),n=a[a.length-1].children.find(c=>c.type==="tfhd"),o=a[a.length-1].children.find(c=>c.type==="tfdt"),u=a[a.length-1].children.find(c=>c.type==="trun"),l=0;return u.sampleDuration.length?l=u.sampleDuration.reduce((c,d)=>c+d,0):l=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+l)/e*1e3},QV=s=>{let e={is3dVideo:!1,stereoMode:0,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}},i=new qt().parse(s),r=new fi(i);if(r.find("sv3d")){e.is3dVideo=!0;let n=r.find("st3d");n&&(e.stereoMode=n.stereoMode);let o=r.find("prhd");o&&(e.projectionData.pose.yaw=o.poseYawDegrees,e.projectionData.pose.pitch=o.posePitchDegrees,e.projectionData.pose.roll=o.poseRollDegrees);let u=r.find("equi");u&&(e.projectionData.bounds.top=u.projectionBoundsTop,e.projectionData.bounds.right=u.projectionBoundsRight,e.projectionData.bounds.bottom=u.projectionBoundsBottom,e.projectionData.bounds.left=u.projectionBoundsLeft)}return e},DI={validateData:FV,parseInit:QV,getIndexRange:()=>{},parseSegments:UV,parseFeedableSegmentChunk:qV,getChunkEndTime:zV,getServerLatencyTimestamps:jV,getTimescaleFromIndex:HV};var ja=D(ke(),1);import{assertNonNullable as Kd,isNonNullable as _I,isNullable as GV}from"@vkontakte/videoplayer-shared/es2024";import{assertNever as WV}from"@vkontakte/videoplayer-shared/es2024";var BI={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"}},CI=s=>{let e=s.getUint8(0),t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);let i=qa(s,t),r=i in BI,a=r?BI[i].type:"binary",n=s.getUint8(t),o=0;n&128?o=1:n&64?o=2:n&32?o=3:n&16?o=4:n&8?o=5:n&4?o=6:n&2?o=7:n&1&&(o=8);let u=new DataView(s.buffer,s.byteOffset+t+1,o-1),l=n&255>>o,p=qa(u),c=l*2**((o-1)*8)+p,d=t+o,h;return d+c>s.byteLength?h=new DataView(s.buffer,s.byteOffset+d):h=new DataView(s.buffer,s.byteOffset+d,c),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:a,tagHeaderSize:d,tagSize:d+c,value:h,valueSize:c}},qa=(s,e=s.byteLength)=>{switch(e){case 1:return s.getUint8(0);case 2:return s.getUint16(0);case 3:return s.getUint8(0)*2**16+s.getUint16(1);case 4:return s.getUint32(0);case 5:return s.getUint8(0)*2**32+s.getUint32(1);case 6:return s.getUint16(0)*2**32+s.getUint32(2);case 7:{let t=s.getUint8(0)*281474976710656+s.getUint16(1)*4294967296+s.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},It=(s,e)=>{switch(e){case"int":return s.getInt8(0);case"uint":return qa(s);case"float":return s.byteLength===4?s.getFloat32(0):s.getFloat64(0);case"string":return new TextDecoder("ascii").decode(s);case"utf8":return new TextDecoder("utf-8").decode(s);case"date":return new Date(Date.UTC(2001,0)+s.getInt8(0)).getTime();case"master":return s;case"binary":return s;default:WV(e)}},Ki=(s,e)=>{let t=0;for(;t<s.byteLength;){let i=new DataView(s.buffer,s.byteOffset+t),r=CI(i);if(!e(r))return;r.type==="master"&&Ki(r.value,e),t=r.value.byteOffset-s.byteOffset+r.valueSize}},VI=s=>{if(s.getUint32(0)!==440786851)return!1;let e,t,i,r=CI(s);return Ki(r.value,({tag:a,type:n,value:o})=>(a===17143?e=It(o,n):a===17026?t=It(o,n):a===17029&&(i=It(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)};var OI=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],YV=[231,22612,22743,167,171,163,160,175],KV=s=>{let e,t,i,r,a=!1,n=!1,o=!1,u,l,p=!1,c=0;return Ki(s,({tag:d,type:h,value:f,valueSize:m})=>{if(d===21419){let S=It(f,h);l=qa(S)}else d!==21420&&(l=void 0);return d===408125543?(e=f.byteOffset,t=f.byteOffset+m):d===357149030?a=!0:d===290298740?n=!0:d===2807729?i=It(f,h):d===17545?r=It(f,h):d===21420&&l===475249515?u=It(f,h):d===374648427?Ki(f,({tag:S,type:g,value:v})=>S===30321?(p=It(v,g)===1,!1):!0):a&&n&&(0,ja.default)(OI,d)&&(o=!0),!o}),Kd(e,"Failed to parse webm Segment start"),Kd(t,"Failed to parse webm Segment end"),Kd(r,"Failed to parse webm Segment duration"),i=i??1e6,{segmentStart:Math.round(e/1e9*i*1e3),segmentEnd:Math.round(t/1e9*i*1e3),timeScale:i,segmentDuration:Math.round(r/1e9*i*1e3),cuesSeekPosition:u,is3dVideo:p,stereoMode:c,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},XV=s=>{if(GV(s.cuesSeekPosition))return;let e=s.segmentStart+s.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},JV=(s,e)=>{let t=!1,i=!1,r=o=>_I(o.time)&&_I(o.position),a=[],n;return Ki(s,({tag:o,type:u,value:l})=>{switch(o){case 475249515:t=!0;break;case 187:n&&r(n)&&a.push(n),n={};break;case 179:n&&(n.time=It(l,u));break;case 183:break;case 241:n&&(n.position=It(l,u));break;default:t&&(0,ja.default)(OI,o)&&(i=!0)}return!(t&&i)}),n&&r(n)&&a.push(n),a.map((o,u)=>{let{time:l,position:p}=o,c=a[u+1];return{status:"none",time:{from:l,to:c?c.time:e.segmentDuration},byte:{from:e.segmentStart+p,to:c?e.segmentStart+c.position-1:e.segmentEnd-1}}})},ZV=s=>{let e=0,t=!1;try{Ki(s,i=>i.tag===524531317?i.tagSize<=s.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):(0,ja.default)(YV,i.tag)?(e+i.tagSize<=s.byteLength&&(e+=i.tagSize,t||=(0,ja.default)([163,160,175],i.tag)),!0):!1)}catch{}return e>0&&e<=s.byteLength&&t?new DataView(s.buffer,s.byteOffset,e):null},NI={validateData:VI,parseInit:KV,getIndexRange:XV,parseSegments:JV,parseFeedableSegmentChunk:ZV};var lt=s=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(s);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return NI;case"mp4":return DI}}throw new ReferenceError(`Unsupported mime type ${s}`)};var Xd=D(Ge(),1);import{videoSizeToQuality as e0}from"@vkontakte/videoplayer-shared/es2024";var mi=({id:s,width:e,height:t,bitrate:i,fps:r,quality:a,streamId:n})=>{let o=(a?$t(a):void 0)??e0({width:e,height:t});return o&&{id:s,quality:o,bitrate:i,size:{width:e,height:t},fps:r,streamId:n}},Ha=({id:s,bitrate:e})=>({id:s,bitrate:e}),FI=({language:s,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:s,label:e}),UI=({language:s,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:s,label:e}),Jd=({id:s,language:e,label:t,codecs:i,isDefault:r})=>({id:s,language:e,label:t,codec:(0,Xd.default)(i.split("."),0),isDefault:r}),Zd=({id:s,language:e,label:t,hdr:i,codecs:r})=>({id:s,language:e,hdr:i,label:t,codec:(0,Xd.default)(r.split("."),0)}),ep=s=>"url"in s,it=s=>s.type==="template";var is=class{constructor(e,t,i,{fetcher:r,tuning:a,getCurrentPosition:n,manifest:o}){this.error$=new n0;this.playingRepresentation$=new za(void 0);this.playingRepresentationInit$=new za(void 0);this.currentSegmentLength$=new za(0);this.onLastSegment$=new za(!1);this.fullyBuffered$=new za(!1);this.initData=new Map;this.initDataPromises=new Map;this.idleCallbacks=new Map;this.parsedInitData=new Map;this.segments=new Map;this.bufferPlaybackQueue=[];this.downloadingBufferItems=[];this.preloadOnly=!1;this.failedDownloads=0;this.lastDataObtainedTimestampMs=0;this.loadByteRangeSegmentsTimeoutId=0;this.currentVirtualBufferSize=0;this.baseUrls=[];this.baseUrlsIndex=0;this.maintainPlaybackBufferMutex=!1;this.maintainNativeBufferMutex=!1;this.bufferClearingMutex=!1;this.abortNativeBufferMutex=!1;this.switchMutex=!1;this.destroyAbortController=new j;this.downloadAbortController=new j;this.subscription=new o0;this.startWith=tp(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);Lt(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.containerParser=lt(t.mime),this.nativeBufferManager.init(t.mime,t.codecs),yield this.loadInits(t);let i=this.initData.get(t.id),r=this.segments.get(t.id),a=this.parsedInitData.get(t.id);Lt(i,"No init buffer for starting representation"),Lt(r,"No segments for starting representation"),await this.nativeBufferManager.addInitSegment(i),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(a)}.bind(this));this.switchTo=tp(this.destroyAbortController.signal,async function*(e,t=!0){if(ve(this.downloadingRepresentationId)||e===this.downloadingRepresentationId||e===this.switchingRepresentationId)return;this.switchMutex=!0,this.switchingRepresentationId=e;let i=this.representations.get(this.downloadingRepresentationId),r=this.representations.get(e);Lt(r,`No such representation ${e}`),Lt(i,`No such representation ${this.downloadingRepresentationId}`),yield this.loadInitIfNeeded(r,"high");let a=this.initData.get(r.id),n=this.segments.get(r.id);Lt(a,"No init buffer for switching representation"),Lt(n,"No segments for switching representation");let o=this.getCurrentPosition()??0,u=c=>c.segment.networkStatus!=="downloaded"||c.segment.time.to-o>this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment,l=c=>{let d=this.representations.get(c.representationId);return Lt(d,"No itemRepresentation for previous track before switch"),c.segment.networkStatus!=="downloaded"||this.forceSwitchCondition(d,r)},p=c=>t?u(c)&&l(c):u(c);this.bufferPlaybackQueue.filter(p).forEach(c=>c.segment.bufferStatus="none"),this.bufferPlaybackQueue=this.bufferPlaybackQueue.filter(c=>!p(c)),this.downloadingRepresentationId=e,this.switchingRepresentationId=null,this.bufferPlaybackQueue.length?(this.abortDownload(),yield this.maintain()):yield this.seek(o),this.switchMutex=!1}.bind(this));this.waitExponentialDownloadDelay=tp(this.downloadAbortController.signal,async function*(){let e=r0(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(t=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(t,e),this.subscription.add(i0(window,"online").pipe(a0()).subscribe(()=>{t(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}))})}.bind(this));this.kind=e,this.nativeBufferManager=t,this.fetcher=r,this.tuning=a,this.getCurrentPosition=n,this.forwardBufferTarget=a.dash.forwardBufferTargetAuto,this.baseUrls=o?.baseUrls??[],this.representations=new Map(i.map(u=>[u.id,u]))}async seek(e){await this.abort(),await this.clearBuffer(),await this.maintain(e)}async maintain(e=this.getCurrentPosition()){ve(e)||(await this.maintainPlaybackBuffer(e),await this.maintainNativeBuffer(),this.actualizeLastSegmentInfo(e))}getForwardPlaybackBufferDuration(e=this.getCurrentPosition()){let t=this.getPlaybackBufferState();return oe(t)&&oe(e)?t.to-e:0}getPlaybackBufferState(){if(!this.bufferPlaybackQueue.length)return null;let t=this.bufferPlaybackQueue[0].segment.time.from,i=this.bufferPlaybackQueue[this.bufferPlaybackQueue.length-1].segment.time.to;return{from:t,to:i}}async abort(){this.abortDownload(),await this.abortNativeBuffer()}findSegmentStartTime(e){let t=this.downloadingRepresentationId??this.playingRepresentationId??"";return this.segments.get(t)?.find(a=>a.time.from<=e&&a.time.to>=e)?.time.from}getRepresentationInitialTime(){return ve(this.playingRepresentationId)?0:(this.segments.get(this.playingRepresentationId)?.[0].time.from??0)/1e3}calculateDurationFromSegments(){if(ve(this.playingRepresentationId))return 0;let e=this.segments.get(this.playingRepresentationId);return(e?(0,qI.default)(e,-1)?.time.to:0)||0}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){if(this.initData.clear(),this.initDataPromises.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),this.downloadAbortController.abort(),this.destroyAbortController.abort(),this.subscription.unsubscribe(),qe)for(let e of this.idleCallbacks.values())qe(e);this.idleCallbacks.clear(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}forceSwitchCondition(e,t){let i=!0;if(this.kind==="video"){let r=mi(e),a=mi(t);i=oe(r)&&oe(a)&&s0(a.quality,r.quality)}else if(this.kind==="audio"){let r=Ha(e),a=Ha(t);i=oe(r?.bitrate)&&oe(a?.bitrate)&&a.bitrate>r.bitrate}return i}async clearBuffer(){this.bufferClearingMutex=!0,await this.nativeBufferManager.clear(this.destroyAbortController.signal),this.bufferPlaybackQueue.forEach(e=>e.segment.bufferStatus="none"),this.bufferPlaybackQueue=[],this.bufferClearingMutex=!1}abortDownload(){this.downloadAbortController.abort(),this.downloadAbortController=new j,this.abortDownloadingItems(),this.maintainPlaybackBufferMutex=!1}abortDownloadingItems(){for(let e of this.downloadingBufferItems)e.segment.networkStatus==="downloading"&&(e.segment.networkStatus="none",e.segment.size=0,e.segment.loadedBytes=0,e.segment.feedingBytes=0,e.segment.fedBytes=0,e.segment.data=null);this.downloadingBufferItems=[]}async abortNativeBuffer(){this.abortNativeBufferMutex=!0;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0,i=await this.nativeBufferManager.abortBuffer(t);return this.abortNativeBufferMutex=!1,i}async loadInits(e){await this.loadInit(e,"high",!0);for(let[t,i]of this.representations)this.idleCallbacks.set(i.id,Mt(async r=>await this.loadInitIfNeeded(i,"low",!1)))}async loadInitIfNeeded(e,t="auto",i=!1){let r=this.initDataPromises.get(e.id),a;this.initData.has(e.id)&&this.segments.has(e.id)?a=Promise.resolve():oe(r)?a=r:a=this.loadInit(e,t,i),await a}async loadInit(e,t="auto",i=!1){try{let r=this.tuning.dash.useFetchPriorityHints?t:"auto",a=this.fetcher.fetchRepresentation(e.segmentReference,this.containerParser,r);this.initDataPromises.set(e.id,a);let{initMetadata:n,initDataView:o,segments:u}=await a??{};if(this.initDataPromises.delete(e.id),ve(o)||ve(u))return;n&&this.parsedInitData.set(e.id,n);let l=o.buffer.slice(o.byteOffset,o.byteOffset+o.byteLength);this.initData.set(e.id,l),this.segments.set(e.id,u),this.failedDownloads=0}catch(r){i&&this.error$.next({id:"LoadInits",category:t0.WTF,message:"loadInit threw",thrown:r})}}async maintainNativeBuffer(){let e=this.getCurrentPosition();if(ve(e)||this.maintainNativeBufferMutex||this.abortNativeBufferMutex||this.bufferClearingMutex||this.switchMutex||this.preloadOnly)return;this.maintainNativeBufferMutex=!0;let t=this.bufferPlaybackQueue.find(o=>this.withinInterval(e,o.segment.time)),i=this.bufferPlaybackQueue.find(o=>o.segment.bufferStatus!=="fed"),r=this.initData.get(i?.representationId??""),a=this.bufferPlaybackQueue[0],n=this.downloadAbortController.signal;oe(r)&&oe(i)&&oe(t)&&this.playingRepresentationId!==i.representationId&&this.withinAppendInterval(e,i.segment.time)&&(i===t||t.segment.bufferStatus==="fed")&&(await this.abortNativeBuffer(),await this.nativeBufferManager.addInitSegment(r,this.downloadAbortController.signal),this.playingRepresentationId=i.representationId,this.playingRepresentation$.next(this.playingRepresentationId)),oe(i)&&this.withinAppendInterval(e,i.segment.time)&&(i.segment.loadedBytes===i.segment.size&&i.segment.bufferStatus==="none"?await this.appendSegmentFully(i,n):await this.appendSegmentPartially(i,n)),oe(a)&&this.withinRemoveInterval(e,a.segment.time)&&await this.removeSegment(a,n),this.pruneVirtualBuffer(e),this.maintainNativeBufferMutex=!1}async maintainPlaybackBuffer(e){Lt(this.downloadingRepresentationId);let t=this.segments.get(this.downloadingRepresentationId),i=this.representations.get(this.downloadingRepresentationId);if(ve(t)||ve(i)||this.maintainPlaybackBufferMutex||this.abortNativeBufferMutex||this.bufferClearingMutex||this.switchMutex)return;this.maintainPlaybackBufferMutex=!0;let r=t.find(n=>e>=n.time.from&&e<n.time.to);oe(r)&&isFinite(r.time.from)&&isFinite(r.time.to)&&this.currentSegmentLength$.next(r?.time.to-r.time.from),this.downloadingBufferItems.length||(this.downloadingBufferItems=this.selectDownloadingItems(e,t)),await this.processCachedItems();let a=this.selectItemsToLoad();await this.loadItems(a,i),this.maintainPlaybackBufferMutex=!1}actualizeLastSegmentInfo(e){let t=this.segments.get(this.downloadingRepresentationId??"");if(ve(t)||t.length===0)return;let i=t[t?.length-1];ve(i)||(this.fullyBuffered$.next(i.time.to-e-this.getForwardPlaybackBufferDuration(e)<this.tuning.dash.bufferTolerance),this.onLastSegment$.next(e-i.time.from>0))}selectDownloadingItems(e,t){Lt(this.downloadingRepresentationId);let i=this.getPlaybackBufferState(),r,a;oe(i)&&this.withinInterval(e,i)?(a=this.forwardBufferTarget-this.getForwardPlaybackBufferDuration(e),r=this.bufferPlaybackQueue[this.bufferPlaybackQueue.length-1].segmentIndex+1):(a=this.forwardBufferTarget,r=t.findIndex(o=>this.withinInterval(e,o.time))),r=r===-1?0:r;let n=[];for(;r<t.length&&a>0;){n.push({representationId:this.downloadingRepresentationId,segmentIndex:r,segment:t[r]});let{from:o,to:u}=t[r].time;a-=u-o,r++}return n}async processCachedItems(){let e=[...this.downloadingBufferItems];for(;e.length&&e[0].segment.networkStatus==="downloaded";)await this.onDownloadItem(e[0]),e.shift()}withinInterval(e,{from:t,to:i},r=this.tuning.dash.bufferTolerance){return oe(e)?e+r>=t&&e<i:!1}withinAppendInterval(e,{from:t,to:i}){let{actionTimeShiftFromSegment:r}=this.tuning.dash;return oe(e)?e+r>=t&&e+r<i||this.withinInterval(e,{from:t,to:i}):!1}withinRemoveInterval(e,{to:t}){let{actionTimeShiftFromSegment:i}=this.tuning.dash;return oe(e)?e-i>t:!1}async appendSegmentFully(e,t){if(ve(e.segment.data))return;e.segment.feedingBytes=e.segment.size,await this.nativeBufferManager.append(e.segment.data,t)&&(e.segment.fedBytes=e.segment.size,this.onItemFullyAppended(e))}async appendSegmentPartially(e,t){if(ve(e.segment.data)||ve(e.segment.loadedBytes)||ve(e.segment.feedingBytes)||ve(e.segment.fedBytes)||ve(e.segment.size))return;let i=e.segment.data,r=new DataView(i.buffer,i.byteOffset+e.segment.feedingBytes,i.byteLength-e.segment.feedingBytes),a=e.segment.loadedBytes!==e.segment.size?this.parseFeedableSegmentChunk(r):r;a?.byteLength&&(e.segment.bufferStatus="partially_fed",e.segment.feedingBytes+=a.byteLength,await this.nativeBufferManager.append(a,t)&&(e.segment.fedBytes+=a.byteLength,e.segment.fedBytes===e.segment.size&&this.onItemFullyAppended(e)))}parseFeedableSegmentChunk(e){return this.containerParser.parseFeedableSegmentChunk(e,!1)}onItemFullyDownloaded(e){e.segment.networkStatus="downloaded"}onItemFullyAppended(e){e.segment.bufferStatus="fed"}async removeSegment(e,t){let{from:i,to:r}=e.segment.time,a=(r-i)/4;await this.nativeBufferManager.remove(0,r-a,t)&&(e.segment.fedBytes=0,e.segment.feedingBytes=0,e.segment.bufferStatus="none",this.bufferPlaybackQueue.shift())}async onDownloadItem(e){if(!this.downloadingBufferItems.find(i=>i===e))return;let t=this.getCurrentPosition();return this.downloadingBufferItems=this.downloadingBufferItems.filter(i=>i!==e||i.segment.networkStatus!=="downloaded"),(this.preloadOnly||oe(t)&&!this.withinRemoveInterval(t,e.segment.time))&&!this.bufferPlaybackQueue.find(i=>i===e)&&this.bufferPlaybackQueue.push(e),this.maintainNativeBuffer()}pruneVirtualBuffer(e){let{maxVirtualBufferSize:t,virtualBufferPruneSize:i,bufferPruningSafeZone:r}=this.tuning.dash;if(this.currentVirtualBufferSize<t)return;let a=this.currentVirtualBufferSize-t+i;for(let n of this.segments.values())for(let o of n)oe(o.size)&&a>0&&o.time.to<=e-r&&o.bufferStatus==="none"&&o.networkStatus==="downloaded"&&(o.data=null,o.networkStatus="none",this.currentVirtualBufferSize-=o.size,a-=o.size);for(let n of this.segments.values())for(let o of[...n].reverse())oe(o.size)&&a>0&&o.time.from>=e+r&&o.bufferStatus==="none"&&o.networkStatus==="downloaded"&&!this.bufferPlaybackQueue.find(u=>u.segment===o)&&!this.downloadingBufferItems.find(u=>u.segment===o)&&(o.data=null,o.networkStatus="none",this.currentVirtualBufferSize-=o.size,a-=o.size)}updateRepresentationsBaseUrlIfNeeded(){if(!this.tuning.dash.enableBaseUrlSupport||!this.baseUrls.length||this.failedDownloads<=this.tuning.dash.maxSegmentRetryCount)return;this.baseUrlsIndex=(this.baseUrlsIndex+1)%this.baseUrls.length;let e=this.baseUrls[this.baseUrlsIndex];for(let t of this.representations.values())this.updateRepresentationBaseUrl(t,e)}};import{ErrorCategory as u0,isNonNullable as l0,isNullable as jI,now as HI}from"@vkontakte/videoplayer-shared/es2024";var uu=class extends is{constructor(e,t,i,r){super(e,t,i,r)}async loadItems(e,t,i="auto"){let{signal:r}=this.downloadAbortController;if(r.aborted||!e.length)return;let{url:a,...n}=this.prepareFetchParams(e,t);if(this.failedDownloads&&await this.waitExponentialDownloadDelay(),!r.aborted)try{await this.fetcher.fetch(a,{...n,priority:i}),this.lastDataObtainedTimestampMs=HI(),this.failedDownloads=0}catch(o){this.abortDownloadingItems(),Le(o)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}selectItemsToLoad(){let e=0,t=0,i=[],r=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,a=this.preloadOnly?this.forwardBufferTarget:0,n=0;for(;n<this.downloadingBufferItems.length&&this.downloadingBufferItems[n].segment.networkStatus==="none"&&(e<=r||t<=a);){let o=this.downloadingBufferItems[n].segment;o.networkStatus="downloading",o.size=1/0,o.loadedBytes=0,o.feedingBytes=0,o.fedBytes=0,i.push(this.downloadingBufferItems[n]),e+=o.byte.to+1-o.byte.from,t+=o.time.to+1-o.time.from,n++}return i}prepareFetchParams(e,t){if(Ue(t.segmentReference))throw new Error("Representation is not byte range type");let{signal:i}=this.downloadAbortController,r=t.segmentReference.url,a={from:e[0].segment.byte.from,to:e[e.length-1].segment.byte.to};return{url:r,range:a,onProgress:async(o,u)=>{if(!i.aborted)try{this.lastDataObtainedTimestampMs=HI(),await this.onSomeDataLoaded({downloadingItems:e,dataView:o,loaded:u,signal:i,globalFrom:a?a.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:u0.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}},signal:i,bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation}}async onSomeDataLoaded({downloadingItems:e,dataView:t,representationId:i,globalFrom:r,loaded:a,signal:n}){let o=this.representations.get(i);if(!(!this.downloadingBufferItems.length||jI(o)||jI(r)||n.aborted))for(let u of e){let{segment:l}=u,p=l.byte.from-r,c=l.byte.to-r,d=c-p+1,h=p<a,f=c<=a;l.size=d,h&&(l.networkStatus==="downloading"&&l.bufferStatus==="none"&&f?(l.data=new DataView(t.buffer,t.byteOffset+p,d),this.currentVirtualBufferSize+=l.size,this.onItemFullyDownloaded(u),l.loadedBytes=Math.min(d,a-p),await this.onDownloadItem(u)):l0(l.feedingBytes)&&this.tuning.dash.enableSubSegmentBufferFeeding&&l.networkStatus==="downloading"&&(l.loadedBytes=Math.min(d,a-p),f&&(this.currentVirtualBufferSize+=l.size,this.onItemFullyDownloaded(u)),l.loadedBytes>l.feedingBytes&&(l.data=new DataView(t.buffer,t.byteOffset+p,l.loadedBytes),await this.onDownloadItem(u))))}}updateRepresentationBaseUrl(e,t){if(Ue(e.segmentReference))throw new Error("Representation is not byte range type");e.segmentReference.url=t}};import{ErrorCategory as c0,isNullable as ip,now as zI}from"@vkontakte/videoplayer-shared/es2024";var rs=class extends is{constructor(e,t,i,r){super(e,t,i,r)}async loadItems(e,t,i="auto"){let{signal:r}=this.downloadAbortController;if(r.aborted||!e.length)return;let{url:a,...n}=this.prepareFetchParams(e,t);if(this.failedDownloads&&await this.waitExponentialDownloadDelay(),!r.aborted)try{let o=await this.fetcher.fetch(a,{...n,priority:i});if(this.lastDataObtainedTimestampMs=zI(),ip(o))return;let u=e[0],l=new DataView(o);u.segment.size=l.byteLength,u.segment.loadedBytes=l.byteLength,u.segment.data=l,this.onItemFullyDownloaded(u),await this.onDownloadItem(u),this.failedDownloads=0}catch(o){this.abortDownloadingItems(),Le(o)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}selectItemsToLoad(){let e=[];for(let t of this.downloadingBufferItems){let i=t.segment;i.networkStatus="downloading",i.size=1/0,i.loadedBytes=0,i.feedingBytes=0,i.fedBytes=0,e.push(t)}return e}prepareFetchParams(e,t){let i=this.getFetchUrl(e,t).toString(),{signal:r}=this.downloadAbortController;return{url:i,onProgress:async(n,o)=>{if(!r.aborted)try{this.lastDataObtainedTimestampMs=zI(),await this.onSomeDataLoaded({downloadingItems:e,dataView:n,loaded:o,signal:r,representationId:t.id})}catch(u){this.error$.next({id:"SegmentFeeding",category:c0.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:u})}},signal:r,bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation}}getFetchUrl(e,t){if(!Ue(t.segmentReference))throw new Error("Representation is not template type");return new URL(e[0].segment.url,t.segmentReference.baseUrl)}async onSomeDataLoaded({downloadingItems:e,dataView:t,representationId:i,loaded:r,signal:a}){let n=e[0],{segment:o}=n,u=this.representations.get(i);!this.downloadingBufferItems.length||ip(u)||ip(o.feedingBytes)||o.networkStatus!=="downloading"||a.aborted||(o.loadedBytes=r,o.loadedBytes>o.feedingBytes&&this.tuning.dash.enableSubSegmentBufferFeeding&&(o.data=new DataView(t.buffer,t.byteOffset,o.loadedBytes),await this.onDownloadItem(n)))}updateRepresentationBaseUrl(e,t){if(!Ue(e.segmentReference))throw new Error("Representation is not template type");e.segmentReference.baseUrl=t}};var rp=D(Wi(),1),WI=D(Ge(),1);import{assertNonNullable as d0,ErrorCategory as p0,isNullable as jt,ValueSubject as QI}from"@vkontakte/videoplayer-shared/es2024";var lu=class extends rs{constructor(t,i,r,a){super(t,i,r,a);this.currentLiveSegmentServerLatency$=new QI(0);this.currentLowLatencySegmentLength$=new QI(0);this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.isActiveLowLatency=a.isActiveLowLatency}updateManifest(t){if(!t||[...this.segments.values()].every(r=>!r.length))return;let i=(0,rp.default)(t.streams[this.kind],r=>r.representations);for(let r of i){if(jt(r)||!Ue(r.segmentReference))return;let a=r.segmentReference.segments.map(p=>({...p,networkStatus:"none",bufferStatus:"none",size:void 0})),n=100,o=this.segments.get(r.id)??[],u=(0,WI.default)(o,-1)?.time.to??0,l=a?.findIndex(p=>u>=p.time.from+n&&u<=p.time.to+n);if(l===-1){let p=this.getActualLiveStartingSegments(r.segmentReference);this.segments.set(r.id,p)}else{let p=a.slice(l+1);this.segments.set(r.id,[...o,...p])}this.representations.set(r.id,r)}}proceedLowLatencyLive(){let t=this.downloadingRepresentationId;d0(t);let i=this.segments.get(t);if(i?.length){let r={representationId:t,segmentIndex:i.length-1,segment:i[i.length-1]};this.updateLowLatencyLive(r)}}getLiveSegmentsToLoadState(t){let i=t?.streams[this.kind],r=(0,rp.default)(i,n=>n.representations).find(n=>n.id===this.downloadingRepresentationId);if(jt(r))return;let a=this.segments.get(r.id);if(a?.length)return{from:a[0].time.from,to:a[a.length-1].time.to}}getRepresentationInitialTime(){if(jt(this.playingRepresentationId))return 0;let t=this.representations.get(this.playingRepresentationId)?.segmentReference;return jt(t)||!Ue(t)?0:this.getActualLiveStartingSegments(t)[0].time.from+this.tuning.dash.bufferTolerance}prepareFetchParams(t,i){return{...super.prepareFetchParams(t,i),isLowLatency:this.isActiveLowLatency()}}async onSomeDataLoaded({downloadingItems:t,...i}){await super.onSomeDataLoaded({downloadingItems:t,...i}),this.isActiveLowLatency()&&this.updateLowLatencyItemTime(t[0])}onItemFullyDownloaded(t){if(super.onItemFullyDownloaded(t),jt(t.segment.data)||!this.isActiveLowLatency())return;let i=t.segment.data,r=this.containerParser,{serverDataReceivedTimestamp:a,serverDataPreparedTime:n}=r.getServerLatencyTimestamps(i);a&&n&&this.currentLiveSegmentServerLatency$.next(n-a),this.updateLowLatencyItemTime(t),this.updateLowLatencyLive(t)}updateLowLatencyItemTime(t){let i=t.segment.data,r=this.representations.get(t.representationId)?.segmentReference;if(jt(t.segment.data)||jt(r)||!Ue(r))return;let a=this.containerParser;if(t.segment.isCurrentLowLatency){let{timescale:n}=r;t.segment.time.to=a.getChunkEndTime(i,n)}}updateLowLatencyLive(t){let i=0;for(let r of this.representations.values()){let a=r.segmentReference;if(!Ue(a))return;let n=this.segments.get(r.id)??[],o=n.find(l=>Math.floor(l.time.from)===Math.floor(t.segment.time.from));if(o?.isCurrentLowLatency&&(o.time.to=t.segment.time.to,i=o.time.to-o.time.from,o.isCurrentLowLatency=!1),!!!n.find(l=>Math.floor(l.time.from)===Math.floor(t.segment.time.to))&&this.isActiveLowLatency()){let l=Math.round(t.segment.time.to*a.timescale/1e3).toString(10),p=tt(a.segmentTemplateUrl,{segmentTime:l});n.push({networkStatus:"none",bufferStatus:"none",time:{from:t.segment.time.to,to:t.segment.time.to+this.tuning.dash.bufferTolerance},url:p,isCurrentLowLatency:!0})}}this.currentLowLatencySegmentLength$.next(i)}parseFeedableSegmentChunk(t){return this.containerParser.parseFeedableSegmentChunk(t,!0)}getFetchUrl(t,i){let r=super.getFetchUrl(t,i);return this.isActiveLowLatency()&&r.searchParams.set("low-latency","yes"),r}async loadInit(t,i="auto",r=!1){try{let a=this.tuning.dash.useFetchPriorityHints?i:"auto",n=this.fetcher.fetchRepresentation(t.segmentReference,this.containerParser,a);this.initDataPromises.set(t.id,n);let{initMetadata:o,initDataView:u,segments:l}=await n??{};if(this.initDataPromises.delete(t.id),jt(u)||jt(l))return;o&&this.parsedInitData.set(t.id,o);let p=this.getActualLiveStartingSegments(t.segmentReference);this.segments.has(t.id)||this.segments.set(t.id,p);let c=u.buffer.slice(u.byteOffset,u.byteOffset+u.byteLength);this.initData.set(t.id,c),this.failedDownloads=0}catch(a){r&&this.error$.next({id:"LoadInits",category:p0.WTF,message:"loadInit threw",thrown:a})}}getActualLiveStartingSegments(t){let i=t.segments,r=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,a=[],n=0,o=i.length-1;do a.unshift(i[o]),n+=i[o].time.to-i[o].time.from,o--;while(n<r&&o>=0);return this.liveInitialAdditionalOffset=n-r,this.isActiveLowLatency()?[a[0]]:a}};var Qa=class{static getBufferManager(e,t,i,r){return r.manifest?.live?new lu(e,t,i,r):Ue(i[0].segmentReference)?new rs(e,t,i,r):new uu(e,t,i,r)}};import{ErrorCategory as m0,fromEvent as b0,isNullable as ss,Subject as g0,Subscription as S0}from"@vkontakte/videoplayer-shared/es2024";import{assertNever as h0,ErrorCategory as GI,Subject as YI}from"@vkontakte/videoplayer-shared/es2024";var f0=18,KI=!1;try{KI=$.browser.isSafari&&!!$.browser.safariVersion&&$.browser.safariVersion<=f0}catch(s){console.error(s)}var sp=class{constructor(e){this.bufferFull$=new YI;this.error$=new YI;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.shift()}this.queue.length&&this.pull()}catch(e){this.error$.next({id:"BufferTaskQueueUnknown",category:GI.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:e})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(i=>{let r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(r=>{let a={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(a),this.pull()})}async abort(e){return new Promise(t=>{let i,r=a=>{this.abortRequested=!1,t(a)};KI&&e?i={operation:"safariAbort",init:e,callback:r}:i={operation:"abort",callback:r};for(let{callback:a}of this.queue)a(!1);this.abortRequested=!0,i&&(this.queue=[i]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){if((this.buffer.updating||this.currentTask||this.destroyed)&&!this.abortRequested)return;let e=this.queue[0];if(!e)return;if(e.signal?.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(r){r instanceof DOMException&&r.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):r instanceof DOMException&&r.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:GI.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:r}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){let{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:h0(t)}}},XI=sp;var de=(s,e)=>{let t=0;for(let i=0;i<s.length;i++){let r=s.start(i)*1e3,a=s.end(i)*1e3;r<=e&&e<=a&&(t=a)}return Math.max(t-e,0)};var Wa=class{constructor(e){this.error$=new g0;this.subscription=new S0;this.mediaSource=e}init(e,t){this.sourceBuffer=this.mediaSource.addSourceBuffer(`${e}; codecs="${t}"`),this.sourceBufferTaskQueue=new XI(this.sourceBuffer),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(i=>this.error$.next(i))),this.subscription.add(b0(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:m0.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"})))}addInitSegment(e,t){return this.sourceBufferTaskQueue.append(e,t)}append(e,t){return this.sourceBufferTaskQueue.append(e,t)}remove(e,t,i){return this.sourceBufferTaskQueue.remove(e,t,i)}async clear(e){let t=this.getBufferState();if(ss(t))return Promise.resolve(!1);let i=!0;await this.sourceBufferTaskQueue.abort();for(let r of t)i&&=await this.sourceBufferTaskQueue.remove(r.from,r.to,e);return i}warmUpMediaSource(){!ss(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}getBufferState(){if(ss(this.sourceBuffer)||!V(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length)return null;let e=[];for(let t=0;t<this.sourceBuffer.buffered.length;t++)e.push({from:this.sourceBuffer.buffered.start(t)*1e3,to:this.sourceBuffer.buffered.end(t)*1e3});return e}getForwardBufferDuration(e){return ss(this.sourceBuffer)||!V(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||ss(e)?0:de(this.sourceBuffer.buffered,e)}async abortBuffer(e){return ss(this.sourceBuffer)?!1:this.sourceBufferTaskQueue.abort(e)}destroy(){if(this.subscription.unsubscribe(),this.sourceBufferTaskQueue?.destroy(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(e){if(!(e instanceof DOMException&&e.name==="NotFoundError"))throw e}this.sourceBuffer=null}};var w0=["timeupdate","progress","play","seeked","stalled","waiting"],eE=["timeupdate","progress","loadeddata","playing","seeked"],du=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.bufferManagers=[];this.nativeBufferManagers=[];this.subscription=new ZI;this.subscriptionRemovable=new E0;this.representationSubscription=new ZI;this.forceEnded$=new gi;this.destroyController=new j;this.state$=new O("none");this.currentVideoRepresentation$=new Z(void 0);this.currentVideoRepresentationInit$=new Z(void 0);this.currentAudioRepresentation$=new Z(void 0);this.currentVideoSegmentLength$=new Z(0);this.currentAudioSegmentLength$=new Z(0);this.error$=new gi;this.manifestRequested=new gi;this.manifestReceived=new gi;this.firstBytesRequested=new gi;this.firstBytesReceived=new gi;this.lastConnectionType$=new Z(void 0);this.lastConnectionReused$=new Z(void 0);this.lastRequestFirstBytes$=new Z(void 0);this.currentLiveTextRepresentation$=new Z(null);this.isLive$=new Z(!1);this.isActiveLive$=new Z(!1);this.isLowLatency$=new Z(!1);this.liveDuration$=new Z(0);this.liveSeekableDuration$=new Z(0);this.liveAvailabilityStartTime$=new Z(0);this.liveStreamStatus$=new Z(void 0);this.currentBuffer$=new Z({from:0,to:0});this.bufferLength$=new Z(0);this.nativeBufferLength$=new Z(0);this.liveLatency$=new Z(void 0);this.liveLoadBufferLength$=new Z(0);this.livePositionFromPlayer$=new Z(0);this.currentStallDuration$=new Z(0);this.videoLastDataObtainedTimestamp$=new Z(0);this.fetcherRecoverableError$=new gi;this.fetcherError$=new gi;this.initRepresentations=JI(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initRepresentationsStart",cu({initialVideo:e,initialAudio:t,sourceHls:i})),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let r={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),manifest:this.manifest};this.createBuffers(r,e,t,i),this.initRepresentationSubscriptions(),yield this.waitStreamToOpen(),this.setSourceDuration(),Ht(this.videoBufferManager),yield Promise.all([this.videoBufferManager.startWith(e),t?this.audioBufferManager?.startWith(t):Promise.resolve()]),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")}.bind(this));this.fetchManifest=JI(this.destroyController.signal,async function*(){try{return yield this.fetcher.fetchManifest(this.manifestUrlString)}catch(e){Ga(this.manifest)&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:Xi.NETWORK,message:"Failed to load manifest",thrown:e})}}.bind(this));this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.forceVideoCodec=e.forceVideoCodec,this.fetcher=new iu({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.subscription.add(this.fetcher.recoverableError$.subscribe(this.fetcherRecoverableError$)),this.subscription.add(this.fetcher.error$.subscribe(this.fetcherError$)),this.initTracerSubscription()}async initManifest(e,t,i){this.tracer.log("initManifest"),this.state$.startTransitionTo("manifest_ready"),this.element=e,this.manifestUrlString=this.prepareManifestUrlString(t,i),this.manifest=await this.updateManifest(),this.manifest?.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:Xi.PARSER,message:"No playable video representations"})}initBuffer(){Ht(this.element),this.state$.setState("running"),this.subscription.add(Ya(...w0.map(t=>Ji(this.element,t)),Ji(window,"online")).subscribe(()=>this.tick(),t=>this.error$.next({id:"DashVKPlayer",category:Xi.WTF,message:"Internal logic error",thrown:t})));let e=[...this.source?.activeSourceBuffers??[]];this.subscription.add(Ya(...e.map(t=>Ji(t,"updateend"))).subscribe(t=>this.reinitDecoderIfNeeded())),this.subscription.add(Ji(this.element,"waiting").subscribe(t=>{this.stallWatchdogSubscription&&(this.stallWatchdogSubscription.unsubscribe(),this.subscriptionRemovable.remove(this.stallWatchdogSubscription)),this.stallWatchdogSubscription=T0(this.tuning.dash.stallWatchdogInterval).subscribe(()=>this.stallWatchdogIntervalCallback(),i=>this.error$.next({id:"StallWatchdogCallback",category:Xi.NETWORK,message:"Can't restore DASH after stall.",thrown:i})),this.subscriptionRemovable.add(this.stallWatchdogSubscription)}))}async switchRepresentation(e,t,i=!1){return{video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e]?.switchTo(t,i)}async seek(e,t=!1){Ht(this.element),Ht(this.videoBufferManager);let i;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?i=e:i=Math.max(this.videoBufferManager.findSegmentStartTime(e)??e,this.audioBufferManager?.findSegmentStartTime(e)??e),this.warmUpMediaSourceIfNeeded(i),this.element.currentTime=i/1e3,await this.videoBufferManager.seek(i),await this.audioBufferManager?.seek(i),this.tracer.log("seek",cu({requestedPosition:e,forcePrecise:t,position:i}))}warmUpMediaSourceIfNeeded(e=this.element?.currentTime){bi(this.element)&&bi(this.source)&&bi(e)&&this.isStreamEnded&&this.element.duration*1e3-e>this.tuning.dash.seekBiasInTheEnd&&this.nativeBufferManagers.forEach(t=>t.warmUpMediaSource())}calculateDurationFromSegments(){return Math.max(this.videoBufferManager?.calculateDurationFromSegments()||0,this.audioBufferManager?.calculateDurationFromSegments()||0)}get isStreamEnded(){return this.source?.readyState==="ended"}getStreams(){return this.manifest?.streams}getCodecs(){return this.manifest?.codecs}setBufferTarget(e){this.bufferManagers.forEach(t=>t.setTarget(e))}setPreloadOnly(e){this.bufferManagers.forEach(t=>t.setPreloadOnly(e))}stop(){this.tracer.log("stop"),this.element?.querySelectorAll("source").forEach(e=>{URL.revokeObjectURL(e.src),e.remove()}),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),this.nativeBufferManagers.forEach(e=>e.destroy()),this.videoBufferManager?.destroy(),this.videoBufferManager=null,this.audioBufferManager?.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}destroy(){this.subscription.unsubscribe(),this.subscriptionRemovable.unsubscribe(),this.representationSubscription.unsubscribe(),this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),bi(this.source)&&this.isStreamNotOpen&&Array.from(this.source.sourceBuffers).every(e=>!e.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}get isStreamNotOpen(){return this.source?.readyState!=="open"}async reinitDecoderIfNeeded(e=!1){let t=this.videoNativeBufferManager?.getBufferState()??[];if(Ga(this.element)||!t.length)return;let i=this.element.currentTime*1e3;this.element.readyState<3&&t.some(r=>i>=r.from&&i<=r.to)&&(e?await this.seek(i):this.element.currentTime=this.element.currentTime)}async stallWatchdogIntervalCallback(){Ht(this.element),Ht(this.source);let{stallWatchdogInterval:e}=this.tuning.dash;if(this.isStreamNotOpen)return;let t=this.currentStallDuration$.getValue()+e;this.currentStallDuration$.next(t);let i={timeInWaiting:t};if(await this.reinitDecoderIfNeeded(t%1e3===0),this.isStallExceeded(t))throw new Error(`Stall timeout exceeded: ${t} ms`);await this.restoreAfterDeepStall(i),this.tracer.log("stallIntervalCallback",cu(i))}isStallExceeded(e){let{crashOnStallTimeout:t,crashOnStallTWithoutDataTimeout:i}=this.tuning.dash,r=I0(),a=100,n=this.videoBufferManager?.lastDataObtainedTimestamp??0;this.videoLastDataObtainedTimestamp$.next(n);let o=this.audioBufferManager?.lastDataObtainedTimestamp??0,u=this.videoBufferManager?.getForwardPlaybackBufferDuration()??0,l=this.audioBufferManager?.getForwardPlaybackBufferDuration()??0,p=bi(this.videoBufferManager)&&u<a&&r-n>i,c=bi(this.audioBufferManager)&&l<a&&r-o>i;return(p||c)&&e>i||e>=t}async updateManifest(){this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=await this.fetchManifest();if(Ga(e))return null;let t=this.parseManifest(e);if(!t)return null;let i=this.getResultManifest(t);return this.tracer.log("updateManifestEnd",cu(i)),i}parseManifest(e){try{return Xr(e??"",this.manifestUrlString)}catch(t){let i=Hr(e)??{id:"ManifestParsing",category:Xi.PARSER,message:"Failed to parse MPD manifest",thrown:t};this.error$.next(i)}}getResultManifest(e){let t={text:e.streams.text,video:[],audio:[]},i=(o,u,l)=>!!(this.element?.canPlayType?.(u)&&Ve()?.isTypeSupported?.(`${u}; codecs="${l}"`)||o==="text"),r,a;for(let o of["video","audio"]){let l=e.streams[o].filter(({mime:c,codecs:d})=>i(o,c,d));t[o]=l;let p;if(this.tuning.dash.codecsPrioritizeEnabled){let c=l.map(({codecs:d})=>d);o==="audio"&&(a=es(c),p=a[0]),o==="video"&&(r=Zr(c),this.forceVideoCodec&&(0,tE.default)(r,this.forceVideoCodec)?p=this.forceVideoCodec:p=r[0]),p&&(t[o]=l.filter(({codecs:d})=>hi(d)===p))}else{let c=new Set(l.map(({codecs:d})=>d));p=Jr(c),p&&(t[o]=l.filter(({codecs:d})=>d.startsWith(p)))}if(o==="video"){let c=this.tuning.preferHDR,d=t.video.some(f=>f.hdr),h=t.video.some(f=>!f.hdr);$.display.isHDR&&c&&d?t.video=t.video.filter(f=>f.hdr):h&&(t.video=t.video.filter(f=>!f.hdr))}}let n={...e,streams:t};return this.tuning.dash.codecsPrioritizeEnabled&&(n.codecs={video:r,audio:a}),n}stopStallWatchdogSubscription(){this.stallWatchdogSubscription?.unsubscribe(),this.currentStallDuration$.next(0)}createBuffers(e,t,i,r){Ht(this.manifest),Ht(this.element);let a=u=>{this.representationSubscription.add(Ji(u,"error").pipe(ap(l=>!!this.element?.played.length)).subscribe(l=>{this.error$.next({id:"VideoSource",category:Xi.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:l})}))};this.source=Ir();let n=document.createElement("source");if(a(n),n.src=URL.createObjectURL(this.source),this.element.appendChild(n),ai())if(r){let u=document.createElement("source");a(u),u.type="application/x-mpegurl",u.src=r.url,this.element.appendChild(u)}else this.element.disableRemotePlayback=!0;let o=this.manifest.streams.video.reduce((u,l)=>[...u,...l.representations],[]);if(this.videoNativeBufferManager=new Wa(this.source),this.videoBufferManager=Qa.getBufferManager("video",this.videoNativeBufferManager,o,e),this.bufferManagers=[this.videoBufferManager],this.nativeBufferManagers=[this.videoNativeBufferManager],bi(i)){this.audioNativeBufferManager=new Wa(this.source);let u=this.manifest.streams.audio.reduce((l,p)=>[...l,...p.representations],[]);this.audioBufferManager=Qa.getBufferManager("audio",this.audioNativeBufferManager,u,e),this.bufferManagers.push(this.audioBufferManager),this.nativeBufferManagers.push(this.audioNativeBufferManager)}}async waitStreamToOpen(){if(this.isStreamNotOpen){let e=this.tuning.dash.sourceOpenTimeout>=0;await new Promise(t=>{e&&(this.timeoutSourceOpenId=setTimeout(()=>{if(this.isStreamNotOpen){t();return}this.error$.next({id:"OpenOfStream",category:Xi.VIDEO_PIPELINE,message:"Failed to open MediaSource",thrown:new Error("Timeout reject when wait sourceopen event"),traceAsLog:!0})},this.tuning.dash.sourceOpenTimeout)),this.source?.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),t()},{once:!0})})}}initRepresentationSubscriptions(){this.representationSubscription.add(this.fetcher.manifestRequested.subscribe(this.manifestRequested)),this.representationSubscription.add(this.fetcher.manifestReceived.subscribe(this.manifestReceived)),this.representationSubscription.add(this.fetcher.firstBytesRequested.subscribe(this.firstBytesRequested)),this.representationSubscription.add(this.fetcher.firstBytesReceived.subscribe(this.firstBytesReceived)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add(Ya(...this.bufferManagers.map(e=>e.error$)).subscribe(this.error$)),Ht(this.videoBufferManager),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.representationSubscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.representationSubscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.initBufferLengthSubscription()}initBufferLengthSubscription(){this.representationSubscription.add(Ya(...eE.map(e=>Ji(this.element,e))).pipe(np(e=>this.videoBufferManager?.getPlaybackBufferState()),ap(bi),np(({from:e,to:t})=>({from:e/1e3,to:t/1e3}))).subscribe(this.currentBuffer$)),this.representationSubscription.add(Ya(...eE.map(e=>Ji(this.element,e))).pipe(np(e=>Math.max(this.videoBufferManager?.getForwardPlaybackBufferDuration()??0,this.audioBufferManager?.getForwardPlaybackBufferDuration()??0)),v0()).subscribe(this.bufferLength$)),this.representationSubscription.add(this.nativeBufferLength$.pipe(ap(e=>e>this.tuning.dash.bufferEmptinessTolerance)).subscribe(e=>this.stopStallWatchdogSubscription()))}initTracerSubscription(){let e=y0(this.tracer.error.bind(this.tracer));this.subscription.add(this.error$.subscribe(e("error")))}async tick(){if(Ga(this.element)||Ga(this.videoBufferManager)||this.isStreamNotOpen)return;let e=this.element.currentTime*1e3,i=(this.videoNativeBufferManager?.getBufferState()??[]).find(r=>e>=r.from&&e<=r.to);this.nativeBufferLength$.next(i?i.to-e:0),await this.videoBufferManager.maintain(e),await this.audioBufferManager?.maintain(e)}};import{assertNonNullable as pu,combine as x0,ErrorCategory as k0,filter as op,filterChanged as P0,fromEvent as A0,isNonNullable as R0,map as up,merge as Ka}from"@vkontakte/videoplayer-shared/es2024";var hu=class extends du{constructor(e){super(e)}prepareManifestUrlString(e,t){return e}initRepresentationSubscriptions(){super.initRepresentationSubscriptions(),this.initDisableStallWatchdogSubscription(),this.initEndOfVideoSubscription()}setSourceDuration(){pu(this.manifest),pu(this.source);let e=[this.manifest.duration??0,...(0,lp.default)((0,lp.default)([...this.manifest.streams.audio,...this.manifest.streams.video],t=>t.representations),t=>{let i=[];return t.duration&&i.push(t.duration),Ue(t.segmentReference)&&t.segmentReference.totalSegmentsDurationMs&&i.push(t.segmentReference.totalSegmentsDurationMs),i})];this.source.duration=Math.max(...e)/1e3}async restoreAfterDeepStall(e){pu(this.element);let t=this.element.currentTime*1e3;await Promise.all([this.videoBufferManager?.maintain(t),this.audioBufferManager?.maintain(t)]),e.position=t}initDisableStallWatchdogSubscription(){pu(this.element);let e=Ka(A0(this.element,"ended"),this.forceEnded$),t=this.nativeBufferLength$.pipe(op(i=>i>this.tuning.dash.bufferEmptinessTolerance));this.representationSubscription.add(Ka(e,t).subscribe(i=>this.stopStallWatchdogSubscription()))}initEndOfVideoSubscription(){let e=Ka(...this.bufferManagers.map(a=>a.fullyBuffered$)).pipe(up(()=>this.bufferManagers.every(a=>a.fullyBuffered$.getValue()))),t=Ka(...this.bufferManagers.map(a=>a.onLastSegment$)).pipe(up(()=>this.bufferManagers.some(a=>a.onLastSegment$.getValue()))),i=x0({allBuffersFull:e,someBufferEnded:t}).pipe(P0(),up(({allBuffersFull:a,someBufferEnded:n})=>a&&n),op(a=>a)),r=()=>{try{this.source?.endOfStream()}catch(a){this.error$.next({id:"EndOfStream",category:k0.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:a})}};this.representationSubscription.add(Ka(this.forceEnded$,i).pipe(op(a=>R0(this.source)&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(n=>!n.updating))).subscribe(r))}};var as=class extends pa{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:i,genericErrorListener:r}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$),this.subscription.add(this.player.currentVideoRepresentation$.pipe($0()).subscribe(a=>{let n=[...this.videoTracksMap.entries()].find(([,{representation:c}])=>c.id===a);if(!n){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[o,{stream:u}]=n,l=this.params.desiredState.videoStream.getTransition();l&&l.to&&l.to.id===u.id&&this.params.desiredState.videoStream.setState(l.to),e.currentVideoTrack$.next(o),e.currentVideoStream$.next(Wo(u));let p=this.player.calculateDurationFromSegments();p&&this.params.output.duration$.next(p/1e3)},r))}getPlayer(){return new hu({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer,forceVideoCodec:this.params.forceVideoCodec})}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};import{assertNever as t_,assertNonNullable as i_,combine as r_,debounce as s_,ErrorCategory as fE,filter as vp,filterChanged as nn,fromEvent as a_,isNonNullable as mE,isNullable as n_,map as on,merge as un,observableFrom as xu,once as bE,Subscription as o_,throttle as u_}from"@vkontakte/videoplayer-shared/es2024";var hE=D(ke(),1),gp=D(Wi(),1);var De=(s,e,t=0)=>{for(let i=0;i<s.length;i++)if(s.start(i)*1e3-t<=e&&s.end(i)*1e3+t>e)return!0;return!1};import{abortable as fp,assertNonNullable as cs,combine as ds,ErrorCategory as ct,filter as Iu,filterChanged as rn,flattenObject as sn,fromEvent as Wt,getTraceSubscriptionMethod as j0,interval as mp,isNonNullable as an,isNullable as cE,map as ps,merge as tr,now as bp,Subject as Gt,Subscription as dE,SubscriptionRemovable as H0,tap as z0,throttle as Q0,ValueSubject as ee}from"@vkontakte/videoplayer-shared/es2024";var mu=D(ke(),1),er=D(Ge(),1),bu=D(Wi(),1);var nE=D(Ro(),1);import{assertNever as M0,ErrorCategory as iE,Subject as rE}from"@vkontakte/videoplayer-shared/es2024";var L0=18,sE=!1;try{sE=$.browser.isSafari&&!!$.browser.safariVersion&&$.browser.safariVersion<=L0}catch(s){console.error(s)}var cp=class{constructor(e,t=!1){this.bufferFull$=new rE;this.error$=new rE;this.queue=[];this.currentTask=null;this.destroyed=!1;this.abortRequested=!1;this.isAbortFixEnabled=!1;this.completeTask=()=>{try{if(this.currentTask){let e=this.currentTask.signal?.aborted;this.currentTask.callback(!e),this.currentTask=null,this.isAbortFixEnabled&&this.queue.shift()}this.queue.length&&this.pull()}catch(e){this.error$.next({id:"BufferTaskQueueUnknown",category:iE.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:e})}};this.buffer=e,this.isAbortFixEnabled=t,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(i=>{let r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(r=>{let a={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(a),this.pull()})}async abort(e){return new Promise(t=>{let i,r=a=>{this.abortRequested=!1,t(a)};sE&&e?i={operation:"safariAbort",init:e,callback:r}:i={operation:"abort",callback:r};for(let{callback:a}of this.queue)a(!1);this.abortRequested=!0,i&&(this.queue=[i]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){if((this.buffer.updating||this.currentTask||this.destroyed)&&!this.abortRequested)return;let e=this.isAbortFixEnabled?this.queue[0]:this.queue.shift();if(!e)return;if(e.signal?.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(r){r instanceof DOMException&&r.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):r instanceof DOMException&&r.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:iE.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:r}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){let{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:M0(t)}}},aE=cp;var ns=s=>{let e=0;for(let t=0;t<s.length;t++)e+=s.end(t)-s.start(t);return e*1e3};import{abortable as Si,assertNonNullable as je,ErrorCategory as zt,fromEvent as dp,getExponentialDelay as pp,isHigher as D0,isNonNullable as vi,isNullable as pe,now as fu,once as B0,Subject as C0,Subscription as V0,ValueSubject as Zi}from"@vkontakte/videoplayer-shared/es2024";var Xa=class{constructor(e,t,i,{fetcher:r,tuning:a,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new Zi(0);this.currentLowLatencySegmentLength$=new Zi(0);this.currentSegmentLength$=new Zi(0);this.onLastSegment$=new Zi(!1);this.fullyBuffered$=new Zi(!1);this.playingRepresentation$=new Zi(void 0);this.playingRepresentationInit$=new Zi(void 0);this.error$=new C0;this.gaps=[];this.subscription=new V0;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new j;this.switchAbortController=new j;this.destroyAbortController=new j;this.useSmartRepresentationSwitch=!1;this.bufferLimit=1/0;this.failedDownloads=0;this.baseUrls=[];this.baseUrlsIndex=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.lastDataObtainedTimestampMs=0;this.loadByteRangeSegmentsTimeoutId=0;this.startWith=Si(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);je(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new aE(this.sourceBuffer,this.tuning.dash.useAbortMSEFix),this.subscription.add(dp(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:zt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o??={id:"SegmentEjection",category:zt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n},this.error$.next(o)})),this.subscription.add(dp(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:zt.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o||!V(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,ns(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=this.getForwardBufferDuration(o),p=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,n*2,l<p).catch(c=>{this.handleAsyncError(c,"pruneBuffer")})})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);let i=this.initData.get(t.id),r=this.segments.get(t.id),a=this.parsedInitData.get(t.id);je(i,"No init buffer for starting representation"),je(r,"No segments for starting representation"),i instanceof ArrayBuffer&&(this.searchGaps(r,t),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(a))}.bind(this));this.switchTo=Si(this.destroyAbortController.signal,async function*(e,t=!1){if(!V(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);je(i,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if(pe(a)||pe(r)?yield this.loadInit(i,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),je(r,"No segments for starting representation"),a=this.initData.get(e),!(!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer||!V(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(a,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer();else{let n=this.getCurrentPosition();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=Si(this.destroyAbortController.signal,async function*(e,t=!1){if(!V(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);je(i,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if(pe(a)||pe(r)?yield this.loadInit(i,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),je(r,"No segments for starting representation"),a=this.initData.get(e),!(!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer||!V(this.mediaSource,this.sourceBuffer)))if(yield this.abort(),yield this.sourceBufferTaskQueue.append(a,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let n=this.getCurrentPosition();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=Si(this.destroyAbortController.signal,async function*(e){let t=(0,bu.default)(e,u=>u.representations);if(!this.downloadingRepresentationId||!t.length)return;this.isSeekingLive=!0;for(let u of this.representations.keys()){let l=t.find(d=>d.id===u);l&&this.representations.set(u,l);let p=this.representations.get(u);if(!p||!it(p.segmentReference)){this.isSeekingLive=!1;return}let c=this.getActualLiveStartingSegments(p.segmentReference);this.segments.set(p.id,c)}let i=this.switchingToRepresentationId??this.downloadingRepresentationId,r=this.representations.get(i);je(r,`Representation not found by id ${i}`);let a=this.segments.get(i);je(a,"No segments for starting representation");let n=this.initData.get(i);if(je(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer)){this.isSeekingLive=!1;return}let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(a,r),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));this.fetcher=r,this.tuning=a,this.compatibilityMode=u,this.forwardBufferTarget=a.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!l?.live,this.baseUrls=l?.baseUrls??[],this.initData=new Map(i.map(p=>[p.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(p=>[p.id,p])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchToWithPreviousAbort(e,t=!1){!V(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new j,Si(this.switchAbortController.signal,async function*(i,r=!1){this.switchingToRepresentationId=i;let a=this.representations.get(i);je(a,`No such representation ${i}`);let n=this.segments.get(i),o=this.initData.get(i);if(pe(o)||pe(n)?yield this.loadInit(a,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(i),je(n,"No segments for starting representation"),o=this.initData.get(i),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer||!V(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(o,this.downloadAbortController.signal),r)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=i,yield this.dropBuffer();else{let u=this.getCurrentPosition();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(){!pe(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 j,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(pe(e)||pe(this.downloadingRepresentationId)||pe(this.playingRepresentationId)||pe(this.sourceBuffer)||!V(this.mediaSource,this.sourceBuffer)||vi(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.representations.get(this.playingRepresentationId),r=this.segments.get(this.downloadingRepresentationId),a=this.segments.get(this.playingRepresentationId);if(je(t,`No such representation ${this.downloadingRepresentationId}`),je(i,`No such representation ${this.playingRepresentationId}`),pe(r)||pe(a))return;let n=r.find(d=>e>=d.time.from&&e<d.time.to);vi(n)&&isFinite(n.time.from)&&isFinite(n.time.to)&&this.currentSegmentLength$.next(n?.time.to-n.time.from);let o=e,u=100;if(this.playingRepresentationId!==this.downloadingRepresentationId){let d=this.getForwardBufferDuration(e),h=mi(i),f=mi(t),m=this.useSmartRepresentationSwitch&&this.tuning.dash.useNewRepresentationSwitch&&this.tuning.dash.useSmartRepresentationSwitch&&vi(h)&&vi(f)&&D0(h.quality,f.quality),S=this.useSmartRepresentationSwitch&&this.tuning.dash.useNewRepresentationSwitch&&this.tuning.dash.useDelayedRepresentationSwitch;if(m||S?o+=Math.min(d,this.tuning.dash.representationSwitchForwardBufferGap):n&&n.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&d>=n.time.to-e+u&&(o=n?n.time.to+u:-1/0),this.tuning.dash.useNewRepresentationSwitch){let v=[...this.segments.entries()].map(([T,y])=>{let x=y.find(A=>e>=A.time.from&&e<A.time.to);return{representationId:T,status:x?.status}}).find(T=>T.status==="fed")?.representationId;v&&(this.playingRepresentationId=v,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)))}}if(isFinite(this.bufferLimit)&&ns(this.sourceBuffer.buffered)>=this.bufferLimit){let d=this.getForwardBufferDuration(e),h=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,d<h).catch(f=>{this.handleAsyncError(f,"pruneBuffer")});return}let p=[];if(!this.activeSegments.size&&(p=this.selectForwardBufferSegments(r,t.segmentReference.type,o),p.length)){let d="auto";if(this.tuning.dash.useFetchPriorityHints&&n)if((0,mu.default)(p,n))d="high";else{let h=(0,er.default)(p,0);h&&h.time.from-n.time.to>=this.forwardBufferTarget/2&&(d="low")}this.loadSegments(p,t,d).catch(h=>{this.handleAsyncError(h,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&n&&n.status==="fed"&&!p.length&&this.getForwardBufferDuration(e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let c=(0,er.default)(r,-1);!this.isLive&&c&&(this.fullyBuffered$.next(c.time.to-e-this.getForwardBufferDuration(e)<u),this.onLastSegment$.next(e-c.time.from>0))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let i=0,r=this.isLive?this.liveInitialAdditionalOffset:0;for(let a of e)Math.trunc(a.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:a.time.from+r,persistent:!0}),i=a.time.to;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,r=[],a=0,n=t.length-1;do r.unshift(t[n]),a+=t[n].time.to-t[n].time.from,n--;while(a<i&&n>=0);return this.liveInitialAdditionalOffset=a-i,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){let t=e?.streams[this.kind];if(!t)return;let i=(0,bu.default)(t,a=>a.representations).find(a=>a.id===this.downloadingRepresentationId);if(!i)return;let r=this.segments.get(i.id);if(r?.length)return{from:r[0].time.from,to:r[r.length-1].time.to}}updateLive(e){if(!e||[...this.segments.values()].every(i=>!i.length))return;let t=(0,bu.default)(e.streams[this.kind],i=>i.representations);for(let i of t){if(!i||!it(i.segmentReference))return;let r=i.segmentReference.segments.map(l=>({...l,status:"none",size:void 0})),a=100,n=this.segments.get(i.id)??[],o=(0,er.default)(n,-1)?.time.to??0,u=r?.findIndex(l=>o>=l.time.from+a&&o<=l.time.to+a);if(u===-1){this.liveUpdateSegmentIndex=0;let l=this.getActualLiveStartingSegments(i.segmentReference);this.segments.set(i.id,l)}else{let l=r.slice(u+1);this.segments.set(i.id,[...n,...l])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;je(e);let t=this.segments.get(e);if(t?.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}calculateDurationFromSegments(){if(!this.playingRepresentationId)return 0;let e=this.segments.get(this.playingRepresentationId);return(e?(0,er.default)(e,-1)?.time.to:0)||0}setSmartRepresentationSwitch(e){this.useSmartRepresentationSwitch=e}updateLowLatencyLiveIfNeeded(e){let t=0;for(let i of this.representations.values()){let r=i.segmentReference;if(!it(r))return;let a=this.segments.get(i.id)??[],n=a.find(u=>Math.floor(u.time.from)===Math.floor(e.time.from));if(n&&!isFinite(n.time.to)&&(n.time.to=e.time.to,t=n.time.to-n.time.from),!!!a.find(u=>Math.floor(u.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let u=Math.round(e.time.to*r.timescale/1e3).toString(10),l=tt(r.segmentTemplateUrl,{segmentTime:u});a.push({status:"none",time:{from:e.time.to,to:1/0},url:l})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){let t=this.switchingToRepresentationId??this.downloadingRepresentationId??this.playingRepresentationId;if(!t)return;let i=this.segments.get(t);return i?i.find(a=>a.time.from<=e&&a.time.to>=e)?.time.from??void 0:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),this.sourceBufferTaskQueue?.destroy(),this.gapDetectionIdleCallback&&qe&&qe(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&qe&&qe(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(e){if(!(e instanceof DOMException&&e.name==="NotFoundError"))throw e}this.sourceBuffer=null,this.downloadAbortController.abort(),this.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,i){return this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){let i=e.findIndex(r=>t>=r.time.from&&t<r.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=i),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,i){let r=this.getForwardBufferDuration(i),a=e.findIndex(({status:d,time:{from:h,to:f}},m)=>{let S=h<=i&&f>=i,g=h>i||S||m===0&&i===0,v=Math.min(this.forwardBufferTarget,this.bufferLimit),T=this.preloadOnly&&h<=i+v||r<v&&f-h>=v||f<=i+v;return(d==="none"||d==="partially_ejected"&&g&&T&&this.sourceBuffer&&V(this.mediaSource,this.sourceBuffer)&&!(De(this.sourceBuffer.buffered,h)&&De(this.sourceBuffer.buffered,f)))&&g&&T});if(a===-1)return[];if(t!=="byteRange")return e.slice(a,a+1);let n=e,o=0,u=0,l=[],p=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,c=this.preloadOnly?this.forwardBufferTarget:0;for(let d=a;d<n.length&&(o<=p||u<=c);d++){let h=n[d];if(o+=h.byte.to+1-h.byte.from,u+=h.time.to+1-h.time.from,h.status==="none"||h.status==="partially_ejected")l.push(h);else break}return l}async loadSegments(e,t,i="auto"){it(t.segmentReference)?await this.loadTemplateSegment(e[0],t,i):await this.loadByteRangeSegments(e,t,i)}async loadTemplateSegment(e,t,i="auto"){e.status="downloading";let r={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(r);let{range:a,url:n,signal:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await Si(o,async function*(){let p=pp(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,p))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let p=await this.fetcher.fetch(n,{range:a,signal:o,onProgress:u,priority:i,isLowLatency:this.isActiveLowLatency(),bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation});if(this.lastDataObtainedTimestampMs=fu(),!p)return;let c=new DataView(p),d=lt(t.mime);if(!isFinite(r.segment.time.to)){let m=t.segmentReference.timescale;r.segment.time.to=d.getChunkEndTime(c,m)}u&&r.feedingBytes&&l?await Promise.all(l):await this.sourceBufferTaskQueue.append(c,o);let{serverDataReceivedTimestamp:h,serverDataPreparedTime:f}=d.getServerLatencyTimestamps(c);h&&f&&this.currentLiveSegmentServerLatency$.next(f-h),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(p){this.abortActiveSegments([e]),Le(p)||(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())it(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}async loadByteRangeSegments(e,t,i="auto"){if(!e.length)return;for(let u of e)u.status="downloading",this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:r,url:a,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(await Si(n,async function*(){let u=pp(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),dp(window,"online").pipe(B0()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(a,{range:r,onProgress:o,signal:n,priority:i,bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation}),this.lastDataObtainedTimestampMs=fu(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),Le(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(it(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:(0,er.default)(e,0).byte.from,to:(0,er.default)(e,-1).byte.to},{signal:a}=this.downloadAbortController;return{url:i,range:r,signal:a,onProgress:async(o,u)=>{if(!a.aborted)try{this.lastDataObtainedTimestampMs=fu(),await this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:a,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:zt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!it(t.segmentReference))throw new Error("Representation is not template type");let i=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&i.searchParams.set("low-latency","yes");let r=i.toString(),{signal:a}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,p)=>{if(!a.aborted)try{this.lastDataObtainedTimestampMs=fu();let c=this.onSomeTemplateDataLoaded({dataView:l,loaded:p,signal:a,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(c)}catch(c){this.error$.next({id:"SegmentFeeding",category:zt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}}:void 0;return{url:r,signal:a,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,mu.default)(e,t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:a}){if(!this.activeSegments.size||!V(this.mediaSource,this.sourceBuffer))return;let n=this.representations.get(t);if(n)for(let o of this.activeSegments){let{segment:u}=o;if(o.representationId===t){if(a.aborted){r();continue}if(o.loadedBytes=i,o.loadedBytes>o.feedingBytes){let l=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),p=lt(n.mime).parseFeedableSegmentChunk(l,this.isLive);p?.byteLength&&(u.status="partially_fed",o.feedingBytes+=p.byteLength,await this.sourceBufferTaskQueue.append(p),o.fedBytes+=p.byteLength)}}}}async onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:a,onSegmentAppendFailed:n}){if(!this.activeSegments.size||!V(this.mediaSource,this.sourceBuffer))return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){let{segment:l}=u;if(u.representationId!==t)continue;if(a.aborted){await n();continue}let p=l.byte.from-i,c=l.byte.to-i,d=c-p+1,h=p<r,f=c<=r;if(!h)continue;let m=lt(o.mime);if(l.status==="downloading"&&f){l.status="downloaded";let S=new DataView(e.buffer,e.byteOffset+p,d);await this.sourceBufferTaskQueue.append(S,a)&&!a.aborted?this.onSegmentFullyAppended(u,t):await n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(l.status==="downloading"||l.status==="partially_fed")&&(u.loadedBytes=Math.min(d,r-p),u.loadedBytes>u.feedingBytes)){let S=new DataView(e.buffer,e.byteOffset+p+u.feedingBytes,u.loadedBytes-u.feedingBytes),g=u.loadedBytes===d?S:m.parseFeedableSegmentChunk(S);g?.byteLength&&(l.status="partially_fed",u.feedingBytes+=g.byteLength,await this.sourceBufferTaskQueue.append(g,a)&&!a.aborted?(u.fedBytes+=g.byteLength,u.fedBytes===d&&this.onSegmentFullyAppended(u,t)):await n())}}}onSegmentFullyAppended(e,t){if(!(pe(this.sourceBuffer)||!V(this.mediaSource,this.sourceBuffer))){!this.isLive&&$.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(De(this.sourceBuffer.buffered,e.segment.time.from,100)&&De(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:zt.VIDEO_PIPELINE,message:"Browser stuck on empty result of adding segment to source buffer"})),this.tuning.dash.useNewRepresentationSwitch||(this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId))),e.segment.status="fed",ep(e.segment)&&(e.segment.size=e.fedBytes);for(let i of this.representations.values())if(i.id!==t)for(let r of this.segments.get(i.id)??[])r.status==="fed"&&Math.round(r.time.from)===Math.round(e.segment.time.from)&&Math.round(r.time.to)===Math.round(e.segment.time.to)&&(r.status="none");this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}}abortSegment(e){e.status==="partially_fed"?e.status="partially_ejected":e.status!=="partially_ejected"&&(e.status="none");for(let t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[r,a]of this.initData.entries()){let n=a instanceof Promise;t||=n,a===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let i=this.representations.get(e);i&&(this.initLoadIdleCallback=Mt(()=>(0,nE.default)(this.loadInit(i,"low",!1),()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",i=!1){let r=this.tuning.dash.useFetchPriorityHints?t:"auto",a=!i&&this.tuning.dash.ignoreNetworkErrorsOnLoadInit,o=(!i&&this.failedDownloads>0?Si(this.destroyAbortController.signal,async function*(){let u=pp(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>setTimeout(l,u))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,lt(e.mime),{priority:r,ignoreNetworkErrors:a})).then(async u=>{if(!u)return;let{init:l,dataView:p,segments:c}=u,d=p.buffer.slice(p.byteOffset,p.byteOffset+p.byteLength);this.initData.set(e.id,d);let h=c;this.isLive&&it(e.segmentReference)&&(h=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,h),l&&this.parsedInitData.set(e.id,l)}).then(()=>this.failedDownloads=0,u=>{a||this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:zt.WTF,message:"loadInit threw",thrown:u})});return this.initData.set(e.id,o),o}async dropBuffer(){for(let e of this.segments.values())for(let t of e)t.status="none";await this.pruneBuffer(0,1/0,!0)}async pruneBuffer(e,t,i=!1){if(!this.sourceBuffer||!V(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||pe(e))return!1;let r=[],a=0,n=u=>{u.sort((p,c)=>p.from-c.from);let l=[u[0]];for(let p=1;p<u.length;p++){let{from:c,to:d}=u[p],h=l[l.length-1];h.to>=c?h.to=Math.max(h.to,d):l.push(u[p])}return l},o=u=>{if(a>=t)return r;r.push({...u.time}),r=n(r);let l=ep(u)?u.size??0:u.byte.to-u.byte.from;a+=l};for(let u of this.segments.values())for(let l of u){let p=l.time.to<=e-this.tuning.dash.bufferPruningSafeZone,c=l.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(p||c)&&l.status==="fed"&&o(l)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let l=this.sourceBuffer.buffered.start(u)*1e3,p=this.sourceBuffer.buffered.end(u)*1e3,c=0;for(let d of this.segments.values())for(let h of d)(0,mu.default)(["none","partially_ejected"],h.status)&&Math.round(h.time.from)<=Math.round(l)&&Math.round(h.time.to)>=Math.round(p)&&c++;if(c===this.segments.size){let d={time:{from:l,to:p},url:"",status:"none"};o(d)}}if(r.length&&i){let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let l of this.segments.values())for(let p of l)p.time.from>=e+u&&p.status==="fed"&&o(p)}return r.length?(await Promise.all(r.map(l=>this.sourceBufferTaskQueue.remove(l.from,l.to)))).reduce((l,p)=>l||p,!1):!1}async abortBuffer(){if(!this.sourceBuffer||!V(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||!V(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||!V(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||pe(e)?0:de(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!(!this.sourceBuffer||!V(this.mediaSource,this.sourceBuffer)))for(let i of t){let r={representation:e,from:i.time.from,to:i.time.to,persistent:!1},{buffered:a}=this.sourceBuffer;for(let n=0;n<a.length;n++){let o=a.start(n)*1e3,u=a.end(n)*1e3;if(!(u<=i.time.from||o>=i.time.to)){if(o<=i.time.from&&u>=i.time.to){r=void 0;break}u>i.time.from&&u<i.time.to&&(r.from=u),o<i.time.to&&o>i.time.from&&(r.to=o)}}r&&r.to-r.from>1&&!this.gaps.some(n=>r&&n.from===r.from&&n.to===r.to)&&this.gaps.push(r)}}detectGapsWhenIdle(e,t){if(this.gapDetectionIdleCallback||!this.sourceBuffer||!V(this.mediaSource,this.sourceBuffer))return;let{buffered:i}=this.sourceBuffer,{usePersistentGaps:r}=this.tuning.dash;this.gaps=this.gaps.filter(a=>{if(r&&a.persistent)return!0;let n=Math.round(a.from),o=Math.round(a.to);for(let u=0;u<i.length;u++)if(n>=Math.round(i.start(u)*1e3)&&o<=Math.round(i.end(u)*1e3))return!1;return!0}),this.gapDetectionIdleCallback=Mt(()=>{try{this.detectGaps(e,t)}catch(a){this.error$.next({id:"GapDetection",category:zt.WTF,message:"detectGaps threw",thrown:a})}finally{this.gapDetectionIdleCallback=null}})}checkEjectedSegments(){if(pe(this.sourceBuffer)||!V(this.mediaSource,this.sourceBuffer)||pe(this.playingRepresentationId))return;let e=[];for(let i=0;i<this.sourceBuffer.buffered.length;i++){let r=Math.floor(this.sourceBuffer.buffered.start(i)*1e3),a=Math.ceil(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:r,to:a})}let t=100;for(let i of this.segments.values())for(let r of i){let{status:a}=r;if(a!=="fed"&&a!=="partially_ejected")continue;let n=Math.floor(r.time.from),o=Math.ceil(r.time.to),u=e.some(p=>p.from-t<=n&&p.to+t>=o),l=e.filter(p=>n>=p.from&&n<p.to-t||o>p.from+t&&o<=p.to);u||(l.length===1?r.status="partially_ejected":this.gaps.some(p=>p.from===r.time.from||p.to===r.time.to)?r.status="partially_ejected":r.status="none")}}handleAsyncError(e,t){this.error$.next({id:t,category:zt.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}};import{abortable as Ja,assertNever as oE,fromEvent as uE,merge as _0,now as Za,Subject as os,ValueSubject as hp,flattenObject as us,ErrorCategory as en,SubscriptionRemovable as O0}from"@vkontakte/videoplayer-shared/es2024";var Su=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:a=!1}){this.manifestRequested$=new os;this.firstBytesManifest$=new os;this.firstBytesRequested$=new os;this.firstBytesReceived$=new os;this.lastConnectionType$=new hp(void 0);this.lastConnectionReused$=new hp(void 0);this.lastRequestFirstBytes$=new hp(void 0);this.recoverableError$=new os;this.error$=new os;this.abortAllController=new j;this.subscription=new O0;this.fetchManifest=Ja(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=Tt(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=Qr(i)),this.manifestRequested$.next();let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(gu);return r?(t.log("success",us({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(r.headers),this.firstBytesManifest$.next(),r.text()):(t.error("error",us({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=Ja(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:a="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1,bufferOptimisation:l=!1,ignoreNetworkErrors:p=!1}={}){let c=e,d=new Headers,h=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{d.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let I=new URL(c,location.href);I.searchParams.append("bytes",`${i.from}-${i.to}`),c=I.toString();break}default:oE(t)}this.requestQuic&&(c=Tt(c));let f=this.abortAllController.signal,m;if(n){let I=new j;if(m=_0(uE(this.abortAllController.signal,"abort"),uE(n,"abort")).subscribe(()=>{try{I.abort()}catch(N){gu(N)}}),this.subscription.add(m),this.abortAllController.signal.aborted||n.aborted)try{I.abort()}catch(N){gu(N)}f=I.signal}let S=0,g=Za();h.log("startRequest",us({url:c,priority:a,rangeMethod:t,range:i,isLowLatency:u,requestStartedAt:g})),this.firstBytesRequested$.next();let v=yield this.doFetch(c,{priority:a,headers:d,signal:f},{ignoreNetworkErrors:p}),T=Za();if(!v)return h.error("error",{message:"No response in request"}),h.end(),this.unsubscribeAbortSubscription(m),null;if(this.throughputEstimator?.addRawRtt(T-g),!v.ok||!v.body){this.unsubscribeAbortSubscription(m);let I=`Fetch error ${v.status}: ${v.statusText}`;return h.error("error",{message:I}),h.end(),Promise.reject(new Error(`Fetch error ${v.status}: ${v.statusText}`))}if(this.onHeadersReceived(v.headers),!r&&!o){this.unsubscribeAbortSubscription(m);let I=Za(),N={requestStartedAt:g,requestEndedAt:I,duration:I-g};return h.log("endRequest",us(N)),h.end(),v.arrayBuffer()}let y=v.body;if(o){let I;[y,I]=v.body.tee(),this.throughputEstimator?.trackStream(I,u)}let x=y.getReader(),A,R=parseInt(v.headers.get("content-length")??"",10);Number.isFinite(R)&&(A=R),!A&&i&&(A=i.to-i.from+1);let w=A?new Uint8Array(A):new Uint8Array(0),B=!1,k=I=>{this.unsubscribeAbortSubscription(m),B=!0,gu(I)},F=Ja(f,async function*({done:I,value:N}){if(S===0&&(this.lastRequestFirstBytes$.next(Za()-g),this.firstBytesReceived$.next()),f.aborted){this.unsubscribeAbortSubscription(m);return}if(!I&&N){if(l&&A)w.set(N,S),S+=N.byteLength;else{let L=new Uint8Array(w.length+N.length);L.set(w),L.set(N,w.length),w=L,S+=N.byteLength}r?.(new DataView(w.buffer),S),yield x?.read().then(F,k)}}.bind(this));yield x?.read().then(F,k),this.unsubscribeAbortSubscription(m);let C=Za(),E={failed:B,requestStartedAt:g,requestEndedAt:C,duration:C-g};return B?(h.error("endRequest",us(E)),h.end(),null):(h.log("endRequest",us(E)),h.end(),w.buffer)}.bind(this));this.fetchByteRangeRepresentation=Ja(this.abortAllController.signal,async function*(e,t,i){if(e.type!=="byteRange")return null;let{from:r,to:a}=e.initRange,n=r,o=a,u=!1,l,p;e.indexRange&&(l=e.indexRange.from,p=e.indexRange.to,u=a+1===l,u&&(n=Math.min(l,r),o=Math.max(p,a))),n=Math.min(n,0);let c=yield this.fetch(e.url,{range:{from:n,to:o},measureThroughput:!1,...i});if(!c)return null;let d=new DataView(c,r-n,a-n+1);if(!t.validateData(d))throw new Error("Invalid media file");let h=t.parseInit(d),f=e.indexRange??t.getIndexRange(h);if(!f)throw new ReferenceError("No way to load representation index");let m;if(u)m=new DataView(c,f.from-n,f.to-f.from+1);else{let g=yield this.fetch(e.url,{range:f,measureThroughput:!1});if(!g)return null;m=new DataView(g)}let S=t.parseSegments(m,h,f);return{init:h,dataView:new DataView(c),segments:S}}.bind(this));this.fetchTemplateRepresentation=Ja(this.abortAllController.signal,async function*(e,t){if(e.type!=="template")return null;let i=new URL(e.initUrl,e.baseUrl).toString(),r=yield this.fetch(i,{measureThroughput:!1,...t});return r?{init:null,segments:e.segments.map(n=>({...n,status:"none",size:void 0})),dataView:new DataView(r)}:null}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=r,this.tracer=i.createComponentTracer("Fetcher"),this.useEnableSubtitlesParam=a}onHeadersReceived(e){let{type:t,reused:i}=zr(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,t,i){let{type:r}=e;switch(r){case"byteRange":return await this.fetchByteRangeRepresentation(e,t,i)??null;case"template":return await this.fetchTemplateRepresentation(e,i)??null;default:oE(r)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}async doFetch(e,t,i){let r=await Ke(e,t);if(r.ok)return r;if(i?.ignoreNetworkErrors)return;let a=await r.text(),n=parseInt(a);if(!isNaN(n))switch(n){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:en.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:en.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:en.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:en.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${n})`,category:en.FATAL})}}unsubscribeAbortSubscription(e){e&&(e.unsubscribe(),this.subscription.remove(e))}},gu=s=>{if(!Le(s))throw s};import{isNullable as N0,ValueSubject as lE}from"@vkontakte/videoplayer-shared/es2024";var yi=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 lE(e.initial),this.debounced$=new lE(e.initial);let t=e.label??"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new Ne(`raw_${t}`),this.smoothedSeries$=new Ne(`smoothed_${t}`),this.reportedSeries$=new Ne(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,i=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=(this.pastMeasures[o]-this.smoothed)**2,i++);this.takenMeasures=i,t/=i;let r=Math.sqrt(t),a=this.smoothed+this.params.deviationFactor*r,n=this.smoothed-this.params.deviationFactor*r;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>a||this.smoothed<n)&&(N0(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 vu=class extends yi{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=Ft(this.slow,e,this.params.emaAlphaSlow),this.fast=Ft(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var yu=class extends yi{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=Id(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Ft(this.emaSmoothed,e,this.params.emaAlpha);let i=_y(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}};var Tu=class extends yi{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?Ft(this.smoothed,t,this.params.emaAlpha):t}};var Qt=class{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new vu({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new yu({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 Tu({initial:e,label:"liveEdgeDelay",...t})}};var ls=(s,e)=>{s&&s.playbackRate!==e&&(s.playbackRate=e)};import{isNullable as F0,ValueSubject as U0}from"@vkontakte/videoplayer-shared/es2024";var tn=class s{constructor(e,t){this.currentRepresentation$=new U0(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(!F0(e))for(let t of this.representations)for(let i of t){let r=i.segmentReference,a=r.segments.length,n=r.segments[0].time.from,o=r.segments[a-1].time.to;if(e<n||e>o)continue;let u=r.segments.find(l=>l.time.from<=e&&l.time.to>=e);!u||this.currentSegment?.time.from===u.time.from&&this.currentSegment.time.to===u.time.to||(this.currentSegment=u,this.currentRepresentation$.next({...i,label:"Live Text",language:"ru",isAuto:!0,url:new URL(u.url,r.baseUrl).toString()}))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e??[]){let i=s.filterRepresentations(t.representations);if(i){this.representations[this.representationsCursor]=i,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!e?.some(t=>s.filterRepresentations(t.representations))}static filterRepresentations(e){return e?.filter(t=>t.kind==="text"&&"segmentReference"in t&&it(t.segmentReference))}};var W0=["timeupdate","progress","play","seeked","stalled","waiting"],G0=["timeupdate","progress","loadeddata","playing","seeked"];var Eu=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.bufferManagers=[];this.subscription=new dE;this.subscriptionRemovable=new H0;this.representationSubscription=new dE;this.state$=new O("none");this.currentVideoRepresentation$=new ee(void 0);this.currentVideoRepresentationInit$=new ee(void 0);this.currentAudioRepresentation$=new ee(void 0);this.currentVideoSegmentLength$=new ee(0);this.currentAudioSegmentLength$=new ee(0);this.error$=new Gt;this.manifestRequested$=new Gt;this.firstBytesManifest$=new Gt;this.manifestReceived$=new Gt;this.firstBytesRequested$=new Gt;this.firstBytesReceived$=new Gt;this.lastConnectionType$=new ee(void 0);this.lastConnectionReused$=new ee(void 0);this.lastRequestFirstBytes$=new ee(void 0);this.currentLiveTextRepresentation$=new ee(null);this.isLive$=new ee(!1);this.isActiveLive$=new ee(!1);this.isLowLatency$=new ee(!1);this.liveDuration$=new ee(0);this.liveSeekableDuration$=new ee(0);this.liveAvailabilityStartTime$=new ee(0);this.liveStreamStatus$=new ee(void 0);this.bufferLength$=new ee(0);this.liveLatency$=new ee(void 0);this.liveLoadBufferLength$=new ee(0);this.livePositionFromPlayer$=new ee(0);this.currentStallDuration$=new ee(0);this.videoLastDataObtainedTimestamp$=new ee(0);this.fetcherRecoverableError$=new Gt;this.fetcherError$=new Gt;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new Gt;this.gapWatchdogActive=!1;this.liveWasInterrupted=!1;this.destroyController=new j;this.initManifest=fp(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=ne(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:ct.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=fp(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:ct.NETWORK,message:"Failed to load manifest",thrown:u})});if(!e)return null;let t=null;try{t=Xr(e??"",this.manifestUrlString),this.manifestReceived$.next()}catch(u){let l=Hr(e)??{id:"ManifestParsing",category:ct.PARSER,message:"Failed to parse MPD manifest",thrown:u};this.error$.next(l)}if(!t)return null;let i=(u,l,p)=>!!(this.element?.canPlayType?.(l)&&Ve()?.isTypeSupported?.(`${l}; codecs="${p}"`)||u==="text");if(t.live){this.isLive$.next(!0);let{availabilityStartTime:u,latestSegmentPublishTime:l,streamIsUnpublished:p,streamIsAlive:c}=t.live,d=(t.duration??0)/1e3;this.liveSeekableDuration$.next(-1*d),this.liveDuration$.next((l-u)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let h="active";if(c||(h=p?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(h),c&&this.liveWasInterrupted){this.liveWasInterrupted=!1,this.stopStallWatchdogSubscription();let f=this.normalizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(f).catch(m=>{this.error$.next({id:"updateManifest",category:ct.VIDEO_PIPELINE,message:"seekLive after stream restore failed",thrown:m})})}}let r={text:t.streams.text,video:[],audio:[]},a,n;for(let u of["video","audio"]){let p=t.streams[u].filter(({mime:d,codecs:h})=>i(u,d,h));r[u]=p;let c;if(this.tuning.dash.codecsPrioritizeEnabled){let d=p.map(({codecs:h})=>h);u==="audio"&&(n=es(d),c=n[0]),u==="video"&&(a=Zr(d),this.forceVideoCodec&&(0,hE.default)(a,this.forceVideoCodec)?c=this.forceVideoCodec:c=a[0]),c&&(r[u]=p.filter(({codecs:h})=>hi(h)===c))}else{let d=new Set(p.map(({codecs:h})=>h));c=Jr(d),c&&(r[u]=p.filter(({codecs:h})=>h.startsWith(c)))}if(u==="video"){let d=this.tuning.preferHDR,h=r.video.some(m=>m.hdr),f=r.video.some(m=>!m.hdr);$.display.isHDR&&d&&h?r.video=r.video.filter(m=>m.hdr):f&&(r.video=r.video.filter(m=>!m.hdr))}}let o={...t,streams:r};return this.tuning.dash.codecsPrioritizeEnabled&&(o.codecs={video:a,audio:n}),this.tracer.log("updateManifestEnd",sn(o)),o}.bind(this));this.initRepresentations=fp(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initRepresentationsStart",sn({initialVideo:e,initialAudio:t,sourceHls:i})),cs(this.manifest),cs(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let r=c=>{this.representationSubscription.add(Wt(c,"error").pipe(Iu(d=>!!this.element?.played.length)).subscribe(d=>{this.error$.next({id:"VideoSource",category:ct.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:d})}))};this.source=Ir();let a=document.createElement("source");if(r(a),a.src=URL.createObjectURL(this.source),this.element.appendChild(a),ai())if(i){let c=document.createElement("source");r(c),c.type="application/x-mpegurl",c.src=i.url,this.element.appendChild(c)}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((c,d)=>[...c,...d.representations],[]);if(this.videoBufferManager=new Xa("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],an(t)){let c=this.manifest.streams.audio.reduce((d,h)=>[...d,...h.representations],[]);this.audioBufferManager=new Xa("audio",this.source,c,n),this.bufferManagers.push(this.audioBufferManager)}if(tn.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new tn(this.manifest.streams.text,n)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add(tr(...G0.map(c=>Wt(this.element,c))).pipe(ps(c=>this.element?de(this.element.buffered,this.element.currentTime*1e3):0),rn(),z0(c=>{c>this.tuning.dash.bufferEmptinessTolerance&&this.stopStallWatchdogSubscription()})).subscribe(this.bufferLength$)),this.representationSubscription.add(tr(Wt(this.element,"ended"),this.forceEnded$).subscribe(()=>{this.stopStallWatchdogSubscription()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe(rn()).subscribe(d=>this.liveStreamEndTimestamp=bp())),this.subscription.add(Wt(this.element,"pause").subscribe(()=>{let{liveUpdateInterval:d}=this.tuning.dash;this.livePauseWatchdogSubscription=mp(d).subscribe(h=>{let f=si(this.manifestUrlString,2);this.manifestUrlString=ne(this.manifestUrlString,f+d,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add(Wt(this.element,"play").subscribe(d=>this.livePauseWatchdogSubscription?.unsubscribe())),this.representationSubscription.add(ds({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(ps(({isActiveLive:d,isLowLatency:h})=>d&&h),rn()).subscribe(d=>{this.isManualDecreasePlaybackInLive()||ls(this.element,1)})),this.representationSubscription.add(ds({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(Iu(({bufferLength:d,isActiveLive:h,isLowLatency:f})=>h&&f&&!!d)).subscribe(({bufferLength:d})=>this.liveBuffer.next(d))),this.representationSubscription.add(this.videoBufferManager.currentLowLatencySegmentLength$.subscribe(d=>{if(!this.isActiveLive$.getValue()&&!this.isLowLatency$.getValue()&&!d)return;let h=this.liveSeekableDuration$.getValue()-d/1e3;this.liveSeekableDuration$.next(Math.max(h,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+d/1e3)})),this.representationSubscription.add(ds({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(Iu(({isLive:d})=>d),rn((d,h)=>h.bufferLength<d.bufferLength),ps(({rtt:d,bufferLength:h,segmentServerLatency:f})=>{let m=si(this.manifestUrlString,2);return(d/2+h+f+m)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(ds({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:d,isActiveLive:h,isLowLatency:f})=>{if(!f||!h)return;let m=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,S=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,g=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,v=d-m;if(this.isManualDecreasePlaybackInLive())return;let T=1;Math.abs(v)>S&&(T=1+Math.sign(v)*g),ls(this.element,T)})),this.representationSubscription.add(this.bufferLength$.subscribe(d=>{let h=0;if(d){let f=(this.element?.currentTime??0)*1e3;h=Math.min(...this.bufferManagers.map(S=>S.getLiveSegmentsToLoadState(this.manifest)?.to??f))-f}this.liveLoadBufferLength$.getValue()!==h&&this.liveLoadBufferLength$.next(h)}));let c=0;this.representationSubscription.add(ds({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(Q0(this.tuning.dash.liveUpdateInterval)).subscribe(async({liveLoadBufferLength:d,bufferLength:h})=>{if(!this.element||this.isUpdatingLive)return;let f=this.element.playbackRate,m=si(this.manifestUrlString,2),S=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,g=Math.min(S,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*f),v=this.tuning.dashCmafLive.normalizedActualBufferOffset*f,T=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*f,y=isFinite(d)?d:h,x=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),A=S<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(A);let R="none";if(x?R="active_low_latency":this.isLowLatency$.getValue()&&A?(this.bufferManagers.forEach(w=>w.proceedLowLatencyLive()),R="active_low_latency"):m!==0&&y<g?R="live_forward_buffering":y<g+T&&(R="live_with_target_offset"),isFinite(d)&&(c=d>c?d:c),R==="live_forward_buffering"||R==="live_with_target_offset"){let w=c-(g+v),B=this.normalizeLiveOffset(Math.trunc(m+w/f)),k=Math.abs(B-m),F=0;!d||k<=this.tuning.dashCmafLive.offsetCalculationError?F=m:B>0&&k>this.tuning.dashCmafLive.offsetCalculationError&&(F=B),this.manifestUrlString=ne(this.manifestUrlString,F,2)}(R==="live_with_target_offset"||R==="live_forward_buffering")&&(c=0,await this.updateLive())},d=>{this.error$.next({id:"updateLive",category:ct.VIDEO_PIPELINE,thrown:d,message:"Failed to update live with subscription"})}))}let u=tr(...this.bufferManagers.map(c=>c.fullyBuffered$)).pipe(ps(()=>this.bufferManagers.every(c=>c.fullyBuffered$.getValue()))),l=tr(...this.bufferManagers.map(c=>c.onLastSegment$)).pipe(ps(()=>this.bufferManagers.some(c=>c.onLastSegment$.getValue()))),p=ds({allBuffersFull:u,someBufferEnded:l}).pipe(rn(),ps(({allBuffersFull:c,someBufferEnded:d})=>c&&d),Iu(c=>c));if(this.representationSubscription.add(tr(this.forceEnded$,p).subscribe(()=>{if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(c=>!c.updating))try{this.source?.endOfStream()}catch(c){this.error$.next({id:"EndOfStream",category:ct.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:c})}})),this.representationSubscription.add(tr(...this.bufferManagers.map(c=>c.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 c=this.tuning.dash.sourceOpenTimeout>=0;yield new Promise(d=>{c&&(this.timeoutSourceOpenId=setTimeout(()=>{if(this.source?.readyState==="open"){d();return}this.error$.next({id:"OpenOfStream",category:ct.VIDEO_PIPELINE,message:"Failed to open MediaSource",thrown:new Error("Timeout reject when wait sourceopen event"),traceAsLog:!0})},this.tuning.dash.sourceOpenTimeout)),this.source?.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),d()},{once:!0})})}if(!this.isLive$.getValue()){let c=[this.manifest.duration??0,...(0,gp.default)((0,gp.default)([...this.manifest.streams.audio,...this.manifest.streams.video],d=>d.representations),d=>{let h=[];return d.duration&&h.push(d.duration),it(d.segmentReference)&&d.segmentReference.totalSegmentsDurationMs&&h.push(d.segmentReference.totalSegmentsDurationMs),h})];this.source.duration=Math.max(...c)/1e3}this.audioBufferManager&&an(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=mp(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:ct.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 Su({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.subscription.add(this.fetcher.recoverableError$.subscribe(this.fetcherRecoverableError$)),this.subscription.add(this.fetcher.error$.subscribe(this.fetcherError$)),this.subscription.add(this.fetcher.manifestRequested$.subscribe(this.manifestRequested$)),this.subscription.add(this.fetcher.firstBytesManifest$.subscribe(this.firstBytesManifest$)),this.subscription.add(this.fetcher.firstBytesRequested$.subscribe(this.firstBytesRequested$)),this.subscription.add(this.fetcher.firstBytesReceived$.subscribe(this.firstBytesReceived$)),this.subscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.subscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.liveBuffer=Qt.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator}),this.initTracerSubscription()}setSmartRepresentationSwitch(e){this.bufferManagers.forEach(t=>t.setSmartRepresentationSwitch(e))}async seekLive(e){cs(this.element),this.updateManifestUrlWithTimeOffset(e),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await this.updateLiveBuffersFromManifest(this.manifest))}updateManifestUrlWithTimeOffset(e){let t=this.liveStreamStatus$.getValue()!=="active"?bp()-this.liveStreamEndTimestamp:0,i=this.normalizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=ne(this.manifestUrlString,i,2)}async updateLiveBuffersFromManifest(e){await this.videoBufferManager?.seekLive(e.streams.video),await this.audioBufferManager?.seekLive(e.streams.audio),this.liveTextManager?.seekLive(e.streams.text)}stopStallWatchdogSubscription(){this.stallWatchdogSubscription?.unsubscribe(),this.currentStallDuration$.next(0)}initBuffer(){cs(this.element),this.state$.setState("running"),this.subscription.add(tr(...W0.map(e=>Wt(this.element,e)),Wt(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:ct.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(Wt(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(Wt(this.element,"waiting").subscribe(()=>{this.tuning.dash.useVideoElementWaitingCurrentTimeReassign&&this.element&&this.element.readyState===2&&!this.element.seeking&&De(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{let{keepSilentStallWatchdogWhenNotActive:t}=this.tuning.dashCmafLive,{crashOnStallTimeout:i,crashOnStallTWithoutDataTimeout:r,liveStallReinitInterval:a,stallWatchdogInterval:n}=this.tuning.dash,o=this.isLive$.getValue(),l=this.liveStreamStatus$.getValue()==="active";if(!this.element||this.source?.readyState!=="open")return;let p=this.currentStallDuration$.getValue();p+=n,this.currentStallDuration$.next(p);let c={timeInWaiting:p},d=bp(),h=100,f=this.videoBufferManager?.lastDataObtainedTimestamp??0;this.videoLastDataObtainedTimestamp$.next(f);let m=this.audioBufferManager?.lastDataObtainedTimestamp??0,S=this.videoBufferManager?.getForwardBufferDuration()??0,g=this.audioBufferManager?.getForwardBufferDuration()??0,v=S<h&&d-f>r,T=this.audioBufferManager&&g<h&&d-m>r;if((!t||l)&&((v||T)&&p>r||p>=i))throw new Error(`Stall timeout exceeded: ${p} ms`);if(o&&p%a===0){let y=this.normalizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);!l&&t?(this.liveWasInterrupted=!0,this.updateManifestUrlWithTimeOffset(y),this.updateManifest()):this.seekLive(y).catch(x=>{this.error$.next({id:"stallIntervalCallback",category:ct.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:x})}),c.liveLastOffset=y}else{let y=this.element.currentTime*1e3;this.videoBufferManager?.maintain(y),this.audioBufferManager?.maintain(y),c.position=y}this.tracer.log("stallIntervalCallback",sn(c))};this.stallWatchdogSubscription&&(this.stallWatchdogSubscription.unsubscribe(),this.subscriptionRemovable.remove(this.stallWatchdogSubscription)),this.stallWatchdogSubscription=mp(this.tuning.dash.stallWatchdogInterval).subscribe(e,t=>{this.error$.next({id:"StallWatchdogCallback",category:ct.NETWORK,message:"Can't restore DASH after stall.",thrown:t})}),this.subscriptionRemovable.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,i=!1){let r={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return this.tuning.useNewSwitchTo?this.currentStallDuration$.getValue()>0?r?.switchToWithPreviousAbort(t,i):r?.switchTo(t,i):r?.switchToOld(t,i)}async seek(e,t){cs(this.element),cs(this.videoBufferManager);let i;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?i=e:i=Math.max(this.videoBufferManager.findSegmentStartTime(e)??e,this.audioBufferManager?.findSegmentStartTime(e)??e),this.warmUpMediaSourceIfNeeded(i),De(this.element.buffered,i)||await Promise.all([this.videoBufferManager.abort(),this.audioBufferManager?.abort()]),!(cE(this.element)||cE(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),this.audioBufferManager?.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",sn({requestedPosition:e,forcePrecise:t,position:i})))}warmUpMediaSourceIfNeeded(e=this.element?.currentTime){an(this.element)&&an(this.source)&&an(e)&&this.source?.readyState==="ended"&&this.element.duration*1e3-e>this.tuning.dash.seekBiasInTheEnd&&this.bufferManagers.forEach(t=>t.warmUpMediaSource())}get isStreamEnded(){return this.source?.readyState==="ended"}stop(){this.tracer.log("stop"),this.element?.querySelectorAll("source").forEach(e=>{URL.revokeObjectURL(e.src),e.remove()}),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),this.videoBufferManager?.destroy(),this.videoBufferManager=null,this.audioBufferManager?.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){return this.manifest?.streams}getCodecs(){return this.manifest?.codecs}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){this.subscription.unsubscribe(),this.subscriptionRemovable.unsubscribe(),this.representationSubscription.unsubscribe(),this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),this.source?.readyState==="open"&&Array.from(this.source.sourceBuffers).every(e=>!e.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=j0(this.tracer.error.bind(this.tracer));this.subscription.add(this.error$.subscribe(e("error")))}isManualDecreasePlaybackInLive(){if(!this.element||!this.isLive$.getValue())return!1;let e=1-this.element.playbackRate;return Number(e.toFixed(2))>Number(this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup.toFixed(2))}normalizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&(this.bufferManagers.forEach(e=>e.updateLive(this.manifest)),this.liveTextManager?.updateLive(this.manifest)),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getDebugBufferState();if(!e)return;let t=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),i={isJumpGapAfterSeekLive:this.isJumpGapAfterSeekLive,isActiveLowLatency:t,initialCurrentTime:this.element.currentTime},{usePersistentGaps:r}=this.tuning.dash;this.isJumpGapAfterSeekLive&&!t&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let a=this.element.currentTime*1e3,n=[],o=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let u of this.bufferManagers)for(let l of u.gaps)(r&&l.persistent||u.playingRepresentation$.getValue()===l.representation)&&l.from-o<=a&&l.to+o>a&&(this.element.duration*1e3-l.to<this.tuning.endGapTolerance?n.push(1/0):n.push(l.to));if(n.length){let u=Math.max(...n)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,u===1/0?this.forceEnded$.next():(this.element.currentTime=u/1e3,i={...i,gapEnds:n,jumpTo:u,resultCurrentTime:this.element.currentTime},this.tracer.log("jumpGap",sn(i)))}}calculateDurationFromSegments(){return Math.max(this.videoBufferManager?.calculateDurationFromSegments()||0,this.audioBufferManager?.calculateDurationFromSegments()||0)}};import{combine as Y0,map as K0,observeElementSize as X0,Subscription as J0,ValueSubject as Sp,noop as Z0}from"@vkontakte/videoplayer-shared/es2024";var wu=class{constructor(){this.subscription=new J0;this.pipSize$=new Sp(void 0);this.videoSize$=new Sp(void 0);this.elementSize$=new Sp(void 0);this.pictureInPictureWindowRemoveEventListener=Z0}connect({observableVideo:e,video:t}){let i=r=>{let a=r.target;this.pipSize$.next({width:a.width,height:a.height})};this.subscription.add(X0(t).subscribe(this.videoSize$)).add(e.enterPip$.subscribe(({pictureInPictureWindow:r})=>{this.pipSize$.next({width:r.width,height:r.height}),r.addEventListener("resize",i),this.pictureInPictureWindowRemoveEventListener=()=>{r.removeEventListener("resize",i)}})).add(e.leavePip$.subscribe(()=>{this.pictureInPictureWindowRemoveEventListener()})).add(Y0({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(K0(({videoSize:r,inPip:a,pipSize:n})=>a?n:r)).subscribe(this.elementSize$))}getValue(){return this.elementSize$.getValue()}subscribe(e,t){return this.elementSize$.subscribe(e,t)}getObservable(){return this.elementSize$}destroy(){this.pictureInPictureWindowRemoveEventListener(),this.subscription.unsubscribe()}};var ir=class{constructor(e){this.subscription=new o_;this.videoState=new O("stopped");this.observableVideo=null;this.droppedFramesManager=new li;this.stallsManager=new qr;this.elementSizeManager=new wu;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new yt;this.audioTrackSwitchHistory=new yt;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(r.state==="requested"&&i?.to!=="paused"&&e!=="stopped"&&t!=="stopped"&&this.seek(r.position,r.forcePrecise),t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.currentNativeBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),P(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"),P(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="ready"&&P(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"&&P(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&P(this.params.desiredState.playbackState,"paused");return;default:return t_(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new di(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 We(e.source.url),this.params=e,this.video=Pe(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(ce(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.player=new Eu({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer,forceVideoCodec:this.params.forceVideoCodec}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params;n_(this.observableVideo)&&(this.observableVideo=$e(this.video),this.subscription.add(()=>this.observableVideo?.destroy()));let i=this.constructor.name,r=n=>{e.error$.next({id:i,category:fE.WTF,message:`${i} internal logic error`,thrown:n})},a=(n,o)=>this.subscription.add(n.subscribe(o,r));return{output:e,desiredState:t,observableVideo:this.observableVideo,genericErrorListener:r,connect:a}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:a}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(vp(c=>!!c.length),bE()).subscribe(c=>{this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:c})}));let n=this.params.desiredState.seekState.stateChangeEnded$.pipe(on(c=>c.to.state!=="none"),nn());this.stallsManager.init({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$,videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,tuning:this.params.tuning.stallsManager,abrParams:this.params.tuning.autoTrackSelection,isBuffering$:i.isBuffering$,looped$:i.looped$,playing$:i.playing$,duration:this.video.duration}),a(i.ended$,e.endedEvent$),a(i.looped$,e.loopedEvent$),a(i.error$,e.error$),a(i.isBuffering$,e.isBuffering$),a(i.currentBuffer$,e.currentBuffer$),a(i.currentBuffer$,e.currentNativeBuffer$),a(i.playing$,e.firstFrameEvent$),a(i.canplay$,e.canplay$),a(i.inPiP$,e.inPiP$),a(i.inFullscreen$,e.inFullscreen$),a(i.loadedMetadata$,e.loadedMetadataEvent$),a(this.player.error$,e.error$),a(this.player.fetcherRecoverableError$,e.fetcherRecoverableError$),a(this.player.fetcherError$,e.fetcherError$),a(this.player.manifestRequested$,e.manifestRequested$),a(this.player.firstBytesManifest$,e.firstBytesManifest$),a(this.player.manifestReceived$,e.manifestReceived$),a(this.player.firstBytesRequested$,e.firstBytesRequested$),a(this.player.firstBytesReceived$,e.firstBytesReceived$),a(this.player.lastConnectionType$,e.httpConnectionType$),a(this.player.lastConnectionReused$,e.httpConnectionReused$),a(this.player.isLive$,e.isLive$),a(this.player.lastRequestFirstBytes$.pipe(vp(mE),bE()),e.firstBytesEvent$),a(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),a(this.videoState.stateChangeEnded$.pipe(on(c=>c.to)),this.params.output.playbackState$),this.subscription.add(i.looped$.subscribe(()=>this.player.warmUpMediaSourceIfNeeded(),r)),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(ot(this.video,t.isLooped,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),pi({subscription:this.subscription,desiredState:t,videoElement$:this.params.output.element$,observableVideo:i}),this.subscription.add(Re(this.video,t.volume,i.volumeState$,r)),this.subscription.add(Qe(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),a(Ye(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),P(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),P(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(i.ended$.subscribe(()=>{this.videoState.setState("paused"),P(t.playbackState,"paused")})),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 d=this.player.getStreams(),h=this.player.getCodecs();if(i_(d,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let m=[];for(let S of d.audio){m.push(Jd(S));let g=[];for(let v of S.representations){let T=Ha(v);g.push(T),this.audioTracksMap.set(T,{stream:S,representation:v})}this.audioStreamsMap.set(S,g)}this.params.output.availableAudioStreams$.next(m)}let f=[];for(let m of d.video){f.push(Zd(m));let S=[];for(let g of m.representations){let v=mi({...g,streamId:m.id});v&&(S.push(v),this.videoTracksMap.set(v,{stream:m,representation:g}))}this.videoStreamsMap.set(m,S)}this.params.output.availableVideoStreams$.next(f);for(let m of d.text)for(let S of m.representations){let g=FI(m,S);this.textTracksMap.set(g,{stream:m,representation:S})}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),h?.video&&this.params.output.availableVideoCodecs$.next(h.video),h?.audio&&this.params.output.availableAudioCodecs$.next(h.audio),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else c==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r));let o=un(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$,a_(this.video,"progress")).pipe(vp(()=>this.videoTracksMap.size>0)),{abrThrottle:u}=this.params.tuning.dash;u&&(o=o.pipe(u_(u))),this.subscription.add(o.subscribe(async()=>{let c=this.player.state$.getState(),d=this.player.state$.getTransition();if(c!=="manifest_ready"&&c!=="running"||d)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let h=this.selectVideoAudioRepresentations();if(!h)return;let[f,m]=h,S=[...this.videoTracksMap.keys()].find(v=>this.videoTracksMap.get(v)?.representation.id===f.id);mE(S)&&(this.stallsManager.lastVideoTrackSelected=S);let g=this.params.desiredState.autoVideoTrackLimits.getTransition();if(g&&this.params.output.autoVideoTrackLimits$.next(g.to),c==="manifest_ready")await this.player.initRepresentations(f.id,m?.id,this.params.sourceHls);else if(await this.player.switchRepresentation("video",f.id),m){let v=!!t.audioStream.getTransition();await this.player.switchRepresentation("audio",m.id,v)}},r)),this.subscription.add(r_({videoState:this.videoState.stateChangeEnded$,autoVideoTrackState:un(xu([t.autoVideoTrackSwitching.getState()]),t.autoVideoTrackSwitching.stateChangeEnded$.pipe(on(c=>c.to)))}).pipe(on(({videoState:c,autoVideoTrackState:d})=>c.to!=="stopped"&&d),nn()).subscribe(c=>this.player.setSmartRepresentationSwitch(c))),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(nn()).subscribe(c=>{let d=[...this.videoTracksMap.entries()].find(([,{representation:g}])=>g.id===c);if(!d){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[h,{stream:f}]=d,m=this.params.desiredState.videoStream.getTransition();m&&m.to&&m.to.id===f.id&&this.params.desiredState.videoStream.setState(m.to),e.currentVideoTrack$.next(h),e.currentVideoStream$.next(Zd(f));let S=this.player.calculateDurationFromSegments();S&&this.params.output.duration$.next(S/1e3)},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(nn()).subscribe(c=>{let d=[...this.audioTracksMap.entries()].find(([,{representation:S}])=>S.id===c);if(!d){e.currentAudioStream$.next(void 0);return}let[h,{stream:f}]=d,m=this.params.desiredState.audioStream.getTransition();m&&m.to&&m.to.id===f.id&&this.params.desiredState.audioStream.setState(m.to),e.currentAudioStream$.next(Jd(f))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(c=>{if(c?.is3dVideo&&this.params.tuning.spherical?.enabled)try{this.init3DScene(c),e.is3DVideo$.next(!0)}catch(d){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${d}`})}else this.destroy3DScene(),this.params.tuning.spherical?.enabled&&e.is3DVideo$.next(!1)},r)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,r)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,r)),this.textTracksManager.connect(this.video,t,e);let l=t.playbackState.stateChangeStarted$.pipe(on(({to:c})=>c==="ready"),nn());this.subscription.add(un(l,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,xu(["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(un(l,this.player.state$.stateChangeEnded$,xu(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let p=un(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,xu(["init"])).pipe(s_(0));this.subscription.add(p.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?Qi:zi,t=this.params.tuning.useNewAutoSelectVideoTrack?Fr:Nr,i=this.params.tuning.useNewAutoSelectVideoTrack?ut:Or,{desiredState:r,output:a}=this.params,n=r.autoVideoTrackSwitching.getState(),o=r.videoTrack.getState()?.id,u=[...this.videoTracksMap.keys()].find(({id:w})=>w===o),l=a.currentVideoTrack$.getValue(),p=r.videoStream.getState()??(u&&this.videoTracksMap.get(u)?.stream)??this.videoStreamsMap.size===1?this.videoStreamsMap.keys().next().value:void 0;if(!p)return;let c=[...this.videoStreamsMap.keys()].find(({id:w})=>w===p.id),d=c&&this.videoStreamsMap.get(c);if(!d)return;let h=de(this.video.buffered,this.video.currentTime*1e3),f;this.player.isActiveLive$.getValue()?f=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?f=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:f=n?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let m=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,S=Math.min(h/Math.min(f,m||1/0),1),g=r.audioStream.getState()??(this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0),v=[...this.audioStreamsMap.keys()].find(({id:w})=>w===g?.id)??this.audioStreamsMap.keys().next().value,T=0;if(v){if(u&&!n){let w=e(u,d,this.audioStreamsMap.get(v)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);T=Math.max(T,w?.bitrate??-1/0)}if(l){let w=e(l,d,this.audioStreamsMap.get(v)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);T=Math.max(T,w?.bitrate??-1/0)}}let y=u;(n||!y)&&(y=i(d,{container:this.elementSizeManager.getValue(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.stallsManager.abrTuningParams,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:T,forwardBufferHealth:S,current:l,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,stallsVideoMaxQualityLimit:this.stallsManager.videoMaxQualityLimit,stallsPredictedThroughput:this.stallsManager.predictedThroughput,abrLogger:this.params.dependencies.abrLogger}));let x=v&&t(y,d,this.audioStreamsMap.get(v)??[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.stallsManager.abrTuningParams,forwardBufferHealth:S,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),A=this.videoTracksMap.get(y)?.representation,R=x&&this.audioTracksMap.get(x)?.representation;if(A&&R)return[A,R];if(A&&!R&&this.audioTracksMap.size===0)return[A,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Me(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:fE.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),Ae(this.video),this.tracer.end()}};var ln=class extends ir{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 yp,merge as gE,filter as SE,filterChanged as vE,isNullable as Tp,map as yE,ValueSubject as Ip,isNonNullable as l_}from"@vkontakte/videoplayer-shared/es2024";var cn=class extends ir{constructor(e){super(e),this.textTracksManager.destroy()}subscribe(){super.subscribe();let e=!1,t=-1,{output:i,observableVideo:r,desiredState:a,connect:n}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canPlayLiveTailBuffer$.next(!0),n(r.timeUpdate$,i.liveBufferTime$),n(this.player.liveSeekableDuration$,i.duration$),n(this.player.liveLatency$,i.liveLatency$);let o=new Ip(1);n(r.playbackRateState$,o),this.params.tuning.dashCmafLive.catchupLiveForMutedInactiveTab&&this.subscription.add(i.elementVisible$.pipe(vE()).subscribe(u=>{let l=i.position$.getValue(),p=i.volume$.getValue(),c=!p.volume||p.muted;!u&&!l&&c?e=!0:u&&e&&(this.seek(0),e=!1)})),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(a.isLowLatency.stateChangeEnded$.pipe(yE(u=>u.to)).subscribe(this.player.isLowLatency$)).add(yp({liveBufferTime:i.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(yE(({liveBufferTime:u,liveAvailabilityStartTime:l})=>u&&l?u*1e3+l+t:void 0)).subscribe(i.liveTime$)).add(yp({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:gE(r.playbackRateState$,new Ip(1))}).pipe(SE(({liveStreamStatus:u,liveDuration:l})=>u==="active"&&!!l)).subscribe(({liveDuration:u,playbackRate:l})=>{let p=i.liveBufferTime$.getValue(),c=i.position$.getValue(),{playbackCatchupSpeedup:d}=this.params.tuning.dashCmafLive.lowLatency;c||l<1-d||this.video.paused||Tp(p)||(t=u-p)})).add(yp({time:i.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:gE(r.playbackRateState$,new Ip(1))}).pipe(vE((u,l)=>this.player.liveStreamStatus$.getValue()==="active"?u.liveDuration===l.liveDuration:u.time===l.time)).subscribe(({time:u,liveDuration:l,playbackRate:p})=>{let c=i.position$.getValue(),{playbackCatchupSpeedup:d}=this.params.tuning.dashCmafLive.lowLatency;if(!c&&!this.video.paused&&p>=1-d||Tp(u)||Tp(l))return;let h=-1*(l-u-t);i.position$.next(Math.min(h,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(u=>{if(u){let l=UI(u);this.params.output.availableTextTracks$.next([l])}})),this.params.tuning.dashCmafLive.externalStopControl||this.subscription.add(this.player.liveStreamStatus$.pipe(SE(u=>l_(u))).subscribe(u=>i.isLiveEnded$.next(u==="unpublished"&&i.position$.getValue()===0)))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=Math.trunc(t/1e3<=Math.abs(this.params.output.duration$.getValue())?t:0);this.player.seekLive(i).then(()=>{this.params.output.position$.next(e/1e3)})}};import{assertNever as __,assertNonNullable as O_,combine as N_,debounce as F_,ErrorCategory as _E,filter as Op,filterChanged as yn,fromEvent as U_,isNonNullable as OE,isNullable as q_,map as Tn,merge as In,observableFrom as Vu,once as NE,Subscription as j_}from"@vkontakte/videoplayer-shared/es2024";var VE=D(ke(),1),Vp=D(Wi(),1);import{abortable as Lp,assertNonNullable as ms,combine as bs,ErrorCategory as Et,filter as Du,filterChanged as gn,flattenObject as Sn,fromEvent as Dt,getTraceSubscriptionMethod as k_,interval as Dp,isNonNullable as vn,isNullable as BE,map as gs,merge as or,now as Bp,Subject as Yt,Subscription as Cp,SubscriptionRemovable as P_,tap as A_,throttle as CE,ValueSubject as te}from"@vkontakte/videoplayer-shared/es2024";var Ru=D(ke(),1),nr=D(Ge(),1),$u=D(Wi(),1);var $E=D(Ro(),1);import{assertNever as c_,ErrorCategory as TE,Subject as IE}from"@vkontakte/videoplayer-shared/es2024";var d_=18,EE=!1;try{EE=$.browser.isSafari&&!!$.browser.safariVersion&&$.browser.safariVersion<=d_}catch(s){console.error(s)}var Ep=class{constructor(e,t=!1){this.bufferFull$=new IE;this.error$=new IE;this.queue=[];this.currentTask=null;this.destroyed=!1;this.abortRequested=!1;this.isAbortFixEnabled=!1;this.completeTask=()=>{try{if(this.currentTask){let e=this.currentTask.signal?.aborted;this.currentTask.callback(!e),this.currentTask=null,this.isAbortFixEnabled&&this.queue.shift()}this.queue.length&&this.pull()}catch(e){this.error$.next({id:"BufferTaskQueueUnknown",category:TE.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:e})}};this.buffer=e,this.isAbortFixEnabled=t,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(i=>{let r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(r=>{let a={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(a),this.pull()})}async abort(e){return new Promise(t=>{let i,r=a=>{this.abortRequested=!1,t(a)};EE&&e?i={operation:"safariAbort",init:e,callback:r}:i={operation:"abort",callback:r};for(let{callback:a}of this.queue)a(!1);this.abortRequested=!0,i&&(this.queue=[i]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){if((this.buffer.updating||this.currentTask||this.destroyed)&&!this.abortRequested)return;let e=this.isAbortFixEnabled?this.queue[0]:this.queue.shift();if(!e)return;if(e.signal?.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(r){r instanceof DOMException&&r.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):r instanceof DOMException&&r.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:TE.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:r}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){let{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:c_(t)}}},wE=Ep;import{abortable as Ti,assertNonNullable as He,ErrorCategory as sr,fromEvent as Ap,getExponentialDelay as Rp,isHigher as b_,isNonNullable as Ii,isNullable as he,now as Au,once as g_,Subject as S_,Subscription as v_,ValueSubject as ar}from"@vkontakte/videoplayer-shared/es2024";var wp=D(Ge(),1);import{videoSizeToQuality as p_,throttleFn as h_}from"@vkontakte/videoplayer-shared/es2024";var dn=({id:s,width:e,height:t,bitrate:i,fps:r,quality:a,streamId:n})=>{let o=(a?$t(a):void 0)??p_({width:e,height:t});return o&&{id:s,quality:o,bitrate:i,size:{width:e,height:t},fps:r,streamId:n}},xE=({id:s,bitrate:e})=>({id:s,bitrate:e}),kE=({language:s,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:s,label:e}),PE=({language:s,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:s,label:e}),xp=({id:s,language:e,label:t,codecs:i,isDefault:r})=>({id:s,language:e,label:t,codec:(0,wp.default)(i.split("."),0),isDefault:r}),kp=({id:s,language:e,label:t,hdr:i,codecs:r})=>({id:s,language:e,hdr:i,label:t,codec:(0,wp.default)(r.split("."),0)}),Pp=s=>"url"in s,rt=s=>s.type==="template";var AE=s=>{s.sort((t,i)=>t.from-i.from);let e=[s[0]];for(let t=1;t<s.length;t++){let{from:i,to:r}=s[t],a=e[e.length-1];a.to>=i?a.to=Math.max(a.to,r):e.push(s[t])}return e},rr=(s,e)=>{for(let t of s)if(e(t))return t;return null},RE=s=>{let e=!1,t=h_(()=>{e=!0},s);return()=>{try{return t(),e}finally{e=!1}}};import{fromEvent as f_,Subscription as m_}from"@vkontakte/videoplayer-shared/es2024";var ku=s=>{let e=[];for(let t=0;t<s.length;t++){let i=Math.floor(s.start(t)*1e3),r=Math.ceil(s.end(t)*1e3);e.push(i,r)}return e};var Pu=class{constructor(e,t){this.lastUpdateTs=0;this.lastCallTs=0;this.prevRanges=[];this.subscription=new m_;this.mediaSource=e,this.sourceBuffer=t,this.subscription.add(f_(this.sourceBuffer,"updateend").subscribe(()=>this.updateend()))}updateend(){if(!V(this.mediaSource,this.sourceBuffer))return;let{prevRanges:e}=this,t=ku(this.sourceBuffer.buffered);this.prevRanges=t,this.isRangesRemoved(e,t)&&(this.lastUpdateTs=Date.now())}isRangesRemoved(e,t){if(e.length!==t.length)return!0;for(let i=0;i<e.length;i+=2){let r=e[i],a=e[i+1],n=t[i],o=t[i+1];if(n>r||o<a)return!0}return!1}wasUpdated(){let{lastCallTs:e,lastUpdateTs:t}=this;return this.lastCallTs=Date.now(),e<=t}destroy(){this.subscription.unsubscribe()}};var pn=class{constructor(e,t,i,{fetcher:r,tuning:a,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new ar(0);this.currentLowLatencySegmentLength$=new ar(0);this.currentSegmentLength$=new ar(0);this.onLastSegment$=new ar(!1);this.fullyBuffered$=new ar(!1);this.playingRepresentation$=new ar(void 0);this.playingRepresentationInit$=new ar(void 0);this.error$=new S_;this.gaps=[];this.subscription=new v_;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new j;this.switchAbortController=new j;this.destroyAbortController=new j;this.useSmartRepresentationSwitch=!1;this.bufferLimit=1/0;this.failedDownloads=0;this.baseUrls=[];this.baseUrlsIndex=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.lastDataObtainedTimestampMs=0;this.loadByteRangeSegmentsTimeoutId=0;this.sourceBufferBufferedDiff=null;this.startWith=Ti(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);He(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new wE(this.sourceBuffer,this.tuning.dash.useAbortMSEFix),this.sourceBufferBufferedDiff=new Pu(this.mediaSource,this.sourceBuffer),this.subscription.add(Ap(this.sourceBuffer,"updateend").subscribe(()=>{this.maintain()})),this.subscription.add(Ap(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:sr.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o||!V(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,ns(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=de(this.sourceBuffer.buffered,o),p=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,n*2,l<p).catch(c=>{this.handleAsyncError(c,"pruneBuffer")})})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);let i=this.initData.get(t.id),r=this.segments.get(t.id),a=this.parsedInitData.get(t.id);He(i,"No init buffer for starting representation"),He(r,"No segments for starting representation"),i instanceof ArrayBuffer&&(this.searchGaps(r,t),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(a))}.bind(this));this.switchTo=Ti(this.destroyAbortController.signal,async function*(e,t=!1){if(!V(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);He(i,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if(he(a)||he(r)?yield this.loadInit(i,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),He(r,"No segments for starting representation"),a=this.initData.get(e),!(!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer||!V(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(a,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer();else{let n=this.getCurrentPosition();Ii(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=Ti(this.destroyAbortController.signal,async function*(e,t=!1){if(!V(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);He(i,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if(he(a)||he(r)?yield this.loadInit(i,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),He(r,"No segments for starting representation"),a=this.initData.get(e),!(!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer||!V(this.mediaSource,this.sourceBuffer)))if(yield this.abort(),yield this.sourceBufferTaskQueue.append(a,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let n=this.getCurrentPosition();Ii(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=Ti(this.destroyAbortController.signal,async function*(e){let t=(0,$u.default)(e,u=>u.representations);if(!this.downloadingRepresentationId||!t.length)return;this.isSeekingLive=!0;for(let u of this.representations.keys()){let l=t.find(d=>d.id===u);l&&this.representations.set(u,l);let p=this.representations.get(u);if(!p||!rt(p.segmentReference)){this.isSeekingLive=!1;return}let c=this.getActualLiveStartingSegments(p.segmentReference);this.segments.set(p.id,c)}let i=this.switchingToRepresentationId??this.downloadingRepresentationId,r=this.representations.get(i);He(r,`Representation not found by id ${i}`);let a=this.segments.get(i);He(a,"No segments for starting representation");let n=this.initData.get(i);if(He(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer)){this.isSeekingLive=!1;return}let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(a,r),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));this.fetcher=r,this.tuning=a,this.compatibilityMode=u,this.forwardBufferTarget=a.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!l?.live,this.baseUrls=l?.baseUrls??[],this.initData=new Map(i.map(p=>[p.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(p=>[p.id,p])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchToWithPreviousAbort(e,t=!1){!V(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new j,Ti(this.switchAbortController.signal,async function*(i,r=!1){this.switchingToRepresentationId=i;let a=this.representations.get(i);He(a,`No such representation ${i}`);let n=this.segments.get(i),o=this.initData.get(i);if(he(o)||he(n)?yield this.loadInit(a,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(i),He(n,"No segments for starting representation"),o=this.initData.get(i),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer||!V(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(o,this.downloadAbortController.signal),r)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=i,yield this.dropBuffer();else{let u=this.getCurrentPosition();Ii(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 j,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(he(e)||he(this.downloadingRepresentationId)||he(this.playingRepresentationId)||he(this.sourceBuffer)||!V(this.mediaSource,this.sourceBuffer)||Ii(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.representations.get(this.playingRepresentationId),r=this.segments.get(this.downloadingRepresentationId),a=this.segments.get(this.playingRepresentationId);if(He(t,`No such representation ${this.downloadingRepresentationId}`),He(i,`No such representation ${this.playingRepresentationId}`),he(r)||he(a))return;let n=r.find(d=>e>=d.time.from&&e<d.time.to);Ii(n)&&isFinite(n.time.from)&&isFinite(n.time.to)&&this.currentSegmentLength$.next(n?.time.to-n.time.from);let o=e,u=100;if(this.playingRepresentationId!==this.downloadingRepresentationId){let d=this.getForwardBufferDuration(e),h=dn(i),f=dn(t),m=this.useSmartRepresentationSwitch&&this.tuning.dash.useNewRepresentationSwitch&&this.tuning.dash.useSmartRepresentationSwitch&&Ii(h)&&Ii(f)&&b_(h.quality,f.quality),S=this.useSmartRepresentationSwitch&&this.tuning.dash.useNewRepresentationSwitch&&this.tuning.dash.useDelayedRepresentationSwitch;if(m||S?o+=Math.min(d,this.tuning.dash.representationSwitchForwardBufferGap):n&&n.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&d>=n.time.to-e+u&&(o=n?n.time.to+u:-1/0),this.tuning.dash.useNewRepresentationSwitch){let v=[...this.segments.entries()].map(([T,y])=>{let x=y.find(A=>e>=A.time.from&&e<A.time.to);return{representationId:T,status:x?.status}}).find(T=>T.status==="fed")?.representationId;v&&(this.playingRepresentationId=v,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)))}}if(isFinite(this.bufferLimit)&&ns(this.sourceBuffer.buffered)>=this.bufferLimit){let d=de(this.sourceBuffer.buffered,e),h=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,d<h).catch(f=>{this.handleAsyncError(f,"pruneBuffer")});return}let p=null;if(!this.activeSegments.size&&(p=this.selectForwardBufferSegments(r,t.segmentReference.type,o),p?.length)){let d="auto";if(this.tuning.dash.useFetchPriorityHints&&n)if((0,Ru.default)(p,n))d="high";else{let h=(0,nr.default)(p,0);h&&h.time.from-n.time.to>=this.forwardBufferTarget/2&&(d="low")}this.loadSegments(p,t,d).catch(h=>{this.handleAsyncError(h,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&n&&n.status==="fed"&&!p?.length&&de(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let c=(0,nr.default)(r,-1);!this.isLive&&c&&(this.fullyBuffered$.next(c.time.to-e-de(this.sourceBuffer.buffered,e)<u),this.onLastSegment$.next(e-c.time.from>0))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let i=0,r=this.isLive?this.liveInitialAdditionalOffset:0;for(let a of e)Math.trunc(a.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:a.time.from+r,persistent:!0}),i=a.time.to;Ii(t.duration)&&t.duration-i>0&&!this.isLive&&this.gaps.push({representation:t.id,from:i,to:t.duration,persistent:!0})}getActualLiveStartingSegments(e){let t=e.segments,i=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,r=[],a=0,n=t.length-1;do r.unshift(t[n]),a+=t[n].time.to-t[n].time.from,n--;while(a<i&&n>=0);return this.liveInitialAdditionalOffset=a-i,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){let t=e?.streams[this.kind];if(!t)return;let i=(0,$u.default)(t,a=>a.representations).find(a=>a.id===this.downloadingRepresentationId);if(!i)return;let r=this.segments.get(i.id);if(r?.length)return{from:r[0].time.from,to:r[r.length-1].time.to}}updateLive(e){if(!e||[...this.segments.values()].every(i=>!i.length))return;let t=(0,$u.default)(e.streams[this.kind],i=>i.representations)??[];for(let i of t){if(!i||!rt(i.segmentReference))return;let r=i.segmentReference.segments.map(l=>({...l,status:"none",size:void 0})),a=100,n=this.segments.get(i.id)??[],o=(0,nr.default)(n,-1)?.time.to??0,u=r?.findIndex(l=>o>=l.time.from+a&&o<=l.time.to+a);if(u===-1){this.liveUpdateSegmentIndex=0;let l=this.getActualLiveStartingSegments(i.segmentReference);this.segments.set(i.id,l)}else{let l=r.slice(u+1);this.segments.set(i.id,[...n,...l])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;He(e);let t=this.segments.get(e);if(t?.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}setSmartRepresentationSwitch(e){this.useSmartRepresentationSwitch=e}updateLowLatencyLiveIfNeeded(e){let t=0;for(let i of this.representations.values()){let r=i.segmentReference;if(!rt(r))return;let a=this.segments.get(i.id);if(!a)continue;let n=a.find(u=>Math.floor(u.time.from)===Math.floor(e.time.from));if(n&&!isFinite(n.time.to)&&(n.time.to=e.time.to,t=n.time.to-n.time.from),!!!a.find(u=>Math.floor(u.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let u=Math.round(e.time.to*r.timescale/1e3).toString(10),l=tt(r.segmentTemplateUrl,{segmentTime:u});a.push({status:"none",time:{from:e.time.to,to:1/0},url:l})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){let t=this.switchingToRepresentationId??this.downloadingRepresentationId??this.playingRepresentationId;if(!t)return;let i=this.segments.get(t);return i?i.find(a=>a.time.from<=e&&a.time.to>=e)?.time.from??void 0:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),this.sourceBufferTaskQueue?.destroy(),this.sourceBufferBufferedDiff?.destroy(),this.gapDetectionIdleCallback&&qe&&qe(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&qe&&qe(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(e){if(!(e instanceof DOMException&&e.name==="NotFoundError"))throw e}this.sourceBuffer=null,this.downloadAbortController.abort(),this.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,i){return this.checkEjectedSegments(),this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){if(this.playingRepresentationId!==this.downloadingRepresentationId){let i=e.findIndex(r=>t>=r.time.from&&t<r.time.to);this.liveUpdateSegmentIndex=i}return this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):null}selectForwardBufferSegmentsRecord(e,t,i){let r=this.getForwardBufferDuration(i),a=e.findIndex(({status:d,time:{from:h,to:f}},m)=>{let S=h<=i&&f>=i,g=h>i||S||m===0&&i===0,v=Math.min(this.forwardBufferTarget,this.bufferLimit),T=this.preloadOnly&&h<=i+v||r<v&&f-h>=v||f<=i+v;return(d==="none"||d==="partially_ejected"&&g&&T&&this.sourceBuffer&&V(this.mediaSource,this.sourceBuffer)&&!(De(this.sourceBuffer.buffered,h)&&De(this.sourceBuffer.buffered,f)))&&g&&T});if(a===-1)return null;if(t!=="byteRange")return e.slice(a,a+1);let n=e,o=0,u=0,l=[],p=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,c=this.preloadOnly?this.forwardBufferTarget:0;for(let d=a;d<n.length&&(o<=p||u<=c);d++){let h=n[d];if(o+=h.byte.to+1-h.byte.from,u+=h.time.to+1-h.time.from,h.status==="none"||h.status==="partially_ejected")l.push(h);else break}return l}async loadSegments(e,t,i="auto"){rt(t.segmentReference)?await this.loadTemplateSegment(e[0],t,i):await this.loadByteRangeSegments(e,t,i)}async loadTemplateSegment(e,t,i="auto"){e.status="downloading";let r={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(r);let{range:a,url:n,signal:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await Ti(o,async function*(){let p=Rp(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,p))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let p=await this.fetcher.fetch(n,{range:a,signal:o,onProgress:u,priority:i,isLowLatency:this.isActiveLowLatency(),bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation});if(this.lastDataObtainedTimestampMs=Au(),!p)return;let c=new DataView(p),d=lt(t.mime);if(!isFinite(r.segment.time.to)){let m=t.segmentReference.timescale;r.segment.time.to=d.getChunkEndTime(c,m)}u&&r.feedingBytes&&l?await Promise.all(l):await this.sourceBufferTaskQueue.append(c,o);let{serverDataReceivedTimestamp:h,serverDataPreparedTime:f}=d.getServerLatencyTimestamps(c);h&&f&&this.currentLiveSegmentServerLatency$.next(f-h),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(p){this.abortActiveSegments([e]),Le(p)||(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())rt(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}async loadByteRangeSegments(e,t,i="auto"){if(!e.length)return;for(let u of e)u.status="downloading",this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:r,url:a,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(await Ti(n,async function*(){let u=Rp(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),Ap(window,"online").pipe(g_()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(a,{range:r,onProgress:o,signal:n,priority:i,bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation}),this.lastDataObtainedTimestampMs=Au(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),Le(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(rt(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:(0,nr.default)(e,0).byte.from,to:(0,nr.default)(e,-1).byte.to},{signal:a}=this.downloadAbortController;return{url:i,range:r,signal:a,onProgress:async(o,u)=>{if(!a.aborted)try{this.lastDataObtainedTimestampMs=Au(),await this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:a,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:sr.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!rt(t.segmentReference))throw new Error("Representation is not template type");let i=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&i.searchParams.set("low-latency","yes");let r=i.toString(),{signal:a}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,p)=>{if(!a.aborted)try{this.lastDataObtainedTimestampMs=Au();let c=this.onSomeTemplateDataLoaded({dataView:l,loaded:p,signal:a,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(c)}catch(c){this.error$.next({id:"SegmentFeeding",category:sr.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}}:void 0;return{url:r,signal:a,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,Ru.default)(e,t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:a}){if(!this.activeSegments.size||!V(this.mediaSource,this.sourceBuffer))return;let n=this.representations.get(t);if(n)for(let o of this.activeSegments){let{segment:u}=o;if(o.representationId===t){if(a.aborted){r();continue}if(o.loadedBytes=i,o.loadedBytes>o.feedingBytes){let l=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),p=lt(n.mime).parseFeedableSegmentChunk(l,this.isLive);p?.byteLength&&(u.status="partially_fed",o.feedingBytes+=p.byteLength,await this.sourceBufferTaskQueue.append(p),o.fedBytes+=p.byteLength)}}}}async onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:a,onSegmentAppendFailed:n}){if(!this.activeSegments.size||!V(this.mediaSource,this.sourceBuffer))return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){if(u.representationId!==t)continue;if(a.aborted){await n();continue}let{segment:l}=u,p=l.byte.from-i,c=l.byte.to-i,d=c-p+1,h=p<r,f=c<=r;if(h){if(l.status==="downloading"&&f){l.status="downloaded";let m=new DataView(e.buffer,e.byteOffset+p,d);await this.sourceBufferTaskQueue.append(m,a)&&!a.aborted?this.onSegmentFullyAppended(u,t):await n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(l.status==="downloading"||l.status==="partially_fed")&&(u.loadedBytes=Math.min(d,r-p),u.loadedBytes>u.feedingBytes)){let m=new DataView(e.buffer,e.byteOffset+p+u.feedingBytes,u.loadedBytes-u.feedingBytes),S=u.loadedBytes===d?m:lt(o.mime).parseFeedableSegmentChunk(m);S?.byteLength&&(l.status="partially_fed",u.feedingBytes+=S.byteLength,await this.sourceBufferTaskQueue.append(S,a)&&!a.aborted?(u.fedBytes+=S.byteLength,u.fedBytes===d&&this.onSegmentFullyAppended(u,t)):await n())}}}}onSegmentFullyAppended(e,t){if(!(he(this.sourceBuffer)||!V(this.mediaSource,this.sourceBuffer))){!this.isLive&&$.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(De(this.sourceBuffer.buffered,e.segment.time.from,100)&&De(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:sr.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",Pp(e.segment)&&(e.segment.size=e.fedBytes);for(let i of this.representations.values()){if(i.id===t)continue;let r=this.segments.get(i.id);if(r)for(let a of r)a.status==="fed"&&Math.round(a.time.from)===Math.round(e.segment.time.from)&&Math.round(a.time.to)===Math.round(e.segment.time.to)&&(a.status="none")}this.isActiveLowLatency()&&this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,e.segment)}}abortSegment(e){e.status==="partially_fed"?e.status="partially_ejected":e.status!=="partially_ejected"&&(e.status="none");for(let t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[r,a]of this.initData.entries()){let n=a instanceof Promise;t||=n,a===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let i=this.representations.get(e);i&&(this.initLoadIdleCallback=Mt(()=>(0,$E.default)(this.loadInit(i,"low",!1),()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",i=!1){let r=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!i&&this.failedDownloads>0?Ti(this.destroyAbortController.signal,async function*(){let o=Rp(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,lt(e.mime),r)).then(o=>{if(!o)return;let{init:u,dataView:l,segments:p}=o,c=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,c);let d=p;this.isLive&&rt(e.segmentReference)&&(d=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,d),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:sr.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||!V(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||he(e))return!1;this.checkEjectedSegments();let r=[],a=0,n=o=>{if(a>=t)return;r.push({...o.time});let u=Pp(o)?o.size??0:o.byte.to-o.byte.from;a+=u};for(let o of this.segments.values())for(let u of o){let l=u.time.to<=e-this.tuning.dash.bufferPruningSafeZone,p=u.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(l||p)&&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,p=0;for(let c of this.segments.values())for(let d of c)(0,Ru.default)(["none","partially_ejected"],d.status)&&Math.round(d.time.from)<=Math.round(u)&&Math.round(d.time.to)>=Math.round(l)&&p++;if(p===this.segments.size){let c={time:{from:u,to:l},url:"",status:"none"};n(c)}}if(r.length&&i){let o=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let u of this.segments.values())for(let l of u)l.time.from>=e+o&&l.status==="fed"&&n(l)}return r.length?(r=AE(r),(await Promise.all(r.map(u=>this.sourceBufferTaskQueue.remove(u.from,u.to)))).reduce((u,l)=>u||l,!1)):!1}async abortBuffer(){if(!this.sourceBuffer||!V(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||!V(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||!V(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||!V(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||he(e)?0:de(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!this.sourceBuffer||!V(this.mediaSource,this.sourceBuffer))return;let{buffered:i}=this.sourceBuffer,r={representation:e,from:t.time.from,to:t.time.to,persistent:!1};for(let a=0;a<i.length;a++){let n=i.start(a)*1e3,o=i.end(a)*1e3;if(!(o<=t.time.from||n>=t.time.to)){if(n<=t.time.from&&o>=t.time.to){r=void 0;break}o>t.time.from&&o<t.time.to&&(r.from=o),n<t.time.to&&n>t.time.from&&(r.to=n)}}r&&r.to-r.from>1&&!this.gaps.some(a=>r&&a.from===r.from&&a.to===r.to)&&this.gaps.push(r)}detectGapsWhenIdle(e,t){if(this.gapDetectionIdleCallback||!this.sourceBuffer||!V(this.mediaSource,this.sourceBuffer))return;let{buffered:i}=this.sourceBuffer;this.gaps=this.gaps.filter(r=>{if(r.persistent)return!0;let a=Math.round(r.from),n=Math.round(r.to);for(let o=0;o<i.length;o++)if(a>=Math.round(i.start(o)*1e3)&&n<=Math.round(i.end(o)*1e3))return!1;return!0}),this.gapDetectionIdleCallback=Mt(()=>{try{this.detectGaps(e,t)}catch(r){this.error$.next({id:"GapDetection",category:sr.WTF,message:"detectGaps threw",thrown:r})}finally{this.gapDetectionIdleCallback=null}})}checkEjectedSegments(){if(he(this.sourceBuffer)||!V(this.mediaSource,this.sourceBuffer)||he(this.playingRepresentationId)||this.sourceBufferBufferedDiff&&!this.sourceBufferBufferedDiff.wasUpdated())return;let e=ku(this.sourceBuffer.buffered),t=100;for(let i of this.segments.values())for(let r of i){let{status:a}=r;if(a!=="fed"&&a!=="partially_ejected")continue;let n=Math.floor(r.time.from),o=Math.ceil(r.time.to),u=!1,l=0;for(let p=0;p<e.length;p+=2){let c=e[p],d=e[p+1];u||(u=c-t<=n&&d+t>=o),(n>=c&&n<d-t||o>c+t&&o<=d)&&(l+=1)}u||(l===1?r.status="partially_ejected":this.gaps.some(p=>p.from===r.time.from||p.to===r.time.to)?r.status="partially_ejected":r.status="none")}}handleAsyncError(e,t){this.error$.next({id:t,category:sr.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}calculateDurationFromSegments(){if(!this.playingRepresentationId)return 0;let e=this.segments.get(this.playingRepresentationId);return(e?(0,nr.default)(e,-1)?.time.to:0)||0}};import{abortable as hn,assertNever as ME,fromEvent as LE,merge as y_,now as fn,Subject as hs,ValueSubject as $p,flattenObject as fs,ErrorCategory as mn,SubscriptionRemovable as T_}from"@vkontakte/videoplayer-shared/es2024";var Lu=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:a=!1}){this.manifestRequested$=new hs;this.firstBytesManifest$=new hs;this.firstBytesRequested$=new hs;this.firstBytesReceived$=new hs;this.lastConnectionType$=new $p(void 0);this.lastConnectionReused$=new $p(void 0);this.lastRequestFirstBytes$=new $p(void 0);this.recoverableError$=new hs;this.error$=new hs;this.abortAllController=new j;this.subscription=new T_;this.fetchManifest=hn(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=Tt(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=Qr(i)),this.manifestRequested$.next();let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(Mu);return r?(t.log("success",fs({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(r.headers),this.firstBytesManifest$.next(),r.text()):(t.error("error",fs({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=hn(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:a="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1,bufferOptimisation:l=!1}={}){let p=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 E=new URL(p,location.href);E.searchParams.append("bytes",`${i.from}-${i.to}`),p=E.toString();break}default:ME(t)}this.requestQuic&&(p=Tt(p));let h=this.abortAllController.signal,f;if(n){let E=new j;if(f=y_(LE(this.abortAllController.signal,"abort"),LE(n,"abort")).subscribe(()=>{try{E.abort()}catch(I){Mu(I)}}),this.subscription.add(f),this.abortAllController.signal.aborted||n.aborted)try{E.abort()}catch(I){Mu(I)}h=E.signal}let m=0,S=fn();d.log("startRequest",fs({url:p,priority:a,rangeMethod:t,range:i,isLowLatency:u,requestStartedAt:S})),this.firstBytesRequested$.next();let g=yield this.doFetch(p,{priority:a,headers:c,signal:h}),v=fn();if(!g)return d.error("error",{message:"No response in request"}),d.end(),this.unsubscribeAbortSubscription(f),null;if(this.throughputEstimator?.addRawRtt(v-S),!g.ok||!g.body){this.unsubscribeAbortSubscription(f);let E=`Fetch error ${g.status}: ${g.statusText}`;return d.error("error",{message:E}),d.end(),Promise.reject(new Error(`Fetch error ${g.status}: ${g.statusText}`))}if(this.onHeadersReceived(g.headers),!r&&!o){this.unsubscribeAbortSubscription(f);let E=fn(),I={requestStartedAt:S,requestEndedAt:E,duration:E-S};return d.log("endRequest",fs(I)),d.end(),g.arrayBuffer()}let T=g.body;if(o){let E;[T,E]=g.body.tee(),this.throughputEstimator?.trackStream(E,u)}let y=T.getReader(),x,A=parseInt(g.headers.get("content-length")??"",10);Number.isFinite(A)&&(x=A),!x&&i&&(x=i.to-i.from+1);let R=x?new Uint8Array(x):new Uint8Array(0),w=!1,B=E=>{this.unsubscribeAbortSubscription(f),w=!0,Mu(E)},k=hn(h,async function*({done:E,value:I}){if(m===0&&(this.lastRequestFirstBytes$.next(fn()-S),this.firstBytesReceived$.next()),h.aborted){this.unsubscribeAbortSubscription(f);return}if(!E&&I){if(l&&x)R.set(I,m),m+=I.byteLength;else{let N=new Uint8Array(R.length+I.length);N.set(R),N.set(I,R.length),R=N,m+=I.byteLength}r?.(new DataView(R.buffer),m),yield y?.read().then(k,B)}}.bind(this));yield y?.read().then(k,B),this.unsubscribeAbortSubscription(f);let F=fn(),C={failed:w,requestStartedAt:S,requestEndedAt:F,duration:F-S};return w?(d.error("endRequest",fs(C)),d.end(),null):(d.log("endRequest",fs(C)),d.end(),R.buffer)}.bind(this));this.fetchByteRangeRepresentation=hn(this.abortAllController.signal,async function*(e,t,i){if(e.type!=="byteRange")return null;let{from:r,to:a}=e.initRange,n=r,o=a,u=!1,l,p;e.indexRange&&(l=e.indexRange.from,p=e.indexRange.to,u=a+1===l,u&&(n=Math.min(l,r),o=Math.max(p,a))),n=Math.min(n,0);let c=yield this.fetch(e.url,{range:{from:n,to:o},priority:i,measureThroughput:!1});if(!c)return null;let d=new DataView(c,r-n,a-n+1);if(!t.validateData(d))throw new Error("Invalid media file");let h=t.parseInit(d),f=e.indexRange??t.getIndexRange(h);if(!f)throw new ReferenceError("No way to load representation index");let m;if(u)m=new DataView(c,f.from-n,f.to-f.from+1);else{let g=yield this.fetch(e.url,{range:f,priority:i,measureThroughput:!1});if(!g)return null;m=new DataView(g)}let S=t.parseSegments(m,h,f);return{init:h,dataView:new DataView(c),segments:S}}.bind(this));this.fetchTemplateRepresentation=hn(this.abortAllController.signal,async function*(e,t){if(e.type!=="template")return null;let i=new URL(e.initUrl,e.baseUrl).toString(),r=yield this.fetch(i,{priority:t,measureThroughput:!1});return r?{init:null,segments:e.segments.map(n=>({...n,status:"none",size:void 0})),dataView:new DataView(r)}:null}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=r,this.tracer=i.createComponentTracer("Fetcher"),this.useEnableSubtitlesParam=a}onHeadersReceived(e){let{type:t,reused:i}=zr(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,t,i="auto"){let{type:r}=e;switch(r){case"byteRange":return await this.fetchByteRangeRepresentation(e,t,i)??null;case"template":return await this.fetchTemplateRepresentation(e,i)??null;default:ME(r)}}destroy(){this.abortAllController.abort(),this.tracer.end(),this.subscription.unsubscribe()}async doFetch(e,t){let i=await Ke(e,t);if(i.ok)return i;let r=await i.text(),a=parseInt(r);if(!isNaN(a))switch(a){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:mn.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:mn.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:mn.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:mn.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${a})`,category:mn.FATAL})}}unsubscribeAbortSubscription(e){e&&(e.unsubscribe(),this.subscription.remove(e))}},Mu=s=>{if(!Le(s))throw s};import{isNullable as I_,ValueSubject as E_}from"@vkontakte/videoplayer-shared/es2024";var bn=class s{constructor(e,t){this.currentRepresentation$=new E_(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(!I_(e))for(let t of this.representations)for(let i of t){let r=i.segmentReference,a=r.segments.length,n=r.segments[0].time.from,o=r.segments[a-1].time.to;if(e<n||e>o)continue;let u=r.segments.find(l=>l.time.from<=e&&l.time.to>=e);!u||this.currentSegment?.time.from===u.time.from&&this.currentSegment.time.to===u.time.to||(this.currentSegment=u,this.currentRepresentation$.next({...i,label:"Live Text",language:"ru",isAuto:!0,url:new URL(u.url,r.baseUrl).toString()}))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e??[]){let i=s.filterRepresentations(t.representations);if(i){this.representations[this.representationsCursor]=i,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!e?.some(t=>s.filterRepresentations(t.representations))}static filterRepresentations(e){return e?.filter(t=>t.kind==="text"&&"segmentReference"in t&&rt(t.segmentReference))}};var R_=["progress","play","seeked","stalled","waiting"],$_=["timeupdate","progress","loadeddata","playing","seeked"];var Bu=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.bufferManagers=[];this.subscription=new Cp;this.subscriptionRemovable=new P_;this.representationSubscription=new Cp;this.state$=new O("none");this.currentVideoRepresentation$=new te(void 0);this.currentVideoRepresentationInit$=new te(void 0);this.currentAudioRepresentation$=new te(void 0);this.currentVideoSegmentLength$=new te(0);this.currentAudioSegmentLength$=new te(0);this.error$=new Yt;this.manifestRequested$=new Yt;this.firstBytesManifest$=new Yt;this.manifestReceived$=new Yt;this.firstBytesRequested$=new Yt;this.firstBytesReceived$=new Yt;this.lastConnectionType$=new te(void 0);this.lastConnectionReused$=new te(void 0);this.lastRequestFirstBytes$=new te(void 0);this.currentLiveTextRepresentation$=new te(null);this.isLive$=new te(!1);this.isActiveLive$=new te(!1);this.isLowLatency$=new te(!1);this.liveDuration$=new te(0);this.liveSeekableDuration$=new te(0);this.liveAvailabilityStartTime$=new te(0);this.liveStreamStatus$=new te(void 0);this.bufferLength$=new te(0);this.liveLatency$=new te(void 0);this.liveLoadBufferLength$=new te(0);this.livePositionFromPlayer$=new te(0);this.currentStallDuration$=new te(0);this.videoLastDataObtainedTimestamp$=new te(0);this.fetcherRecoverableError$=new Yt;this.fetcherError$=new Yt;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new Yt;this.gapWatchdogActive=!1;this.destroyController=new j;this.initManifest=Lp(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=ne(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:Et.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=Lp(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:Et.NETWORK,message:"Failed to load manifest",thrown:u})});if(!e)return null;let t=null;try{t=Xr(e??"",this.manifestUrlString),this.manifestReceived$.next()}catch(u){let l=Hr(e)??{id:"ManifestParsing",category:Et.PARSER,message:"Failed to parse MPD manifest",thrown:u};this.error$.next(l)}if(!t)return null;let i=(u,l,p)=>!!(this.element?.canPlayType?.(l)&&Ve()?.isTypeSupported?.(`${l}; codecs="${p}"`)||u==="text");if(t.live){this.isLive$.next(!!t.live);let{availabilityStartTime:u,latestSegmentPublishTime:l,streamIsUnpublished:p,streamIsAlive:c}=t.live,d=(t.duration??0)/1e3;this.liveSeekableDuration$.next(-1*d),this.liveDuration$.next((l-u)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let h="active";c||(h=p?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(h)}let r={text:t.streams.text,video:[],audio:[]},a,n;for(let u of["video","audio"]){let p=t.streams[u].filter(({mime:d,codecs:h})=>i(u,d,h));r[u]=p;let c;if(this.tuning.dash.codecsPrioritizeEnabled){let d=p.map(({codecs:h})=>h);u==="audio"&&(n=es(d),c=n[0]),u==="video"&&(a=Zr(d),this.forceVideoCodec&&(0,VE.default)(a,this.forceVideoCodec)?c=this.forceVideoCodec:c=a[0]),c&&(r[u]=p.filter(({codecs:h})=>hi(h)===c))}else{let d=new Set(p.map(({codecs:h})=>h));c=Jr(d),c&&(r[u]=p.filter(({codecs:h})=>h.startsWith(c)))}if(u==="video"){let d=this.tuning.preferHDR,h=r.video.some(m=>m.hdr),f=r.video.some(m=>!m.hdr);$.display.isHDR&&d&&h?r.video=r.video.filter(m=>m.hdr):f&&(r.video=r.video.filter(m=>!m.hdr))}}let o={...t,streams:r};return this.tuning.dash.codecsPrioritizeEnabled&&(o.codecs={video:a,audio:n}),this.tracer.log("updateManifestEnd",Sn(o)),o}.bind(this));this.initRepresentations=Lp(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initRepresentationsStart",Sn({initialVideo:e,initialAudio:t,sourceHls:i})),ms(this.manifest),ms(this.element),this.representationSubscription.unsubscribe(),this.representationSubscription=new Cp,this.state$.startTransitionTo("representations_ready");let r=d=>{this.representationSubscription.add(Dt(d,"error").pipe(Du(h=>!!this.element?.played.length)).subscribe(h=>{this.error$.next({id:"VideoSource",category:Et.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=Ir();let a=document.createElement("source");if(r(a),a.src=URL.createObjectURL(this.source),this.element.appendChild(a),ai())if(i){let d=document.createElement("source");r(d),d.type="application/x-mpegurl",d.src=i.url,this.element.appendChild(d)}else this.element.disableRemotePlayback=!0;this.isActiveLive$.next(this.isLive$.getValue());let n={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),manifest:this.manifest},o=this.manifest.streams.video.reduce((d,h)=>[...d,...h.representations],[]);if(this.videoBufferManager=new pn("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],vn(t)){let d=this.manifest.streams.audio.reduce((h,f)=>[...h,...f.representations],[]);this.audioBufferManager=new pn("audio",this.source,d,n),this.bufferManagers.push(this.audioBufferManager)}bn.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new bn(this.manifest.streams.text,n)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$));let u=()=>{this.stallWatchdogSubscription?.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add(or(...$_.map(d=>Dt(this.element,d))).pipe(gs(d=>this.element?de(this.element.buffered,this.element.currentTime*1e3):0),gn(),A_(d=>{d>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add(or(Dt(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe(gn()).subscribe(h=>this.liveStreamEndTimestamp=Bp())),this.subscription.add(Dt(this.element,"pause").subscribe(()=>{this.livePauseWatchdogSubscription=Dp(1e3).subscribe(h=>{let f=si(this.manifestUrlString,2);this.manifestUrlString=ne(this.manifestUrlString,f+1e3,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add(Dt(this.element,"play").subscribe(h=>this.livePauseWatchdogSubscription?.unsubscribe())),this.representationSubscription.add(bs({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(gs(({isActiveLive:h,isLowLatency:f})=>h&&f),gn()).subscribe(h=>{this.isManualDecreasePlaybackInLive()||ls(this.element,1)})),this.representationSubscription.add(bs({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(Du(({bufferLength:h,isActiveLive:f,isLowLatency:m})=>f&&m&&!!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(bs({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(Du(({isLive:h})=>h),gn((h,f)=>f.bufferLength<h.bufferLength),gs(({rtt:h,bufferLength:f,segmentServerLatency:m})=>{let S=si(this.manifestUrlString,2);return(h/2+f+m+S)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(bs({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:h,isActiveLive:f,isLowLatency:m})=>{if(!m||!f)return;let S=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,g=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,v=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,T=h-S;if(this.isManualDecreasePlaybackInLive())return;let y=1;Math.abs(T)>g&&(y=1+Math.sign(T)*v),ls(this.element,y)})),this.representationSubscription.add(this.bufferLength$.subscribe(h=>{let f=0;if(h){let m=(this.element?.currentTime??0)*1e3;f=Math.min(...this.bufferManagers.map(g=>g.getLiveSegmentsToLoadState(this.manifest)?.to??m))-m}this.liveLoadBufferLength$.getValue()!==f&&this.liveLoadBufferLength$.next(f)}));let d=0;this.representationSubscription.add(bs({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(CE(1e3)).subscribe(async({liveLoadBufferLength:h,bufferLength:f})=>{if(!this.element||this.isUpdatingLive)return;let m=this.element.playbackRate,S=si(this.manifestUrlString,2),g=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,v=Math.min(g,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*m),T=this.tuning.dashCmafLive.normalizedActualBufferOffset*m,y=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*m,x=isFinite(h)?h:f,A=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),R=g<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(R);let w="none";if(A?w="active_low_latency":this.isLowLatency$.getValue()&&R?(this.bufferManagers.forEach(B=>B.proceedLowLatencyLive()),w="active_low_latency"):S!==0&&x<v?w="live_forward_buffering":x<v+y&&(w="live_with_target_offset"),isFinite(h)&&(d=h>d?h:d),w==="live_forward_buffering"||w==="live_with_target_offset"){let B=d-(v+T),k=this.normolizeLiveOffset(Math.trunc(S+B/m)),F=Math.abs(k-S),C=0;!h||F<=this.tuning.dashCmafLive.offsetCalculationError?C=S:k>0&&F>this.tuning.dashCmafLive.offsetCalculationError&&(C=k),this.manifestUrlString=ne(this.manifestUrlString,C,2)}(w==="live_with_target_offset"||w==="live_forward_buffering")&&(d=0,await this.updateLive())},h=>{this.error$.next({id:"updateLive",category:Et.VIDEO_PIPELINE,thrown:h,message:"Failed to update live with subscription"})}))}let l=or(...this.bufferManagers.map(d=>d.fullyBuffered$)).pipe(gs(()=>this.bufferManagers.every(d=>d.fullyBuffered$.getValue()))),p=or(...this.bufferManagers.map(d=>d.onLastSegment$)).pipe(gs(()=>this.bufferManagers.some(d=>d.onLastSegment$.getValue()))),c=bs({allBuffersFull:l,someBufferEnded:p}).pipe(gn(),gs(({allBuffersFull:d,someBufferEnded:h})=>d&&h),Du(d=>d));if(this.representationSubscription.add(or(this.forceEnded$,c).subscribe(()=>{if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(d=>!d.updating))try{this.source?.endOfStream()}catch(d){this.error$.next({id:"EndOfStream",category:Et.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:d})}})),this.representationSubscription.add(or(...this.bufferManagers.map(d=>d.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.representationSubscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.representationSubscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.liveTextManager&&this.representationSubscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$)),this.source.readyState!=="open"){let d=this.tuning.dash.sourceOpenTimeout>=0;yield new Promise(h=>{d&&(this.timeoutSourceOpenId=setTimeout(()=>{if(this.source?.readyState==="open"){h();return}this.error$.next({id:"OpenOfStream",category:Et.VIDEO_PIPELINE,message:"Failed to open MediaSource",thrown:new Error("Timeout reject when wait sourceopen event"),traceAsLog:!0})},this.tuning.dash.sourceOpenTimeout)),this.source?.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),h()},{once:!0})})}if(!this.isLive$.getValue()){let d=[this.manifest.duration??0,...(0,Vp.default)((0,Vp.default)([...this.manifest.streams.audio,...this.manifest.streams.video],h=>h.representations),h=>{let f=[];return h.duration&&f.push(h.duration),rt(h.segmentReference)&&h.segmentReference.totalSegmentsDurationMs&&f.push(h.segmentReference.totalSegmentsDurationMs),f})];this.source.duration=Math.max(...d)/1e3}this.audioBufferManager&&vn(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=Dp(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:Et.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 Lu({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.subscription.add(this.fetcher.recoverableError$.subscribe(this.fetcherRecoverableError$)),this.subscription.add(this.fetcher.error$.subscribe(this.fetcherError$)),this.subscription.add(this.fetcher.manifestRequested$.subscribe(this.manifestRequested$)),this.subscription.add(this.fetcher.firstBytesManifest$.subscribe(this.firstBytesManifest$)),this.subscription.add(this.fetcher.firstBytesRequested$.subscribe(this.firstBytesRequested$)),this.subscription.add(this.fetcher.firstBytesReceived$.subscribe(this.firstBytesReceived$)),this.subscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.subscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.liveBuffer=Qt.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator}),this.initTracerSubscription()}setSmartRepresentationSwitch(e){this.bufferManagers.forEach(t=>t.setSmartRepresentationSwitch(e))}async seekLive(e){ms(this.element);let t=this.liveStreamStatus$.getValue()!=="active"?Bp()-this.liveStreamEndTimestamp:0,i=this.normolizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=ne(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(){ms(this.element),this.state$.setState("running");let e=Dt(this.element,"timeupdate");this.tuning.dash.timeupdateEventTickThrottle&&(e=e.pipe(CE(this.tuning.dash.timeupdateEventTickThrottle))),this.subscription.add(or(...R_.map(t=>Dt(this.element,t)),Dt(window,"online"),e).subscribe(()=>this.tick(),t=>{this.error$.next({id:"DashVKPlayer",category:Et.WTF,message:"Internal logic error",thrown:t})})),this.subscription.add(Dt(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(Dt(this.element,"waiting").subscribe(()=>{this.tuning.dash.useVideoElementWaitingCurrentTimeReassign&&this.element&&this.element.readyState===HTMLMediaElement.HAVE_CURRENT_DATA&&!this.element.seeking&&De(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let t=()=>{if(!this.element||this.source?.readyState!=="open")return;let i=this.currentStallDuration$.getValue();i+=50,this.currentStallDuration$.next(i);let r={timeInWaiting:i},a=Bp(),n=100,o=this.videoBufferManager?.lastDataObtainedTimestamp??0;this.videoLastDataObtainedTimestamp$.next(o);let u=this.audioBufferManager?.lastDataObtainedTimestamp??0,l=this.videoBufferManager?.getForwardBufferDuration()??0,p=this.audioBufferManager?.getForwardBufferDuration()??0,c=l<n&&a-o>this.tuning.dash.crashOnStallTWithoutDataTimeout,d=this.audioBufferManager&&p<n&&a-u>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((c||d)&&i>this.tuning.dash.crashOnStallTWithoutDataTimeout||i>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${i} ms`);if(this.isLive$.getValue()&&i%2e3===0){let h=this.normolizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(h).catch(f=>{this.error$.next({id:"stallIntervalCallback",category:Et.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:f})}),r.liveLastOffset=h}else{let h=this.element.currentTime*1e3;this.videoBufferManager?.maintain(h),this.audioBufferManager?.maintain(h),r.position=h}this.tracer.log("stallIntervalCallback",Sn(r))};this.stallWatchdogSubscription&&(this.stallWatchdogSubscription.unsubscribe(),this.subscriptionRemovable.remove(this.stallWatchdogSubscription)),this.stallWatchdogSubscription=Dp(50).subscribe(t,i=>{this.error$.next({id:"StallWatchdogCallback",category:Et.NETWORK,message:"Can't restore DASH after stall.",thrown:i})}),this.subscriptionRemovable.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,i=!1){let r={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return this.tuning.useNewSwitchTo?this.currentStallDuration$.getValue()>0?r?.switchToWithPreviousAbort(t,i):r?.switchTo(t,i):r?.switchToOld(t,i)}async seek(e,t){ms(this.element),ms(this.videoBufferManager);let i;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?i=e:i=Math.max(this.videoBufferManager.findSegmentStartTime(e)??e,this.audioBufferManager?.findSegmentStartTime(e)??e),this.warmUpMediaSourceIfNeeded(i),De(this.element.buffered,i)||await Promise.all([this.videoBufferManager.abort(),this.audioBufferManager?.abort()]),!(BE(this.element)||BE(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),this.audioBufferManager?.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",Sn({requestedPosition:e,forcePrecise:t,position:i})))}warmUpMediaSourceIfNeeded(e=this.element?.currentTime){vn(this.element)&&vn(this.source)&&vn(e)&&this.source?.readyState==="ended"&&this.element.duration*1e3-e>this.tuning.dash.seekBiasInTheEnd&&this.bufferManagers.forEach(t=>t.warmUpMediaSource())}get isStreamEnded(){return this.source?.readyState==="ended"}stop(){this.tracer.log("stop"),this.element?.querySelectorAll("source").forEach(e=>{URL.revokeObjectURL(e.src),e.remove()}),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),this.videoBufferManager?.destroy(),this.videoBufferManager=null,this.audioBufferManager?.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){return this.manifest?.streams}getCodecs(){return this.manifest?.codecs}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){this.subscription.unsubscribe(),this.subscriptionRemovable.unsubscribe(),this.representationSubscription.unsubscribe(),this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),this.source?.readyState==="open"&&Array.from(this.source.sourceBuffers).every(e=>!e.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=k_(this.tracer.error.bind(this.tracer));this.subscription.add(this.error$.subscribe(e("error")))}isManualDecreasePlaybackInLive(){return!this.element||!this.isLive$.getValue()?!1:1-this.element.playbackRate>this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&(this.bufferManagers.forEach(e=>e.updateLive(this.manifest)),this.liveTextManager?.updateLive(this.manifest)),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getBufferedTo();if(e===null)return;let t=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),i=this.isJumpGapAfterSeekLive,r=this.element.currentTime;this.isJumpGapAfterSeekLive&&!t&&this.element.currentTime>e&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let a=this.element.currentTime*1e3,n=null,o=this.element.readyState===HTMLMediaElement.HAVE_METADATA?this.tuning.endGapTolerance:0;for(let u of this.bufferManagers)for(let l of u.gaps)(l.persistent||u.playingRepresentation$.getValue()===l.representation)&&l.from-o<=a&&l.to+o>a&&(this.element.duration*1e3-l.to<this.tuning.endGapTolerance?n=1/0:(n===null||l.to>n)&&(n=l.to));if(n!==null){let u=n+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,u===1/0?this.forceEnded$.next():(this.element.currentTime=u/1e3,this.tracer.log("jumpGap",Sn({isJumpGapAfterSeekLive:i,isActiveLowLatency:t,initialCurrentTime:r,jumpTo:u,resultCurrentTime:this.element.currentTime})))}}calculateDurationFromSegments(){return Math.max(this.videoBufferManager?.calculateDurationFromSegments()||0,this.audioBufferManager?.calculateDurationFromSegments()||0)}};import{combine as M_,map as L_,observeElementSize as D_,Subscription as B_,ValueSubject as _p,noop as C_}from"@vkontakte/videoplayer-shared/es2024";var Cu=class{constructor(){this.subscription=new B_;this.pipSize$=new _p(void 0);this.videoSize$=new _p(void 0);this.elementSize$=new _p(void 0);this.pictureInPictureWindowRemoveEventListener=C_}connect({observableVideo:e,video:t}){let i=r=>{let a=r.target;this.pipSize$.next({width:a.width,height:a.height})};this.subscription.add(D_(t).subscribe(this.videoSize$)).add(e.enterPip$.subscribe(({pictureInPictureWindow:r})=>{this.pipSize$.next({width:r.width,height:r.height}),r.addEventListener("resize",i),this.pictureInPictureWindowRemoveEventListener=()=>{r.removeEventListener("resize",i)}})).add(e.leavePip$.subscribe(()=>{this.pictureInPictureWindowRemoveEventListener()})).add(M_({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(L_(({videoSize:r,inPip:a,pipSize:n})=>a?n:r)).subscribe(this.elementSize$))}getValue(){return this.elementSize$.getValue()}subscribe(e,t){return this.elementSize$.subscribe(e,t)}getObservable(){return this.elementSize$}destroy(){this.pictureInPictureWindowRemoveEventListener(),this.subscription.unsubscribe()}};var ur=class{constructor(e){this.subscription=new j_;this.videoState=new O("stopped");this.observableVideo=null;this.droppedFramesManager=new li;this.stallsManager=new qr;this.elementSizeManager=new Cu;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new yt;this.audioTrackSwitchHistory=new yt;this.selectedRepresentations={audio:null,video:null};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(r.state==="requested"&&i?.to!=="paused"&&e!=="stopped"&&t!=="stopped"&&this.seek(r.position,r.forcePrecise),t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.currentNativeBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),P(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"),P(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="ready"&&P(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"&&P(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&P(this.params.desiredState.playbackState,"paused");return;default:return __(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new di(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 We(e.source.url),this.params=e,this.video=Pe(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(ce(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 Bu({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;q_(this.observableVideo)&&(this.observableVideo=$e(this.video),this.subscription.add(()=>this.observableVideo?.destroy()));let i=this.constructor.name,r=n=>{e.error$.next({id:i,category:_E.WTF,message:`${i} internal logic error`,thrown:n})},a=(n,o)=>this.subscription.add(n.subscribe(o,r));return{output:e,desiredState:t,observableVideo:this.observableVideo,genericErrorListener:r,connect:a}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:a}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(Op(c=>!!c.length),NE()).subscribe(c=>{this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:c})}));let n=this.params.desiredState.seekState.stateChangeEnded$.pipe(Tn(c=>c.to.state!=="none"),yn());this.stallsManager.init({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$,videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,tuning:this.params.tuning.stallsManager,abrParams:this.params.tuning.autoTrackSelection,isBuffering$:i.isBuffering$,looped$:i.looped$,playing$:i.playing$,duration:this.video.duration}),a(i.ended$,e.endedEvent$),a(i.looped$,e.loopedEvent$),a(i.error$,e.error$),a(i.isBuffering$,e.isBuffering$),a(i.currentBuffer$,e.currentBuffer$),a(i.currentBuffer$,e.currentNativeBuffer$),a(i.playing$,e.firstFrameEvent$),a(i.canplay$,e.canplay$),a(i.inPiP$,e.inPiP$),a(i.inFullscreen$,e.inFullscreen$),a(i.loadedMetadata$,e.loadedMetadataEvent$),a(this.player.error$,e.error$),a(this.player.fetcherRecoverableError$,e.fetcherRecoverableError$),a(this.player.fetcherError$,e.fetcherError$),a(this.player.manifestRequested$,e.manifestRequested$),a(this.player.firstBytesManifest$,e.firstBytesManifest$),a(this.player.manifestReceived$,e.manifestReceived$),a(this.player.firstBytesRequested$,e.firstBytesRequested$),a(this.player.firstBytesReceived$,e.firstBytesReceived$),a(this.player.lastConnectionType$,e.httpConnectionType$),a(this.player.lastConnectionReused$,e.httpConnectionReused$),a(this.player.isLive$,e.isLive$),a(this.player.lastRequestFirstBytes$.pipe(Op(OE),NE()),e.firstBytesEvent$),a(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),a(this.videoState.stateChangeEnded$.pipe(Tn(c=>c.to)),this.params.output.playbackState$),this.subscription.add(i.looped$.subscribe(()=>this.player.warmUpMediaSourceIfNeeded(),r)),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(ot(this.video,t.isLooped,r)),this.subscription.add(Re(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Qe(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),a(Ye(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),P(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),P(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(i.ended$.subscribe(()=>{this.videoState.setState("paused"),P(t.playbackState,"paused")})),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 d=this.player.getStreams(),h=this.player.getCodecs();if(O_(d,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let m=[];for(let S of d.audio){m.push(xp(S));let g=[];for(let v of S.representations){let T=xE(v);g.push(T),this.audioTracksMap.set(T,{stream:S,representation:v})}this.audioStreamsMap.set(S,g)}this.params.output.availableAudioStreams$.next(m)}let f=[];for(let m of d.video){f.push(kp(m));let S=[];for(let g of m.representations){let v=dn({...g,streamId:m.id});v&&(S.push(v),this.videoTracksMap.set(v,{stream:m,representation:g}))}this.videoStreamsMap.set(m,S)}this.params.output.availableVideoStreams$.next(f);for(let m of d.text)for(let S of m.representations){let g=kE(m,S);this.textTracksMap.set(g,{stream:m,representation:S})}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),h?.video&&this.params.output.availableVideoCodecs$.next(h.video),h?.audio&&this.params.output.availableAudioCodecs$.next(h.audio),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else c==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r));let{vktvAbrThrottle:o}=this.params.tuning.dash,u=o&&RE(o)||null;this.subscription.add(In(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$,U_(this.video,"progress")).pipe(Op(()=>this.videoTracksMap.size>0)).subscribe(async()=>{let c=this.player.state$.getState(),d=this.player.state$.getTransition();if(c!=="manifest_ready"&&c!=="running"||d||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 m=rr(this.videoTracksMap.keys(),g=>this.videoTracksMap.get(g)?.representation.id===h.id);OE(m)&&(this.stallsManager.lastVideoTrackSelected=m);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 g=!!t.audioStream.getTransition();await this.player.switchRepresentation("audio",f.id,g)}},r)),this.subscription.add(N_({videoState:this.videoState.stateChangeEnded$,autoVideoTrackState:In(Vu([t.autoVideoTrackSwitching.getState()]),t.autoVideoTrackSwitching.stateChangeEnded$.pipe(Tn(c=>c.to)))}).pipe(Tn(({videoState:c,autoVideoTrackState:d})=>c.to!=="stopped"&&d),yn()).subscribe(c=>this.player.setSmartRepresentationSwitch(c))),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(yn()).subscribe(c=>{let d=rr(this.videoTracksMap.entries(),([,{representation:g}])=>g.id===c);if(!d){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[h,{stream:f}]=d,m=this.params.desiredState.videoStream.getTransition();m&&m.to&&m.to.id===f.id&&this.params.desiredState.videoStream.setState(m.to),e.currentVideoTrack$.next(h),e.currentVideoStream$.next(kp(f));let S=this.player.calculateDurationFromSegments();S&&this.params.output.duration$.next(S/1e3)},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(yn()).subscribe(c=>{let d=rr(this.audioTracksMap.entries(),([,{representation:S}])=>S.id===c);if(!d){e.currentAudioStream$.next(void 0);return}let[h,{stream:f}]=d,m=this.params.desiredState.audioStream.getTransition();m&&m.to&&m.to.id===f.id&&this.params.desiredState.audioStream.setState(m.to),e.currentAudioStream$.next(xp(f))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(c=>{if(c?.is3dVideo&&this.params.tuning.spherical?.enabled)try{this.init3DScene(c),e.is3DVideo$.next(!0)}catch(d){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${d}`})}else this.destroy3DScene(),this.params.tuning.spherical?.enabled&&e.is3DVideo$.next(!1)},r)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,r)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,r)),this.textTracksManager.connect(this.video,t,e);let l=t.playbackState.stateChangeStarted$.pipe(Tn(({to:c})=>c==="ready"),yn());this.subscription.add(In(l,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,Vu(["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(In(l,this.player.state$.stateChangeEnded$,Vu(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let p=In(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Vu(["init"])).pipe(F_(0));this.subscription.add(p.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?Qi:zi,t=this.params.tuning.useNewAutoSelectVideoTrack?Fr:Nr,i=this.params.tuning.useNewAutoSelectVideoTrack?ut:Or,{desiredState:r,output:a}=this.params,n=r.autoVideoTrackSwitching.getState(),o=r.videoTrack.getState()?.id,u=rr(this.videoTracksMap.keys(),w=>w.id===o),l=a.currentVideoTrack$.getValue(),p=r.videoStream.getState()??(u&&this.videoTracksMap.get(u)?.stream)??this.videoStreamsMap.size===1?this.videoStreamsMap.keys().next().value:void 0;if(!p)return;let c=rr(this.videoStreamsMap.keys(),w=>w.id===p.id),d=c&&this.videoStreamsMap.get(c);if(!d)return;let h=de(this.video.buffered,this.video.currentTime*1e3),f;this.player.isActiveLive$.getValue()?f=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?f=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:f=n?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let m=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,S=Math.min(h/Math.min(f,m||1/0),1),g=r.audioStream.getState()??(this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0),v=g?.id&&rr(this.audioStreamsMap.keys(),w=>w.id===g.id)||this.audioStreamsMap.keys().next().value,T=0;if(v){if(u&&!n){let w=e(u,d,this.audioStreamsMap.get(v)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);T=Math.max(T,w?.bitrate??-1/0)}if(l){let w=e(l,d,this.audioStreamsMap.get(v)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);T=Math.max(T,w?.bitrate??-1/0)}}let y=u;(n||!y)&&(y=i(d,{container:this.elementSizeManager.getValue(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.stallsManager.abrTuningParams,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:T,forwardBufferHealth:S,current:l,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,stallsVideoMaxQualityLimit:this.stallsManager.videoMaxQualityLimit,stallsPredictedThroughput:this.stallsManager.predictedThroughput,abrLogger:this.params.dependencies.abrLogger}));let x=v&&t(y,d,this.audioStreamsMap.get(v)??[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.stallsManager.abrTuningParams,forwardBufferHealth:S,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),A=this.videoTracksMap.get(y)?.representation,R=x&&this.audioTracksMap.get(x)?.representation;A&&R?(this.selectedRepresentations.video=A,this.selectedRepresentations.audio=R):A&&!R&&this.audioTracksMap.size===0&&(this.selectedRepresentations.video=A,this.selectedRepresentations.audio=null)}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Me(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:_E.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),Ae(this.video),this.tracer.end()}};var En=class extends ur{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 Np,merge as FE,filter as UE,filterChanged as qE,isNullable as Fp,map as jE,ValueSubject as Up,isNonNullable as H_}from"@vkontakte/videoplayer-shared/es2024";var wn=class extends ur{constructor(e){super(e),this.textTracksManager.destroy()}subscribe(){super.subscribe();let e=!1,t=-1,{output:i,observableVideo:r,desiredState:a,connect:n}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canPlayLiveTailBuffer$.next(!0),n(r.timeUpdate$,i.liveBufferTime$),n(this.player.liveSeekableDuration$,i.duration$),n(this.player.liveLatency$,i.liveLatency$);let o=new Up(1);n(r.playbackRateState$,o),this.params.tuning.dashCmafLive.catchupLiveForMutedInactiveTab&&this.subscription.add(i.elementVisible$.pipe(qE()).subscribe(u=>{let l=i.position$.getValue(),p=i.volume$.getValue(),c=!p.volume||p.muted;!u&&!l&&c?e=!0:u&&e&&(this.seek(0),e=!1)})),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(a.isLowLatency.stateChangeEnded$.pipe(jE(u=>u.to)).subscribe(this.player.isLowLatency$)).add(Np({liveBufferTime:i.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(jE(({liveBufferTime:u,liveAvailabilityStartTime:l})=>u&&l?u+l:void 0)).subscribe(i.liveTime$)).add(this.player.liveStreamStatus$.pipe(UE(u=>H_(u))).subscribe(u=>i.isLiveEnded$.next(u!=="active"&&i.position$.getValue()===0))).add(Np({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:FE(r.playbackRateState$,new Up(1))}).pipe(UE(({liveStreamStatus:u,liveDuration:l})=>u==="active"&&!!l)).subscribe(({liveDuration:u,playbackRate:l})=>{let p=i.liveBufferTime$.getValue(),c=i.position$.getValue(),{playbackCatchupSpeedup:d}=this.params.tuning.dashCmafLive.lowLatency;c||l<1-d||this.video.paused||Fp(p)||(t=u-p)})).add(Np({time:i.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:FE(r.playbackRateState$,new Up(1))}).pipe(qE((u,l)=>this.player.liveStreamStatus$.getValue()==="active"?u.liveDuration===l.liveDuration:u.time===l.time)).subscribe(({time:u,liveDuration:l,playbackRate:p})=>{let c=i.position$.getValue(),{playbackCatchupSpeedup:d}=this.params.tuning.dashCmafLive.lowLatency;if(!c&&!this.video.paused&&p>=1-d||Fp(u)||Fp(l))return;let h=-1*(l-u-t);i.position$.next(Math.min(h,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(u=>{if(u){let l=PE(u);this.params.output.availableTextTracks$.next([l])}}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=Math.trunc(t/1e3<=Math.abs(this.params.output.duration$.getValue())?t:0);this.player.seekLive(i).then(()=>{this.params.output.position$.next(e/1e3)})}};var HE="X-Playback-Duration",qp=async s=>{let e=await Ke(s),t=await e.text(),i=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t)?.[1];return i?parseInt(i,10):e.headers.has(HE)?parseInt(e.headers.get(HE),10):void 0};import{assertNever as tO,combine as iO,debounce as rO,ErrorCategory as Nu,filter as sO,filterChanged as aO,isNonNullable as WE,isNullable as Fu,map as GE,merge as nO,observableFrom as oO,Subscription as uO,ValueSubject as zp,VideoQuality as lO}from"@vkontakte/videoplayer-shared/es2024";var Hp=D(fc(),1);import{videoSizeToQuality as z_,getExponentialDelay as Q_}from"@vkontakte/videoplayer-shared/es2024";var W_=s=>{let e=null;if(s.QUALITY&&(e=$t(s.QUALITY)),!e&&s.RESOLUTION){let[t,i]=s.RESOLUTION.split("x").map(r=>parseInt(r,10));e=z_({width:t,height:i})}return e??null},G_=(s,e)=>{let t=s.split(`
|
|
179
|
+
`),i=[],r=[];for(let a=0;a<t.length;a++){let n=t[a],o=n.match(/^#EXT-X-STREAM-INF:(.+)/),u=n.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!o&&!u)){if(o){let l=(0,Hp.default)(o[1].split(",").map(S=>S.split("="))),p=l.QUALITY??`stream-${l.BANDWIDTH}`,c=W_(l),d;l.BANDWIDTH&&(d=parseInt(l.BANDWIDTH,10)/1e3||void 0),!d&&l["AVERAGE-BANDWIDTH"]&&(d=parseInt(l["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let h=l["FRAME-RATE"]?parseFloat(l["FRAME-RATE"]):void 0,f;if(l.RESOLUTION){let[S,g]=l.RESOLUTION.split("x").map(v=>parseInt(v,10));S&&g&&(f={width:S,height:g})}let m=new URL(t[++a],e).toString();c&&i.push({id:p,quality:c,url:m,bandwidth:d,size:f,fps:h})}if(u){let l=(0,Hp.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,"")])),p=l.URI?.replace(/playlist$/,"subtitles.vtt"),c=l.LANGUAGE,d=l.NAME;p&&c&&r.push({type:"internal",id:c,label:d,language:c,url:p,isAuto:!1})}}}if(!i.length)throw new Error("Empty manifest");return{qualityManifests:i,textTracks:r}},Y_=s=>new Promise(e=>{setTimeout(()=>{e()},s)}),jp=0,zE=async(s,e=s,t,i)=>{let a=await(await Ke(s,i)).text();jp+=1;try{let{qualityManifests:n,textTracks:o}=G_(a,e);return{qualityManifests:n,textTracks:o}}catch{if(jp<=t.manifestRetryMaxCount)return await Y_(Q_(jp-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),zE(s,e,t)}return{qualityManifests:[],textTracks:[]}},_u=zE;import{isNonNullable as K_,Subscription as X_,throttle as J_,ValueSubject as QE,Subject as Z_,ErrorCategory as eO}from"@vkontakte/videoplayer-shared/es2024";var Ou=class{constructor(e,t,i,r,a){this.subscription=new X_;this.abortControllers={destroy:new j,nextManifest:null};this.prepareUrl=void 0;this.currentTextTrackData=null;this.availableTextTracks$=new QE(null);this.getCurrentTime$=new QE(null);this.error$=new Z_;this.params={fetchManifestData:i,sourceUrl:r,downloadThreshold:a},this.subscription.add(e.pipe(J_(1e3)).subscribe(n=>{this.processLiveTime(n)})),this.getCurrentTime$.next(()=>this.currentTextTrackData?this.currentTextTrackData.playlist.segmentStartTime/1e3+t.currentTime:0)}destroy(){this.subscription.unsubscribe(),this.abortControllers.destroy.abort()}async prepare(e){try{let t=new URL(e);t.searchParams.set("enable-subtitles","yes"),this.prepareUrl=t.toString();let{textTracks:i}=await this.fetchManifestData();await this.processTextTracks(i,this.params.sourceUrl)}catch(t){this.error("prepare",t)}}async processTextTracks(e,t){try{let i=await this.parseTextTracks(e,t);i&&(this.currentTextTrackData=i)}catch(i){this.error("processTextTracks",i)}}async parseTextTracks(e,t){for(let i of e){let r=new URL(i.url,t).toString(),n=await(await Ke(r,{signal:this.abortControllers.destroy.signal})).text(),o=this.parsePlaylist(n,r);return{textTrack:i,playlist:o}}}parsePlaylist(e,t){let i={mediaSequence:0,programDateTime:"",segments:[],targetDuration:0,vkPlaybackDuration:0,segmentStartTime:0,vkStartTime:""},r=e.split(`
|
|
180
|
+
`),a=0;for(let n=0;n<r.length;++n){let o=r[n];switch(!0){case o.startsWith("#EXTINF:"):{let u=r[++n],l=new URL(u,t).toString(),p=Number(this.extractPlaylistRowValue("#EXTINF:",o))*1e3;if(i.segments.push({time:{from:a,to:a+p},url:l}),a=a+p,!i.segmentStartTime){let c=new Date(i.vkStartTime).valueOf(),d=new Date(i.programDateTime).valueOf();i.segmentStartTime=d-c}break}case o.startsWith("#EXT-X-TARGETDURATION:"):i.targetDuration=Number(this.extractPlaylistRowValue("#EXT-X-TARGETDURATION:",o));break;case o.startsWith("#EXT-X-MEDIA-SEQUENCE:"):i.mediaSequence=Number(this.extractPlaylistRowValue("#EXT-X-MEDIA-SEQUENCE:",o));break;case o.startsWith("#EXT-X-VK-PLAYBACK-DURATION:"):i.vkPlaybackDuration=Number(this.extractPlaylistRowValue("#EXT-X-VK-PLAYBACK-DURATION:",o));break;case o.startsWith("#EXT-X-PROGRAM-DATE-TIME:"):{let u=this.extractPlaylistRowValue("#EXT-X-PROGRAM-DATE-TIME:",o);i.programDateTime=u;let l=new Date(u);l.setMilliseconds(0),a=l.valueOf();break}case o.startsWith("#EXT-X-VK-START-TIME:"):i.vkStartTime=this.extractPlaylistRowValue("#EXT-X-VK-START-TIME:",o);break}}return i}extractPlaylistRowValue(e,t){switch(e){case"#EXTINF:":return t.substring(e.length,t.length-1);default:return t.substring(e.length)}}processLiveTime(e){if(K_(e)&&this.currentTextTrackData){let{segments:t}=this.currentTextTrackData.playlist,{from:i}=t[0].time,{to:r}=t[t.length-1].time;if(e<i||e>r)return;r-e<this.params.downloadThreshold&&this.fetchNextManifestData();for(let n of t)if(n.time.from<=e&&n.time.to>=e){this.availableTextTracks$.next([{...this.currentTextTrackData.textTrack,url:n.url,isAuto:!0}]);break}}}async fetchNextManifestData(){try{if(this.abortControllers.nextManifest)return;this.abortControllers.nextManifest=new j;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:eO.WTF,thrown:t,message:e})}};var xn=class{constructor(e){this.subscription=new uO;this.videoState=new O("stopped");this.textTracksManager=null;this.liveTextManager=null;this.manifests$=new zp([]);this.liveOffset=new qi;this.manifestStartTime$=new zp(void 0);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.currentNativeBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),P(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(a||n||o){let p=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(p),this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if(r?.to!=="paused"&&l.state==="requested"){this.videoState.startTransitionTo("ready"),this.seek(l.position&&l.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":i==="ready"?P(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),P(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):r?.to==="playing"&&P(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 p=this.liveOffset.getTotalOffset();p>=this.maxSeekBackTime$.getValue()&&(p=0,this.liveOffset.resetTo(p)),this.liveOffset.resume(),this.params.output.position$.next(-p/1e3),this.prepare()}else r?.to==="paused"&&(P(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return tO(t)}};this.params=e,this.video=Pe(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:lO.INVARIANT,url:this.params.source.url};let t=(i,r)=>_u(i,this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},r);this.params.tuning.useHlsLiveNewTextManager?this.liveTextManager=new Ou(this.params.output.liveTime$,this.video,t,this.params.source.url,this.params.tuning.hlsLiveNewTextManagerDownloadThreshold):this.textTracksManager=new We(e.source.url),t(this.generateLiveUrl()).then(({qualityManifests:i,textTracks:r})=>{i.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:Nu.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.liveTextManager?.processTextTracks(r,this.params.source.url),this.manifests$.next([this.masterManifest,...i])}).catch(i=>{this.params.output.error$.next({id:"ExtractHlsQualities",category:Nu.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(ce(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new zp(e.source.maxSeekBackTime??1/0),this.subscribe()}selectManifest(){let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),a=r?.to?.id??t.getState()?.id??"master",n=this.manifests$.getValue();if(!n.length)return;let o=i?"master":a;return i&&!r&&t.startTransitionTo(this.masterManifest),n.find(u=>u.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsLiveProvider",category:Nu.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},r=$e(this.video);this.subscription.add(()=>r.destroy());let a=(o,u)=>this.subscription.add(o.subscribe(u,i));a(r.ended$,e.endedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.currentBuffer$,e.currentNativeBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.loadedMetadata$,e.loadedMetadataEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(Re(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Qe(this.video,t.playbackRate,r.playbackRateState$,i)),a(Ye(this.video),e.elementVisible$),this.liveTextManager?(a(this.liveTextManager.getCurrentTime$,this.params.output.getCurrentTime$),a(this.liveTextManager.error$,this.params.output.error$)):this.textTracksManager&&this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),P(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),P(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.liveTextManager&&this.subscription.add(this.liveTextManager.availableTextTracks$.subscribe(o=>{o&&this.params.output.availableTextTracks$.next(o)})),this.subscription.add(this.maxSeekBackTime$.pipe(aO(),GE(o=>-o/1e3)).subscribe(this.params.output.duration$,i)),this.subscription.add(r.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),p=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&WE(l.to)){let c=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let d=this.manifests$.getValue().find(h=>h.id===c);d&&(this.params.output.currentVideoTrack$.next(d),this.params.output.hostname$.next(ce(d.url)))}p&&this.params.desiredState.autoVideoTrackSwitching.setState(p.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o&&o.state==="requested"&&this.seek(o.position)},i)),this.subscription.add(r.loadedData$.subscribe(()=>{let o=this.video?.getStartDate?.()?.getTime();this.manifestStartTime$.next(o||void 0)},i)),this.subscription.add(iO({startTime:this.manifestStartTime$.pipe(sO(WE)),currentTime:r.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),i)),this.subscription.add(this.manifests$.pipe(GE(o=>o.map(({id:u,quality:l,size:p,bandwidth:c,fps:d})=>({id:u,quality:l,size:p,fps:d,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,i));let n=nO(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,oO(["init"])).pipe(rO(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),Ae(this.video)}prepare(){let e=this.selectManifest();if(Fu(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:o,min:u}=t?.to??i??{};for(let[l,p]of[[o,"mq"],[u,"lq"]]){let c=String(parseFloat(l||""));p&&l&&r.searchParams.set(p,c)}}let a=this.params.format==="HLS_LIVE_CMAF"?2:0,n=ne(r.toString(),this.liveOffset.getTotalOffset(),a);this.liveTextManager?.prepare(n),this.video.setAttribute("src",n),this.video.load(),qp(n).then(o=>{if(!Fu(o))this.maxSeekBackTime$.next(o);else{let u=this.params.source.maxSeekBackTime??this.maxSeekBackTime$.getValue();(Fu(u)||!isFinite(u))&&Ke(n).then(l=>l.text()).then(l=>{let p=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(l)?.[1];if(p){let c=new URL(p,n).toString();qp(c).then(d=>{Fu(d)||this.maxSeekBackTime$.next(d)})}}).catch(()=>{})}})}playIfAllowed(){Me(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),P(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Nu.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=ne(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 cO,debounce as dO,ErrorCategory as Qp,fromEvent as Wp,isNonNullable as pO,isNullable as hO,map as YE,merge as KE,observableFrom as XE,Subscription as fO,ValueSubject as JE,VideoQuality as mO}from"@vkontakte/videoplayer-shared/es2024";var kn=class{constructor(e){this.subscription=new fO;this.videoState=new O("stopped");this.manifests$=new JE([]);this.unmuteAfterBrowserResetsHappened=new JE(!1);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.currentNativeBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),P(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(a||n||o){let p=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(p);let{currentTime:c}=this.video;this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:c*1e3,forcePrecise:!0});return}switch(r?.to!=="paused"&&l.state==="requested"&&this.seek(l.position),t){case"ready":i==="ready"?P(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):r?.to==="playing"&&P(this.params.desiredState.playbackState,"playing");return;case"paused":i==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):r?.to==="paused"&&P(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return cO(t)}};this.textTracksManager=new We(e.source.url),this.params=e,this.video=Pe(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:mO.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(ce(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.manifestRequested$.next(),_u(ne(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:t,textTracks:i})=>{this.params.output.firstBytesManifest$.next(),this.manifests$.next([this.masterManifest,...t]),this.params.output.manifestReceived$.next(),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(i)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:Qp.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),a=r?.to?.id??t.getState()?.id??"master",n=this.manifests$.getValue();if(!n.length)return;let o=i?"master":a;return i&&(!r||!r.from)&&t.startTransitionTo(this.masterManifest),n.find(u=>u.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsProvider",category:Qp.WTF,message:"HlsProvider internal logic error",thrown:o})},r=$e(this.video);this.subscription.add(()=>r.destroy());let a=(o,u)=>this.subscription.add(o.subscribe(u));if(a(r.timeUpdate$,e.position$),a(r.durationChange$,e.duration$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.currentBuffer$,e.currentNativeBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.loadedMetadata$,e.loadedMetadataEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.seeked$,e.seekedEvent$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),a(this.videoState.stateChangeEnded$.pipe(YE(o=>o.to)),this.params.output.playbackState$),this.subscription.add(ot(this.video,t.isLooped,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Qe(this.video,t.playbackRate,r.playbackRateState$,i)),pi({subscription:this.subscription,desiredState:t,videoElement$:this.params.output.element$,observableVideo:r}),this.subscription.add(Re(this.video,t.volume,r.volumeState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),P(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),P(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i).add(r.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),p=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&pO(l.to)){let h=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let f=this.manifests$.getValue().find(m=>m.id===h);f&&(this.params.output.currentVideoTrack$.next(f),this.params.output.hostname$.next(ce(f.url)))}let c=this.params.desiredState.playbackRate.getState(),d=this.params.output.element$.getValue()?.playbackRate;if(c!==d){let h=this.params.output.element$.getValue();h&&(this.params.desiredState.playbackRate.setState(c),h.playbackRate=c)}p&&this.params.desiredState.autoVideoTrackSwitching.setState(p.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o.state==="requested"&&this.seek(o.position)},i))),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(r.ended$.subscribe(()=>{this.videoState.setState("paused"),P(t.playbackState,"paused")})),this.subscription.add(this.manifests$.pipe(YE(o=>o.map(({id:u,quality:l,size:p,bandwidth:c,fps:d})=>({id:u,quality:l,size:p,fps:d,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,i)),!$.device.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(KE(Wp(o,"addtrack"),Wp(o,"removetrack"),Wp(o,"change"),XE(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},i))}let n=KE(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,XE(["init"])).pipe(dO(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Ae(this.video)}prepare(){let e=this.selectManifest();if(hO(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:a,min:n}=t?.to??i??{};for(let[o,u]of[[a,"mq"],[n,"lq"]]){let l=String(parseFloat(o||""));u&&o&&r.searchParams.set(u,l)}}this.video.setAttribute("src",r.toString()),this.video.load()}playIfAllowed(){Me(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Qp.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var tw=D(ni(),1),Gp=D(Di(),1),iw=D(Ge(),1);import{assertNever as bO,assertNonNullable as ZE,debounce as gO,ErrorCategory as ew,isHigherOrEqual as SO,isLowerOrEqual as vO,isNonNullable as yO,merge as TO,observableFrom as IO,Subscription as EO,map as wO}from"@vkontakte/videoplayer-shared/es2024";var Pn=class{constructor(e){this.subscription=new EO;this.videoState=new O("stopped");this.trackUrls={};this.textTracksManager=new We;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.currentNativeBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),P(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let a=this.params.desiredState.autoVideoTrackLimits.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.seekState.getState();if(a&&e!=="ready"&&!n){this.handleQualityLimitTransition(a.to);return}if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(n){let{currentTime:u}=this.video;this.prepare(),o.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:u*1e3,forcePrecise:!0});return}switch(i?.to!=="paused"&&o.state==="requested"&&this.seek(o.position),e){case"ready":t==="ready"?P(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),P(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"&&P(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&P(this.params.desiredState.playbackState,"paused");return;default:return bO(e)}};this.params=e,this.video=Pe(e.container,e.tuning),this.params.output.element$.next(this.video),(0,tw.default)(this.params.source).reverse().forEach(([t,i],r)=>{let a=r.toString(10);this.trackUrls[a]={track:{quality:t,id:a},url:i}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next((0,Gp.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:ew.WTF,message:"MpegProvider internal logic error",thrown:o})},r=$e(this.video);this.subscription.add(()=>r.destroy());let a=(o,u)=>this.subscription.add(o.subscribe(u,i));a(r.timeUpdate$,e.position$),a(r.durationChange$,e.duration$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentNativeBuffer$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.loadedMetadata$,e.loadedMetadataEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.seeked$,e.seekedEvent$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),a(this.videoState.stateChangeEnded$.pipe(wO(o=>o.to)),this.params.output.playbackState$),this.subscription.add(ot(this.video,t.isLooped,i)),pi({subscription:this.subscription,desiredState:t,videoElement$:this.params.output.element$,observableVideo:r}),this.subscription.add(Re(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Qe(this.video,t.playbackRate,r.playbackRateState$,i)),a(Ye(this.video),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),P(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),P(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready");let o=this.params.desiredState.videoTrack.getTransition();if(o&&yO(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 p=this.params.output.element$.getValue();p&&(this.params.desiredState.playbackRate.setState(u),p.playbackRate=u)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(r.ended$.subscribe(()=>{this.videoState.setState("paused"),P(t.playbackState,"paused")})),this.textTracksManager.connect(this.video,t,e);let n=TO(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,IO(["init"])).pipe(gO(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),Ae(this.video)}prepare(){let e=this.params.desiredState.videoTrack.getState()?.id;ZE(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];ZE(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=Tt(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(ce(t))}playIfAllowed(){Me(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:ew.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 p=ut(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(p)},r=this.params.output.currentVideoTrack$.getValue()?.quality,a=!!(e.max||e.min),n=(0,Gp.default)(this.trackUrls).map(l=>l.track);if(!r||!a||Cr(e,n[0].quality,(0,iw.default)(n,-1)?.quality)){i();return}let o=e.max?vO(r,e.max):!0,u=e.min?SO(r,e.min):!0;o&&u||i(e)}};import{assertNever as sw,debounce as AO,merge as aw,observableFrom as RO,Subscription as $O,map as nw,ValueSubject as MO,ErrorCategory as Kp,VideoQuality as LO}from"@vkontakte/videoplayer-shared/es2024";import{ErrorCategory as xO}from"@vkontakte/videoplayer-shared/es2024";var rw=["stun:videostun.mycdn.me:80"],kO=1e3,PO=3,Yp=()=>null,Uu=class{constructor(e,t){this.ws=null;this.peerConnection=null;this.serverUrl="";this.streamKey="";this.stream=null;this.signalingType="JOIN";this.retryCount=0;this.externalStartCallback=Yp;this.externalStopCallback=Yp;this.externalErrorCallback=Yp;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:rw}]};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:xO.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),kO)}normalizeOptions(e={}){let t={stunServerList:rw,maxRetryNumber:PO,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var An=class{constructor(e){this.videoState=new O("stopped");this.maxSeekBackTime$=new MO(0);this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.pause(),this.video.srcObject=null,this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.currentNativeBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),P(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let a=this.params.desiredState.videoTrack.getTransition();if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(a){this.prepare();return}switch(e){case"ready":t==="paused"?(this.videoState.setState("paused"),P(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"&&P(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&P(this.params.desiredState.playbackState,"paused");return;default:return sw(e)}};this.subscription=new $O,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=Pe(e.container,e.tuning),this.liveStreamClient=new Uu(this.params.source.url,{maxRetryNumber:this.params.tuning.webrtc.connectionRetryMaxNumber,errorChanel:this.params.output.error$}),this.liveStreamClient.onStart(this.onLiveStreamStart.bind(this)),this.liveStreamClient.onStop(this.onLiveStreamStop.bind(this)),this.liveStreamClient.onError(this.onLiveStreamError.bind(this)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),Ae(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,i=n=>{e.error$.next({id:"WebRTCLiveProvider",category:Kp.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};this.subscription.add(aw(this.videoState.stateChangeStarted$.pipe(nw(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(nw(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})}));let r=$e(this.video);this.subscription.add(()=>r.destroy());let a=(n,o)=>this.subscription.add(n.subscribe(o,i));a(r.timeUpdate$,e.liveTime$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.currentBuffer$,e.currentNativeBuffer$),a(Ye(this.video),this.params.output.elementVisible$),this.subscription.add(r.durationChange$.subscribe(n=>{e.duration$.next(n===1/0?0:n)})).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused")},i)).add(r.playing$.subscribe(()=>{this.videoState.setState("playing")},i)).add(r.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(Re(this.video,t.volume,r.volumeState$,i)).add(r.volumeState$.subscribe(e.volume$,i)).add(this.videoState.stateChangeEnded$.subscribe(n=>{switch(n.to){case"stopped":e.position$.next(0),e.duration$.next(0),t.playbackState.setState("stopped");break;case"ready":break;case"paused":t.playbackState.setState("paused");break;case"playing":t.playbackState.setState("playing");break;default:return sw(n.to)}},i)).add(aw(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,RO(["init"])).pipe(AO(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(ce(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:LO.INVARIANT}),this.video.srcObject=e,P(this.params.desiredState.playbackState,"playing")}onLiveStreamStop(){this.videoState.startTransitionTo("stopped"),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.currentNativeBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.params.output.endedEvent$.next()}onLiveStreamError(e){this.onLiveStreamStop(),this.params.output.error$.next({id:"WebRTC stream runtime error",category:Kp.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){Me(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Kp.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var Ss=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 Rn,assertNonNullable as Kt,ErrorCategory as qu,filter as pw,isNonNullable as hw,isNullable as NO,map as FO,merge as UO,once as qO,Subject as ie,Subscription as fw,ValueSubject as U,flattenObject as Xp,devNull as jO}from"@vkontakte/videoplayer-shared/es2024";import{Observable as DO,map as ow,Subscription as BO,Subject as CO}from"@vkontakte/videoplayer-shared/es2024";var uw=s=>new DO(e=>{let t=new BO,i=s.desiredPlaybackState$.stateChangeStarted$.pipe(ow(({from:l,to:p})=>`${l}-${p}`)),r=s.desiredPlaybackState$.stateChangeEnded$,a=s.providerChanged$.pipe(ow(({type:l})=>l!==void 0)),n=new CO,o=0,u="unknown";return t.add(i.subscribe(l=>{o&&window.clearTimeout(o),u=l,o=window.setTimeout(()=>n.next(l),s.maxTransitionInterval),_({m:"hangup.set",l,id:o})})),t.add(r.subscribe(()=>{_({m:"hangup.cl",id:o}),window.clearTimeout(o),u="unknown",o=0})),t.add(a.subscribe(l=>{o&&(_({m:"hangup.rs.0",id:o}),window.clearTimeout(o),o=0,l&&(o=window.setTimeout(()=>n.next(u),s.maxTransitionInterval),_({m:"hangup.rs.1",id:o})))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});import{ErrorCategory as VO,Subscription as _O,combine as OO,filter as cw,once as dw}from"@vkontakte/videoplayer-shared/es2024";function lw(){return new(window.AudioContext||window.webkitAudioContext)}var vs=class s{constructor(e,t,i,r){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=i;this.volumeMultiplier=r;this.destroyController=new j;this.subscriptions=new _O;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe(cw(a=>!!a.type),dw()).subscribe(({type:a})=>this.subscribe(a)))}static{this.errorId="VolumeMultiplierManager"}subscribe(e){$.browser.isSafari&&e!=="MPEG"||this.subscriptions.add(OO({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(cw(({playbackState:t,video:i,volume:{muted:r,volume:a}})=>t==="playing"&&!!i&&!r&&!!a),dw()).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=lw();this.audioContext=i;let r=i.createGain();if(this.gainNode=r,r.gain.value=t,r.connect(i.destination),i.state==="suspended"&&(await i.resume(),this.destroyController.signal.aborted))return!1;let a=i.createMediaElementSource(e);return this.mediaElementSource=a,a.connect(r),!0}cleanup(){this.mediaElementSource&&(this.mediaElementSource.disconnect(),this.mediaElementSource=null),this.gainNode&&(this.gainNode.disconnect(),this.gainNode=null),this.audioContext&&(this.audioContext.state!=="closed"&&this.audioContext.close(),this.audioContext=null)}destroy(){this.destroyController.abort(),this.subscriptions.unsubscribe(),this.cleanup()}handleError(e){this.volumeMultiplierError$.next({id:s.errorId,category:VO.VIDEO_PIPELINE,message:e?.message??`${s.errorId} exception`,thrown:e})}};var HO={chunkDuration:5e3,maxParallelRequests:5},$n=class{constructor(e){this.current$=new U({type:void 0});this.providerError$=new ie;this.noAvailableProvidersError$=new ie;this.volumeMultiplierError$=new ie;this.providerOutput={position$:new U(0),duration$:new U(1/0),volume$:new U({muted:!1,volume:1}),availableVideoStreams$:new U([]),currentVideoStream$:new U(void 0),availableVideoTracks$:new U([]),currentVideoTrack$:new U(void 0),availableVideoCodecs$:new U([]),availableAudioStreams$:new U([]),currentAudioStream$:new U(void 0),availableAudioTracks$:new U([]),availableAudioCodecs$:new U([]),currentVideoSegmentLength$:new U(0),currentAudioSegmentLength$:new U(0),isAudioAvailable$:new U(!0),autoVideoTrackLimitingAvailable$:new U(!1),autoVideoTrackLimits$:new U(void 0),currentBuffer$:new U(void 0),currentNativeBuffer$:new U(void 0),isBuffering$:new U(!0),error$:new ie,fetcherError$:new ie,fetcherRecoverableError$:new ie,warning$:new ie,willSeekEvent$:new ie,soundProhibitedEvent$:new ie,seekedEvent$:new ie,loopedEvent$:new ie,endedEvent$:new ie,manifestRequested$:new ie,firstBytesManifest$:new ie,manifestReceived$:new ie,firstBytesRequested$:new ie,firstBytesReceived$:new ie,firstBytesEvent$:new ie,loadedMetadataEvent$:new ie,firstFrameEvent$:new ie,canplay$:new ie,isLive$:new U(void 0),isLiveEnded$:new U(null),canPlayLiveTailBuffer$:new U(!1),isLowLatency$:new U(!1),canChangePlaybackSpeed$:new U(!0),liveTime$:new U(void 0),liveBufferTime$:new U(void 0),liveLatency$:new U(void 0),severeStallOccurred$:new ie,availableTextTracks$:new U([]),currentTextTrack$:new U(void 0),hostname$:new U(void 0),httpConnectionType$:new U(void 0),httpConnectionReused$:new U(void 0),inPiP$:new U(!1),inFullscreen$:new U(!1),element$:new U(void 0),elementVisible$:new U(!0),availableSources$:new U(void 0),is3DVideo$:new U(!1),playbackState$:new U(""),getCurrentTime$:new U(null)};this.subscription=new fw;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=Nl([...RI(this.params.tuning),...AI(this.params.tuning)]).filter(l=>hw(e.sources[l])),{forceFormat:i,formatsToAvoid:r}=this.params.tuning,a=[];i?a=[i]:r.length?a=[...t.filter(l=>!(0,Jp.default)(r,l)),...t.filter(l=>(0,Jp.default)(r,l))]:a=t,this.log({message:`Selected formats: ${a.join(" > ")}`}),this.tracer.log("Selected formats",Xp(a)),this.screenFormatsIterator=new Ss(a);let n=[...Yd(!0),...Yd(!1)];this.chromecastFormatsIterator=new Ss(n.filter(l=>hw(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:o=1,tuning:{useVolumeMultiplier:u}}=this.params;u&&o!==1&&vs.isSupported()&&(this.volumeMultiplierManager=new vs(this.providerOutput,this.current$,this.volumeMultiplierError$,o))}init(){_.reset(),this.subscription.add(this.initProviderErrorHandling()).add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()})).add(this.providerOutput.availableVideoCodecs$.subscribe(e=>{!this.videoCodecsIterator&&e.length>1&&(this.videoCodecsIterator=new Ss(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(NO(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:qu.WTF,message:"Failed to create provider",thrown:r})}i?this.current$.next({type:t,provider:i,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.tracer.log("reinitProvider"),this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.tracer.log("switchToNextProvider",{destination:e}),this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}switchToNextVideoCodec(){this.params.tuning.dash.codecsPrioritizeEnabled&&!this.videoCodecsIterator.isLast()&&(this.tracer.log("switchToNextVideoCodec"),this.destroyProvider(),this.videoCodecsIterator.next(),this.initProvider())}destroyProvider(){let e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"}),this.tracer.log("destroyProvider"),e.destroy();let t=this.providerOutput.position$.getValue()*1e3,i=this.params.desiredState.seekState.getState(),r=i.state!=="none";if(this.params.desiredState.seekState.setState({state:"requested",position:r?i.position:t,forcePrecise:r?i.forcePrecise:!1}),e.scene3D){let n=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:n.x,y:n.y})}let a=this.providerOutput.isBuffering$;a.getValue()||a.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),this.tracer.log("createProvider",{destination:e,format:t}),e){case"SCREEN":return this.createScreenProvider(t);case"CHROMECAST":return this.createChromecastProvider(t);default:return Rn(e)}}createScreenProvider(e){let{sources:t,container:i,desiredState:r,panelSize:a}=this.params,n=this.providerOutput,o={container:i,source:null,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning,panelSize:a};switch(e){case"DASH_SEP":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_ONDEMAND":case"DASH_STREAMS":{let u=this.applyFailoverHost(t[e]),l=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return Kt(u),this.params.tuning.useNewDashProvider?new En({...o,source:u,sourceHls:l,forceVideoCodec:this.videoCodecsIterator?.getValue()}):this.params.tuning.useDashProviderVirtual&&!$.device.isMobile?new as({...o,source:u,sourceHls:l,forceVideoCodec:this.videoCodecsIterator?.getValue()}):this.params.tuning.useDashProviderVirtualMobile&&$.device.isMobile?new as({...o,source:u,sourceHls:l,forceVideoCodec:this.videoCodecsIterator?.getValue()}):new ln({...o,source:u,sourceHls:l,forceVideoCodec:this.videoCodecsIterator?.getValue()})}case"DASH_LIVE_CMAF":{let u=this.applyFailoverHost(t[e]);return Kt(u),this.params.tuning.useNewDashProvider?new wn({...o,source:u}):new cn({...o,source:u})}case"HLS":case"HLS_ONDEMAND":case"HLS_FMP4":{let u=this.applyFailoverHost(t[e]);return Kt(u),new kn({...o,source:u})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let u=this.applyFailoverHost(t[e]);return Kt(u),new xn({...o,source:u,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let u=this.applyFailoverHost(t[e]);return Kt(u),new Pn({...o,source:u})}case"DASH_LIVE":{let u=this.applyFailoverHost(t[e]);return Kt(u),new My({...o,source:u,config:{...HO,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let u=this.applyFailoverHost(t[e]);return Kt(u),new An({container:i,source:u,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return Rn(e)}}createChromecastProvider(e){let{sources:t,container:i,desiredState:r,meta:a}=this.params,n=this.providerOutput,o={meta:a,container:i,source:t,format:e,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning};if(this.params.tuning.chromecastPresentationApi&&this.params.dependencies.chromecastInitializer instanceof _t){let{chromecastConnector:l}=this.params.dependencies.chromecastInitializer;return Kt(l),new Os({...o,chromecastConnector:l})}let u=this.params.dependencies.chromecastInitializer.connection$.getValue();return Kt(u),new ea({...o,connection:u})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?"CHROMECAST":"SCREEN"}chooseFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case"CHROMECAST":return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return Rn(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return Rn(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 Rn(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;let t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;let i=r=>{let a=new URL(r);return a.host=t,a.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return{...e,url:i(e.url)}}return(0,mw.default)((0,Zp.default)(e).map(([r,a])=>[r,i(a)]))}initProviderErrorHandling(){let e=new fw,t=!1,i=0;e.add(UO(this.providerOutput.error$.pipe(pw(a=>!this.params.tuning.ignoreAudioRendererError||!a.message||!/AUDIO_RENDERER_ERROR/ig.test(a.message))),uw({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(FO(a=>({id:`ProviderHangup:${a}`,category:qu.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(pw(({to:n})=>n==="playing"),qO()).subscribe(()=>t=!0);e.add(a)}));let r=()=>{let a=_.drain(),{logDashLiveDebug:n,sendDashLiveDebug:o}=this.params.tuning;if(n&&window.console.log(`===== DASH_LIVE DEBUG START ====
|
|
181
|
+
`,a.map(({time:u,data:l,stack:p})=>`${u}: ${JSON.stringify(l)}${p?`
|
|
182
|
+
`+p:""}`).join(`
|
|
183
|
+
`),`
|
|
184
|
+
===== DASH_LIVE DEBUG END ====`),o){let u=a.reduce((l,{time:p,data:c,stack:d})=>{let h=(0,Zp.default)(c).map(([f,m])=>`${f}:${m}`).join(",");return l+=`${p}: ${h}${d?`: ${d}`:""};`,l},"");jO.push("core",{key:"vp_dash_live_debug",strings:[u]})}};return e.add(this.providerError$.subscribe(a=>{a.id.startsWith("ProviderHangup")&&(_({m:"final.0",e:a.id}),r())})).add(this.noAvailableProvidersError$.subscribe(()=>{_({m:"final.1"}),r()})),e.add(this.providerError$.subscribe(a=>{let n=this.current$.getValue().destination,o={error:a,currentDestination:n};if(n==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("CHROMECAST"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let u=a.category===qu.NETWORK,l=a.category===qu.FATAL,p=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),c=i<this.params.tuning.providerErrorLimit&&!l,d=this.videoCodecsIterator&&!this.videoCodecsIterator.isLast()&&this.params.tuning.dash.codecsPrioritizeEnabled,h=p&&!l&&(u&&t||!c);o={...o,isNetworkError:u,isFatalError:l,haveFailoverHost:p,tryFailover:h,canReinitProvider:c},c?(i++,this.reinitProvider()):h?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):d?this.switchToNextVideoCodec():(i=0,this.switchToNextProvider(n??"SCREEN"))}a.traceAsLog?this.tracer.log("providerInfo",Xp(o)):this.tracer.error("providerError",Xp(o))})),e}};import{fromEvent as ju,once as zO,combine as QO,Subscription as bw,ValueSubject as eh,map as gw,filter as WO,isNonNullable as Hu,now as st,safeStorage as th}from"@vkontakte/videoplayer-shared/es2024";var GO=5e3,Sw="one_video_throughput",vw="one_video_rtt",Mn=window.navigator.connection,yw=()=>{let s=Mn?.downlink;if(Hu(s)&&s!==10)return s*1e3},Tw=()=>{let s=Mn?.rtt;if(Hu(s)&&s!==3e3)return s},Iw=(s,e,t)=>{let i=t*8,r=i/s;return i/(r+e)},ih=class s{constructor(e){this.subscription=new bw;this.concurrentDownloads=new Set;this.tuningConfig=e;let t=s.load(Sw)||(e.useBrowserEstimation?yw():void 0)||GO,i=s.load(vw)??(e.useBrowserEstimation?Tw():void 0)??0;if(this.throughput$=new eh(t),this.rtt$=new eh(i),this.rttAdjustedThroughput$=new eh(Iw(t,i,e.rttPenaltyRequestSize)),this.throughput=Qt.getSmoothedValue(t,-1,e),this.rtt=Qt.getSmoothedValue(i,1,e),e.useBrowserEstimation){let r=()=>{let n=yw();n&&this.throughput.next(n);let o=Tw();Hu(o)&&this.rtt.next(o)};Mn&&"onchange"in Mn&&this.subscription.add(ju(Mn,"change").subscribe(r)),r()}this.subscription.add(this.throughput.smoothed$.subscribe(r=>{th.set(Sw,r.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(r=>{th.set(vw,r.toFixed(0))})),this.subscription.add(this.throughput.debounced$.pipe(gw(r=>Math.round(r))).subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(QO({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(gw(({throughput:r,rtt:a})=>Iw(r,a,e.rttPenaltyRequestSize)),WO(r=>{let a=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(r-a)/a>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,i=st(),r=new bw;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add(ju(e,"progress").pipe(zO()).subscribe(a=>{t=a.loaded,i=st()}));break;case 1:case 0:r.add(ju(e,"loadstart").subscribe(()=>{t=0,i=st()}));break}r.add(ju(e,"loadend").subscribe(a=>{if(e.status===200){let n=a.loaded,o=st(),u=n-t,l=o-i;this.addRawSpeed(u,l,1)}this.concurrentDownloads.delete(e),r.unsubscribe()}))}trackStream(e,t=!1){let i=e.getReader();if(!i){e.cancel("Could not get reader");return}let r=0,a=st(),n=0,o=st(),u=p=>{this.concurrentDownloads.delete(e),i.releaseLock(),e.cancel(`Throughput Estimator error: ${p}`).catch(()=>{})},l=async({done:p,value:c})=>{if(p)!t&&this.addRawSpeed(r,st()-a,1),this.concurrentDownloads.delete(e);else if(c){if(t){let d=st();if(d-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||d-a>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let f=o-a;f&&this.addRawSpeed(n,f,1,t),n=c.byteLength,a=st()}else n+=c.byteLength;o=st()}else r+=c.byteLength,n+=c.byteLength,n>=this.tuningConfig.streamMinSampleSize&&st()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,st()-o,this.concurrentDownloads.size),n=0,o=st());await i?.read().then(l,u)}};this.concurrentDownloads.add(e),i?.read().then(l,u)}addRawSpeed(e,t,i=1,r=!1){if(s.sanityCheck(e,t,r)){let a=e*8/t;this.throughput.next(a*i)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,i=!1){let r=e*8/t;return!(!r||!isFinite(r)||r>1e6||r<30||i&&e<1e4||!i&&e<10*1024||!i&&t<=20)}static load(e){let t=th.get(e);if(Hu(t))return parseInt(t,10)??void 0}},Ew=ih;import{fillWithDefault as YO,VideoQuality as zu}from"@vkontakte/videoplayer-shared/es2024";var ww={configName:["core"],throughputEstimator:{type:"EmaAndMa",emaAlphaSlow:.2,emaAlphaFast:.7,emaAlpha:.45,basisTrendChangeCount:10,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1*1024*1024,streamMinSampleSize:10*1024,streamMinSampleTime:300,deviationDepth:20,deviationFactor:.5,lowLatency:{continuesByteSequenceInterval:50,maxLastEvaluationTimeout:300}},autoTrackSelection:{maxBitrateFactorAtEmptyBuffer:4,bitrateFactorAtEmptyBuffer:2.8,minBitrateFactorAtEmptyBuffer:1.5,bitrateAudioFactorAtEmptyBuffer:10,maxBitrateFactorAtFullBuffer:3,bitrateFactorAtFullBuffer:2,minBitrateFactorAtFullBuffer:1,bitrateAudioFactorAtFullBuffer:7,minVideoAudioRatio:5,minAvailableThroughputAudioRatio:5,usePixelRatio:!0,pixelRatioMultiplier:void 0,pixelRatioLogBase:3,pixelRatioLogCoefficients:[1,0,1],limitByContainer:!0,maxContainerSizeFactor:2,containerSizeFactor:1.3,minContainerSizeFactor:1,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldownIncreaseQuality:15e3,trackCooldownDecreaseQuality:3e3,backgroundVideoQualityLimit:zu.Q_4320P,activeVideoAreaThreshold:.1,highQualityLimit:zu.Q_720P,trafficSavingLimit:zu.Q_480P},stallsManager:{enabled:!1,ignoreDynamicAbrForShortVideo:!1,stallDurationNoDataBeforeQualityDecrease:500,stallDurationToBeCount:100,stallCountBeforeQualityDecrease:3,resetQualityRestrictionTimeout:1e4,ignoreStallsOnSeek:!0,stallsMetricsHistoryLength:20,maxPossibleStallDuration:3e4,minTvtToBeCounted:120,maxTvtToBeCounted:10800,significantTvt:600,targetStallsDurationPerTvt:1,deviationStallsDurationPerTvt:.5,criticalStallsDurationPerTvt:6,abrAdjustingSpeed:.1,emaAlpha:.6,useTotalStallsDurationPerTvt:!0,useAverageStallsDurationPerTvt:!0,useEmaStallsDurationPerTvt:!0},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:zu.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,seekBiasInTheEnd:2e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,maxVirtualBufferSize:250*1024*1024,virtualBufferPruneSize:100*1024*1024,representationSwitchForwardBufferGap:15e3,crashOnStallTimeout:25e3,crashOnStallTWithoutDataTimeout:5e3,enableSubSegmentBufferFeeding:!0,bufferEmptinessTolerance:100,useNewRepresentationSwitch:!1,useDelayedRepresentationSwitch:!1,useSmartRepresentationSwitch:!1,useFetchPriorityHints:!0,useAbortMSEFix:!1,enableBaseUrlSupport:!0,maxSegmentRetryCount:5,sourceOpenTimeout:1e3,vktvAbrThrottle:0,timeupdateEventTickThrottle:300,fetcherBufferOptimisation:!0,codecsPrioritizeEnabled:!1,usePersistentGaps:!1,abrThrottle:0,useVideoElementWaitingCurrentTimeReassign:!0,stallWatchdogInterval:100,liveUpdateInterval:1e3,liveStallReinitInterval:3e3,ignoreNetworkErrorsOnLoadInit:!1,bufferTolerance:100,actionTimeShiftFromSegment:500},dashCmafLive:{externalStopControl:!1,keepSilentStallWatchdogWhenNotActive:!1,maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,maxLiveDuration:7200,catchupLiveForMutedInactiveTab:!0,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:250,playbackCatchupSpeedup:.05,isActiveOnDefault:!1,bufferEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:"07A4434E",chromecastPresentationApi:!1,useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"dash",iosPreferredFormat:"hls",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,useNewSwitchTo:!1,useNewDashProvider:!1,useDashProviderVirtual:!1,useDashProviderVirtualMobile:!1,useNewAutoSelectVideoTrack:!1,useSafariEndlessRequestBugfix:!0,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,useHlsLiveNewTextManager:!1,exposeInternalsToGlobal:!1,hlsLiveNewTextManagerDownloadThreshold:4e3,disableYandexPiP:!1,asyncResolveClientChecker:!1,autostartOnlyIfVisible:!1,changePlaybackStateToPausedWhenEnded:!1,suppressExceptionsInObservables:!0,devNullLogEnabled:!1,collectingDecodingInfoEnabled:!1,sendDashLiveDebug:!1,logDashLiveDebug:!1},xw=s=>({...YO(s,ww),configName:[...s.configName??[],...ww.configName]});import{assertNonNullable as sh,combine as Xt,ErrorCategory as Qu,filter as fe,filterChanged as Y,fromEvent as ah,isNonNullable as Mw,isNullable as nN,Logger as oN,map as G,mapTo as Lw,merge as Ei,now as Wu,once as ye,Subject as Q,Subscription as Dw,tap as nh,ValueSubject as M,isHigher as uN,isInvariantQuality as Bw,flattenObject as wi,throttle as oh,getTraceSubscriptionMethod as Cw,TracerFactory as lN,InternalsExposure as cN,getPlayerId as dN,devNull as Gu}from"@vkontakte/videoplayer-shared/es2024";import{merge as KO,map as XO,filter as kw,isNonNullable as JO}from"@vkontakte/videoplayer-shared/es2024";var rh=({seekState:s,position$:e})=>KO(s.stateChangeEnded$.pipe(XO(({to:t})=>t.state==="none"?void 0:(t.position??NaN)/1e3),kw(JO)),e.pipe(kw(()=>s.getState().state==="none")));import{assertNonNullable as ZO}from"@vkontakte/videoplayer-shared/es2024";var Pw=s=>{let e=typeof s.container=="string"?document.getElementById(s.container):s.container;return ZO(e,`Wrong container or containerId {${s.container}}`),e};import{filter as eN,once as tN}from"@vkontakte/videoplayer-shared/es2024";var Aw=(s,e,t,i)=>{s!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&t?.getValue().length===0?t.pipe(eN(r=>r.length>0),tN()).subscribe(r=>{r.find(i)&&e.startTransitionTo(s)}):(s===void 0||t?.getValue().find(i))&&e.startTransitionTo(s)};var Rw=D(ni(),1);import{devNull as iN}from"@vkontakte/videoplayer-shared/es2024";var $w=()=>{let s="mediaCapabilities"in navigator?rN:sN,e=Mt(async()=>{let t=await Promise.all((0,Rw.default)(aN).map(async([r,a])=>({codec:r,supported:await s(a)}))),i=[$.browser.current,...t.map(r=>JSON.stringify(r))].slice(0,16);return iN.push("core",{key:"videoplayer_decoding_info",strings:i}),t});return()=>qe(e)},rN=async s=>{if(!s)return Promise.resolve({supported:!1});let e={["channels"in s?"audio":"video"]:s};return await navigator.mediaCapabilities.decodingInfo({type:"media-source",...e})},sN=s=>{if(!s)return Promise.resolve({supported:!1});let e="channels"in s?document.createElement("audio"):document.createElement("video");return Promise.resolve({supported:e.canPlayType(s?.contentType??"")==="probably"})},aN={H264:{contentType:'video/mp4; codecs="avc1.4D400C"',width:720,height:720,bitrate:2886,framerate:30},H265:{contentType:'video/mp4; codecs="hvc1.1.6.L123.B0"',width:720,height:720,bitrate:2886,framerate:30},VP8:{contentType:'video/webm; codecs="vp8"',width:720,height:720,bitrate:2886,framerate:30},VP9:{contentType:'video/webm; codecs="vp09.00.10.08"',width:720,height:720,bitrate:2886,framerate:30},AV1:{contentType:'video/mp4; codecs="av01.0.01M.08"',width:720,height:720,bitrate:2886,framerate:30},OPUS:{contentType:'audio/ogg; codecs="opus"',channels:"2",bitrate:128e3},AAC_LC:{contentType:'audio/mp4; codecs="mp4a.40.2"',channels:"2",bitrate:128e3},AC3:{contentType:'audio/mp4; codecs="ac-3"',channels:"6",bitrate:128e3},EAC3:{contentType:'audio/mp4; codecs="ec-3"',channels:"6",bitrate:128e3},AAC_HE_V1:{contentType:'audio/mp4; codecs="mp4a.40.5"',channels:"2",bitrate:128e3},AAC_HE_V2:{contentType:'audio/mp4; codecs="mp4a.40.29"',channels:"2",bitrate:128e3},AAC_xHE:{contentType:'audio/mp4; codecs="mp4a.40.42"',channels:"2",bitrate:128e3}};var Yu=class{constructor(e={configName:[]},t=lN.createRootTracer(!1),i){this.subscription=new Dw;this.logger=new oN;this.abrLogger=this.logger.createComponentLog("ABR");this.internalsExposure=null;this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new M(!1);this.hasLiveOffsetByPausedTimer=0;this.playerInitRequest=0;this.playerInited=new M(!1);this.wasSetStartedQuality=!1;this.desiredState={playbackState:new O("stopped"),seekState:new O({state:"none"}),volume:new O({volume:1,muted:!1}),videoTrack:new O(void 0),videoStream:new O(void 0),audioStream:new O(void 0),autoVideoTrackSwitching:new O(!0),autoVideoTrackLimits:new O({}),isLooped:new O(!1),isLowLatency:new O(!1),playbackRate:new O(1),externalTextTracks:new O([]),internalTextTracks:new O([]),currentTextTrack:new O(void 0),textTrackCuesSettings:new O({}),cameraOrientation:new O({x:0,y:0})};this.info={playbackState$:new M(void 0),position$:new M(0),duration$:new M(1/0),muted$:new M(!1),volume$:new M(1),availableVideoStreams$:new M([]),currentVideoStream$:new M(void 0),availableQualities$:new M([]),availableQualitiesFps$:new M({}),currentQuality$:new M(void 0),isAutoQualityEnabled$:new M(!0),autoQualityLimitingAvailable$:new M(!1),autoQualityLimits$:new M({}),predefinedQualityLimitType$:new M("unknown"),availableAudioStreams$:new M([]),currentAudioStream$:new M(void 0),availableAudioTracks$:new M([]),isAudioAvailable$:new M(!0),currentPlaybackRate$:new M(1),currentBuffer$:new M({start:0,end:0}),currentNativeBuffer$:new M({start:0,end:0}),isBuffering$:new M(!0),isStalled$:new M(!1),isEnded$:new M(!1),isLooped$:new M(!1),isLive$:new M(void 0),isLiveEnded$:new M(null),canPlayLiveTailBuffer$:new M(!1),canChangePlaybackSpeed$:new M(void 0),atLiveEdge$:new M(void 0),atLiveDurationEdge$:new M(void 0),liveTime$:new M(void 0),liveBufferTime$:new M(void 0),liveLatency$:new M(void 0),currentFormat$:new M(void 0),availableTextTracks$:new M([]),currentTextTrack$:new M(void 0),throughputEstimation$:new M(void 0),rttEstimation$:new M(void 0),videoBitrate$:new M(void 0),hostname$:new M(void 0),httpConnectionType$:new M(void 0),httpConnectionReused$:new M(void 0),surface$:new M("none"),chromecastState$:new M("NOT_AVAILABLE"),chromecastDeviceName$:new M(void 0),intrinsicVideoSize$:new M(void 0),availableSources$:new M(void 0),is3DVideo$:new M(!1),currentVideoSegmentLength$:new M(0),currentAudioSegmentLength$:new M(0)};this.events={inited$:new Q,ready$:new Q,started$:new Q,playing$:new Q,paused$:new Q,stopped$:new Q,willReady$: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,manifestRequested$:new Q,firstBytesManifest$:new Q,manifestReceived$:new Q,firstBytesRequested$:new Q,firstBytesReceived$: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 M(void 0),tuningConfigName$:new M([]),enableDebugTelemetry$:new M(!1),dumpTelemetry:ey,getCurrentTime$:new M(null)};this.initLogs(),this.tuning=xw(e),this.tracer=t,this.tuning.suppressExceptionsInObservables&&((0,uh.default)(this.info).forEach(a=>a.setSuppressErrors(!0)),(0,uh.default)(this.events).forEach(a=>a.setSuppressErrors(!0))),this.experimental.tuningConfigName$.next(this.tuning.configName);let r={receiverApplicationId:this.tuning.chromecastReceiverId,isDisabled:this.tuning.disableChromecast,dependencies:{logger:this.logger}};if(this.chromecastInitializer=this.tuning.chromecastPresentationApi?new _t(r):new Yn(r),this.throughputEstimator=new Ew(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new cN("core",dN(i?.playerId)),this.internalsExposure.expose({player:this})),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),this.devNullLog=i?.onDevNullLog,Gu.create("core"),Proxy&&Reflect)return new Proxy(this,{get:(a,n,o)=>{let u=Reflect.get(a,n,o);return typeof u!="function"?u:(...l)=>{try{return u.apply(a,l)}catch(p){let c=l.map(f=>JSON.stringify(f,(m,S)=>{let g=typeof S;return(0,Vw.default)(["number","string","boolean"],g)?S:S===null?null:`<${g}>`})),d=`Player.${String(n)}`,h=`Exception calling ${d} (${c.join(", ")})`;throw this.events.fatalError$.next({id:d,category:Qu.WTF,message:h,thrown:p}),p}}}})}initVideo(e){this.config=e,this.internalsExposure?.expose({config:e,logger:this.logger,tuning:this.tuning}),this.setMuted(this.tuning.isAudioDisabled);let t=()=>{let{container:a,...n}=e;this.tracer.log("initVideo",wi(n)),this.domContainer=Pw(e),this.chromecastInitializer.contentId=e.meta?.videoId,this.providerContainer=new $n({sources:e.sources,meta:e.meta??{},failoverHosts:e.failoverHosts??[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,tracer:this.tracer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning,volumeMultiplier:e.volumeMultiplier,panelSize:e.panelSize}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.initTracerSubscription(),this.providerContainer.init(),this.setLiveLowLatency(this.tuning.dashCmafLive.lowLatency.isActiveOnDefault),this.initDebugTelemetry(),this.initWakeLock(),this.playerInited.next(!0),this.devNullLog&&this.tuning.devNullLogEnabled?(Gu.subscribe("core",this.devNullLog),this.tuning.collectingDecodingInfoEnabled&&(this.collectDecodingInfoDestroyCb=$w())):Gu.destroy("core")},i=()=>{this.tuning.autostartOnlyIfVisible&&window.requestAnimationFrame?this.playerInitRequest=window.requestAnimationFrame(()=>t()):t()},r=()=>{this.tuning.asyncResolveClientChecker?$.isInited$.pipe(fe(a=>!!a),ye()).subscribe(()=>{console.log("Core SDK async start"),i()}):i()};return this.isNotActiveTabCase()?(this.tracer.log("request play from hidden tab"),ah(document,"visibilitychange").pipe(ye()).subscribe(r)):r(),this}destroy(){this.tracer.log("destroy"),window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.playerInitRequest&&window.cancelAnimationFrame(this.playerInitRequest),this.events.willDestruct$.next(),this.stop(),this.providerContainer?.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe(),this.tracer.end(),this.internalsExposure?.destroy(),Gu.destroy("core"),this.collectDecodingInfoDestroyCb?.()}waitInit(e){this.playerInited.getValue()?e():this.subscription.add(this.playerInited.pipe(fe(t=>!!t),ye()).subscribe(e))}prepare(){return this.waitInit(()=>{let e=this.desiredState.playbackState;this.tracer.log("prepare",{currentPlayBackState:e.getState()}),e.getState()==="stopped"&&e.startTransitionTo("ready")}),this}play(){return this.waitInit(()=>{let e=this.desiredState.playbackState;this.tracer.log("play",{currentPlayBackState:e.getState()}),e.getState()!=="playing"&&e.startTransitionTo("playing")}),this}pause(){return this.waitInit(()=>{let e=this.desiredState.playbackState;this.tracer.log("pause",{currentPlayBackState:e.getState()}),e.getState()!=="paused"&&e.startTransitionTo("paused")}),this}stop(){return this.waitInit(()=>{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.waitInit(()=>{let i=this.info.duration$.getValue(),r=this.info.isLive$.getValue(),a=e;e>=i&&!r&&(a=i-this.tuning.seekNearDurationBias),this.tracer.log("seekTime",{duration:i,isLive:r,time:e,calculatedTime:a,forcePrecise:t}),Number.isFinite(a)&&(this.events.willSeek$.next({from:this.getExactTime(),to:a}),this.desiredState.seekState.setState({state:"requested",position:a*1e3,forcePrecise:t}))}),this}seekPercent(e){return this.waitInit(()=>{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.waitInit(()=>{let i=this.desiredState.volume,a=i.getTransition()?.to.muted??this.info.muted$.getValue(),n=t??(this.tuning.isAudioDisabled||a);this.tracer.log("setVolume",{volume:e,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:n}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"&&!(this.chromecastInitializer instanceof _t)?this.chromecastInitializer.setVolume(e):i.startTransitionTo({volume:e,muted:n})}),this}setMuted(e,t=!1){return this.waitInit(()=>{let i=this.desiredState.volume,r=this.tuning.isAudioDisabled&&!t||e,n=i.getTransition()?.to.volume??this.info.volume$.getValue();this.tracer.log("setMuted",{isMuted:e,nextMuted:r,volume:n,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue()}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"&&!(this.chromecastInitializer instanceof _t)?this.chromecastInitializer.setMuted(r):i.startTransitionTo({volume:n,muted:r})}),this}setVideoStream(e){return this.waitInit(()=>{this.desiredState.videoStream.startTransitionTo(e)}),this}setAudioStream(e){return this.waitInit(()=>{this.desiredState.audioStream.startTransitionTo(e)}),this}setQuality(e){return this.waitInit(()=>{sh(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(fe(i=>i.length>0),ye()).subscribe(i=>{this.setVideoTrackIdByQuality(i,e)}):this.explicitInitialQuality=e:t.length>0&&this.setVideoTrackIdByQuality(t,e)}),this}setAutoQuality(e){return this.waitInit(()=>{this.tracer.log("setAutoQuality",{enable:e}),this.desiredState.autoVideoTrackSwitching.startTransitionTo(e)}),this}setAutoQualityLimits(e){return this.waitInit(()=>{this.tracer.log("setAutoQualityLimits",wi(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e)}),this}setPredefinedQualityLimits(e){return this.waitInit(()=>{if(this.info.predefinedQualityLimitType$.getValue()===e)return this;let{highQualityLimit:t,trafficSavingLimit:i}=this.tuning.autoTrackSelection,r;switch(e){case"high_quality":r={min:t,max:void 0};break;case"traffic_saving":r={max:i,min:void 0};break;default:r={max:void 0,min:void 0}}this.setAutoQualityLimits(r)}),this}setPlaybackRate(e){return this.waitInit(()=>{this.tracer.log("setPlaybackRate",{playbackRate:e}),this.desiredState.playbackRate.startTransitionTo(e)}),this}setExternalTextTracks(e){return this.waitInit(()=>{e.length&&this.tracer.log("setExternalTextTracks",wi(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t})))}),this}selectTextTrack(e){return this.waitInit(()=>{Aw(e,this.desiredState.currentTextTrack,this.providerContainer?.providerOutput.availableTextTracks$,t=>t.id===e),this.tracer.log("selectTextTrack",{textTrackId:e})}),this}setTextTrackCueSettings(e){return this.waitInit(()=>{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.waitInit(()=>{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.waitInit(()=>{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.waitInit(()=>{let t=this.getScene3D();this.tracer.log("stopCameraManualRotation",{isScene3DAvailable:!!t,immediate:e}),t&&t.stopCameraManualRotation(e)}),this}moveCameraFocusPX(e,t){return this.waitInit(()=>{let i=this.getScene3D();if(this.tracer.log("moveCameraFocusPX",{isScene3DAvailable:!!i,dxpx:e,dypx:t}),i){let r=i.getCameraRotation(),a=i.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:r.x+a.x,y:r.y+a.y})}}),this}holdCamera(){return this.waitInit(()=>{let e=this.getScene3D();e&&e.holdCamera()}),this}releaseCamera(){return this.waitInit(()=>{let e=this.getScene3D();e&&e.releaseCamera()}),this}getExactTime(){if(!this.providerContainer)return 0;let e=this.providerContainer.providerOutput.element$.getValue();if(nN(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),i=t.state==="none"?void 0:t.position;return Mw(i)?i/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){let e=this.providerContainer?.current$.getValue();if(e?.provider?.scene3D)return e.provider.scene3D}setIntrinsicVideoSize(...e){let t={width:e.reduce((i,{width:r})=>i||r||0,0),height:e.reduce((i,{height:r})=>i||r||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(Ei(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(G(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(G(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(G(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(G(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(G(e=>e.to)).subscribe(e=>{this.info.autoQualityLimits$.next(e);let{highQualityLimit:t,trafficSavingLimit:i}=this.tuning.autoTrackSelection;this.info.predefinedQualityLimitType$.next(iy(e,t,i))})),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(fe(({from:e})=>e==="stopped"),ye()).subscribe(()=>{this.initedAt=Wu(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case"ready":this.events.ready$.next();break;case"playing":this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case"paused":this.events.paused$.next();break;case"stopped":this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case"ready":this.events.willReady$.next();break;case"paused":this.events.willPause$.next();break;case"playing":this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case"stopped":this.events.willStop$.next();break;default:}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("willSeekEvent",wi(n)),n.state==="requested"?this.desiredState.seekState.setState({...n,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:Qu.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe(ye()).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",wi(n)),n.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe(G(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(G(n=>n.destination),Y()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(Xt({availableVideoTracks:e.providerOutput.availableVideoTracks$,currentVideoStream:e.providerOutput.currentVideoStream$}).pipe(G(({availableVideoTracks:n,currentVideoStream:o})=>n.filter(u=>o?o.id===u.streamId:!0).map(({quality:u})=>u).sort((u,l)=>Bw(u)?1:Bw(l)?-1:uN(l,u)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(n=>{let o={};for(let u of n)u.fps&&(o[u.quality]=u.fps);this.info.availableQualitiesFps$.next(o)})).add(e.providerOutput.availableAudioStreams$.subscribe(this.info.availableAudioStreams$)).add(e.providerOutput.currentVideoStream$.subscribe(this.info.currentVideoStream$)).add(e.providerOutput.currentAudioStream$.subscribe(this.info.currentAudioStream$)).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.pipe(Y()).subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.pipe(fe(n=>Mw(n))).subscribe(n=>{this.info.currentQuality$.next(n?.quality),this.info.videoBitrate$.next(n?.bitrate)})).add(e.providerOutput.currentVideoSegmentLength$.pipe(Y((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe(Y((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(Y()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(Y()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(Y()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.autoVideoTrackLimits$.subscribe(n=>{this.desiredState.autoVideoTrackLimits.setState(n??{})})).add(e.providerOutput.currentBuffer$.pipe(G(n=>n?{start:n.from,end:n.to}:{start:0,end:0})).subscribe(this.info.currentBuffer$)).add(e.providerOutput.currentNativeBuffer$.pipe(G(n=>n?{start:n.from,end:n.to}:{start:0,end:0})).subscribe(this.info.currentNativeBuffer$)).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(nh(n=>n&&this.stop())).subscribe(this.info.isLiveEnded$)).add(e.providerOutput.canPlayLiveTailBuffer$.subscribe(this.info.canPlayLiveTailBuffer$)).add(e.providerOutput.canChangePlaybackSpeed$.subscribe(this.info.canChangePlaybackSpeed$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.liveBufferTime$.subscribe(this.info.liveBufferTime$)).add(e.providerOutput.liveLatency$.subscribe(this.info.liveLatency$)).add(Xt({hasLiveOffsetByPaused:Ei(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(G(n=>n.to),Y(),G(n=>n==="paused")),isLowLatency:e.providerOutput.isLowLatency$}).subscribe(({hasLiveOffsetByPaused:n,isLowLatency:o})=>{if(window.clearTimeout(this.hasLiveOffsetByPausedTimer),n){this.hasLiveOffsetByPausedTimer=window.setTimeout(()=>{this.hasLiveOffsetByPaused.next(!0)},this.getActiveLiveDelay(o));return}this.hasLiveOffsetByPaused.next(!1)})).add(Xt({atLiveEdge:Xt({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:rh({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(G(({isLive:n,position:o,isLowLatency:u})=>{let l=this.getActiveLiveDelay(u);return n&&Math.abs(o)<l/1e3}),Y(),nh(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(G(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add(Xt({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(G(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),Y(),nh(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(G(n=>n.muted),Y()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(G(n=>n.volume),Y()).subscribe(this.info.volume$)).add(rh({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(e.providerOutput.seekedEvent$.subscribe(()=>{this.info.isEnded$.getValue()&&this.tuning.changePlaybackStateToPausedWhenEnded&&this.play()})).add(Ei(e.providerOutput.endedEvent$.pipe(Lw(!0)),e.providerOutput.seekedEvent$.pipe(Lw(!1))).pipe(Y()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.providerOutput.fetcherRecoverableError$.subscribe(this.events.fetcherRecoverableError$)).add(e.providerOutput.fetcherError$.subscribe(this.events.fatalError$)).add(e.volumeMultiplierError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe(G(n=>({id:n?`No${n}`:"NoProviders",category:Qu.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.manifestRequested$.pipe(ye()).subscribe(this.events.manifestRequested$)).add(e.providerOutput.firstBytesManifest$.pipe(ye()).subscribe(this.events.firstBytesManifest$)).add(e.providerOutput.manifestReceived$.pipe(ye()).subscribe(this.events.manifestReceived$)).add(e.providerOutput.firstBytesRequested$.pipe(ye()).subscribe(this.events.firstBytesRequested$)).add(e.providerOutput.firstBytesReceived$.pipe(ye()).subscribe(this.events.firstBytesReceived$)).add(e.providerOutput.firstBytesEvent$.pipe(ye(),G(n=>n??Wu()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(ye(),G(()=>Wu()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(ye(),G(()=>Wu()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$)).add(e.providerOutput.availableSources$.subscribe(this.info.availableSources$));let t=new M(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let i=new M(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(fe(({to:n})=>n==="playing"),ye()).subscribe(()=>i.next(!1)));let r=0,a=Ei(e.providerOutput.isBuffering$,t,i).pipe(G(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||i.getValue();return n&&!o}),Y());this.subscription.add(a.subscribe(n=>{n?r=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(r),this.info.isStalled$.next(!1))})),this.subscription.add(Ei(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(Ei(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(),p=this.chromecastInitializer.castState$.getValue(),c;p==="CONNECTED"?c="second_screen":u?l?n?c="pip":o?c="fullscreen":c="inline":c="invisible":c="none",this.info.surface$.getValue()!==c&&this.info.surface$.next(c)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(G(e=>e?.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new Dw;this.subscription.add(t),this.subscription.add(e.current$.pipe(Y((i,r)=>i.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(fe(i=>i.length>0),ye()).subscribe(i=>{this.setStartingVideoTrack(i)}))}))}setStartingVideoTrack(e){let t;this.wasSetStartedQuality=!0;let i=this.explicitInitialQuality??this.info.currentQuality$.getValue();i&&(t=e.find(({quality:r})=>r===i),t||this.setAutoQuality(!0)),t||(t=ut(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(Ei(this.desiredState.videoTrack.stateChangeStarted$.pipe(G(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(G(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(G(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(G(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(G(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(G(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(G(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(G(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(G(e=>({component:"desiredState",message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`}))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){let e=this.providerContainer?.providerOutput;sh(this.providerContainer),sh(e),Zv(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(t=>Jv(t)),this.providerContainer.current$.subscribe(({type:t})=>sa("provider",t)),e.duration$.subscribe(t=>sa("duration",t)),e.availableVideoTracks$.pipe(fe(t=>!!t.length),ye()).subscribe(t=>sa("tracks",t)),this.events.fatalError$.subscribe(new Ne("fatalError")),this.events.managedError$.subscribe(new Ne("managedError")),e.position$.subscribe(new Ne("position")),e.currentVideoTrack$.pipe(G(t=>t?.quality)).subscribe(new Ne("quality")),this.info.currentBuffer$.subscribe(new Ne("buffer")),e.isBuffering$.subscribe(new Ne("isBuffering"))].forEach(t=>this.subscription.add(t)),sa("codecs",$.video.supportedCodecs)}initTracerSubscription(){let e=Cw(this.tracer.log.bind(this.tracer)),t=Cw(this.tracer.error.bind(this.tracer));this.subscription.add(this.info.playbackState$.subscribe(e("playbackState"))).add(this.info.isLooped$.subscribe(e("isLooped"))).add(this.info.currentPlaybackRate$.pipe(Y()).subscribe(e("currentPlaybackRate"))).add(this.info.isAutoQualityEnabled$.subscribe(e("isAutoQualityEnabled"))).add(this.info.autoQualityLimits$.subscribe(e("autoQualityLimits"))).add(this.info.currentFormat$.subscribe(e("currentFormat"))).add(this.info.availableQualities$.subscribe(e("availableQualities"))).add(this.info.availableQualitiesFps$.subscribe(e("availableQualitiesFps"))).add(this.info.availableAudioTracks$.subscribe(e("availableAudioTracks"))).add(this.info.isAudioAvailable$.subscribe(e("isAudioAvailable"))).add(Xt({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe(fe(({currentQuality:i,videoBitrate:r})=>!!i&&!!r),Y((i,r)=>i.currentQuality===r.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe(fe(i=>i>0),Y()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe(fe(i=>i>0),Y()).subscribe(e("currentAudioSegmentLength"))).add(this.info.hostname$.subscribe(e("hostname"))).add(this.info.currentTextTrack$.subscribe(e("currentTextTrack"))).add(this.info.availableTextTracks$.subscribe(e("availableTextTracks"))).add(this.info.autoQualityLimitingAvailable$.subscribe(e("autoQualityLimitingAvailable"))).add(Xt({currentBuffer:this.info.currentBuffer$.pipe(fe(i=>i.end>0),Y((i,r)=>i.end===r.end&&i.start===r.start)),position:this.info.position$.pipe(Y())}).pipe(oh(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe(Y()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe(Y()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe(Y()).subscribe(e("canChangePlaybackSpeed"))).add(Xt({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(fe(({liveTime:i,liveBufferTime:r})=>!!i&&!!r),oh(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(Y(),fe(i=>i===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(Y(),fe(i=>i===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe(Y()).subscribe(e("muted"))).add(this.info.volume$.pipe(Y()).subscribe(e("volume"))).add(this.info.isEnded$.pipe(Y(),fe(i=>i===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add(Xt({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(fe(({throughputEstimation:i,rtt:r})=>!!i&&!!r),oh(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(Y(),fe(i=>i===!0)).subscribe(e("is3DVideo"))).add(this.info.surface$.subscribe(e("surface"))).add(this.events.ended$.subscribe(e("ended"))).add(this.events.looped$.subscribe(e("looped"))).add(this.events.managedError$.subscribe(t("managedError"))).add(this.events.fatalError$.subscribe(t("fatalError"))).add(this.events.firstBytes$.subscribe(e("firstBytes"))).add(this.events.firstFrame$.subscribe(e("firstFrame"))).add(this.events.canplay$.subscribe(e("canplay")))}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e,t=()=>{e?.release(),e=void 0},i=async()=>{t(),e=await window.navigator.wakeLock.request("screen").catch(r=>{r instanceof DOMException&&r.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:Qu.DOM,message:String(r)})})};this.subscription.add(Ei(ah(document,"visibilitychange"),ah(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let r=document.visibilityState==="visible",a=this.desiredState.playbackState.getState()==="playing",n=!!e&&!e?.released;r&&a?n||i():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let i=e.find(r=>r.quality===t);this.tracer.log("setVideoTrackIdByQuality",wi({quality:t,availableTracks:wi(e),track:wi(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&&!la()}};import{Subscription as Mse,Observable as Lse,Subject as Dse,ValueSubject as Bse,VideoQuality as Cse}from"@vkontakte/videoplayer-shared/es2024";var Vse=`@vkontakte/videoplayer-core@${dh}`;export{ws as ChromecastState,Ju as HttpConnectionType,Lse as Observable,we as PlaybackState,Yu as Player,Fn as PredefinedQualityLimits,Vse as SDK_VERSION,Dse as Subject,Mse as Subscription,Zu as Surface,dh as VERSION,Bse as ValueSubject,Ct as VideoFormat,Cse as VideoQuality,nA as areValidLiveRecordSources,$ as clientChecker,Ci as isMobile};
|