@vkontakte/videoplayer-core 2.0.135-dev.f94adb28.0 → 2.0.136-beta.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/es2015.cjs.js +46 -53
- package/es2015.esm.js +42 -49
- package/es2018.cjs.js +54 -61
- package/es2018.esm.js +54 -61
- package/es2024.cjs.js +53 -60
- package/es2024.esm.js +51 -58
- package/esnext.cjs.js +53 -60
- package/esnext.esm.js +51 -58
- package/evergreen.esm.js +39 -46
- package/package.json +2 -2
- package/types/providers/DashProvider/baseDashProvider.d.ts +2 -1
- package/types/providers/DashProvider/lib/LiveTextManager.d.ts +1 -1
- package/types/providers/DashProvider/lib/buffer.d.ts +2 -1
- package/types/providers/DashProvider/lib/fetcher.d.ts +2 -1
- package/types/providers/DashProvider/lib/player.d.ts +6 -1
- package/types/providers/DashProvider/lib/types.d.ts +2 -159
- package/types/providers/DashProvider/lib/utils.d.ts +1 -2
- package/types/providers/DashProviderNew/baseDashProvider.d.ts +2 -1
- package/types/providers/DashProviderNew/lib/LiveTextManager.d.ts +1 -1
- package/types/providers/DashProviderNew/lib/buffer.d.ts +2 -1
- package/types/providers/DashProviderNew/lib/fetcher.d.ts +2 -1
- package/types/providers/DashProviderNew/lib/player.d.ts +6 -1
- package/types/providers/DashProviderNew/lib/types.d.ts +2 -159
- package/types/providers/DashProviderNew/lib/utils.d.ts +1 -2
- package/types/providers/utils/error.d.ts +1 -0
- package/types/providers/{DashProvider/lib → utils}/parsers/index.d.ts +1 -1
- package/types/providers/{DashProviderNew/lib → utils}/parsers/mpd.d.ts +1 -1
- package/types/providers/{DashProvider/lib → utils}/parsers/mpeg/BoxModel.d.ts +4 -4
- package/types/providers/{DashProvider/lib → utils}/parsers/mpeg/BoxParser.d.ts +2 -2
- package/types/providers/{DashProvider/lib → utils}/parsers/mpeg/box.d.ts +8 -8
- package/types/providers/utils/parsers/mpeg/boxes/avc1.d.ts +8 -0
- package/types/providers/{DashProvider/lib → utils}/parsers/mpeg/boxes/equi.d.ts +2 -2
- package/types/providers/{DashProvider/lib → utils}/parsers/mpeg/boxes/ftyp.d.ts +2 -2
- package/types/providers/utils/parsers/mpeg/boxes/index.d.ts +26 -0
- package/types/providers/{DashProvider/lib → utils}/parsers/mpeg/boxes/mdat.d.ts +2 -2
- package/types/providers/utils/parsers/mpeg/boxes/mdia.d.ts +8 -0
- package/types/providers/{DashProvider/lib → utils}/parsers/mpeg/boxes/mfhd.d.ts +2 -2
- package/types/providers/utils/parsers/mpeg/boxes/minf.d.ts +8 -0
- package/types/providers/utils/parsers/mpeg/boxes/moof.d.ts +8 -0
- package/types/providers/utils/parsers/mpeg/boxes/moov.d.ts +8 -0
- package/types/providers/{DashProvider/lib → utils}/parsers/mpeg/boxes/mvhd.d.ts +2 -2
- package/types/providers/{DashProvider/lib → utils}/parsers/mpeg/boxes/prhd.d.ts +2 -2
- package/types/providers/utils/parsers/mpeg/boxes/proj.d.ts +8 -0
- package/types/providers/{DashProvider/lib → utils}/parsers/mpeg/boxes/sidx.d.ts +2 -2
- package/types/providers/{DashProvider/lib → utils}/parsers/mpeg/boxes/st3d.d.ts +2 -2
- package/types/providers/utils/parsers/mpeg/boxes/stbl.d.ts +8 -0
- package/types/providers/{DashProvider/lib → utils}/parsers/mpeg/boxes/stsd.d.ts +2 -2
- package/types/providers/utils/parsers/mpeg/boxes/sv3d.d.ts +8 -0
- package/types/providers/{DashProvider/lib → utils}/parsers/mpeg/boxes/tfdt.d.ts +2 -2
- package/types/providers/{DashProvider/lib → utils}/parsers/mpeg/boxes/tfhd.d.ts +2 -2
- package/types/providers/{DashProvider/lib → utils}/parsers/mpeg/boxes/tkhd.d.ts +2 -2
- package/types/providers/utils/parsers/mpeg/boxes/traf.d.ts +8 -0
- package/types/providers/utils/parsers/mpeg/boxes/trak.d.ts +8 -0
- package/types/providers/{DashProvider/lib → utils}/parsers/mpeg/boxes/trun.d.ts +2 -2
- package/types/providers/{DashProvider/lib → utils}/parsers/mpeg/boxes/unknown.d.ts +1 -1
- package/types/providers/utils/parsers/mpeg/boxes/uuid.d.ts +18 -0
- package/types/providers/{DashProvider/lib → utils}/parsers/mpeg/fullBox.d.ts +2 -2
- package/types/providers/{DashProvider/lib → utils}/parsers/mpeg/isobmff.d.ts +1 -1
- package/types/providers/utils/parsers/types.d.ts +159 -0
- package/types/providers/{DashProvider/lib → utils}/parsers/webm/webm.d.ts +1 -1
- package/types/utils/tuningConfig.d.ts +2 -4
- package/types/providers/DashProvider/lib/parsers/mpd.d.ts +0 -3
- package/types/providers/DashProvider/lib/parsers/mpeg/boxes/avc1.d.ts +0 -8
- package/types/providers/DashProvider/lib/parsers/mpeg/boxes/index.d.ts +0 -26
- package/types/providers/DashProvider/lib/parsers/mpeg/boxes/mdia.d.ts +0 -8
- package/types/providers/DashProvider/lib/parsers/mpeg/boxes/minf.d.ts +0 -8
- package/types/providers/DashProvider/lib/parsers/mpeg/boxes/moof.d.ts +0 -8
- package/types/providers/DashProvider/lib/parsers/mpeg/boxes/moov.d.ts +0 -8
- package/types/providers/DashProvider/lib/parsers/mpeg/boxes/proj.d.ts +0 -8
- package/types/providers/DashProvider/lib/parsers/mpeg/boxes/stbl.d.ts +0 -8
- package/types/providers/DashProvider/lib/parsers/mpeg/boxes/sv3d.d.ts +0 -8
- package/types/providers/DashProvider/lib/parsers/mpeg/boxes/traf.d.ts +0 -8
- package/types/providers/DashProvider/lib/parsers/mpeg/boxes/trak.d.ts +0 -8
- package/types/providers/DashProvider/lib/parsers/mpeg/boxes/uuid.d.ts +0 -11
- package/types/providers/DashProviderNew/lib/parsers/ietf/index.d.ts +0 -13
- package/types/providers/DashProviderNew/lib/parsers/index.d.ts +0 -3
- package/types/providers/DashProviderNew/lib/parsers/mpeg/BoxModel.d.ts +0 -20
- package/types/providers/DashProviderNew/lib/parsers/mpeg/BoxParser.d.ts +0 -21
- package/types/providers/DashProviderNew/lib/parsers/mpeg/BoxTypeEnum.d.ts +0 -30
- package/types/providers/DashProviderNew/lib/parsers/mpeg/box.d.ts +0 -74
- package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/avc1.d.ts +0 -8
- package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/equi.d.ts +0 -21
- package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/ftyp.d.ts +0 -17
- package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/index.d.ts +0 -26
- package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/mdat.d.ts +0 -15
- package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/mdia.d.ts +0 -8
- package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/mfhd.d.ts +0 -11
- package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/minf.d.ts +0 -8
- package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/moof.d.ts +0 -8
- package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/moov.d.ts +0 -8
- package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/mvhd.d.ts +0 -35
- package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/prhd.d.ts +0 -16
- package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/proj.d.ts +0 -8
- package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/sidx.d.ts +0 -48
- package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/st3d.d.ts +0 -23
- package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/stbl.d.ts +0 -8
- package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/stsd.d.ts +0 -11
- package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/sv3d.d.ts +0 -8
- package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/tfdt.d.ts +0 -17
- package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/tfhd.d.ts +0 -22
- package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/tkhd.d.ts +0 -42
- package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/traf.d.ts +0 -8
- package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/trak.d.ts +0 -8
- package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/trun.d.ts +0 -31
- package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/unknown.d.ts +0 -6
- package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/uuid.d.ts +0 -11
- package/types/providers/DashProviderNew/lib/parsers/mpeg/fullBox.d.ts +0 -15
- package/types/providers/DashProviderNew/lib/parsers/mpeg/isobmff.d.ts +0 -12
- package/types/providers/DashProviderNew/lib/parsers/webm/ebml.d.ts +0 -76
- package/types/providers/DashProviderNew/lib/parsers/webm/webm.d.ts +0 -3
- /package/types/providers/{DashProvider/lib → utils}/parsers/ietf/index.d.ts +0 -0
- /package/types/providers/{DashProvider/lib → utils}/parsers/mpeg/BoxTypeEnum.d.ts +0 -0
- /package/types/providers/{DashProvider/lib → utils}/parsers/webm/ebml.d.ts +0 -0
package/es2018.esm.js
CHANGED
|
@@ -1,127 +1,127 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @vkontakte/videoplayer-core v2.0.
|
|
3
|
-
*
|
|
4
|
-
* https://st.mycdn.me/static/vkontakte-videoplayer/2-0-
|
|
2
|
+
* @vkontakte/videoplayer-core v2.0.136-beta.0
|
|
3
|
+
* Fri, 11 Jul 2025 16:07:23 GMT
|
|
4
|
+
* https://st.mycdn.me/static/vkontakte-videoplayer/2-0-136/doc/
|
|
5
5
|
*/
|
|
6
|
-
var LE=Object.create;var Lh=Object.defineProperty;var BE=Object.getOwnPropertyDescriptor;var $E=Object.getOwnPropertyNames;var DE=Object.getPrototypeOf,CE=Object.prototype.hasOwnProperty;var b=(s,e)=>()=>(e||s((e={exports:{}}).exports,e),e.exports);var VE=(s,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of $E(e))!CE.call(s,r)&&r!==t&&Lh(s,r,{get:()=>e[r],enumerable:!(i=BE(e,r))||i.enumerable});return s};var N=(s,e,t)=>(t=s!=null?LE(DE(s)):{},VE(e||!s||!s.__esModule?Lh(t,"default",{value:s,enumerable:!0}):t,s));var ve=b((Ol,$h)=>{"use strict";var ea=function(s){return s&&s.Math===Math&&s};$h.exports=ea(typeof globalThis=="object"&&globalThis)||ea(typeof window=="object"&&window)||ea(typeof self=="object"&&self)||ea(typeof global=="object"&&global)||ea(typeof Ol=="object"&&Ol)||function(){return this}()||Function("return this")()});var Oe=b((JO,Dh)=>{"use strict";Dh.exports=function(s){try{return!!s()}catch(e){return!0}}});var ta=b((ZO,Ch)=>{"use strict";var OE=Oe();Ch.exports=!OE(function(){var s=function(){}.bind();return typeof s!="function"||s.hasOwnProperty("prototype")})});var _l=b((e_,Fh)=>{"use strict";var _E=ta(),_h=Function.prototype,Vh=_h.apply,Oh=_h.call;Fh.exports=typeof Reflect=="object"&&Reflect.apply||(_E?Oh.bind(Vh):function(){return Oh.apply(Vh,arguments)})});var Le=b((t_,qh)=>{"use strict";var Nh=ta(),Uh=Function.prototype,Fl=Uh.call,FE=Nh&&Uh.bind.bind(Fl,Fl);qh.exports=Nh?FE:function(s){return function(){return Fl.apply(s,arguments)}}});var Wi=b((i_,Hh)=>{"use strict";var jh=Le(),NE=jh({}.toString),UE=jh("".slice);Hh.exports=function(s){return UE(NE(s),8,-1)}});var Nl=b((r_,zh)=>{"use strict";var qE=Wi(),jE=Le();zh.exports=function(s){if(qE(s)==="Function")return jE(s)}});var ge=b((s_,Qh)=>{"use strict";var Ul=typeof document=="object"&&document.all;Qh.exports=typeof Ul=="undefined"&&Ul!==void 0?function(s){return typeof s=="function"||s===Ul}:function(s){return typeof s=="function"}});var ft=b((a_,Gh)=>{"use strict";var HE=Oe();Gh.exports=!HE(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var mt=b((n_,Wh)=>{"use strict";var zE=ta(),To=Function.prototype.call;Wh.exports=zE?To.bind(To):function(){return To.apply(To,arguments)}});var ql=b(Xh=>{"use strict";var Yh={}.propertyIsEnumerable,Kh=Object.getOwnPropertyDescriptor,QE=Kh&&!Yh.call({1:2},1);Xh.f=QE?function(e){var t=Kh(this,e);return!!t&&t.enumerable}:Yh});var ia=b((u_,Jh)=>{"use strict";Jh.exports=function(s,e){return{enumerable:!(s&1),configurable:!(s&2),writable:!(s&4),value:e}}});var ef=b((l_,Zh)=>{"use strict";var GE=Le(),WE=Oe(),YE=Wi(),jl=Object,KE=GE("".split);Zh.exports=WE(function(){return!jl("z").propertyIsEnumerable(0)})?function(s){return YE(s)==="String"?KE(s,""):jl(s)}:jl});var Tr=b((c_,tf)=>{"use strict";tf.exports=function(s){return s==null}});var Pi=b((d_,rf)=>{"use strict";var XE=Tr(),JE=TypeError;rf.exports=function(s){if(XE(s))throw new JE("Can't call method on "+s);return s}});var Yi=b((p_,sf)=>{"use strict";var ZE=ef(),ew=Pi();sf.exports=function(s){return ZE(ew(s))}});var bt=b((h_,af)=>{"use strict";var tw=ge();af.exports=function(s){return typeof s=="object"?s!==null:tw(s)}});var Ir=b((f_,nf)=>{"use strict";nf.exports={}});var pi=b((m_,uf)=>{"use strict";var Hl=Ir(),zl=ve(),iw=ge(),of=function(s){return iw(s)?s:void 0};uf.exports=function(s,e){return arguments.length<2?of(Hl[s])||of(zl[s]):Hl[s]&&Hl[s][e]||zl[s]&&zl[s][e]}});var ra=b((b_,lf)=>{"use strict";var rw=Le();lf.exports=rw({}.isPrototypeOf)});var Ki=b((g_,pf)=>{"use strict";var sw=ve(),cf=sw.navigator,df=cf&&cf.userAgent;pf.exports=df?String(df):""});var Gl=b((S_,Sf)=>{"use strict";var gf=ve(),Ql=Ki(),hf=gf.process,ff=gf.Deno,mf=hf&&hf.versions||ff&&ff.version,bf=mf&&mf.v8,$t,Io;bf&&($t=bf.split("."),Io=$t[0]>0&&$t[0]<4?1:+($t[0]+$t[1]));!Io&&Ql&&($t=Ql.match(/Edge\/(\d+)/),(!$t||$t[1]>=74)&&($t=Ql.match(/Chrome\/(\d+)/),$t&&(Io=+$t[1])));Sf.exports=Io});var Wl=b((v_,yf)=>{"use strict";var vf=Gl(),aw=Oe(),nw=ve(),ow=nw.String;yf.exports=!!Object.getOwnPropertySymbols&&!aw(function(){var s=Symbol("symbol detection");return!ow(s)||!(Object(s)instanceof Symbol)||!Symbol.sham&&vf&&vf<41})});var Yl=b((y_,Tf)=>{"use strict";var uw=Wl();Tf.exports=uw&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var Kl=b((T_,If)=>{"use strict";var lw=pi(),cw=ge(),dw=ra(),pw=Yl(),hw=Object;If.exports=pw?function(s){return typeof s=="symbol"}:function(s){var e=lw("Symbol");return cw(e)&&dw(e.prototype,hw(s))}});var sa=b((I_,xf)=>{"use strict";var fw=String;xf.exports=function(s){try{return fw(s)}catch(e){return"Object"}}});var jt=b((x_,Ef)=>{"use strict";var mw=ge(),bw=sa(),gw=TypeError;Ef.exports=function(s){if(mw(s))return s;throw new gw(bw(s)+" is not a function")}});var aa=b((E_,wf)=>{"use strict";var Sw=jt(),vw=Tr();wf.exports=function(s,e){var t=s[e];return vw(t)?void 0:Sw(t)}});var Pf=b((w_,Af)=>{"use strict";var Xl=mt(),Jl=ge(),Zl=bt(),yw=TypeError;Af.exports=function(s,e){var t,i;if(e==="string"&&Jl(t=s.toString)&&!Zl(i=Xl(t,s))||Jl(t=s.valueOf)&&!Zl(i=Xl(t,s))||e!=="string"&&Jl(t=s.toString)&&!Zl(i=Xl(t,s)))return i;throw new yw("Can't convert object to primitive value")}});var Dt=b((A_,kf)=>{"use strict";kf.exports=!0});var Lf=b((P_,Mf)=>{"use strict";var Rf=ve(),Tw=Object.defineProperty;Mf.exports=function(s,e){try{Tw(Rf,s,{value:e,configurable:!0,writable:!0})}catch(t){Rf[s]=e}return e}});var na=b((k_,Df)=>{"use strict";var Iw=Dt(),xw=ve(),Ew=Lf(),Bf="__core-js_shared__",$f=Df.exports=xw[Bf]||Ew(Bf,{});($f.versions||($f.versions=[])).push({version:"3.38.0",mode:Iw?"pure":"global",copyright:"\xA9 2014-2024 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.38.0/LICENSE",source:"https://github.com/zloirock/core-js"})});var ec=b((R_,Vf)=>{"use strict";var Cf=na();Vf.exports=function(s,e){return Cf[s]||(Cf[s]=e||{})}});var xr=b((M_,Of)=>{"use strict";var ww=Pi(),Aw=Object;Of.exports=function(s){return Aw(ww(s))}});var Ct=b((L_,_f)=>{"use strict";var Pw=Le(),kw=xr(),Rw=Pw({}.hasOwnProperty);_f.exports=Object.hasOwn||function(e,t){return Rw(kw(e),t)}});var tc=b((B_,Ff)=>{"use strict";var Mw=Le(),Lw=0,Bw=Math.random(),$w=Mw(1 .toString);Ff.exports=function(s){return"Symbol("+(s===void 0?"":s)+")_"+$w(++Lw+Bw,36)}});var _e=b(($_,Uf)=>{"use strict";var Dw=ve(),Cw=ec(),Nf=Ct(),Vw=tc(),Ow=Wl(),_w=Yl(),Er=Dw.Symbol,ic=Cw("wks"),Fw=_w?Er.for||Er:Er&&Er.withoutSetter||Vw;Uf.exports=function(s){return Nf(ic,s)||(ic[s]=Ow&&Nf(Er,s)?Er[s]:Fw("Symbol."+s)),ic[s]}});var zf=b((D_,Hf)=>{"use strict";var Nw=mt(),qf=bt(),jf=Kl(),Uw=aa(),qw=Pf(),jw=_e(),Hw=TypeError,zw=jw("toPrimitive");Hf.exports=function(s,e){if(!qf(s)||jf(s))return s;var t=Uw(s,zw),i;if(t){if(e===void 0&&(e="default"),i=Nw(t,s,e),!qf(i)||jf(i))return i;throw new Hw("Can't convert object to primitive value")}return e===void 0&&(e="number"),qw(s,e)}});var rc=b((C_,Qf)=>{"use strict";var Qw=zf(),Gw=Kl();Qf.exports=function(s){var e=Qw(s,"string");return Gw(e)?e:e+""}});var xo=b((V_,Wf)=>{"use strict";var Ww=ve(),Gf=bt(),sc=Ww.document,Yw=Gf(sc)&&Gf(sc.createElement);Wf.exports=function(s){return Yw?sc.createElement(s):{}}});var ac=b((O_,Yf)=>{"use strict";var Kw=ft(),Xw=Oe(),Jw=xo();Yf.exports=!Kw&&!Xw(function(){return Object.defineProperty(Jw("div"),"a",{get:function(){return 7}}).a!==7})});var Jf=b(Xf=>{"use strict";var Zw=ft(),eA=mt(),tA=ql(),iA=ia(),rA=Yi(),sA=rc(),aA=Ct(),nA=ac(),Kf=Object.getOwnPropertyDescriptor;Xf.f=Zw?Kf:function(e,t){if(e=rA(e),t=sA(t),nA)try{return Kf(e,t)}catch(i){}if(aA(e,t))return iA(!eA(tA.f,e,t),e[t])}});var nc=b((F_,Zf)=>{"use strict";var oA=Oe(),uA=ge(),lA=/#|\.prototype\./,oa=function(s,e){var t=dA[cA(s)];return t===hA?!0:t===pA?!1:uA(e)?oA(e):!!e},cA=oa.normalize=function(s){return String(s).replace(lA,".").toLowerCase()},dA=oa.data={},pA=oa.NATIVE="N",hA=oa.POLYFILL="P";Zf.exports=oa});var wr=b((N_,tm)=>{"use strict";var em=Nl(),fA=jt(),mA=ta(),bA=em(em.bind);tm.exports=function(s,e){return fA(s),e===void 0?s:mA?bA(s,e):function(){return s.apply(e,arguments)}}});var oc=b((U_,im)=>{"use strict";var gA=ft(),SA=Oe();im.exports=gA&&SA(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var Ht=b((q_,rm)=>{"use strict";var vA=bt(),yA=String,TA=TypeError;rm.exports=function(s){if(vA(s))return s;throw new TA(yA(s)+" is not an object")}});var Xi=b(am=>{"use strict";var IA=ft(),xA=ac(),EA=oc(),Eo=Ht(),sm=rc(),wA=TypeError,uc=Object.defineProperty,AA=Object.getOwnPropertyDescriptor,lc="enumerable",cc="configurable",dc="writable";am.f=IA?EA?function(e,t,i){if(Eo(e),t=sm(t),Eo(i),typeof e=="function"&&t==="prototype"&&"value"in i&&dc in i&&!i[dc]){var r=AA(e,t);r&&r[dc]&&(e[t]=i.value,i={configurable:cc in i?i[cc]:r[cc],enumerable:lc in i?i[lc]:r[lc],writable:!1})}return uc(e,t,i)}:uc:function(e,t,i){if(Eo(e),t=sm(t),Eo(i),xA)try{return uc(e,t,i)}catch(r){}if("get"in i||"set"in i)throw new wA("Accessors not supported");return"value"in i&&(e[t]=i.value),e}});var Ar=b((H_,nm)=>{"use strict";var PA=ft(),kA=Xi(),RA=ia();nm.exports=PA?function(s,e,t){return kA.f(s,e,RA(1,t))}:function(s,e,t){return s[e]=t,s}});var Ee=b((z_,um)=>{"use strict";var ua=ve(),MA=_l(),LA=Nl(),BA=ge(),$A=Jf().f,DA=nc(),Pr=Ir(),CA=wr(),kr=Ar(),om=Ct();na();var VA=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 MA(s,this,arguments)};return e.prototype=s.prototype,e};um.exports=function(s,e){var t=s.target,i=s.global,r=s.stat,a=s.proto,n=i?ua:r?ua[t]:ua[t]&&ua[t].prototype,o=i?Pr:Pr[t]||kr(Pr,t,{})[t],u=o.prototype,l,d,c,h,p,f,m,g,S;for(h in e)l=DA(i?h:t+(r?".":"#")+h,s.forced),d=!l&&n&&om(n,h),f=o[h],d&&(s.dontCallGetSet?(S=$A(n,h),m=S&&S.value):m=n[h]),p=d&&m?m:e[h],!(!l&&!a&&typeof f==typeof p)&&(s.bind&&d?g=CA(p,ua):s.wrap&&d?g=VA(p):a&&BA(p)?g=LA(p):g=p,(s.sham||p&&p.sham||f&&f.sham)&&kr(g,"sham",!0),kr(o,h,g),a&&(c=t+"Prototype",om(Pr,c)||kr(Pr,c,{}),kr(Pr[c],h,p),s.real&&u&&(l||!u[h])&&kr(u,h,p)))}});var cm=b((Q_,lm)=>{"use strict";var OA=Math.ceil,_A=Math.floor;lm.exports=Math.trunc||function(e){var t=+e;return(t>0?_A:OA)(t)}});var la=b((G_,dm)=>{"use strict";var FA=cm();dm.exports=function(s){var e=+s;return e!==e||e===0?0:FA(e)}});var hm=b((W_,pm)=>{"use strict";var NA=la(),UA=Math.max,qA=Math.min;pm.exports=function(s,e){var t=NA(s);return t<0?UA(t+e,0):qA(t,e)}});var pc=b((Y_,fm)=>{"use strict";var jA=la(),HA=Math.min;fm.exports=function(s){var e=jA(s);return e>0?HA(e,9007199254740991):0}});var Rr=b((K_,mm)=>{"use strict";var zA=pc();mm.exports=function(s){return zA(s.length)}});var hc=b((X_,gm)=>{"use strict";var QA=Yi(),GA=hm(),WA=Rr(),bm=function(s){return function(e,t,i){var r=QA(e),a=WA(r);if(a===0)return!s&&-1;var n=GA(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}};gm.exports={includes:bm(!0),indexOf:bm(!1)}});var ca=b((J_,Sm)=>{"use strict";Sm.exports=function(){}});var vm=b(()=>{"use strict";var YA=Ee(),KA=hc().includes,XA=Oe(),JA=ca(),ZA=XA(function(){return!Array(1).includes()});YA({target:"Array",proto:!0,forced:ZA},{includes:function(e){return KA(this,e,arguments.length>1?arguments[1]:void 0)}});JA("includes")});var ki=b((tF,ym)=>{"use strict";var eP=pi();ym.exports=eP});var Im=b((iF,Tm)=>{"use strict";vm();var tP=ki();Tm.exports=tP("Array","includes")});var Em=b((rF,xm)=>{"use strict";var iP=Im();xm.exports=iP});var gt=b((sF,wm)=>{"use strict";var rP=Em();wm.exports=rP});var Po=b((bF,$m)=>{"use strict";var dP=ec(),pP=tc(),Bm=dP("keys");$m.exports=function(s){return Bm[s]||(Bm[s]=pP(s))}});var Cm=b((gF,Dm)=>{"use strict";var hP=Oe();Dm.exports=!hP(function(){function s(){}return s.prototype.constructor=null,Object.getPrototypeOf(new s)!==s.prototype})});var ko=b((SF,Om)=>{"use strict";var fP=Ct(),mP=ge(),bP=xr(),gP=Po(),SP=Cm(),Vm=gP("IE_PROTO"),bc=Object,vP=bc.prototype;Om.exports=SP?bc.getPrototypeOf:function(s){var e=bP(s);if(fP(e,Vm))return e[Vm];var t=e.constructor;return mP(t)&&e instanceof t?t.prototype:e instanceof bc?vP:null}});var Ro=b((vF,_m)=>{"use strict";_m.exports={}});var Um=b((yF,Nm)=>{"use strict";var yP=Le(),gc=Ct(),TP=Yi(),IP=hc().indexOf,xP=Ro(),Fm=yP([].push);Nm.exports=function(s,e){var t=TP(s),i=0,r=[],a;for(a in t)!gc(xP,a)&&gc(t,a)&&Fm(r,a);for(;e.length>i;)gc(t,a=e[i++])&&(~IP(r,a)||Fm(r,a));return r}});var Sc=b((TF,qm)=>{"use strict";qm.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var vc=b((IF,jm)=>{"use strict";var EP=Um(),wP=Sc();jm.exports=Object.keys||function(e){return EP(e,wP)}});var yc=b((xF,Wm)=>{"use strict";var zm=ft(),AP=Oe(),Qm=Le(),PP=ko(),kP=vc(),RP=Yi(),MP=ql().f,Gm=Qm(MP),LP=Qm([].push),BP=zm&&AP(function(){var s=Object.create(null);return s[2]=2,!Gm(s,2)}),Hm=function(s){return function(e){for(var t=RP(e),i=kP(t),r=BP&&PP(t)===null,a=i.length,n=0,o=[],u;a>n;)u=i[n++],(!zm||(r?u in t:Gm(t,u)))&&LP(o,s?[u,t[u]]:t[u]);return o}};Wm.exports={entries:Hm(!0),values:Hm(!1)}});var Ym=b(()=>{"use strict";var $P=Ee(),DP=yc().entries;$P({target:"Object",stat:!0},{entries:function(e){return DP(e)}})});var Xm=b((AF,Km)=>{"use strict";Ym();var CP=Ir();Km.exports=CP.Object.entries});var Zm=b((PF,Jm)=>{"use strict";var VP=Xm();Jm.exports=VP});var Ji=b((kF,eb)=>{"use strict";var OP=Zm();eb.exports=OP});var Zi=b((RF,tb)=>{"use strict";tb.exports={}});var sb=b((MF,rb)=>{"use strict";var _P=ve(),FP=ge(),ib=_P.WeakMap;rb.exports=FP(ib)&&/native code/.test(String(ib))});var Ec=b((LF,ob)=>{"use strict";var NP=sb(),nb=ve(),UP=bt(),qP=Ar(),Tc=Ct(),Ic=na(),jP=Po(),HP=Ro(),ab="Object already initialized",xc=nb.TypeError,zP=nb.WeakMap,Mo,da,Lo,QP=function(s){return Lo(s)?da(s):Mo(s,{})},GP=function(s){return function(e){var t;if(!UP(e)||(t=da(e)).type!==s)throw new xc("Incompatible receiver, "+s+" required");return t}};NP||Ic.state?(Vt=Ic.state||(Ic.state=new zP),Vt.get=Vt.get,Vt.has=Vt.has,Vt.set=Vt.set,Mo=function(s,e){if(Vt.has(s))throw new xc(ab);return e.facade=s,Vt.set(s,e),e},da=function(s){return Vt.get(s)||{}},Lo=function(s){return Vt.has(s)}):(er=jP("state"),HP[er]=!0,Mo=function(s,e){if(Tc(s,er))throw new xc(ab);return e.facade=s,qP(s,er,e),e},da=function(s){return Tc(s,er)?s[er]:{}},Lo=function(s){return Tc(s,er)});var Vt,er;ob.exports={set:Mo,get:da,has:Lo,enforce:QP,getterFor:GP}});var Pc=b((BF,lb)=>{"use strict";var wc=ft(),WP=Ct(),ub=Function.prototype,YP=wc&&Object.getOwnPropertyDescriptor,Ac=WP(ub,"name"),KP=Ac&&function(){}.name==="something",XP=Ac&&(!wc||wc&&YP(ub,"name").configurable);lb.exports={EXISTS:Ac,PROPER:KP,CONFIGURABLE:XP}});var db=b(cb=>{"use strict";var JP=ft(),ZP=oc(),ek=Xi(),tk=Ht(),ik=Yi(),rk=vc();cb.f=JP&&!ZP?Object.defineProperties:function(e,t){tk(e);for(var i=ik(t),r=rk(t),a=r.length,n=0,o;a>n;)ek.f(e,o=r[n++],i[o]);return e}});var kc=b((DF,pb)=>{"use strict";var sk=pi();pb.exports=sk("document","documentElement")});var Bc=b((CF,vb)=>{"use strict";var ak=Ht(),nk=db(),hb=Sc(),ok=Ro(),uk=kc(),lk=xo(),ck=Po(),fb=">",mb="<",Mc="prototype",Lc="script",gb=ck("IE_PROTO"),Rc=function(){},Sb=function(s){return mb+Lc+fb+s+mb+"/"+Lc+fb},bb=function(s){s.write(Sb("")),s.close();var e=s.parentWindow.Object;return s=null,e},dk=function(){var s=lk("iframe"),e="java"+Lc+":",t;return s.style.display="none",uk.appendChild(s),s.src=String(e),t=s.contentWindow.document,t.open(),t.write(Sb("document.F=Object")),t.close(),t.F},Bo,$o=function(){try{Bo=new ActiveXObject("htmlfile")}catch(e){}$o=typeof document!="undefined"?document.domain&&Bo?bb(Bo):dk():bb(Bo);for(var s=hb.length;s--;)delete $o[Mc][hb[s]];return $o()};ok[gb]=!0;vb.exports=Object.create||function(e,t){var i;return e!==null?(Rc[Mc]=ak(e),i=new Rc,Rc[Mc]=null,i[gb]=e):i=$o(),t===void 0?i:nk.f(i,t)}});var Mr=b((VF,yb)=>{"use strict";var pk=Ar();yb.exports=function(s,e,t,i){return i&&i.enumerable?s[e]=t:pk(s,e,t),s}});var Vc=b((OF,xb)=>{"use strict";var hk=Oe(),fk=ge(),mk=bt(),bk=Bc(),Tb=ko(),gk=Mr(),Sk=_e(),vk=Dt(),Cc=Sk("iterator"),Ib=!1,hi,$c,Dc;[].keys&&(Dc=[].keys(),"next"in Dc?($c=Tb(Tb(Dc)),$c!==Object.prototype&&(hi=$c)):Ib=!0);var yk=!mk(hi)||hk(function(){var s={};return hi[Cc].call(s)!==s});yk?hi={}:vk&&(hi=bk(hi));fk(hi[Cc])||gk(hi,Cc,function(){return this});xb.exports={IteratorPrototype:hi,BUGGY_SAFARI_ITERATORS:Ib}});var Do=b((_F,wb)=>{"use strict";var Tk=_e(),Ik=Tk("toStringTag"),Eb={};Eb[Ik]="z";wb.exports=String(Eb)==="[object z]"});var pa=b((FF,Ab)=>{"use strict";var xk=Do(),Ek=ge(),Co=Wi(),wk=_e(),Ak=wk("toStringTag"),Pk=Object,kk=Co(function(){return arguments}())==="Arguments",Rk=function(s,e){try{return s[e]}catch(t){}};Ab.exports=xk?Co:function(s){var e,t,i;return s===void 0?"Undefined":s===null?"Null":typeof(t=Rk(e=Pk(s),Ak))=="string"?t:kk?Co(e):(i=Co(e))==="Object"&&Ek(e.callee)?"Arguments":i}});var kb=b((NF,Pb)=>{"use strict";var Mk=Do(),Lk=pa();Pb.exports=Mk?{}.toString:function(){return"[object "+Lk(this)+"]"}});var ha=b((UF,Mb)=>{"use strict";var Bk=Do(),$k=Xi().f,Dk=Ar(),Ck=Ct(),Vk=kb(),Ok=_e(),Rb=Ok("toStringTag");Mb.exports=function(s,e,t,i){var r=t?s:s&&s.prototype;r&&(Ck(r,Rb)||$k(r,Rb,{configurable:!0,value:e}),i&&!Bk&&Dk(r,"toString",Vk))}});var Bb=b((qF,Lb)=>{"use strict";var _k=Vc().IteratorPrototype,Fk=Bc(),Nk=ia(),Uk=ha(),qk=Zi(),jk=function(){return this};Lb.exports=function(s,e,t,i){var r=e+" Iterator";return s.prototype=Fk(_k,{next:Nk(+!i,t)}),Uk(s,r,!1,!0),qk[r]=jk,s}});var Db=b((jF,$b)=>{"use strict";var Hk=Le(),zk=jt();$b.exports=function(s,e,t){try{return Hk(zk(Object.getOwnPropertyDescriptor(s,e)[t]))}catch(i){}}});var Vb=b((HF,Cb)=>{"use strict";var Qk=bt();Cb.exports=function(s){return Qk(s)||s===null}});var _b=b((zF,Ob)=>{"use strict";var Gk=Vb(),Wk=String,Yk=TypeError;Ob.exports=function(s){if(Gk(s))return s;throw new Yk("Can't set "+Wk(s)+" as a prototype")}});var Oc=b((QF,Fb)=>{"use strict";var Kk=Db(),Xk=bt(),Jk=Pi(),Zk=_b();Fb.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var s=!1,e={},t;try{t=Kk(Object.prototype,"__proto__","set"),t(e,[]),s=e instanceof Array}catch(i){}return function(r,a){return Jk(r),Zk(a),Xk(r)&&(s?t(r,a):r.__proto__=a),r}}():void 0)});var Kb=b((GF,Yb)=>{"use strict";var eR=Ee(),tR=mt(),Vo=Dt(),Gb=Pc(),iR=ge(),rR=Bb(),Nb=ko(),Ub=Oc(),sR=ha(),aR=Ar(),_c=Mr(),nR=_e(),qb=Zi(),Wb=Vc(),oR=Gb.PROPER,uR=Gb.CONFIGURABLE,jb=Wb.IteratorPrototype,Oo=Wb.BUGGY_SAFARI_ITERATORS,fa=nR("iterator"),Hb="keys",ma="values",zb="entries",Qb=function(){return this};Yb.exports=function(s,e,t,i,r,a,n){rR(t,e,i);var o=function(S){if(S===r&&h)return h;if(!Oo&&S&&S in d)return d[S];switch(S){case Hb:return function(){return new t(this,S)};case ma:return function(){return new t(this,S)};case zb:return function(){return new t(this,S)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,d=s.prototype,c=d[fa]||d["@@iterator"]||r&&d[r],h=!Oo&&c||o(r),p=e==="Array"&&d.entries||c,f,m,g;if(p&&(f=Nb(p.call(new s)),f!==Object.prototype&&f.next&&(!Vo&&Nb(f)!==jb&&(Ub?Ub(f,jb):iR(f[fa])||_c(f,fa,Qb)),sR(f,u,!0,!0),Vo&&(qb[u]=Qb))),oR&&r===ma&&c&&c.name!==ma&&(!Vo&&uR?aR(d,"name",ma):(l=!0,h=function(){return tR(c,this)})),r)if(m={values:o(ma),keys:a?h:o(Hb),entries:o(zb)},n)for(g in m)(Oo||l||!(g in d))&&_c(d,g,m[g]);else eR({target:e,proto:!0,forced:Oo||l},m);return(!Vo||n)&&d[fa]!==h&&_c(d,fa,h,{name:r}),qb[e]=h,m}});var Jb=b((WF,Xb)=>{"use strict";Xb.exports=function(s,e){return{value:s,done:e}}});var Nc=b((YF,rg)=>{"use strict";var lR=Yi(),Fc=ca(),Zb=Zi(),tg=Ec(),cR=Xi().f,dR=Kb(),_o=Jb(),pR=Dt(),hR=ft(),ig="Array Iterator",fR=tg.set,mR=tg.getterFor(ig);rg.exports=dR(Array,"Array",function(s,e){fR(this,{type:ig,target:lR(s),index:0,kind:e})},function(){var s=mR(this),e=s.target,t=s.index++;if(!e||t>=e.length)return s.target=void 0,_o(void 0,!0);switch(s.kind){case"keys":return _o(t,!1);case"values":return _o(e[t],!1)}return _o([t,e[t]],!1)},"values");var eg=Zb.Arguments=Zb.Array;Fc("keys");Fc("values");Fc("entries");if(!pR&&hR&&eg.name!=="values")try{cR(eg,"name",{value:"values"})}catch(s){}});var ag=b((KF,sg)=>{"use strict";var bR=_e(),gR=Zi(),SR=bR("iterator"),vR=Array.prototype;sg.exports=function(s){return s!==void 0&&(gR.Array===s||vR[SR]===s)}});var Uc=b((XF,og)=>{"use strict";var yR=pa(),ng=aa(),TR=Tr(),IR=Zi(),xR=_e(),ER=xR("iterator");og.exports=function(s){if(!TR(s))return ng(s,ER)||ng(s,"@@iterator")||IR[yR(s)]}});var lg=b((JF,ug)=>{"use strict";var wR=mt(),AR=jt(),PR=Ht(),kR=sa(),RR=Uc(),MR=TypeError;ug.exports=function(s,e){var t=arguments.length<2?RR(s):e;if(AR(t))return PR(wR(t,s));throw new MR(kR(s)+" is not iterable")}});var pg=b((ZF,dg)=>{"use strict";var LR=mt(),cg=Ht(),BR=aa();dg.exports=function(s,e,t){var i,r;cg(s);try{if(i=BR(s,"return"),!i){if(e==="throw")throw t;return t}i=LR(i,s)}catch(a){r=!0,i=a}if(e==="throw")throw t;if(r)throw i;return cg(i),t}});var No=b((eN,bg)=>{"use strict";var $R=wr(),DR=mt(),CR=Ht(),VR=sa(),OR=ag(),_R=Rr(),hg=ra(),FR=lg(),NR=Uc(),fg=pg(),UR=TypeError,Fo=function(s,e){this.stopped=s,this.result=e},mg=Fo.prototype;bg.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=$R(e,i),l,d,c,h,p,f,m,g=function(v){return l&&fg(l,"normal",v),new Fo(!0,v)},S=function(v){return r?(CR(v),o?u(v[0],v[1],g):u(v[0],v[1])):o?u(v,g):u(v)};if(a)l=s.iterator;else if(n)l=s;else{if(d=NR(s),!d)throw new UR(VR(s)+" is not iterable");if(OR(d)){for(c=0,h=_R(s);h>c;c++)if(p=S(s[c]),p&&hg(mg,p))return p;return new Fo(!1)}l=FR(s,d)}for(f=a?s.next:l.next;!(m=DR(f,l)).done;){try{p=S(m.value)}catch(v){fg(l,"throw",v)}if(typeof p=="object"&&p&&hg(mg,p))return p}return new Fo(!1)}});var Sg=b((tN,gg)=>{"use strict";var qR=ft(),jR=Xi(),HR=ia();gg.exports=function(s,e,t){qR?jR.f(s,e,HR(0,t)):s[e]=t}});var vg=b(()=>{"use strict";var zR=Ee(),QR=No(),GR=Sg();zR({target:"Object",stat:!0},{fromEntries:function(e){var t={};return QR(e,function(i,r){GR(t,i,r)},{AS_ENTRIES:!0}),t}})});var Tg=b((sN,yg)=>{"use strict";Nc();vg();var WR=Ir();yg.exports=WR.Object.fromEntries});var xg=b((aN,Ig)=>{"use strict";Ig.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 wg=b(()=>{"use strict";Nc();var YR=xg(),KR=ve(),XR=ha(),Eg=Zi();for(Uo in YR)XR(KR[Uo],Uo),Eg[Uo]=Eg.Array;var Uo});var Pg=b((uN,Ag)=>{"use strict";var JR=Tg();wg();Ag.exports=JR});var qc=b((lN,kg)=>{"use strict";var ZR=Pg();kg.exports=ZR});var Rg=b(()=>{"use strict"});var jc=b((pN,Mg)=>{"use strict";var ba=ve(),eM=Ki(),tM=Wi(),qo=function(s){return eM.slice(0,s.length)===s};Mg.exports=function(){return qo("Bun/")?"BUN":qo("Cloudflare-Workers")?"CLOUDFLARE":qo("Deno/")?"DENO":qo("Node.js/")?"NODE":ba.Bun&&typeof Bun.version=="string"?"BUN":ba.Deno&&typeof Deno.version=="object"?"DENO":tM(ba.process)==="process"?"NODE":ba.window&&ba.document?"BROWSER":"REST"}()});var jo=b((hN,Lg)=>{"use strict";var iM=jc();Lg.exports=iM==="NODE"});var $g=b((fN,Bg)=>{"use strict";var rM=Xi();Bg.exports=function(s,e,t){return rM.f(s,e,t)}});var Vg=b((mN,Cg)=>{"use strict";var sM=pi(),aM=$g(),nM=_e(),oM=ft(),Dg=nM("species");Cg.exports=function(s){var e=sM(s);oM&&e&&!e[Dg]&&aM(e,Dg,{configurable:!0,get:function(){return this}})}});var _g=b((bN,Og)=>{"use strict";var uM=ra(),lM=TypeError;Og.exports=function(s,e){if(uM(e,s))return s;throw new lM("Incorrect invocation")}});var zc=b((gN,Fg)=>{"use strict";var cM=Le(),dM=ge(),Hc=na(),pM=cM(Function.toString);dM(Hc.inspectSource)||(Hc.inspectSource=function(s){return pM(s)});Fg.exports=Hc.inspectSource});var Gc=b((SN,Hg)=>{"use strict";var hM=Le(),fM=Oe(),Ng=ge(),mM=pa(),bM=pi(),gM=zc(),Ug=function(){},qg=bM("Reflect","construct"),Qc=/^\s*(?:class|function)\b/,SM=hM(Qc.exec),vM=!Qc.test(Ug),ga=function(e){if(!Ng(e))return!1;try{return qg(Ug,[],e),!0}catch(t){return!1}},jg=function(e){if(!Ng(e))return!1;switch(mM(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return vM||!!SM(Qc,gM(e))}catch(t){return!0}};jg.sham=!0;Hg.exports=!qg||fM(function(){var s;return ga(ga.call)||!ga(Object)||!ga(function(){s=!0})||s})?jg:ga});var Qg=b((vN,zg)=>{"use strict";var yM=Gc(),TM=sa(),IM=TypeError;zg.exports=function(s){if(yM(s))return s;throw new IM(TM(s)+" is not a constructor")}});var Wc=b((yN,Wg)=>{"use strict";var Gg=Ht(),xM=Qg(),EM=Tr(),wM=_e(),AM=wM("species");Wg.exports=function(s,e){var t=Gg(s).constructor,i;return t===void 0||EM(i=Gg(t)[AM])?e:xM(i)}});var Kg=b((TN,Yg)=>{"use strict";var PM=Le();Yg.exports=PM([].slice)});var Jg=b((IN,Xg)=>{"use strict";var kM=TypeError;Xg.exports=function(s,e){if(s<e)throw new kM("Not enough arguments");return s}});var Yc=b((xN,Zg)=>{"use strict";var RM=Ki();Zg.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(RM)});var sd=b((EN,uS)=>{"use strict";var St=ve(),MM=_l(),LM=wr(),eS=ge(),BM=Ct(),oS=Oe(),tS=kc(),$M=Kg(),iS=xo(),DM=Jg(),CM=Yc(),VM=jo(),td=St.setImmediate,id=St.clearImmediate,OM=St.process,Kc=St.Dispatch,_M=St.Function,rS=St.MessageChannel,FM=St.String,Xc=0,Sa={},sS="onreadystatechange",va,tr,Jc,Zc;oS(function(){va=St.location});var rd=function(s){if(BM(Sa,s)){var e=Sa[s];delete Sa[s],e()}},ed=function(s){return function(){rd(s)}},aS=function(s){rd(s.data)},nS=function(s){St.postMessage(FM(s),va.protocol+"//"+va.host)};(!td||!id)&&(td=function(e){DM(arguments.length,1);var t=eS(e)?e:_M(e),i=$M(arguments,1);return Sa[++Xc]=function(){MM(t,void 0,i)},tr(Xc),Xc},id=function(e){delete Sa[e]},VM?tr=function(s){OM.nextTick(ed(s))}:Kc&&Kc.now?tr=function(s){Kc.now(ed(s))}:rS&&!CM?(Jc=new rS,Zc=Jc.port2,Jc.port1.onmessage=aS,tr=LM(Zc.postMessage,Zc)):St.addEventListener&&eS(St.postMessage)&&!St.importScripts&&va&&va.protocol!=="file:"&&!oS(nS)?(tr=nS,St.addEventListener("message",aS,!1)):sS in iS("script")?tr=function(s){tS.appendChild(iS("script"))[sS]=function(){tS.removeChild(this),rd(s)}}:tr=function(s){setTimeout(ed(s),0)});uS.exports={set:td,clear:id}});var dS=b((wN,cS)=>{"use strict";var lS=ve(),NM=ft(),UM=Object.getOwnPropertyDescriptor;cS.exports=function(s){if(!NM)return lS[s];var e=UM(lS,s);return e&&e.value}});var ad=b((AN,hS)=>{"use strict";var pS=function(){this.head=null,this.tail=null};pS.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}}};hS.exports=pS});var mS=b((PN,fS)=>{"use strict";var qM=Ki();fS.exports=/ipad|iphone|ipod/i.test(qM)&&typeof Pebble!="undefined"});var gS=b((kN,bS)=>{"use strict";var jM=Ki();bS.exports=/web0s(?!.*chrome)/i.test(jM)});var ES=b((RN,xS)=>{"use strict";var Br=ve(),HM=dS(),SS=wr(),nd=sd().set,zM=ad(),QM=Yc(),GM=mS(),WM=gS(),od=jo(),vS=Br.MutationObserver||Br.WebKitMutationObserver,yS=Br.document,TS=Br.process,Ho=Br.Promise,cd=HM("queueMicrotask"),Lr,ud,ld,zo,IS;cd||(ya=new zM,Ta=function(){var s,e;for(od&&(s=TS.domain)&&s.exit();e=ya.get();)try{e()}catch(t){throw ya.head&&Lr(),t}s&&s.enter()},!QM&&!od&&!WM&&vS&&yS?(ud=!0,ld=yS.createTextNode(""),new vS(Ta).observe(ld,{characterData:!0}),Lr=function(){ld.data=ud=!ud}):!GM&&Ho&&Ho.resolve?(zo=Ho.resolve(void 0),zo.constructor=Ho,IS=SS(zo.then,zo),Lr=function(){IS(Ta)}):od?Lr=function(){TS.nextTick(Ta)}:(nd=SS(nd,Br),Lr=function(){nd(Ta)}),cd=function(s){ya.head||Lr(),ya.add(s)});var ya,Ta;xS.exports=cd});var AS=b((MN,wS)=>{"use strict";wS.exports=function(s,e){try{arguments.length===1?console.error(s):console.error(s,e)}catch(t){}}});var Qo=b((LN,PS)=>{"use strict";PS.exports=function(s){try{return{error:!1,value:s()}}catch(e){return{error:!0,value:e}}}});var ir=b((BN,kS)=>{"use strict";var YM=ve();kS.exports=YM.Promise});var $r=b(($N,BS)=>{"use strict";var KM=ve(),Ia=ir(),XM=ge(),JM=nc(),ZM=zc(),eL=_e(),RS=jc(),tL=Dt(),dd=Gl(),MS=Ia&&Ia.prototype,iL=eL("species"),pd=!1,LS=XM(KM.PromiseRejectionEvent),rL=JM("Promise",function(){var s=ZM(Ia),e=s!==String(Ia);if(!e&&dd===66||tL&&!(MS.catch&&MS.finally))return!0;if(!dd||dd<51||!/native code/.test(s)){var t=new Ia(function(a){a(1)}),i=function(a){a(function(){},function(){})},r=t.constructor={};if(r[iL]=i,pd=t.then(function(){})instanceof i,!pd)return!0}return!e&&(RS==="BROWSER"||RS==="DENO")&&!LS});BS.exports={CONSTRUCTOR:rL,REJECTION_EVENT:LS,SUBCLASSING:pd}});var Dr=b((DN,DS)=>{"use strict";var $S=jt(),sL=TypeError,aL=function(s){var e,t;this.promise=new s(function(i,r){if(e!==void 0||t!==void 0)throw new sL("Bad Promise constructor");e=i,t=r}),this.resolve=$S(e),this.reject=$S(t)};DS.exports.f=function(s){return new aL(s)}});var ZS=b(()=>{"use strict";var nL=Ee(),oL=Dt(),Ko=jo(),Ri=ve(),_r=mt(),CS=Mr(),VS=Oc(),uL=ha(),lL=Vg(),cL=jt(),Yo=ge(),dL=bt(),pL=_g(),hL=Wc(),US=sd().set,gd=ES(),fL=AS(),mL=Qo(),bL=ad(),qS=Ec(),Xo=ir(),Sd=$r(),jS=Dr(),Jo="Promise",HS=Sd.CONSTRUCTOR,gL=Sd.REJECTION_EVENT,SL=Sd.SUBCLASSING,hd=qS.getterFor(Jo),vL=qS.set,Cr=Xo&&Xo.prototype,rr=Xo,Go=Cr,zS=Ri.TypeError,fd=Ri.document,vd=Ri.process,md=jS.f,yL=md,TL=!!(fd&&fd.createEvent&&Ri.dispatchEvent),QS="unhandledrejection",IL="rejectionhandled",OS=0,GS=1,xL=2,yd=1,WS=2,Wo,_S,EL,FS,YS=function(s){var e;return dL(s)&&Yo(e=s.then)?e:!1},KS=function(s,e){var t=e.value,i=e.state===GS,r=i?s.ok:s.fail,a=s.resolve,n=s.reject,o=s.domain,u,l,d;try{r?(i||(e.rejection===WS&&AL(e),e.rejection=yd),r===!0?u=t:(o&&o.enter(),u=r(t),o&&(o.exit(),d=!0)),u===s.promise?n(new zS("Promise-chain cycle")):(l=YS(u))?_r(l,u,a,n):a(u)):n(t)}catch(c){o&&!d&&o.exit(),n(c)}},XS=function(s,e){s.notified||(s.notified=!0,gd(function(){for(var t=s.reactions,i;i=t.get();)KS(i,s);s.notified=!1,e&&!s.rejection&&wL(s)}))},JS=function(s,e,t){var i,r;TL?(i=fd.createEvent("Event"),i.promise=e,i.reason=t,i.initEvent(s,!1,!0),Ri.dispatchEvent(i)):i={promise:e,reason:t},!gL&&(r=Ri["on"+s])?r(i):s===QS&&fL("Unhandled promise rejection",t)},wL=function(s){_r(US,Ri,function(){var e=s.facade,t=s.value,i=NS(s),r;if(i&&(r=mL(function(){Ko?vd.emit("unhandledRejection",t,e):JS(QS,e,t)}),s.rejection=Ko||NS(s)?WS:yd,r.error))throw r.value})},NS=function(s){return s.rejection!==yd&&!s.parent},AL=function(s){_r(US,Ri,function(){var e=s.facade;Ko?vd.emit("rejectionHandled",e):JS(IL,e,s.value)})},Vr=function(s,e,t){return function(i){s(e,i,t)}},Or=function(s,e,t){s.done||(s.done=!0,t&&(s=t),s.value=e,s.state=xL,XS(s,!0))},bd=function(s,e,t){if(!s.done){s.done=!0,t&&(s=t);try{if(s.facade===e)throw new zS("Promise can't be resolved itself");var i=YS(e);i?gd(function(){var r={done:!1};try{_r(i,e,Vr(bd,r,s),Vr(Or,r,s))}catch(a){Or(r,a,s)}}):(s.value=e,s.state=GS,XS(s,!1))}catch(r){Or({done:!1},r,s)}}};if(HS&&(rr=function(e){pL(this,Go),cL(e),_r(Wo,this);var t=hd(this);try{e(Vr(bd,t),Vr(Or,t))}catch(i){Or(t,i)}},Go=rr.prototype,Wo=function(e){vL(this,{type:Jo,done:!1,notified:!1,parent:!1,reactions:new bL,rejection:!1,state:OS,value:void 0})},Wo.prototype=CS(Go,"then",function(e,t){var i=hd(this),r=md(hL(this,rr));return i.parent=!0,r.ok=Yo(e)?e:!0,r.fail=Yo(t)&&t,r.domain=Ko?vd.domain:void 0,i.state===OS?i.reactions.add(r):gd(function(){KS(r,i)}),r.promise}),_S=function(){var s=new Wo,e=hd(s);this.promise=s,this.resolve=Vr(bd,e),this.reject=Vr(Or,e)},jS.f=md=function(s){return s===rr||s===EL?new _S(s):yL(s)},!oL&&Yo(Xo)&&Cr!==Object.prototype)){FS=Cr.then,SL||CS(Cr,"then",function(e,t){var i=this;return new rr(function(r,a){_r(FS,i,r,a)}).then(e,t)},{unsafe:!0});try{delete Cr.constructor}catch(s){}VS&&VS(Cr,Go)}nL({global:!0,constructor:!0,wrap:!0,forced:HS},{Promise:rr});uL(rr,Jo,!1,!0);lL(Jo)});var sv=b((ON,rv)=>{"use strict";var PL=_e(),tv=PL("iterator"),iv=!1;try{ev=0,Td={next:function(){return{done:!!ev++}},return:function(){iv=!0}},Td[tv]=function(){return this},Array.from(Td,function(){throw 2})}catch(s){}var ev,Td;rv.exports=function(s,e){try{if(!e&&!iv)return!1}catch(r){return!1}var t=!1;try{var i={};i[tv]=function(){return{next:function(){return{done:t=!0}}}},s(i)}catch(r){}return t}});var Id=b((_N,av)=>{"use strict";var kL=ir(),RL=sv(),ML=$r().CONSTRUCTOR;av.exports=ML||!RL(function(s){kL.all(s).then(void 0,function(){})})});var nv=b(()=>{"use strict";var LL=Ee(),BL=mt(),$L=jt(),DL=Dr(),CL=Qo(),VL=No(),OL=Id();LL({target:"Promise",stat:!0,forced:OL},{all:function(e){var t=this,i=DL.f(t),r=i.resolve,a=i.reject,n=CL(function(){var o=$L(t.resolve),u=[],l=0,d=1;VL(e,function(c){var h=l++,p=!1;d++,BL(o,t,c).then(function(f){p||(p=!0,u[h]=f,--d||r(u))},a)}),--d||r(u)});return n.error&&a(n.value),i.promise}})});var uv=b(()=>{"use strict";var _L=Ee(),FL=Dt(),NL=$r().CONSTRUCTOR,Ed=ir(),UL=pi(),qL=ge(),jL=Mr(),ov=Ed&&Ed.prototype;_L({target:"Promise",proto:!0,forced:NL,real:!0},{catch:function(s){return this.then(void 0,s)}});!FL&&qL(Ed)&&(xd=UL("Promise").prototype.catch,ov.catch!==xd&&jL(ov,"catch",xd,{unsafe:!0}));var xd});var lv=b(()=>{"use strict";var HL=Ee(),zL=mt(),QL=jt(),GL=Dr(),WL=Qo(),YL=No(),KL=Id();HL({target:"Promise",stat:!0,forced:KL},{race:function(e){var t=this,i=GL.f(t),r=i.reject,a=WL(function(){var n=QL(t.resolve);YL(e,function(o){zL(n,t,o).then(i.resolve,r)})});return a.error&&r(a.value),i.promise}})});var cv=b(()=>{"use strict";var XL=Ee(),JL=Dr(),ZL=$r().CONSTRUCTOR;XL({target:"Promise",stat:!0,forced:ZL},{reject:function(e){var t=JL.f(this),i=t.reject;return i(e),t.promise}})});var wd=b((GN,dv)=>{"use strict";var eB=Ht(),tB=bt(),iB=Dr();dv.exports=function(s,e){if(eB(s),tB(e)&&e.constructor===s)return e;var t=iB.f(s),i=t.resolve;return i(e),t.promise}});var fv=b(()=>{"use strict";var rB=Ee(),sB=pi(),pv=Dt(),aB=ir(),hv=$r().CONSTRUCTOR,nB=wd(),oB=sB("Promise"),uB=pv&&!hv;rB({target:"Promise",stat:!0,forced:pv||hv},{resolve:function(e){return nB(uB&&this===oB?aB:this,e)}})});var mv=b(()=>{"use strict";ZS();nv();uv();lv();cv();fv()});var vv=b(()=>{"use strict";var lB=Ee(),cB=Dt(),Zo=ir(),dB=Oe(),gv=pi(),Sv=ge(),pB=Wc(),bv=wd(),hB=Mr(),Pd=Zo&&Zo.prototype,fB=!!Zo&&dB(function(){Pd.finally.call({then:function(){}},function(){})});lB({target:"Promise",proto:!0,real:!0,forced:fB},{finally:function(s){var e=pB(this,gv("Promise")),t=Sv(s);return this.then(t?function(i){return bv(e,s()).then(function(){return i})}:s,t?function(i){return bv(e,s()).then(function(){throw i})}:s)}});!cB&&Sv(Zo)&&(Ad=gv("Promise").prototype.finally,Pd.finally!==Ad&&hB(Pd,"finally",Ad,{unsafe:!0}));var Ad});var Tv=b((eU,yv)=>{"use strict";Rg();mv();vv();var mB=ki();yv.exports=mB("Promise","finally")});var xv=b((tU,Iv)=>{"use strict";var bB=Tv();Iv.exports=bB});var eu=b((iU,Ev)=>{"use strict";var gB=xv();Ev.exports=gB});var Ov=b(()=>{"use strict";var LB=Ee(),BB=yc().values;LB({target:"Object",stat:!0},{values:function(e){return BB(e)}})});var Fv=b((NU,_v)=>{"use strict";Ov();var $B=Ir();_v.exports=$B.Object.values});var Uv=b((UU,Nv)=>{"use strict";var DB=Fv();Nv.exports=DB});var nr=b((qU,qv)=>{"use strict";var CB=Uv();qv.exports=CB});var ay=b(()=>{"use strict";var s$=Ee(),a$=xr(),n$=Rr(),o$=la(),u$=ca();s$({target:"Array",proto:!0},{at:function(e){var t=a$(this),i=n$(t),r=o$(e),a=r>=0?r:i+r;return a<0||a>=i?void 0:t[a]}});u$("at")});var oy=b((Xq,ny)=>{"use strict";ay();var l$=ki();ny.exports=l$("Array","at")});var ly=b((Jq,uy)=>{"use strict";var c$=oy();uy.exports=c$});var Ot=b((Zq,cy)=>{"use strict";var d$=ly();cy.exports=d$});var Kd=b((Fj,jy)=>{"use strict";var z$=Wi();jy.exports=Array.isArray||function(e){return z$(e)==="Array"}});var zy=b((Nj,Hy)=>{"use strict";var Q$=TypeError,G$=9007199254740991;Hy.exports=function(s){if(s>G$)throw Q$("Maximum allowed index exceeded");return s}});var Wy=b((Uj,Gy)=>{"use strict";var W$=Kd(),Y$=Rr(),K$=zy(),X$=wr(),Qy=function(s,e,t,i,r,a,n,o){for(var u=r,l=0,d=n?X$(n,o):!1,c,h;l<i;)l in t&&(c=d?d(t[l],l,e):t[l],a>0&&W$(c)?(h=Y$(c),u=Qy(s,e,c,h,u,a-1)-1):(K$(u+1),s[u]=c),u++),l++;return u};Gy.exports=Qy});var Jy=b((qj,Xy)=>{"use strict";var Yy=Kd(),J$=Gc(),Z$=bt(),eD=_e(),tD=eD("species"),Ky=Array;Xy.exports=function(s){var e;return Yy(s)&&(e=s.constructor,J$(e)&&(e===Ky||Yy(e.prototype))?e=void 0:Z$(e)&&(e=e[tD],e===null&&(e=void 0))),e===void 0?Ky:e}});var eT=b((jj,Zy)=>{"use strict";var iD=Jy();Zy.exports=function(s,e){return new(iD(s))(e===0?0:e)}});var tT=b(()=>{"use strict";var rD=Ee(),sD=Wy(),aD=jt(),nD=xr(),oD=Rr(),uD=eT();rD({target:"Array",proto:!0},{flatMap:function(e){var t=nD(this),i=oD(t),r;return aD(e),r=uD(t,0),r.length=sD(r,t,t,i,0,1,e,arguments.length>1?arguments[1]:void 0),r}})});var iT=b(()=>{"use strict";var lD=ca();lD("flatMap")});var sT=b((Wj,rT)=>{"use strict";tT();iT();var cD=ki();rT.exports=cD("Array","flatMap")});var nT=b((Yj,aT)=>{"use strict";var dD=sT();aT.exports=dD});var Fa=b((Kj,oT)=>{"use strict";var pD=nT();oT.exports=pD});var Na=b((Xj,uT)=>{"use strict";var hD=pa(),fD=String;uT.exports=function(s){if(hD(s)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return fD(s)}});var Xd=b((Jj,lT)=>{"use strict";lT.exports=`
|
|
7
|
-
\v\f\r \xA0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF`});var pT=b((Zj,dT)=>{"use strict";var mD=Le(),bD=Pi(),gD=Na(),Zd=Xd(),cT=mD("".replace),SD=RegExp("^["+Zd+"]+"),vD=RegExp("(^|[^"+Zd+"])["+Zd+"]+$"),Jd=function(s){return function(e){var t=gD(bD(e));return s&1&&(t=cT(t,SD,"")),s&2&&(t=cT(t,vD,"$1")),t}};dT.exports={start:Jd(1),end:Jd(2),trim:Jd(3)}});var bT=b((eH,mT)=>{"use strict";var yD=Pc().PROPER,TD=Oe(),hT=Xd(),fT="\u200B\x85\u180E";mT.exports=function(s){return TD(function(){return!!hT[s]()||fT[s]()!==fT||yD&&hT[s].name!==s})}});var ep=b((tH,gT)=>{"use strict";var ID=pT().start,xD=bT();gT.exports=xD("trimStart")?function(){return ID(this)}:"".trimStart});var vT=b(()=>{"use strict";var ED=Ee(),ST=ep();ED({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==ST},{trimLeft:ST})});var TT=b(()=>{"use strict";vT();var wD=Ee(),yT=ep();wD({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==yT},{trimStart:yT})});var xT=b((nH,IT)=>{"use strict";TT();var AD=ki();IT.exports=AD("String","trimLeft")});var wT=b((oH,ET)=>{"use strict";var PD=xT();ET.exports=PD});var PT=b((uH,AT)=>{"use strict";var kD=wT();AT.exports=kD});var qT=b(()=>{"use strict"});var jT=b(()=>{"use strict"});var zT=b((q3,HT)=>{"use strict";var XD=bt(),JD=Wi(),ZD=_e(),e0=ZD("match");HT.exports=function(s){var e;return XD(s)&&((e=s[e0])!==void 0?!!e:JD(s)==="RegExp")}});var GT=b((j3,QT)=>{"use strict";var t0=Ht();QT.exports=function(){var s=t0(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 KT=b((H3,YT)=>{"use strict";var i0=mt(),r0=Ct(),s0=ra(),a0=GT(),WT=RegExp.prototype;YT.exports=function(s){var e=s.flags;return e===void 0&&!("flags"in WT)&&!r0(s,"flags")&&s0(WT,s)?i0(a0,s):e}});var JT=b((z3,XT)=>{"use strict";var np=Le(),n0=xr(),o0=Math.floor,sp=np("".charAt),u0=np("".replace),ap=np("".slice),l0=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,c0=/\$([$&'`]|\d{1,2})/g;XT.exports=function(s,e,t,i,r,a){var n=t+s.length,o=i.length,u=c0;return r!==void 0&&(r=n0(r),u=l0),u0(a,u,function(l,d){var c;switch(sp(d,0)){case"$":return"$";case"&":return s;case"`":return ap(e,0,t);case"'":return ap(e,n);case"<":c=r[ap(d,1,-1)];break;default:var h=+d;if(h===0)return l;if(h>o){var p=o0(h/10);return p===0?l:p<=o?i[p-1]===void 0?sp(d,1):i[p-1]+sp(d,1):l}c=i[h-1]}return c===void 0?"":c})}});var tI=b(()=>{"use strict";var d0=Ee(),p0=mt(),up=Le(),ZT=Pi(),h0=ge(),f0=Tr(),m0=zT(),Jr=Na(),b0=aa(),g0=KT(),S0=JT(),v0=_e(),y0=Dt(),T0=v0("replace"),I0=TypeError,op=up("".indexOf),x0=up("".replace),eI=up("".slice),E0=Math.max;d0({target:"String",proto:!0},{replaceAll:function(e,t){var i=ZT(this),r,a,n,o,u,l,d,c,h,p,f=0,m="";if(!f0(e)){if(r=m0(e),r&&(a=Jr(ZT(g0(e))),!~op(a,"g")))throw new I0("`.replaceAll` does not allow non-global regexes");if(n=b0(e,T0),n)return p0(n,e,i,t);if(y0&&r)return x0(Jr(i),e,t)}for(o=Jr(i),u=Jr(e),l=h0(t),l||(t=Jr(t)),d=u.length,c=E0(1,d),h=op(o,u);h!==-1;)p=l?Jr(t(u,h,o)):S0(u,o,h,[],void 0,t),m+=eI(o,f,h)+p,f=h+d,h=h+c>o.length?-1:op(o,u,h+c);return f<o.length&&(m+=eI(o,f)),m}})});var rI=b((W3,iI)=>{"use strict";qT();jT();tI();var w0=ki();iI.exports=w0("String","replaceAll")});var aI=b((Y3,sI)=>{"use strict";var A0=rI();sI.exports=A0});var lp=b((K3,nI)=>{"use strict";var P0=aI();nI.exports=P0});var uI=b((X3,oI)=>{"use strict";var k0=la(),R0=Na(),M0=Pi(),L0=RangeError;oI.exports=function(e){var t=R0(M0(this)),i="",r=k0(e);if(r<0||r===1/0)throw new L0("Wrong number of repetitions");for(;r>0;(r>>>=1)&&(t+=t))r&1&&(i+=t);return i}});var hI=b((J3,pI)=>{"use strict";var dI=Le(),B0=pc(),lI=Na(),$0=uI(),D0=Pi(),C0=dI($0),V0=dI("".slice),O0=Math.ceil,cI=function(s){return function(e,t,i){var r=lI(D0(e)),a=B0(t),n=r.length,o=i===void 0?" ":lI(i),u,l;return a<=n||o===""?r:(u=a-n,l=C0(o,O0(u/o.length)),l.length>u&&(l=V0(l,0,u)),s?r+l:l+r)}};pI.exports={start:cI(!1),end:cI(!0)}});var mI=b((Z3,fI)=>{"use strict";var _0=Ki();fI.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(_0)});var bI=b(()=>{"use strict";var F0=Ee(),N0=hI().start,U0=mI();F0({target:"String",proto:!0,forced:U0},{padStart:function(e){return N0(this,e,arguments.length>1?arguments[1]:void 0)}})});var SI=b((iz,gI)=>{"use strict";bI();var q0=ki();gI.exports=q0("String","padStart")});var yI=b((rz,vI)=>{"use strict";var j0=SI();vI.exports=j0});var cp=b((sz,TI)=>{"use strict";var H0=yI();TI.exports=H0});var Bh="2.0.135-dev.f94adb28.0";var et=(r=>(r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused",r))(et||{}),di=(y=>(y.MPEG="MPEG",y.DASH="DASH",y.DASH_SEP="DASH_SEP",y.DASH_SEP_VK="DASH_SEP",y.DASH_WEBM="DASH_WEBM",y.DASH_WEBM_AV1="DASH_WEBM_AV1",y.DASH_STREAMS="DASH_STREAMS",y.DASH_WEBM_VK="DASH_WEBM",y.DASH_ONDEMAND="DASH_ONDEMAND",y.DASH_ONDEMAND_VK="DASH_ONDEMAND",y.DASH_LIVE="DASH_LIVE",y.DASH_LIVE_CMAF="DASH_LIVE_CMAF",y.DASH_LIVE_WEBM="DASH_LIVE_WEBM",y.HLS="HLS",y.HLS_ONDEMAND="HLS_ONDEMAND",y.HLS_JS="HLS",y.HLS_LIVE="HLS_LIVE",y.HLS_LIVE_CMAF="HLS_LIVE_CMAF",y.WEB_RTC_LIVE="WEB_RTC_LIVE",y))(di||{});var vo=(r=>(r.NOT_AVAILABLE="NOT_AVAILABLE",r.AVAILABLE="AVAILABLE",r.CONNECTING="CONNECTING",r.CONNECTED="CONNECTED",r))(vo||{}),Cl=(i=>(i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic",i))(Cl||{});var Vl=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(Vl||{}),yo=(i=>(i.TRAFFIC_SAVING="traffic_saving",i.HIGH_QUALITY="high_quality",i.UNKNOWN="unknown",i))(yo||{});var ME=N(gt(),1);import{assertNever as Lm,assertNonNullable as sP,isNonNullable as wo,ValueSubject as fc,Subject as aP,Subscription as nP,merge as oP,observableFrom as uP,fromEvent as Pm,map as km,tap as Rm,filterChanged as lP,isNullable as mc,ErrorCategory as Mm}from"@vkontakte/videoplayer-shared/es2018";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 Ao=class{constructor(e){this.connection$=new fc(void 0);this.castState$=new fc("NOT_AVAILABLE");this.errorEvent$=new aP;this.realCastState$=new fc("NOT_AVAILABLE");this.subscription=new nP;this.isDestroyed=!1;var a;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");let t="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${t}`}),e.isDisabled||!t)return;let i=wo((a=window.chrome)==null?void 0:a.cast),r=!!window.__onGCastApiAvailable;i?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&!this.isDestroyed&&this.initializeCastApi()},r||Am("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:Mm.NETWORK,message:"Script loading failed!"})))}connect(){var e;(e=cast.framework.CastContext.getInstance())==null||e.requestSession()}disconnect(){var e,t;(t=(e=cast.framework.CastContext.getInstance())==null?void 0:e.getCurrentSession())==null||t.endSession(!0)}stopMedia(){return new Promise((e,t)=>{var i,r,a;(a=(r=(i=cast.framework.CastContext.getInstance())==null?void 0:i.getCurrentSession())==null?void 0:r.getMediaSession())==null||a.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){wo(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();mc(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();mc(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(Pm(i,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(r=>{var a,n,o;switch(r.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(o=(n=(a=i.getCurrentSession())==null?void 0:a.getMediaSession())==null?void 0:n.media)==null?void 0:o.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return Lm(r.sessionState)}})).add(oP(Pm(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(Rm(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),km(r=>r.castState)),uP([i.getCastState()])).pipe(lP(),km(cP),Rm(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{var o,u;let a=r==="CONNECTED",n=wo(this.connection$.getValue());if(a&&!n){let l=i.getCurrentSession();sP(l);let d=l.getCastDevice(),c=(u=(o=l.getMediaSession())==null?void 0:o.media)==null?void 0:u.contentId;(mc(c)||c===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:l,castDevice:d}))}else!a&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(r==="CONNECTED"?wo(this.connection$.getValue())?"CONNECTED":"AVAILABLE":r)}))}initializeCastApi(){var r;let e,t,i;try{e=cast.framework.CastContext.getInstance(),t=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,i=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(a){return}try{e.setOptions({receiverApplicationId:(r=this.params.receiverApplicationId)!=null?r:t,autoJoinPolicy:i}),this.initListeners()}catch(a){this.errorEvent$.next({id:"ChromecastInitializer",category:Mm.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:a})}}},cP=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 Lm(s)}};var xh=N(gt(),1),dE=N(Ji(),1),pE=N(qc(),1);var Dv=N(eu(),1);import{assertNever as wv}from"@vkontakte/videoplayer-shared/es2018";var Se=(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:wv(t)}return s},Mi=(s,e)=>{var t;switch(e){case 0:return NaN;case 1:{let i=new URL(s);return Number(i.searchParams.get("playback_shift"))}case 2:{let i=new URL(s);return Number((t=i.searchParams.get("offset_p"))!=null?t:0)}default:wv(e)}};var M=(s,e,t=!1)=>{let i=s.getTransition();(t||!i||i.to===e)&&s.setState(e)};import{isNonNullable as SB,Subject as tu,merge as Av}from"@vkontakte/videoplayer-shared/es2018";var G=class{constructor(e){this.transitionStarted$=new tu;this.transitionEnded$=new tu;this.transitionUpdated$=new tu;this.forceChanged$=new tu;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||SB(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 vB}from"@vkontakte/videoplayer-shared/es2018";var Pv=s=>{switch(s){case"MPEG":case"DASH":case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":case"HLS":case"HLS_ONDEMAND":return!1;case"DASH_LIVE":case"DASH_LIVE_CMAF":case"HLS_LIVE":case"HLS_LIVE_CMAF":case"DASH_LIVE_WEBM":case"WEB_RTC_LIVE":return!0;default:return vB(s)}};import{assertNever as Fr,assertNonNullable as sr,debounce as kv,ErrorCategory as Rv,fromEvent as ar,isNonNullable as Mv,map as Lv,merge as Bv,observableFrom as yB,Subject as TB,Subscription as kd,timeout as IB,getHighestQuality as xB}from"@vkontakte/videoplayer-shared/es2018";var EB=5,wB=5,AB=500,$v=7e3,xa=class{constructor(e){this.subscription=new kd;this.loadMediaTimeoutSubscription=new kd;this.videoState=new G("stopped");this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(a)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.stop());return}if(!t){if((r==null?void 0:r.to)!=="paused"&&a.state==="requested"&&e!=="stopped"){this.seek(a.position/1e3);return}switch(i){case"ready":{switch(e){case"playing":case"paused":case"ready":break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:Fr(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:Fr(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:Fr(e)}break}default:Fr(i)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(Pv(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 kd;this.subscription.add(e),this.subscription.add(Bv(this.videoState.stateChangeStarted$.pipe(Lv(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe(Lv(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 TB;e.add(r.pipe(kv(AB)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let a=NaN;e.add(ar(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)>EB)&&r.next(o),a=o})),e.add(ar(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(ar(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(ar(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t(ar(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<wB&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),M(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:Fr(n)}}),t(ar(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t(ar(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});let i=Bv(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,yB(["init"])).pipe(kv(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"),M(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),M(this.params.desiredState.playbackState,"playing"));let i=this.params.output.isLive$.getValue();this.params.output.duration$.next(i?0:t.duration),this.params.output.position$.next(i?0:t.currentTime),this.params.desiredState.seekState.setState({state:"none"})}}prepare(){let e=this.params.format;this.log({message:`[prepare] format: ${e}`});let t=this.createMediaInfo(e),i=this.createLoadRequest(t);this.loadMedia(i)}handleRemotePause(){let e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="paused"||e==="playing")&&(this.videoState.setState("paused"),M(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="playing"||e==="paused")&&(this.videoState.setState("playing"),M(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){var t;let e=this.videoState.getTransition();(e==null?void 0:e.to)==="ready"&&this.videoState.setState("ready"),((t=this.params.desiredState.playbackState.getTransition())==null?void 0:t.to)==="ready"&&M(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){var r,a;let t=this.params.output.volume$.getValue(),i={volume:(r=e.volume)!=null?r:t.volume,muted:(a=e.muted)!=null?a:t.muted};(i.volume!==t.volume||i.muted!==i.muted)&&this.params.output.volume$.next(i)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:i}=this.params.connection;t.currentTime=e,i.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){var l;let t=this.params.source,i,r,a;switch(e){case"MPEG":{let d=t[e];sr(d);let c=xB(Object.keys(d));sr(c);let h=d[c];sr(h),i=h,r="video/mp4",a=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let d=t[e];sr(d),i=d.url,r="application/x-mpegurl",a=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":{let d=t[e];sr(d),i=d.url,r="application/dash+xml",a=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let d=t[e];sr(d),i=d.url,r="application/dash+xml",a=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let d=t[e];sr(d),i=Se(d.url),r="application/x-mpegurl",a=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let d="Unsupported format for Chromecast",c=new Error(d);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:Rv.VIDEO_PIPELINE,message:d,thrown:c}),c}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return Fr(e)}let n=new chrome.cast.media.MediaInfo((l=this.params.meta.videoId)!=null?l:i,r);n.contentUrl=i,n.streamType=a,n.metadata=new chrome.cast.media.GenericMediaMetadata;let{title:o,subtitle:u}=this.params.meta;return Mv(o)&&(n.metadata.title=o),Mv(u)&&(n.metadata.subtitle=u),n}createLoadRequest(e){let t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;let i=this.params.desiredState.seekState.getState();return i.state==="applying"||i.state==="requested"?t.currentTime=this.params.output.isLive$.getValue()?0:i.position/1e3:t.currentTime=0,t}loadMedia(e){let t=this.params.connection.session.loadMedia(e),i=new Promise((r,a)=>{this.loadMediaTimeoutSubscription.add(IB($v).subscribe(()=>a(`timeout(${$v})`)))});(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:Rv.VIDEO_PIPELINE,message:a,thrown:r})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var Wd=N(gt(),1);import{clearVideoElement as Vv}from"@vkontakte/videoplayer-shared/es2018";import{clearVideoElement as PB}from"@vkontakte/videoplayer-shared/es2018";var Cv=s=>{try{s.pause(),s.playbackRate=0,PB(s),s.remove()}catch(e){console.error(e)}};import{fromEvent as kB,Subscription as RB}from"@vkontakte/videoplayer-shared/es2018";var Rd=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)}},Md=window.WeakMap?new WeakMap:new Rd,Ld=window.WeakMap?new WeakMap:new Map,MB=(s,e=20)=>{let t=0;return kB(s,"ratechange").subscribe(i=>{t++,t>=e&&(s.currentTime=s.currentTime,t=0)})},tt=(s,{audioVideoSyncRate:e,disableYandexPiP:t})=>{let i=s.querySelector("video"),r=!!i;i?Vv(i):(i=document.createElement("video"),s.appendChild(i)),Md.set(i,r);let a=new RB;return a.add(MB(i,e)),Ld.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},it=s=>{let e=Ld.get(s);e==null||e.unsubscribe(),Ld.delete(s);let t=Md.get(s);Md.delete(s),t?Vv(s):Cv(s)};var $d=N(nr(),1);import{assertNonNullable as wa,isNonNullable as Qt,isNullable as _B,fromEvent as Nr,merge as jv,observableFrom as Hv,filterChanged as zv,map as Aa,Subject as Qv,Subscription as FB,ValueSubject as NB,ErrorCategory as UB}from"@vkontakte/videoplayer-shared/es2018";import{isNonNullable as Bd,isNullable as VB,Subscription as OB}from"@vkontakte/videoplayer-shared/es2018";var iu=(s,e,t,{equal:i=(n,o)=>n===o,changed$:r,onError:a}={})=>{let n=s.getState(),o=e(),u=VB(r),l=new OB;return r&&l.add(r.subscribe(d=>{let c=s.getState();i(d,c)&&s.setState(d)},a)),i(o,n)||(t(n),u&&s.setState(n)),l.add(s.stateChangeStarted$.subscribe(d=>{t(d.to),u&&s.setState(d.to)},a)),l},zt=(s,e,t)=>iu(e,()=>s.loop,i=>{Bd(i)&&(s.loop=i)},{onError:t}),rt=(s,e,t,i)=>iu(e,()=>({muted:s.muted,volume:s.volume}),r=>{Bd(r)&&(s.muted=r.muted,s.volume=r.volume)},{equal:(r,a)=>r===a||(r==null?void 0:r.muted)===(a==null?void 0:a.muted)&&(r==null?void 0:r.volume)===(a==null?void 0:a.volume),changed$:t,onError:i}),It=(s,e,t,i)=>iu(e,()=>s.playbackRate,r=>{Bd(r)&&(s.playbackRate=r)},{changed$:t,onError:i}),Ea=iu;var qB=s=>["__",s.language,s.label].join("|"),jB=(s,e)=>{if(s.id===e)return!0;let[t,i,r]=e.split("|");return s.language===i&&s.label===r},Dd=class s{constructor(e){this.available$=new Qv;this.current$=new NB(void 0);this.error$=new Qv;this.subscription=new FB;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:UB.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(Ea(t.internalTextTracks,()=>(0,$d.default)(this.internalTracks),a=>{Qt(a)&&this.setInternal(a)},{equal:(a,n)=>Qt(a)&&Qt(n)&&a.length===n.length&&a.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(Aa(a=>a.filter(({type:n})=>n==="internal"))),onError:r})),this.subscription.add(Ea(t.externalTextTracks,()=>(0,$d.default)(this.externalTracks),a=>{Qt(a)&&this.setExternal(a)},{equal:(a,n)=>Qt(a)&&Qt(n)&&a.length===n.length&&a.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(Aa(a=>a.filter(({type:n})=>n==="external"))),onError:r})),this.subscription.add(Ea(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(Ea(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let a of this.htmlTextTracksAsArray())this.applyCueSettings(a.cues),this.applyCueSettings(a.activeCues)}))}subscribe(){wa(this.video);let{textTracks:e}=this.video;this.subscription.add(Nr(e,"addtrack").subscribe(()=>{let i=this.current$.getValue();i&&this.select(i)})),this.subscription.add(jv(Nr(e,"addtrack"),Nr(e,"removetrack"),Hv(["init"])).pipe(Aa(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),zv((i,r)=>i.length===r.length&&i.every(({id:a},n)=>a===r[n].id))).subscribe(this.available$)),this.subscription.add(jv(Nr(e,"change"),Hv(["init"])).pipe(Aa(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),Aa(i=>i&&this.htmlTextTrackToITextTrack(i).id),zv()).subscribe(this.current$));let t=i=>{var r,a;return this.applyCueSettings((a=(r=i.target)==null?void 0:r.activeCues)!=null?a:null)};this.subscription.add(Nr(e,"addtrack").subscribe(i=>{var a,n;(a=i.track)==null||a.addEventListener("cuechange",t);let r=o=>{var l,d,c,h,p;let u=(d=(l=o.target)==null?void 0:l.cues)!=null?d:null;u&&u.length&&(this.applyCueSettings((h=(c=o.target)==null?void 0:c.cues)!=null?h:null),(p=o.target)==null||p.removeEventListener("cuechange",r))};(n=i.track)==null||n.addEventListener("cuechange",r)})),this.subscription.add(Nr(e,"removetrack").subscribe(i=>{var r;(r=i.track)==null||r.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;let t=this.cueSettings.getState();for(let i of Array.from(e)){let r=i;Qt(t.align)&&(r.align=t.align),Qt(t.position)&&(r.position=t.position),Qt(t.size)&&(r.size=t.size),Qt(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){wa(this.video);let t=[...this.video.textTracks];return e?t:t.filter(s.isHealthyTrack)}htmlTextTrackToITextTrack(e){var o,u,l,d,c;let{language:t,label:i}=e,r=e.id?e.id:qB(e),a=this.externalTracks.has(r),n=(l=a?(o=this.externalTracks.get(r))==null?void 0:o.isAuto:(u=this.internalTracks.get(r))==null?void 0:u.isAuto)!=null?l:r.includes("auto");return a?{id:r,type:"external",isAuto:n,language:t,label:i,url:(d=this.externalTracks.get(r))==null?void 0:d.url}:{id:r,type:"internal",isAuto:n,language:t,label:i,url:(c=this.internalTracks.get(r))==null?void 0:c.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(i=>i.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){let t=[...this.externalTracks];e.filter(({id:i,language:r,isAuto:a})=>!this.internalTracks.has(i)&&!t.some(([,n])=>n.language===r&&n.isAuto===a)).forEach(i=>this.attach(i)),Array.from(this.internalTracks).filter(([i])=>!e.find(r=>r.id===i)).forEach(([,i])=>this.detach(i))}select(e){wa(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(_B(e)||!jB(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){wa(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){wa(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)}},xt=Dd;var or=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 Gv=s=>{let e=s;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e==null?void 0:e.parentNode;return e!=null?e:void 0},Cd=s=>{let e=Gv(s);return!!(e&&e.fullscreenElement&&e.fullscreenElement===s)},Wv=s=>{let e=Gv(s);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===s)};import{fromEvent as Ye,map as Gt,merge as lu,filterChanged as iy,isNonNullable as ry,Subject as JB,filter as Od,mapTo as _d,combine as ZB,once as e$,throttle as t$,ErrorCategory as i$,ValueSubject as sy,Subscription as r$}from"@vkontakte/videoplayer-shared/es2018";var HB=3,Yv=(s,e,t=HB)=>{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 ru=class{constructor(){this._isMiuiBrowser=!1}get current(){return this._current}get isChrome(){return this.current==="Chrome"}get isFirefox(){return this.current==="Firefox"}get isSafari(){return this.current==="Safari"}get isOpera(){return this.current==="Opera"}get isEdge(){return this.current==="Edge"}get isYandex(){return this.current==="Yandex"}get isSamsungBrowser(){return this.current==="SamsungBrowser"}get currentVersion(){return this._current_version}get chromeVersion(){return this._chromeVersion}get firefoxVersion(){return this._firefoxVersion}get safariVersion(){return this._safariVersion}get operaVersion(){return this._operaVersion}get edgeVersion(){return this._edgeVersion}get yandexVersion(){return this._yandexVersion}get isMiuiBrowser(){return this._isMiuiBrowser}detect(){let{userAgent:e}=navigator;try{let t=/yabrowser/i.test(e)?"Yandex":void 0,i=/samsungbrowser/i.test(e)?"SamsungBrowser":void 0,r=/chrome|crios/i.test(e)?"Chrome":void 0,a=/chromium/i.test(e)?"Chromium":void 0,n=/firefox|fxios/i.test(e)?"Firefox":void 0,o=/webkit|safari|khtml/i.test(e)?"Safari":void 0,u=/opr\//i.test(e)?"Opera":void 0,l=/edg/i.test(e)?"Edge":void 0;this._isMiuiBrowser=/(XiaoMi)|(MiuiBrowser)/i.test(e),this._current=t||i||n||u||l||r||a||o||"Rest"}catch(t){console.error(t)}this.isChrome&&this.detectChromeVersion(),this.isFirefox&&this.detectFirefoxVersion(),this.isSafari&&this.detectSafariVersion(),this.isOpera&&this.detectOperaVersion(),this.isEdge&&this.detectEdgeVersion(),this.isYandex&&this.detectYandexVersion()}detectVersion(e){try{let{userAgent:t}=window.navigator,i=t.match(e);if(!i)return;let r=i[1],a=parseInt(r,10);if(!isNaN(a))return this._current_version=a,a}catch(t){console.error(t)}}detectChromeVersion(){this._chromeVersion=this.detectVersion(/Chrome\/(\d+\.\d+)/)}detectFirefoxVersion(){this._firefoxVersion=this.detectVersion(/Firefox\/(\d+\.\d+)/)}detectSafariVersion(){this._safariVersion=this.detectVersion(/Version\/(\d+)/)}detectOperaVersion(){this._operaVersion=this.detectVersion(/OPR\/(\d+\.\d+)/)}detectEdgeVersion(){this._edgeVersion=this.detectVersion(/Edg\/(\d+\.\d+)/)}detectYandexVersion(){this._yandexVersion=this.detectVersion(/YaBrowser\/(\d+\.\d+\.\d+)/)}};var Kv=N(gt(),1);var Pa=()=>{var s,e;return/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test((s=navigator.appVersion)!=null?s:navigator.userAgent)||((e=navigator==null?void 0:navigator.userAgentData)==null?void 0:e.mobile)};var su=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,Kv.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=Pa()}catch(t){console.error(t)}this.detectDevice(e),this.detectHighEntropyValues(),this.isIOS&&this.detectIOSVersion()}async detectHighEntropyValues(){let{userAgentData:e}=navigator;if(e!=null&&e.getHighEntropyValues){let t=await e.getHighEntropyValues(["architecture","bitness","brands","mobile","platform","formFactor","model","platformVersion","wow64"]);this._highEntropyValues=t}}detectDevice(e){try{let t=/android/i.test(e)?"Android":void 0,i=/iphone/i.test(e)?"iPhone":void 0,r=/ipad/i.test(e)?"iPad":void 0,a=/ipod/i.test(e)?"iPod":void 0,n=/mac/i.test(e)?"Mac":void 0,o=/webOS|BlackBerry|IEMobile|Opera Mini/i.test(e)?"RestMobile":void 0;this._current=t||i||r||a||o||n||"Desktop"}catch(t){console.error(t)}}detectIOSVersion(){try{if(this._highEntropyValues.platformVersion){let a=this._highEntropyValues.platformVersion.split(".").slice(0,2).join("."),n=parseFloat(a);this._iosVersion=n;return}let{userAgent:e}=window.navigator,t=e.match(/OS (\d+(_\d+)?)/i);if(!t)return;let i=t[1].replace(/_/g,".");if(!i)return;let r=parseFloat(i);if(isNaN(r))return;this._iosVersion=r}catch(e){console.error(e)}}};var au=class{get isTouch(){return typeof this._maxTouchPoints=="number"?this._maxTouchPoints>1:"ontouchstart"in window}get maxTouchPoints(){return this._maxTouchPoints}get height(){return this._height}get width(){return this._width}get screenHeight(){return this._screenHeight}get screenWidth(){return this._screenWidth}get pixelRatio(){return this._pixelRatio}get isHDR(){return this._isHdr}get colorDepth(){return this._colorDepth}detect(){var t;let{maxTouchPoints:e}=navigator;try{this._maxTouchPoints=e!=null?e:0,this._isHdr=!!((t=matchMedia("(dynamic-range: high)"))!=null&&t.matches),this._colorDepth=screen.colorDepth}catch(i){console.error(i)}try{this._pixelRatio=window.devicePixelRatio||1,this._height=screen.height,this._width=screen.width,this._height=screen.height,this._screenHeight=this._height*this._pixelRatio,this._screenWidth=this._width*this._pixelRatio}catch(i){console.error(i)}}};var vt=()=>window.ManagedMediaSource||window.MediaSource,Ur=()=>{var s,e;return!!(window.ManagedMediaSource&&((e=(s=window.ManagedSourceBuffer)==null?void 0:s.prototype)!=null&&e.appendBuffer))},Xv=()=>{var s,e;return!!(window.MediaSource&&((e=(s=window.SourceBuffer)==null?void 0:s.prototype)!=null&&e.appendBuffer))},nu=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var zB=document.createElement("video"),QB='video/mp4; codecs="avc1.42000a,mp4a.40.2"',GB='video/mp4; codecs="hev1.1.6.L93.B0"',Jv='video/webm; codecs="vp09.00.10.08"',Zv='video/webm; codecs="av01.0.00M.08"',WB='audio/mp4; codecs="mp4a.40.2"',YB='audio/webm; codecs="opus"',ey,KB=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:Zv}}),window.navigator.mediaCapabilities.decodingInfo({...s,video:{...s.video,contentType:Jv}})]);ey={DASH_WEBM_AV1:e,DASH_WEBM:t}};KB().catch(s=>{console.log(zB),console.error(s)});var ou=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 ey}get supportedCodecs(){return Object.keys(this._codecs).filter(e=>this._codecs[e])}get nativeHlsSupported(){return this._nativeHlsSupported}detect(){var e,t,i,r,a,n,o,u,l,d,c,h,p,f,m,g,S,v,y,I;this._video=document.createElement("video");try{this._protocols={mms:Ur(),mse:Xv(),hls:!!((t=(e=this._video).canPlayType)!=null&&t.call(e,"application/x-mpegurl")||(r=(i=this._video).canPlayType)!=null&&r.call(i,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},this._containers={mp4:!!((n=(a=this._video).canPlayType)!=null&&n.call(a,"video/mp4")),webm:!!((u=(o=this._video).canPlayType)!=null&&u.call(o,"video/webm")),cmaf:!0};let T=!!((d=(l=vt())==null?void 0:l.isTypeSupported)!=null&&d.call(l,QB)),E=!!((h=(c=vt())==null?void 0:c.isTypeSupported)!=null&&h.call(c,GB)),O=!!((f=(p=vt())==null?void 0:p.isTypeSupported)!=null&&f.call(p,WB));this._codecs={h264:T,h265:E,vp9:!!((g=(m=vt())==null?void 0:m.isTypeSupported)!=null&&g.call(m,Jv)),av1:!!((v=(S=vt())==null?void 0:S.isTypeSupported)!=null&&v.call(S,Zv)),aac:O,opus:!!((I=(y=vt())==null?void 0:y.isTypeSupported)!=null&&I.call(y,YB)),mpeg:(T||E)&&O},this._nativeHlsSupported=this._protocols.hls&&this._containers.mp4}catch(T){console.error(T)}try{this.destroyVideoElement()}catch(T){console.error("Error destroying video element:",T)}}destroyVideoElement(){var t;if(!this._video)return;if(this._video.pause(),this._video.currentTime=0,this._video.removeAttribute("src"),this._video.src="",this._video.load(),this._video.remove){this._video.remove(),this._video=null;return}this._video.parentNode&&this._video.parentNode.removeChild(this._video);let e=this._video.cloneNode(!1);(t=this._video.parentNode)==null||t.replaceChild(e,this._video),this._video=null}};var ty="audio/mpeg",uu=class{supportMp3(){return this._codecs.mp3&&this._containers.mpeg}detect(){var e,t,i,r;this._audio=document.createElement("audio");try{this._containers={mpeg:!!((t=(e=this._audio).canPlayType)!=null&&t.call(e,ty))},this._codecs={mp3:!!((r=(i=vt())==null?void 0:i.isTypeSupported)!=null&&r.call(i,ty))}}catch(a){console.error(a)}try{this.destroyAudioElement()}catch(a){console.error("Error destroying audio element:",a)}}destroyAudioElement(){var t;if(!this._audio)return;if(this._audio.pause(),this._audio.currentTime=0,this._audio.removeAttribute("src"),this._audio.src="",this._audio.load(),this._audio.remove){this._audio.remove(),this._audio=null;return}this._audio.parentNode&&this._audio.parentNode.removeChild(this._audio);let e=this._audio.cloneNode(!1);(t=this._audio.parentNode)==null||t.replaceChild(e,this._audio),this._audio=null}};import{ValueSubject as XB}from"@vkontakte/videoplayer-shared/es2018";var Vd=class{constructor(){this.isInited$=new XB(!1);this._displayChecker=new au,this._deviceChecker=new su(this._displayChecker),this._browserChecker=new ru,this._videoChecker=new ou(this._deviceChecker,this._browserChecker),this._audioChecker=new uu,this.detect()}get display(){return this._displayChecker}get device(){return this._deviceChecker}get browser(){return this._browserChecker}get video(){return this._videoChecker}get audio(){return this._audioChecker}async detect(){this._displayChecker.detect(),this._deviceChecker.detect(),this._browserChecker.detect(),this._videoChecker.detect(),this._audioChecker.detect(),this.isInited$.next(!0)}},j=new Vd;var st=s=>{let e=P=>Ye(s,P).pipe(_d(void 0)),t=new r$,i=()=>t.unsubscribe(),r=lu(Ye(s,"progress"),Ye(s,"timeupdate")).pipe(Gt(()=>Yv(s.buffered,s.currentTime))),a=j.browser.isSafari?ZB({play:e("play").pipe(e$()),playing:e("playing")}).pipe(_d(void 0)):e("playing"),n=Ye(s,"volumechange").pipe(Gt(()=>({muted:s.muted,volume:s.volume}))),o=Ye(s,"ratechange").pipe(Gt(()=>s.playbackRate)),u=Ye(s,"error").pipe(Od(()=>!!(s.error||s.played.length)),Gt(()=>{var C;let P=s.error;return{id:P?`MediaError#${P.code}`:"HtmlVideoError",category:i$.VIDEO_PIPELINE,message:P?P.message:"Error event from HTML video element",thrown:(C=s.error)!=null?C:void 0}})),l=Ye(s,"timeupdate").pipe(Gt(()=>s.currentTime)),d=["waiting","seeking","seeked","timeupdate"],c=new JB,h=.3,p;t.add(lu(...d.map(P=>Ye(s,P))).subscribe(P=>{let C=s.currentTime;s.loop&&ry(p)&&ry(C)&&p>=s.duration-h&&C<=h&&c.next(p),p=C}));let f=e("pause").pipe(Od(()=>!s.error&&p!==s.duration)),m=Ye(s,"enterpictureinpicture"),g=Ye(s,"leavepictureinpicture"),S=new sy(Wv(s));t.add(m.subscribe(()=>S.next(!0))),t.add(g.subscribe(()=>S.next(!1)));let v=new sy(Cd(s)),y=Ye(s,"fullscreenchange");t.add(y.pipe(Gt(()=>Cd(s))).subscribe(v));let I=.1,T=1e3,E=Ye(s,"timeupdate").pipe(Gt(P=>s.duration-s.currentTime<I),iy()),O=lu(E.pipe(Od(P=>!s.loop&&P)),Ye(s,"ended")).pipe(t$(T),_d(void 0)),w=lu(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(P=>Ye(s,P)),E.pipe(Gt(P=>({type:P?"ended":"unknown"})))).pipe(Gt(P=>j.browser.isFirefox&&P.type==="ended"?s.readyState<2:s.readyState<3),iy());return{playing$:a,pause$:f,canplay$:e("canplay"),ended$:O,looped$:c,error$:u,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:l,durationChange$:Ye(s,"durationchange").pipe(Gt(()=>s.duration)),isBuffering$:w,currentBuffer$:r,volumeState$:n,playbackRateState$:o,inPiP$:S,inFullscreen$:v,enterPip$:m,leavePip$:g,destroy:i}};import{VideoQuality as Li}from"@vkontakte/videoplayer-shared/es2018";var Bi=s=>{switch(s){case"mobile":return Li.Q_144P;case"lowest":return Li.Q_240P;case"low":return Li.Q_360P;case"sd":case"medium":return Li.Q_480P;case"hd":case"high":return Li.Q_720P;case"fullhd":case"full":return Li.Q_1080P;case"quadhd":case"quad":return Li.Q_1440P;case"ultrahd":case"ultra":return Li.Q_2160P}};var Xe=N(Ot(),1),Ud=N(gt(),1),ur=N(Ji(),1);import{isNonNullable as re,isNullable as fu,now as yy,isHigher as mu,isHigherOrEqual as jr,isInvariantQuality as bu,isLowerOrEqual as Hr,videoSizeToQuality as Ty,assertNotEmptyArray as gu,assertNonNullable as Iy}from"@vkontakte/videoplayer-shared/es2018";var Fd=!1,mi={},dy=s=>{Fd=s},py=()=>{mi={}},hy=s=>{s(mi)},ka=(s,e)=>{var t;Fd&&(mi.meta=(t=mi.meta)!=null?t:{},mi.meta[s]=e)},Ke=class{constructor(e){this.name=e}next(e){var i,r;if(!Fd)return;mi.series=(i=mi.series)!=null?i:{};let t=(r=mi.series[this.name])!=null?r:[];t.push([Date.now(),e]),mi.series[this.name]=t}};import{isHigher as p$,isHigherOrEqual as a1,isLower as fy,isLowerOrEqual as n1,isNonNullable as cu,isNullable as h$,videoHeightToQuality as du}from"@vkontakte/videoplayer-shared/es2018";function Nd(s,e,t){return!s.max&&s.min===e?"high_quality":!s.min&&s.max===t?"traffic_saving":"unknown"}function pu(s,e,t){return!!s&&Nd(s,e,t)==="high_quality"}function qr(s,e,t){return h$(s)||cu(s.min)&&cu(s.max)&&fy(s.max,s.min)||cu(s.min)&&e&&p$(s.min,e)||cu(s.max)&&t&&fy(s.max,t)}function my({limits:s,highestAvailableHeight:e,lowestAvailableHeight:t}){return qr({max:s!=null&&s.max?du(s.max):void 0,min:s!=null&&s.min?du(s.min):void 0},e?du(e):void 0,t?du(t):void 0)}var xy=new Ke("best_bitrate"),Su=(s,e,t)=>(e-t)*Math.pow(2,-10*s)+t;var zr=s=>(e,t)=>s*(Number(e.bitrate)-Number(t.bitrate)),$i=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=yy()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},vu='Assertion "ABR Tracks is empty array" failed',hu=new WeakMap,by=new WeakMap,gy=new WeakMap,Ra=(s,e,t,i)=>{var u;let r=[...e].sort(zr(1)),a=[...t].sort(zr(1)),n=a.filter(l=>re(l.bitrate)&&re(s.bitrate)?s.bitrate/l.bitrate>i:!0),o=(u=(0,Xe.default)(a,Math.round(a.length*r.indexOf(s)/(r.length+1))))!=null?u:(0,Xe.default)(a,-1);return o&&(0,Ud.default)(n,o)?o:n.length?(0,Xe.default)(n,-1):(0,Xe.default)(a,0)},Ma=(s,e,t,i)=>{var u;let r=hu.get(e);r||(r=[...e].sort(zr(1)),hu.set(e,r));let a=hu.get(t);a||(a=[...t].sort(zr(1)),hu.set(t,a));let n=gy.get(s);n||(n=a.filter(l=>re(l.bitrate)&&re(s.bitrate)?s.bitrate/l.bitrate>i:!0),gy.set(s,n));let o=(u=(0,Xe.default)(a,Math.round(a.length*r.indexOf(s)/(r.length+1))))!=null?u:(0,Xe.default)(a,-1);return o&&(0,Ud.default)(n,o)?o:n.length?(0,Xe.default)(n,-1):(0,Xe.default)(a,0)},Sy=s=>"quality"in s,yu=(s,e,t,i)=>{var n;let r=re((n=i==null?void 0:i.last)==null?void 0:n.bitrate)&&re(t==null?void 0:t.bitrate)&&i.last.bitrate<t.bitrate?s.trackCooldownIncreaseQuality:s.trackCooldownDecreaseQuality,a=t&&i&&i.history[t.id]&&yy()-i.history[t.id]<=r&&(!i.last||t.id!==i.last.id);if(t!=null&&t.id&&i&&!a&&i.recordSelection(t),a&&(i!=null&&i.last)){let o=i.last;i==null||i.recordSwitch(o);let u=Sy(o)?"video":"audio",l=Sy(o)?o.quality:o.bitrate;return e({message:`
|
|
6
|
+
var NE=Object.create;var Vp=Object.defineProperty;var UE=Object.getOwnPropertyDescriptor;var qE=Object.getOwnPropertyNames;var HE=Object.getPrototypeOf,jE=Object.prototype.hasOwnProperty;var g=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports);var QE=(a,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of qE(e))!jE.call(a,r)&&r!==t&&Vp(a,r,{get:()=>e[r],enumerable:!(i=UE(e,r))||i.enumerable});return a};var O=(a,e,t)=>(t=a!=null?NE(HE(a)):{},QE(e||!a||!a.__esModule?Vp(t,"default",{value:a,enumerable:!0}):t,a));var oe=g((fu,Op)=>{"use strict";var Wr=function(a){return a&&a.Math===Math&&a};Op.exports=Wr(typeof globalThis=="object"&&globalThis)||Wr(typeof window=="object"&&window)||Wr(typeof self=="object"&&self)||Wr(typeof global=="object"&&global)||Wr(typeof fu=="object"&&fu)||function(){return this}()||Function("return this")()});var pe=g((jV,Fp)=>{"use strict";Fp.exports=function(a){try{return!!a()}catch(e){return!0}}});var zr=g((QV,Np)=>{"use strict";var GE=pe();Np.exports=!GE(function(){var a=function(){}.bind();return typeof a!="function"||a.hasOwnProperty("prototype")})});var mu=g((GV,jp)=>{"use strict";var WE=zr(),Hp=Function.prototype,Up=Hp.apply,qp=Hp.call;jp.exports=typeof Reflect=="object"&&Reflect.apply||(WE?qp.bind(Up):function(){return qp.apply(Up,arguments)})});var he=g((WV,Wp)=>{"use strict";var Qp=zr(),Gp=Function.prototype,bu=Gp.call,zE=Qp&&Gp.bind.bind(bu,bu);Wp.exports=Qp?zE:function(a){return function(){return bu.apply(a,arguments)}}});var hi=g((zV,Yp)=>{"use strict";var zp=he(),YE=zp({}.toString),KE=zp("".slice);Yp.exports=function(a){return KE(YE(a),8,-1)}});var gu=g((YV,Kp)=>{"use strict";var XE=hi(),JE=he();Kp.exports=function(a){if(XE(a)==="Function")return JE(a)}});var ue=g((KV,Xp)=>{"use strict";var Su=typeof document=="object"&&document.all;Xp.exports=typeof Su=="undefined"&&Su!==void 0?function(a){return typeof a=="function"||a===Su}:function(a){return typeof a=="function"}});var Ue=g((XV,Jp)=>{"use strict";var ZE=pe();Jp.exports=!ZE(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var qe=g((JV,Zp)=>{"use strict";var ex=zr(),Xs=Function.prototype.call;Zp.exports=ex?Xs.bind(Xs):function(){return Xs.apply(Xs,arguments)}});var vu=g(ih=>{"use strict";var eh={}.propertyIsEnumerable,th=Object.getOwnPropertyDescriptor,tx=th&&!eh.call({1:2},1);ih.f=tx?function(e){var t=th(this,e);return!!t&&t.enumerable}:eh});var Yr=g((e_,rh)=>{"use strict";rh.exports=function(a,e){return{enumerable:!(a&1),configurable:!(a&2),writable:!(a&4),value:e}}});var sh=g((t_,ah)=>{"use strict";var ix=he(),rx=pe(),ax=hi(),yu=Object,sx=ix("".split);ah.exports=rx(function(){return!yu("z").propertyIsEnumerable(0)})?function(a){return ax(a)==="String"?sx(a,""):yu(a)}:yu});var Kr=g((i_,nh)=>{"use strict";nh.exports=function(a){return a==null}});var Qt=g((r_,oh)=>{"use strict";var nx=Kr(),ox=TypeError;oh.exports=function(a){if(nx(a))throw new ox("Can't call method on "+a);return a}});var fi=g((a_,uh)=>{"use strict";var ux=sh(),lx=Qt();uh.exports=function(a){return ux(lx(a))}});var $e=g((s_,lh)=>{"use strict";var cx=ue();lh.exports=function(a){return typeof a=="object"?a!==null:cx(a)}});var mi=g((n_,ch)=>{"use strict";ch.exports={}});var Pt=g((o_,ph)=>{"use strict";var Tu=mi(),Iu=oe(),dx=ue(),dh=function(a){return dx(a)?a:void 0};ph.exports=function(a,e){return arguments.length<2?dh(Tu[a])||dh(Iu[a]):Tu[a]&&Tu[a][e]||Iu[a]&&Iu[a][e]}});var Xr=g((u_,hh)=>{"use strict";var px=he();hh.exports=px({}.isPrototypeOf)});var bi=g((l_,bh)=>{"use strict";var hx=oe(),fh=hx.navigator,mh=fh&&fh.userAgent;bh.exports=mh?String(mh):""});var xu=g((c_,Ih)=>{"use strict";var Th=oe(),Eu=bi(),gh=Th.process,Sh=Th.Deno,vh=gh&&gh.versions||Sh&&Sh.version,yh=vh&&vh.v8,rt,Js;yh&&(rt=yh.split("."),Js=rt[0]>0&&rt[0]<4?1:+(rt[0]+rt[1]));!Js&&Eu&&(rt=Eu.match(/Edge\/(\d+)/),(!rt||rt[1]>=74)&&(rt=Eu.match(/Chrome\/(\d+)/),rt&&(Js=+rt[1])));Ih.exports=Js});var wu=g((d_,xh)=>{"use strict";var Eh=xu(),fx=pe(),mx=oe(),bx=mx.String;xh.exports=!!Object.getOwnPropertySymbols&&!fx(function(){var a=Symbol("symbol detection");return!bx(a)||!(Object(a)instanceof Symbol)||!Symbol.sham&&Eh&&Eh<41})});var Au=g((p_,wh)=>{"use strict";var gx=wu();wh.exports=gx&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var Pu=g((h_,Ah)=>{"use strict";var Sx=Pt(),vx=ue(),yx=Xr(),Tx=Au(),Ix=Object;Ah.exports=Tx?function(a){return typeof a=="symbol"}:function(a){var e=Sx("Symbol");return vx(e)&&yx(e.prototype,Ix(a))}});var Jr=g((f_,Ph)=>{"use strict";var Ex=String;Ph.exports=function(a){try{return Ex(a)}catch(e){return"Object"}}});var ft=g((m_,Rh)=>{"use strict";var xx=ue(),wx=Jr(),Ax=TypeError;Rh.exports=function(a){if(xx(a))return a;throw new Ax(wx(a)+" is not a function")}});var Zr=g((b_,kh)=>{"use strict";var Px=ft(),Rx=Kr();kh.exports=function(a,e){var t=a[e];return Rx(t)?void 0:Px(t)}});var $h=g((g_,Lh)=>{"use strict";var Ru=qe(),ku=ue(),Lu=$e(),kx=TypeError;Lh.exports=function(a,e){var t,i;if(e==="string"&&ku(t=a.toString)&&!Lu(i=Ru(t,a))||ku(t=a.valueOf)&&!Lu(i=Ru(t,a))||e!=="string"&&ku(t=a.toString)&&!Lu(i=Ru(t,a)))return i;throw new kx("Can't convert object to primitive value")}});var at=g((S_,Mh)=>{"use strict";Mh.exports=!0});var Bh=g((v_,Ch)=>{"use strict";var Dh=oe(),Lx=Object.defineProperty;Ch.exports=function(a,e){try{Lx(Dh,a,{value:e,configurable:!0,writable:!0})}catch(t){Dh[a]=e}return e}});var ea=g((y_,Oh)=>{"use strict";var $x=at(),Mx=oe(),Dx=Bh(),Vh="__core-js_shared__",_h=Oh.exports=Mx[Vh]||Dx(Vh,{});(_h.versions||(_h.versions=[])).push({version:"3.43.0",mode:$x?"pure":"global",copyright:"\xA9 2014-2025 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.43.0/LICENSE",source:"https://github.com/zloirock/core-js"})});var $u=g((T_,Nh)=>{"use strict";var Fh=ea();Nh.exports=function(a,e){return Fh[a]||(Fh[a]=e||{})}});var Wi=g((I_,Uh)=>{"use strict";var Cx=Qt(),Bx=Object;Uh.exports=function(a){return Bx(Cx(a))}});var st=g((E_,qh)=>{"use strict";var Vx=he(),_x=Wi(),Ox=Vx({}.hasOwnProperty);qh.exports=Object.hasOwn||function(e,t){return Ox(_x(e),t)}});var Mu=g((x_,Hh)=>{"use strict";var Fx=he(),Nx=0,Ux=Math.random(),qx=Fx(1.1.toString);Hh.exports=function(a){return"Symbol("+(a===void 0?"":a)+")_"+qx(++Nx+Ux,36)}});var ye=g((w_,Qh)=>{"use strict";var Hx=oe(),jx=$u(),jh=st(),Qx=Mu(),Gx=wu(),Wx=Au(),zi=Hx.Symbol,Du=jx("wks"),zx=Wx?zi.for||zi:zi&&zi.withoutSetter||Qx;Qh.exports=function(a){return jh(Du,a)||(Du[a]=Gx&&jh(zi,a)?zi[a]:zx("Symbol."+a)),Du[a]}});var Yh=g((A_,zh)=>{"use strict";var Yx=qe(),Gh=$e(),Wh=Pu(),Kx=Zr(),Xx=$h(),Jx=ye(),Zx=TypeError,ew=Jx("toPrimitive");zh.exports=function(a,e){if(!Gh(a)||Wh(a))return a;var t=Kx(a,ew),i;if(t){if(e===void 0&&(e="default"),i=Yx(t,a,e),!Gh(i)||Wh(i))return i;throw new Zx("Can't convert object to primitive value")}return e===void 0&&(e="number"),Xx(a,e)}});var Cu=g((P_,Kh)=>{"use strict";var tw=Yh(),iw=Pu();Kh.exports=function(a){var e=tw(a,"string");return iw(e)?e:e+""}});var Zs=g((R_,Jh)=>{"use strict";var rw=oe(),Xh=$e(),Bu=rw.document,aw=Xh(Bu)&&Xh(Bu.createElement);Jh.exports=function(a){return aw?Bu.createElement(a):{}}});var Vu=g((k_,Zh)=>{"use strict";var sw=Ue(),nw=pe(),ow=Zs();Zh.exports=!sw&&!nw(function(){return Object.defineProperty(ow("div"),"a",{get:function(){return 7}}).a!==7})});var rf=g(tf=>{"use strict";var uw=Ue(),lw=qe(),cw=vu(),dw=Yr(),pw=fi(),hw=Cu(),fw=st(),mw=Vu(),ef=Object.getOwnPropertyDescriptor;tf.f=uw?ef:function(e,t){if(e=pw(e),t=hw(t),mw)try{return ef(e,t)}catch(i){}if(fw(e,t))return dw(!lw(cw.f,e,t),e[t])}});var _u=g(($_,af)=>{"use strict";var bw=pe(),gw=ue(),Sw=/#|\.prototype\./,ta=function(a,e){var t=yw[vw(a)];return t===Iw?!0:t===Tw?!1:gw(e)?bw(e):!!e},vw=ta.normalize=function(a){return String(a).replace(Sw,".").toLowerCase()},yw=ta.data={},Tw=ta.NATIVE="N",Iw=ta.POLYFILL="P";af.exports=ta});var Yi=g((M_,nf)=>{"use strict";var sf=gu(),Ew=ft(),xw=zr(),ww=sf(sf.bind);nf.exports=function(a,e){return Ew(a),e===void 0?a:xw?ww(a,e):function(){return a.apply(e,arguments)}}});var Ou=g((D_,of)=>{"use strict";var Aw=Ue(),Pw=pe();of.exports=Aw&&Pw(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var mt=g((C_,uf)=>{"use strict";var Rw=$e(),kw=String,Lw=TypeError;uf.exports=function(a){if(Rw(a))return a;throw new Lw(kw(a)+" is not an object")}});var gi=g(cf=>{"use strict";var $w=Ue(),Mw=Vu(),Dw=Ou(),en=mt(),lf=Cu(),Cw=TypeError,Fu=Object.defineProperty,Bw=Object.getOwnPropertyDescriptor,Nu="enumerable",Uu="configurable",qu="writable";cf.f=$w?Dw?function(e,t,i){if(en(e),t=lf(t),en(i),typeof e=="function"&&t==="prototype"&&"value"in i&&qu in i&&!i[qu]){var r=Bw(e,t);r&&r[qu]&&(e[t]=i.value,i={configurable:Uu in i?i[Uu]:r[Uu],enumerable:Nu in i?i[Nu]:r[Nu],writable:!1})}return Fu(e,t,i)}:Fu:function(e,t,i){if(en(e),t=lf(t),en(i),Mw)try{return Fu(e,t,i)}catch(r){}if("get"in i||"set"in i)throw new Cw("Accessors not supported");return"value"in i&&(e[t]=i.value),e}});var Ki=g((V_,df)=>{"use strict";var Vw=Ue(),_w=gi(),Ow=Yr();df.exports=Vw?function(a,e,t){return _w.f(a,e,Ow(1,t))}:function(a,e,t){return a[e]=t,a}});var de=g((__,hf)=>{"use strict";var ia=oe(),Fw=mu(),Nw=gu(),Uw=ue(),qw=rf().f,Hw=_u(),Xi=mi(),jw=Yi(),Ji=Ki(),pf=st();ea();var Qw=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 Fw(a,this,arguments)};return e.prototype=a.prototype,e};hf.exports=function(a,e){var t=a.target,i=a.global,r=a.stat,s=a.proto,n=i?ia:r?ia[t]:ia[t]&&ia[t].prototype,o=i?Xi:Xi[t]||Ji(Xi,t,{})[t],u=o.prototype,l,c,d,f,p,h,m,b,S;for(f in e)l=Hw(i?f:t+(r?".":"#")+f,a.forced),c=!l&&n&&pf(n,f),h=o[f],c&&(a.dontCallGetSet?(S=qw(n,f),m=S&&S.value):m=n[f]),p=c&&m?m:e[f],!(!l&&!s&&typeof h==typeof p)&&(a.bind&&c?b=jw(p,ia):a.wrap&&c?b=Qw(p):s&&Uw(p)?b=Nw(p):b=p,(a.sham||p&&p.sham||h&&h.sham)&&Ji(b,"sham",!0),Ji(o,f,b),s&&(d=t+"Prototype",pf(Xi,d)||Ji(Xi,d,{}),Ji(Xi[d],f,p),a.real&&u&&(l||!u[f])&&Ji(u,f,p)))}});var mf=g((O_,ff)=>{"use strict";var Gw=Math.ceil,Ww=Math.floor;ff.exports=Math.trunc||function(e){var t=+e;return(t>0?Ww:Gw)(t)}});var ra=g((F_,bf)=>{"use strict";var zw=mf();bf.exports=function(a){var e=+a;return e!==e||e===0?0:zw(e)}});var Sf=g((N_,gf)=>{"use strict";var Yw=ra(),Kw=Math.max,Xw=Math.min;gf.exports=function(a,e){var t=Yw(a);return t<0?Kw(t+e,0):Xw(t,e)}});var Hu=g((U_,vf)=>{"use strict";var Jw=ra(),Zw=Math.min;vf.exports=function(a){var e=Jw(a);return e>0?Zw(e,9007199254740991):0}});var Zi=g((q_,yf)=>{"use strict";var eA=Hu();yf.exports=function(a){return eA(a.length)}});var ju=g((H_,If)=>{"use strict";var tA=fi(),iA=Sf(),rA=Zi(),Tf=function(a){return function(e,t,i){var r=tA(e),s=rA(r);if(s===0)return!a&&-1;var n=iA(i,s),o;if(a&&t!==t){for(;s>n;)if(o=r[n++],o!==o)return!0}else for(;s>n;n++)if((a||n in r)&&r[n]===t)return a||n||0;return!a&&-1}};If.exports={includes:Tf(!0),indexOf:Tf(!1)}});var aa=g((j_,Ef)=>{"use strict";Ef.exports=function(){}});var xf=g(()=>{"use strict";var aA=de(),sA=ju().includes,nA=pe(),oA=aa(),uA=nA(function(){return!Array(1).includes()});aA({target:"Array",proto:!0,forced:uA},{includes:function(e){return sA(this,e,arguments.length>1?arguments[1]:void 0)}});oA("includes")});var Gt=g((W_,wf)=>{"use strict";var lA=Pt();wf.exports=lA});var Pf=g((z_,Af)=>{"use strict";xf();var cA=Gt();Af.exports=cA("Array","includes")});var kf=g((Y_,Rf)=>{"use strict";var dA=Pf();Rf.exports=dA});var Ye=g((K_,Lf)=>{"use strict";var pA=kf();Lf.exports=pA});var an=g((uO,Of)=>{"use strict";var yA=$u(),TA=Mu(),_f=yA("keys");Of.exports=function(a){return _f[a]||(_f[a]=TA(a))}});var Nf=g((lO,Ff)=>{"use strict";var IA=pe();Ff.exports=!IA(function(){function a(){}return a.prototype.constructor=null,Object.getPrototypeOf(new a)!==a.prototype})});var sn=g((cO,qf)=>{"use strict";var EA=st(),xA=ue(),wA=Wi(),AA=an(),PA=Nf(),Uf=AA("IE_PROTO"),Wu=Object,RA=Wu.prototype;qf.exports=PA?Wu.getPrototypeOf:function(a){var e=wA(a);if(EA(e,Uf))return e[Uf];var t=e.constructor;return xA(t)&&e instanceof t?t.prototype:e instanceof Wu?RA:null}});var nn=g((dO,Hf)=>{"use strict";Hf.exports={}});var Gf=g((pO,Qf)=>{"use strict";var kA=he(),zu=st(),LA=fi(),$A=ju().indexOf,MA=nn(),jf=kA([].push);Qf.exports=function(a,e){var t=LA(a),i=0,r=[],s;for(s in t)!zu(MA,s)&&zu(t,s)&&jf(r,s);for(;e.length>i;)zu(t,s=e[i++])&&(~$A(r,s)||jf(r,s));return r}});var Yu=g((hO,Wf)=>{"use strict";Wf.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var Ku=g((fO,zf)=>{"use strict";var DA=Gf(),CA=Yu();zf.exports=Object.keys||function(e){return DA(e,CA)}});var Xu=g((mO,Zf)=>{"use strict";var Kf=Ue(),BA=pe(),Xf=he(),VA=sn(),_A=Ku(),OA=fi(),FA=vu().f,Jf=Xf(FA),NA=Xf([].push),UA=Kf&&BA(function(){var a=Object.create(null);return a[2]=2,!Jf(a,2)}),Yf=function(a){return function(e){for(var t=OA(e),i=_A(t),r=UA&&VA(t)===null,s=i.length,n=0,o=[],u;s>n;)u=i[n++],(!Kf||(r?u in t:Jf(t,u)))&&NA(o,a?[u,t[u]]:t[u]);return o}};Zf.exports={entries:Yf(!0),values:Yf(!1)}});var em=g(()=>{"use strict";var qA=de(),HA=Xu().entries;qA({target:"Object",stat:!0},{entries:function(e){return HA(e)}})});var im=g((SO,tm)=>{"use strict";em();var jA=mi();tm.exports=jA.Object.entries});var am=g((vO,rm)=>{"use strict";var QA=im();rm.exports=QA});var er=g((yO,sm)=>{"use strict";var GA=am();sm.exports=GA});var Si=g((TO,nm)=>{"use strict";nm.exports={}});var lm=g((IO,um)=>{"use strict";var WA=oe(),zA=ue(),om=WA.WeakMap;um.exports=zA(om)&&/native code/.test(String(om))});var tl=g((EO,pm)=>{"use strict";var YA=lm(),dm=oe(),KA=$e(),XA=Ki(),Ju=st(),Zu=ea(),JA=an(),ZA=nn(),cm="Object already initialized",el=dm.TypeError,eP=dm.WeakMap,on,sa,un,tP=function(a){return un(a)?sa(a):on(a,{})},iP=function(a){return function(e){var t;if(!KA(e)||(t=sa(e)).type!==a)throw new el("Incompatible receiver, "+a+" required");return t}};YA||Zu.state?(nt=Zu.state||(Zu.state=new eP),nt.get=nt.get,nt.has=nt.has,nt.set=nt.set,on=function(a,e){if(nt.has(a))throw new el(cm);return e.facade=a,nt.set(a,e),e},sa=function(a){return nt.get(a)||{}},un=function(a){return nt.has(a)}):(vi=JA("state"),ZA[vi]=!0,on=function(a,e){if(Ju(a,vi))throw new el(cm);return e.facade=a,XA(a,vi,e),e},sa=function(a){return Ju(a,vi)?a[vi]:{}},un=function(a){return Ju(a,vi)});var nt,vi;pm.exports={set:on,get:sa,has:un,enforce:tP,getterFor:iP}});var al=g((xO,fm)=>{"use strict";var il=Ue(),rP=st(),hm=Function.prototype,aP=il&&Object.getOwnPropertyDescriptor,rl=rP(hm,"name"),sP=rl&&function(){}.name==="something",nP=rl&&(!il||il&&aP(hm,"name").configurable);fm.exports={EXISTS:rl,PROPER:sP,CONFIGURABLE:nP}});var bm=g(mm=>{"use strict";var oP=Ue(),uP=Ou(),lP=gi(),cP=mt(),dP=fi(),pP=Ku();mm.f=oP&&!uP?Object.defineProperties:function(e,t){cP(e);for(var i=dP(t),r=pP(t),s=r.length,n=0,o;s>n;)lP.f(e,o=r[n++],i[o]);return e}});var sl=g((AO,gm)=>{"use strict";var hP=Pt();gm.exports=hP("document","documentElement")});var ll=g((PO,xm)=>{"use strict";var fP=mt(),mP=bm(),Sm=Yu(),bP=nn(),gP=sl(),SP=Zs(),vP=an(),vm=">",ym="<",ol="prototype",ul="script",Im=vP("IE_PROTO"),nl=function(){},Em=function(a){return ym+ul+vm+a+ym+"/"+ul+vm},Tm=function(a){a.write(Em("")),a.close();var e=a.parentWindow.Object;return a=null,e},yP=function(){var a=SP("iframe"),e="java"+ul+":",t;return a.style.display="none",gP.appendChild(a),a.src=String(e),t=a.contentWindow.document,t.open(),t.write(Em("document.F=Object")),t.close(),t.F},ln,cn=function(){try{ln=new ActiveXObject("htmlfile")}catch(e){}cn=typeof document!="undefined"?document.domain&&ln?Tm(ln):yP():Tm(ln);for(var a=Sm.length;a--;)delete cn[ol][Sm[a]];return cn()};bP[Im]=!0;xm.exports=Object.create||function(e,t){var i;return e!==null?(nl[ol]=fP(e),i=new nl,nl[ol]=null,i[Im]=e):i=cn(),t===void 0?i:mP.f(i,t)}});var tr=g((RO,wm)=>{"use strict";var TP=Ki();wm.exports=function(a,e,t,i){return i&&i.enumerable?a[e]=t:TP(a,e,t),a}});var hl=g((kO,Rm)=>{"use strict";var IP=pe(),EP=ue(),xP=$e(),wP=ll(),Am=sn(),AP=tr(),PP=ye(),RP=at(),pl=PP("iterator"),Pm=!1,Rt,cl,dl;[].keys&&(dl=[].keys(),"next"in dl?(cl=Am(Am(dl)),cl!==Object.prototype&&(Rt=cl)):Pm=!0);var kP=!xP(Rt)||IP(function(){var a={};return Rt[pl].call(a)!==a});kP?Rt={}:RP&&(Rt=wP(Rt));EP(Rt[pl])||AP(Rt,pl,function(){return this});Rm.exports={IteratorPrototype:Rt,BUGGY_SAFARI_ITERATORS:Pm}});var dn=g((LO,Lm)=>{"use strict";var LP=ye(),$P=LP("toStringTag"),km={};km[$P]="z";Lm.exports=String(km)==="[object z]"});var na=g(($O,$m)=>{"use strict";var MP=dn(),DP=ue(),pn=hi(),CP=ye(),BP=CP("toStringTag"),VP=Object,_P=pn(function(){return arguments}())==="Arguments",OP=function(a,e){try{return a[e]}catch(t){}};$m.exports=MP?pn:function(a){var e,t,i;return a===void 0?"Undefined":a===null?"Null":typeof(t=OP(e=VP(a),BP))=="string"?t:_P?pn(e):(i=pn(e))==="Object"&&DP(e.callee)?"Arguments":i}});var Dm=g((MO,Mm)=>{"use strict";var FP=dn(),NP=na();Mm.exports=FP?{}.toString:function(){return"[object "+NP(this)+"]"}});var oa=g((DO,Bm)=>{"use strict";var UP=dn(),qP=gi().f,HP=Ki(),jP=st(),QP=Dm(),GP=ye(),Cm=GP("toStringTag");Bm.exports=function(a,e,t,i){var r=t?a:a&&a.prototype;r&&(jP(r,Cm)||qP(r,Cm,{configurable:!0,value:e}),i&&!UP&&HP(r,"toString",QP))}});var _m=g((CO,Vm)=>{"use strict";var WP=hl().IteratorPrototype,zP=ll(),YP=Yr(),KP=oa(),XP=Si(),JP=function(){return this};Vm.exports=function(a,e,t,i){var r=e+" Iterator";return a.prototype=zP(WP,{next:YP(+!i,t)}),KP(a,r,!1,!0),XP[r]=JP,a}});var Fm=g((BO,Om)=>{"use strict";var ZP=he(),eR=ft();Om.exports=function(a,e,t){try{return ZP(eR(Object.getOwnPropertyDescriptor(a,e)[t]))}catch(i){}}});var Um=g((VO,Nm)=>{"use strict";var tR=$e();Nm.exports=function(a){return tR(a)||a===null}});var Hm=g((_O,qm)=>{"use strict";var iR=Um(),rR=String,aR=TypeError;qm.exports=function(a){if(iR(a))return a;throw new aR("Can't set "+rR(a)+" as a prototype")}});var fl=g((OO,jm)=>{"use strict";var sR=Fm(),nR=$e(),oR=Qt(),uR=Hm();jm.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var a=!1,e={},t;try{t=sR(Object.prototype,"__proto__","set"),t(e,[]),a=e instanceof Array}catch(i){}return function(r,s){return oR(r),uR(s),nR(r)&&(a?t(r,s):r.__proto__=s),r}}():void 0)});var tb=g((FO,eb)=>{"use strict";var lR=de(),cR=qe(),hn=at(),Jm=al(),dR=ue(),pR=_m(),Qm=sn(),Gm=fl(),hR=oa(),fR=Ki(),ml=tr(),mR=ye(),Wm=Si(),Zm=hl(),bR=Jm.PROPER,gR=Jm.CONFIGURABLE,zm=Zm.IteratorPrototype,fn=Zm.BUGGY_SAFARI_ITERATORS,ua=mR("iterator"),Ym="keys",la="values",Km="entries",Xm=function(){return this};eb.exports=function(a,e,t,i,r,s,n){pR(t,e,i);var o=function(S){if(S===r&&f)return f;if(!fn&&S&&S in c)return c[S];switch(S){case Ym:return function(){return new t(this,S)};case la:return function(){return new t(this,S)};case Km:return function(){return new t(this,S)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,c=a.prototype,d=c[ua]||c["@@iterator"]||r&&c[r],f=!fn&&d||o(r),p=e==="Array"&&c.entries||d,h,m,b;if(p&&(h=Qm(p.call(new a)),h!==Object.prototype&&h.next&&(!hn&&Qm(h)!==zm&&(Gm?Gm(h,zm):dR(h[ua])||ml(h,ua,Xm)),hR(h,u,!0,!0),hn&&(Wm[u]=Xm))),bR&&r===la&&d&&d.name!==la&&(!hn&&gR?fR(c,"name",la):(l=!0,f=function(){return cR(d,this)})),r)if(m={values:o(la),keys:s?f:o(Ym),entries:o(Km)},n)for(b in m)(fn||l||!(b in c))&&ml(c,b,m[b]);else lR({target:e,proto:!0,forced:fn||l},m);return(!hn||n)&&c[ua]!==f&&ml(c,ua,f,{name:r}),Wm[e]=f,m}});var rb=g((NO,ib)=>{"use strict";ib.exports=function(a,e){return{value:a,done:e}}});var gl=g((UO,ub)=>{"use strict";var SR=fi(),bl=aa(),ab=Si(),nb=tl(),vR=gi().f,yR=tb(),mn=rb(),TR=at(),IR=Ue(),ob="Array Iterator",ER=nb.set,xR=nb.getterFor(ob);ub.exports=yR(Array,"Array",function(a,e){ER(this,{type:ob,target:SR(a),index:0,kind:e})},function(){var a=xR(this),e=a.target,t=a.index++;if(!e||t>=e.length)return a.target=null,mn(void 0,!0);switch(a.kind){case"keys":return mn(t,!1);case"values":return mn(e[t],!1)}return mn([t,e[t]],!1)},"values");var sb=ab.Arguments=ab.Array;bl("keys");bl("values");bl("entries");if(!TR&&IR&&sb.name!=="values")try{vR(sb,"name",{value:"values"})}catch(a){}});var cb=g((qO,lb)=>{"use strict";var wR=ye(),AR=Si(),PR=wR("iterator"),RR=Array.prototype;lb.exports=function(a){return a!==void 0&&(AR.Array===a||RR[PR]===a)}});var Sl=g((HO,pb)=>{"use strict";var kR=na(),db=Zr(),LR=Kr(),$R=Si(),MR=ye(),DR=MR("iterator");pb.exports=function(a){if(!LR(a))return db(a,DR)||db(a,"@@iterator")||$R[kR(a)]}});var fb=g((jO,hb)=>{"use strict";var CR=qe(),BR=ft(),VR=mt(),_R=Jr(),OR=Sl(),FR=TypeError;hb.exports=function(a,e){var t=arguments.length<2?OR(a):e;if(BR(t))return VR(CR(t,a));throw new FR(_R(a)+" is not iterable")}});var gb=g((QO,bb)=>{"use strict";var NR=qe(),mb=mt(),UR=Zr();bb.exports=function(a,e,t){var i,r;mb(a);try{if(i=UR(a,"return"),!i){if(e==="throw")throw t;return t}i=NR(i,a)}catch(s){r=!0,i=s}if(e==="throw")throw t;if(r)throw i;return mb(i),t}});var gn=g((GO,Tb)=>{"use strict";var qR=Yi(),HR=qe(),jR=mt(),QR=Jr(),GR=cb(),WR=Zi(),Sb=Xr(),zR=fb(),YR=Sl(),vb=gb(),KR=TypeError,bn=function(a,e){this.stopped=a,this.result=e},yb=bn.prototype;Tb.exports=function(a,e,t){var i=t&&t.that,r=!!(t&&t.AS_ENTRIES),s=!!(t&&t.IS_RECORD),n=!!(t&&t.IS_ITERATOR),o=!!(t&&t.INTERRUPTED),u=qR(e,i),l,c,d,f,p,h,m,b=function(y){return l&&vb(l,"normal"),new bn(!0,y)},S=function(y){return r?(jR(y),o?u(y[0],y[1],b):u(y[0],y[1])):o?u(y,b):u(y)};if(s)l=a.iterator;else if(n)l=a;else{if(c=YR(a),!c)throw new KR(QR(a)+" is not iterable");if(GR(c)){for(d=0,f=WR(a);f>d;d++)if(p=S(a[d]),p&&Sb(yb,p))return p;return new bn(!1)}l=zR(a,c)}for(h=s?a.next:l.next;!(m=HR(h,l)).done;){try{p=S(m.value)}catch(y){vb(l,"throw",y)}if(typeof p=="object"&&p&&Sb(yb,p))return p}return new bn(!1)}});var Eb=g((WO,Ib)=>{"use strict";var XR=Ue(),JR=gi(),ZR=Yr();Ib.exports=function(a,e,t){XR?JR.f(a,e,ZR(0,t)):a[e]=t}});var xb=g(()=>{"use strict";var ek=de(),tk=gn(),ik=Eb();ek({target:"Object",stat:!0},{fromEntries:function(e){var t={};return tk(e,function(i,r){ik(t,i,r)},{AS_ENTRIES:!0}),t}})});var Ab=g((KO,wb)=>{"use strict";gl();xb();var rk=mi();wb.exports=rk.Object.fromEntries});var Rb=g((XO,Pb)=>{"use strict";Pb.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 Lb=g(()=>{"use strict";gl();var ak=Rb(),sk=oe(),nk=oa(),kb=Si();for(Sn in ak)nk(sk[Sn],Sn),kb[Sn]=kb.Array;var Sn});var Mb=g((eF,$b)=>{"use strict";var ok=Ab();Lb();$b.exports=ok});var vl=g((tF,Db)=>{"use strict";var uk=Mb();Db.exports=uk});var Cb=g(()=>{"use strict"});var yl=g((aF,Bb)=>{"use strict";var ca=oe(),lk=bi(),ck=hi(),vn=function(a){return lk.slice(0,a.length)===a};Bb.exports=function(){return vn("Bun/")?"BUN":vn("Cloudflare-Workers")?"CLOUDFLARE":vn("Deno/")?"DENO":vn("Node.js/")?"NODE":ca.Bun&&typeof Bun.version=="string"?"BUN":ca.Deno&&typeof Deno.version=="object"?"DENO":ck(ca.process)==="process"?"NODE":ca.window&&ca.document?"BROWSER":"REST"}()});var yn=g((sF,Vb)=>{"use strict";var dk=yl();Vb.exports=dk==="NODE"});var Ob=g((nF,_b)=>{"use strict";var pk=gi();_b.exports=function(a,e,t){return pk.f(a,e,t)}});var Ub=g((oF,Nb)=>{"use strict";var hk=Pt(),fk=Ob(),mk=ye(),bk=Ue(),Fb=mk("species");Nb.exports=function(a){var e=hk(a);bk&&e&&!e[Fb]&&fk(e,Fb,{configurable:!0,get:function(){return this}})}});var Hb=g((uF,qb)=>{"use strict";var gk=Xr(),Sk=TypeError;qb.exports=function(a,e){if(gk(e,a))return a;throw new Sk("Incorrect invocation")}});var Il=g((lF,jb)=>{"use strict";var vk=he(),yk=ue(),Tl=ea(),Tk=vk(Function.toString);yk(Tl.inspectSource)||(Tl.inspectSource=function(a){return Tk(a)});jb.exports=Tl.inspectSource});var xl=g((cF,Yb)=>{"use strict";var Ik=he(),Ek=pe(),Qb=ue(),xk=na(),wk=Pt(),Ak=Il(),Gb=function(){},Wb=wk("Reflect","construct"),El=/^\s*(?:class|function)\b/,Pk=Ik(El.exec),Rk=!El.test(Gb),da=function(e){if(!Qb(e))return!1;try{return Wb(Gb,[],e),!0}catch(t){return!1}},zb=function(e){if(!Qb(e))return!1;switch(xk(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return Rk||!!Pk(El,Ak(e))}catch(t){return!0}};zb.sham=!0;Yb.exports=!Wb||Ek(function(){var a;return da(da.call)||!da(Object)||!da(function(){a=!0})||a})?zb:da});var Xb=g((dF,Kb)=>{"use strict";var kk=xl(),Lk=Jr(),$k=TypeError;Kb.exports=function(a){if(kk(a))return a;throw new $k(Lk(a)+" is not a constructor")}});var wl=g((pF,Zb)=>{"use strict";var Jb=mt(),Mk=Xb(),Dk=Kr(),Ck=ye(),Bk=Ck("species");Zb.exports=function(a,e){var t=Jb(a).constructor,i;return t===void 0||Dk(i=Jb(t)[Bk])?e:Mk(i)}});var tg=g((hF,eg)=>{"use strict";var Vk=he();eg.exports=Vk([].slice)});var rg=g((fF,ig)=>{"use strict";var _k=TypeError;ig.exports=function(a,e){if(a<e)throw new _k("Not enough arguments");return a}});var Al=g((mF,ag)=>{"use strict";var Ok=bi();ag.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(Ok)});var Bl=g((bF,hg)=>{"use strict";var He=oe(),Fk=mu(),Nk=Yi(),sg=ue(),Uk=st(),pg=pe(),ng=sl(),qk=tg(),og=Zs(),Hk=rg(),jk=Al(),Qk=yn(),Ml=He.setImmediate,Dl=He.clearImmediate,Gk=He.process,Pl=He.Dispatch,Wk=He.Function,ug=He.MessageChannel,zk=He.String,Rl=0,pa={},lg="onreadystatechange",ha,yi,kl,Ll;pg(function(){ha=He.location});var Cl=function(a){if(Uk(pa,a)){var e=pa[a];delete pa[a],e()}},$l=function(a){return function(){Cl(a)}},cg=function(a){Cl(a.data)},dg=function(a){He.postMessage(zk(a),ha.protocol+"//"+ha.host)};(!Ml||!Dl)&&(Ml=function(e){Hk(arguments.length,1);var t=sg(e)?e:Wk(e),i=qk(arguments,1);return pa[++Rl]=function(){Fk(t,void 0,i)},yi(Rl),Rl},Dl=function(e){delete pa[e]},Qk?yi=function(a){Gk.nextTick($l(a))}:Pl&&Pl.now?yi=function(a){Pl.now($l(a))}:ug&&!jk?(kl=new ug,Ll=kl.port2,kl.port1.onmessage=cg,yi=Nk(Ll.postMessage,Ll)):He.addEventListener&&sg(He.postMessage)&&!He.importScripts&&ha&&ha.protocol!=="file:"&&!pg(dg)?(yi=dg,He.addEventListener("message",cg,!1)):lg in og("script")?yi=function(a){ng.appendChild(og("script"))[lg]=function(){ng.removeChild(this),Cl(a)}}:yi=function(a){setTimeout($l(a),0)});hg.exports={set:Ml,clear:Dl}});var bg=g((gF,mg)=>{"use strict";var fg=oe(),Yk=Ue(),Kk=Object.getOwnPropertyDescriptor;mg.exports=function(a){if(!Yk)return fg[a];var e=Kk(fg,a);return e&&e.value}});var Vl=g((SF,Sg)=>{"use strict";var gg=function(){this.head=null,this.tail=null};gg.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}}};Sg.exports=gg});var yg=g((vF,vg)=>{"use strict";var Xk=bi();vg.exports=/ipad|iphone|ipod/i.test(Xk)&&typeof Pebble!="undefined"});var Ig=g((yF,Tg)=>{"use strict";var Jk=bi();Tg.exports=/web0s(?!.*chrome)/i.test(Jk)});var kg=g((TF,Rg)=>{"use strict";var rr=oe(),Zk=bg(),Eg=Yi(),_l=Bl().set,eL=Vl(),tL=Al(),iL=yg(),rL=Ig(),Ol=yn(),xg=rr.MutationObserver||rr.WebKitMutationObserver,wg=rr.document,Ag=rr.process,Tn=rr.Promise,Ul=Zk("queueMicrotask"),ir,Fl,Nl,In,Pg;Ul||(fa=new eL,ma=function(){var a,e;for(Ol&&(a=Ag.domain)&&a.exit();e=fa.get();)try{e()}catch(t){throw fa.head&&ir(),t}a&&a.enter()},!tL&&!Ol&&!rL&&xg&&wg?(Fl=!0,Nl=wg.createTextNode(""),new xg(ma).observe(Nl,{characterData:!0}),ir=function(){Nl.data=Fl=!Fl}):!iL&&Tn&&Tn.resolve?(In=Tn.resolve(void 0),In.constructor=Tn,Pg=Eg(In.then,In),ir=function(){Pg(ma)}):Ol?ir=function(){Ag.nextTick(ma)}:(_l=Eg(_l,rr),ir=function(){_l(ma)}),Ul=function(a){fa.head||ir(),fa.add(a)});var fa,ma;Rg.exports=Ul});var $g=g((IF,Lg)=>{"use strict";Lg.exports=function(a,e){try{arguments.length===1?console.error(a):console.error(a,e)}catch(t){}}});var En=g((EF,Mg)=>{"use strict";Mg.exports=function(a){try{return{error:!1,value:a()}}catch(e){return{error:!0,value:e}}}});var Ti=g((xF,Dg)=>{"use strict";var aL=oe();Dg.exports=aL.Promise});var ar=g((wF,_g)=>{"use strict";var sL=oe(),ba=Ti(),nL=ue(),oL=_u(),uL=Il(),lL=ye(),Cg=yl(),cL=at(),ql=xu(),Bg=ba&&ba.prototype,dL=lL("species"),Hl=!1,Vg=nL(sL.PromiseRejectionEvent),pL=oL("Promise",function(){var a=uL(ba),e=a!==String(ba);if(!e&&ql===66||cL&&!(Bg.catch&&Bg.finally))return!0;if(!ql||ql<51||!/native code/.test(a)){var t=new ba(function(s){s(1)}),i=function(s){s(function(){},function(){})},r=t.constructor={};if(r[dL]=i,Hl=t.then(function(){})instanceof i,!Hl)return!0}return!e&&(Cg==="BROWSER"||Cg==="DENO")&&!Vg});_g.exports={CONSTRUCTOR:pL,REJECTION_EVENT:Vg,SUBCLASSING:Hl}});var sr=g((AF,Fg)=>{"use strict";var Og=ft(),hL=TypeError,fL=function(a){var e,t;this.promise=new a(function(i,r){if(e!==void 0||t!==void 0)throw new hL("Bad Promise constructor");e=i,t=r}),this.resolve=Og(e),this.reject=Og(t)};Fg.exports.f=function(a){return new fL(a)}});var sS=g(()=>{"use strict";var mL=de(),bL=at(),Pn=yn(),Wt=oe(),gL=mi(),lr=qe(),Ng=tr(),Ug=fl(),SL=oa(),vL=Ub(),yL=ft(),An=ue(),TL=$e(),IL=Hb(),EL=wl(),Gg=Bl().set,zl=kg(),xL=$g(),wL=En(),AL=Vl(),Wg=tl(),Rn=Ti(),Yl=ar(),zg=sr(),kn="Promise",Yg=Yl.CONSTRUCTOR,PL=Yl.REJECTION_EVENT,RL=Yl.SUBCLASSING,jl=Wg.getterFor(kn),kL=Wg.set,nr=Rn&&Rn.prototype,Ii=Rn,xn=nr,Kg=Wt.TypeError,Ql=Wt.document,Kl=Wt.process,Gl=zg.f,LL=Gl,$L=!!(Ql&&Ql.createEvent&&Wt.dispatchEvent),Xg="unhandledrejection",ML="rejectionhandled",qg=0,Jg=1,DL=2,Xl=1,Zg=2,wn,Hg,eS,jg,tS=function(a){var e;return TL(a)&&An(e=a.then)?e:!1},iS=function(a,e){var t=e.value,i=e.state===Jg,r=i?a.ok:a.fail,s=a.resolve,n=a.reject,o=a.domain,u,l,c;try{r?(i||(e.rejection===Zg&&BL(e),e.rejection=Xl),r===!0?u=t:(o&&o.enter(),u=r(t),o&&(o.exit(),c=!0)),u===a.promise?n(new Kg("Promise-chain cycle")):(l=tS(u))?lr(l,u,s,n):s(u)):n(t)}catch(d){o&&!c&&o.exit(),n(d)}},rS=function(a,e){a.notified||(a.notified=!0,zl(function(){for(var t=a.reactions,i;i=t.get();)iS(i,a);a.notified=!1,e&&!a.rejection&&CL(a)}))},aS=function(a,e,t){var i,r;$L?(i=Ql.createEvent("Event"),i.promise=e,i.reason=t,i.initEvent(a,!1,!0),Wt.dispatchEvent(i)):i={promise:e,reason:t},!PL&&(r=Wt["on"+a])?r(i):a===Xg&&xL("Unhandled promise rejection",t)},CL=function(a){lr(Gg,Wt,function(){var e=a.facade,t=a.value,i=Qg(a),r;if(i&&(r=wL(function(){Pn?Kl.emit("unhandledRejection",t,e):aS(Xg,e,t)}),a.rejection=Pn||Qg(a)?Zg:Xl,r.error))throw r.value})},Qg=function(a){return a.rejection!==Xl&&!a.parent},BL=function(a){lr(Gg,Wt,function(){var e=a.facade;Pn?Kl.emit("rejectionHandled",e):aS(ML,e,a.value)})},or=function(a,e,t){return function(i){a(e,i,t)}},ur=function(a,e,t){a.done||(a.done=!0,t&&(a=t),a.value=e,a.state=DL,rS(a,!0))},Wl=function(a,e,t){if(!a.done){a.done=!0,t&&(a=t);try{if(a.facade===e)throw new Kg("Promise can't be resolved itself");var i=tS(e);i?zl(function(){var r={done:!1};try{lr(i,e,or(Wl,r,a),or(ur,r,a))}catch(s){ur(r,s,a)}}):(a.value=e,a.state=Jg,rS(a,!1))}catch(r){ur({done:!1},r,a)}}};if(Yg&&(Ii=function(e){IL(this,xn),yL(e),lr(wn,this);var t=jl(this);try{e(or(Wl,t),or(ur,t))}catch(i){ur(t,i)}},xn=Ii.prototype,wn=function(e){kL(this,{type:kn,done:!1,notified:!1,parent:!1,reactions:new AL,rejection:!1,state:qg,value:null})},wn.prototype=Ng(xn,"then",function(e,t){var i=jl(this),r=Gl(EL(this,Ii));return i.parent=!0,r.ok=An(e)?e:!0,r.fail=An(t)&&t,r.domain=Pn?Kl.domain:void 0,i.state===qg?i.reactions.add(r):zl(function(){iS(r,i)}),r.promise}),Hg=function(){var a=new wn,e=jl(a);this.promise=a,this.resolve=or(Wl,e),this.reject=or(ur,e)},zg.f=Gl=function(a){return a===Ii||a===eS?new Hg(a):LL(a)},!bL&&An(Rn)&&nr!==Object.prototype)){jg=nr.then,RL||Ng(nr,"then",function(e,t){var i=this;return new Ii(function(r,s){lr(jg,i,r,s)}).then(e,t)},{unsafe:!0});try{delete nr.constructor}catch(a){}Ug&&Ug(nr,xn)}mL({global:!0,constructor:!0,wrap:!0,forced:Yg},{Promise:Ii});eS=gL.Promise;SL(Ii,kn,!1,!0);vL(kn)});var cS=g((kF,lS)=>{"use strict";var VL=ye(),oS=VL("iterator"),uS=!1;try{nS=0,Jl={next:function(){return{done:!!nS++}},return:function(){uS=!0}},Jl[oS]=function(){return this},Array.from(Jl,function(){throw 2})}catch(a){}var nS,Jl;lS.exports=function(a,e){try{if(!e&&!uS)return!1}catch(r){return!1}var t=!1;try{var i={};i[oS]=function(){return{next:function(){return{done:t=!0}}}},a(i)}catch(r){}return t}});var Zl=g((LF,dS)=>{"use strict";var _L=Ti(),OL=cS(),FL=ar().CONSTRUCTOR;dS.exports=FL||!OL(function(a){_L.all(a).then(void 0,function(){})})});var pS=g(()=>{"use strict";var NL=de(),UL=qe(),qL=ft(),HL=sr(),jL=En(),QL=gn(),GL=Zl();NL({target:"Promise",stat:!0,forced:GL},{all:function(e){var t=this,i=HL.f(t),r=i.resolve,s=i.reject,n=jL(function(){var o=qL(t.resolve),u=[],l=0,c=1;QL(e,function(d){var f=l++,p=!1;c++,UL(o,t,d).then(function(h){p||(p=!0,u[f]=h,--c||r(u))},s)}),--c||r(u)});return n.error&&s(n.value),i.promise}})});var fS=g(()=>{"use strict";var WL=de(),zL=at(),YL=ar().CONSTRUCTOR,tc=Ti(),KL=Pt(),XL=ue(),JL=tr(),hS=tc&&tc.prototype;WL({target:"Promise",proto:!0,forced:YL,real:!0},{catch:function(a){return this.then(void 0,a)}});!zL&&XL(tc)&&(ec=KL("Promise").prototype.catch,hS.catch!==ec&&JL(hS,"catch",ec,{unsafe:!0}));var ec});var mS=g(()=>{"use strict";var ZL=de(),e$=qe(),t$=ft(),i$=sr(),r$=En(),a$=gn(),s$=Zl();ZL({target:"Promise",stat:!0,forced:s$},{race:function(e){var t=this,i=i$.f(t),r=i.reject,s=r$(function(){var n=t$(t.resolve);a$(e,function(o){e$(n,t,o).then(i.resolve,r)})});return s.error&&r(s.value),i.promise}})});var bS=g(()=>{"use strict";var n$=de(),o$=sr(),u$=ar().CONSTRUCTOR;n$({target:"Promise",stat:!0,forced:u$},{reject:function(e){var t=o$.f(this),i=t.reject;return i(e),t.promise}})});var ic=g((FF,gS)=>{"use strict";var l$=mt(),c$=$e(),d$=sr();gS.exports=function(a,e){if(l$(a),c$(e)&&e.constructor===a)return e;var t=d$.f(a),i=t.resolve;return i(e),t.promise}});var yS=g(()=>{"use strict";var p$=de(),h$=Pt(),SS=at(),f$=Ti(),vS=ar().CONSTRUCTOR,m$=ic(),b$=h$("Promise"),g$=SS&&!vS;p$({target:"Promise",stat:!0,forced:SS||vS},{resolve:function(e){return m$(g$&&this===b$?f$:this,e)}})});var TS=g(()=>{"use strict";sS();pS();fS();mS();bS();yS()});var wS=g(()=>{"use strict";var S$=de(),v$=at(),Ln=Ti(),y$=pe(),ES=Pt(),xS=ue(),T$=wl(),IS=ic(),I$=tr(),ac=Ln&&Ln.prototype,E$=!!Ln&&y$(function(){ac.finally.call({then:function(){}},function(){})});S$({target:"Promise",proto:!0,real:!0,forced:E$},{finally:function(a){var e=T$(this,ES("Promise")),t=xS(a);return this.then(t?function(i){return IS(e,a()).then(function(){return i})}:a,t?function(i){return IS(e,a()).then(function(){throw i})}:a)}});!v$&&xS(Ln)&&(rc=ES("Promise").prototype.finally,ac.finally!==rc&&I$(ac,"finally",rc,{unsafe:!0}));var rc});var PS=g((GF,AS)=>{"use strict";Cb();TS();wS();var x$=Gt();AS.exports=x$("Promise","finally")});var kS=g((WF,RS)=>{"use strict";var w$=PS();RS.exports=w$});var $n=g((zF,LS)=>{"use strict";var A$=kS();LS.exports=A$});var HS=g(()=>{"use strict";var N$=de(),U$=Xu().values;N$({target:"Object",stat:!0},{values:function(e){return U$(e)}})});var QS=g((MN,jS)=>{"use strict";HS();var q$=mi();jS.exports=q$.Object.values});var WS=g((DN,GS)=>{"use strict";var H$=QS();GS.exports=H$});var dr=g((CN,zS)=>{"use strict";var j$=WS();zS.exports=j$});var dv=g(()=>{"use strict";var hM=de(),fM=Wi(),mM=Zi(),bM=ra(),gM=aa();hM({target:"Array",proto:!0},{at:function(e){var t=fM(this),i=mM(t),r=bM(e),s=r>=0?r:i+r;return s<0||s>=i?void 0:t[s]}});gM("at")});var hv=g((HU,pv)=>{"use strict";dv();var SM=Gt();pv.exports=SM("Array","at")});var mv=g((jU,fv)=>{"use strict";var vM=hv();fv.exports=vM});var ot=g((QU,bv)=>{"use strict";var yM=mv();bv.exports=yM});var Pc=g((V1,Xv)=>{"use strict";var eD=hi();Xv.exports=Array.isArray||function(e){return eD(e)==="Array"}});var Zv=g((_1,Jv)=>{"use strict";var tD=TypeError,iD=9007199254740991;Jv.exports=function(a){if(a>iD)throw tD("Maximum allowed index exceeded");return a}});var iy=g((O1,ty)=>{"use strict";var rD=Pc(),aD=Zi(),sD=Zv(),nD=Yi(),ey=function(a,e,t,i,r,s,n,o){for(var u=r,l=0,c=n?nD(n,o):!1,d,f;l<i;)l in t&&(d=c?c(t[l],l,e):t[l],s>0&&rD(d)?(f=aD(d),u=ey(a,e,d,f,u,s-1)-1):(sD(u+1),a[u]=d),u++),l++;return u};ty.exports=ey});var ny=g((F1,sy)=>{"use strict";var ry=Pc(),oD=xl(),uD=$e(),lD=ye(),cD=lD("species"),ay=Array;sy.exports=function(a){var e;return ry(a)&&(e=a.constructor,oD(e)&&(e===ay||ry(e.prototype))?e=void 0:uD(e)&&(e=e[cD],e===null&&(e=void 0))),e===void 0?ay:e}});var uy=g((N1,oy)=>{"use strict";var dD=ny();oy.exports=function(a,e){return new(dD(a))(e===0?0:e)}});var ly=g(()=>{"use strict";var pD=de(),hD=iy(),fD=ft(),mD=Wi(),bD=Zi(),gD=uy();pD({target:"Array",proto:!0},{flatMap:function(e){var t=mD(this),i=bD(t),r;return fD(e),r=gD(t,0),r.length=hD(r,t,t,i,0,1,e,arguments.length>1?arguments[1]:void 0),r}})});var cy=g(()=>{"use strict";var SD=aa();SD("flatMap")});var py=g((Q1,dy)=>{"use strict";ly();cy();var vD=Gt();dy.exports=vD("Array","flatMap")});var fy=g((G1,hy)=>{"use strict";var yD=py();hy.exports=yD});var Ma=g((W1,my)=>{"use strict";var TD=fy();my.exports=TD});var Da=g((z1,by)=>{"use strict";var ID=na(),ED=String;by.exports=function(a){if(ID(a)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return ED(a)}});var Rc=g((Y1,gy)=>{"use strict";gy.exports=`
|
|
7
|
+
\v\f\r \xA0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF`});var yy=g((K1,vy)=>{"use strict";var xD=he(),wD=Qt(),AD=Da(),Lc=Rc(),Sy=xD("".replace),PD=RegExp("^["+Lc+"]+"),RD=RegExp("(^|[^"+Lc+"])["+Lc+"]+$"),kc=function(a){return function(e){var t=AD(wD(e));return a&1&&(t=Sy(t,PD,"")),a&2&&(t=Sy(t,RD,"$1")),t}};vy.exports={start:kc(1),end:kc(2),trim:kc(3)}});var xy=g((X1,Ey)=>{"use strict";var kD=al().PROPER,LD=pe(),Ty=Rc(),Iy="\u200B\x85\u180E";Ey.exports=function(a){return LD(function(){return!!Ty[a]()||Iy[a]()!==Iy||kD&&Ty[a].name!==a})}});var $c=g((J1,wy)=>{"use strict";var $D=yy().start,MD=xy();wy.exports=MD("trimStart")?function(){return $D(this)}:"".trimStart});var Py=g(()=>{"use strict";var DD=de(),Ay=$c();DD({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==Ay},{trimLeft:Ay})});var ky=g(()=>{"use strict";Py();var CD=de(),Ry=$c();CD({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==Ry},{trimStart:Ry})});var $y=g((rH,Ly)=>{"use strict";ky();var BD=Gt();Ly.exports=BD("String","trimLeft")});var Dy=g((aH,My)=>{"use strict";var VD=$y();My.exports=VD});var By=g((sH,Cy)=>{"use strict";var _D=Dy();Cy.exports=_D});var Xy=g(()=>{"use strict"});var Jy=g(()=>{"use strict"});var eT=g((QQ,Zy)=>{"use strict";var oC=$e(),uC=hi(),lC=ye(),cC=lC("match");Zy.exports=function(a){var e;return oC(a)&&((e=a[cC])!==void 0?!!e:uC(a)==="RegExp")}});var rT=g((GQ,iT)=>{"use strict";var dC=oe(),pC=pe(),tT=dC.RegExp,hC=!pC(function(){var a=!0;try{tT(".","d")}catch(u){a=!1}var e={},t="",i=a?"dgimsy":"gimsy",r=function(u,l){Object.defineProperty(e,u,{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 o=Object.getOwnPropertyDescriptor(tT.prototype,"flags").get.call(e);return o!==i||t!==i});iT.exports={correct:hC}});var sT=g((WQ,aT)=>{"use strict";var fC=mt();aT.exports=function(){var a=fC(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 uT=g((zQ,oT)=>{"use strict";var mC=qe(),bC=st(),gC=Xr(),nT=rT(),SC=sT(),vC=RegExp.prototype;oT.exports=nT.correct?function(a){return a.flags}:function(a){return!nT.correct&&gC(vC,a)&&!bC(a,"flags")?mC(SC,a):a.flags}});var cT=g((YQ,lT)=>{"use strict";var Vc=he(),yC=Wi(),TC=Math.floor,Cc=Vc("".charAt),IC=Vc("".replace),Bc=Vc("".slice),EC=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,xC=/\$([$&'`]|\d{1,2})/g;lT.exports=function(a,e,t,i,r,s){var n=t+a.length,o=i.length,u=xC;return r!==void 0&&(r=yC(r),u=EC),IC(s,u,function(l,c){var d;switch(Cc(c,0)){case"$":return"$";case"&":return a;case"`":return Bc(e,0,t);case"'":return Bc(e,n);case"<":d=r[Bc(c,1,-1)];break;default:var f=+c;if(f===0)return l;if(f>o){var p=TC(f/10);return p===0?l:p<=o?i[p-1]===void 0?Cc(c,1):i[p-1]+Cc(c,1):l}d=i[f-1]}return d===void 0?"":d})}});var hT=g(()=>{"use strict";var wC=de(),AC=qe(),Oc=he(),dT=Qt(),PC=ue(),RC=$e(),kC=eT(),xr=Da(),LC=Zr(),$C=uT(),MC=cT(),DC=ye(),CC=at(),BC=DC("replace"),VC=TypeError,_c=Oc("".indexOf),_C=Oc("".replace),pT=Oc("".slice),OC=Math.max;wC({target:"String",proto:!0},{replaceAll:function(e,t){var i=dT(this),r,s,n,o,u,l,c,d,f,p,h=0,m="";if(RC(e)){if(r=kC(e),r&&(s=xr(dT($C(e))),!~_c(s,"g")))throw new VC("`.replaceAll` does not allow non-global regexes");if(n=LC(e,BC),n)return AC(n,e,i,t);if(CC&&r)return _C(xr(i),e,t)}for(o=xr(i),u=xr(e),l=PC(t),l||(t=xr(t)),c=u.length,d=OC(1,c),f=_c(o,u);f!==-1;)p=l?xr(t(u,f,o)):MC(u,o,f,[],void 0,t),m+=pT(o,h,f)+p,h=f+c,f=f+d>o.length?-1:_c(o,u,f+d);return h<o.length&&(m+=pT(o,h)),m}})});var mT=g((JQ,fT)=>{"use strict";Xy();Jy();hT();var FC=Gt();fT.exports=FC("String","replaceAll")});var gT=g((ZQ,bT)=>{"use strict";var NC=mT();bT.exports=NC});var vT=g((eG,ST)=>{"use strict";var UC=gT();ST.exports=UC});var TT=g((tG,yT)=>{"use strict";var qC=ra(),HC=Da(),jC=Qt(),QC=RangeError;yT.exports=function(e){var t=HC(jC(this)),i="",r=qC(e);if(r<0||r===1/0)throw new QC("Wrong number of repetitions");for(;r>0;(r>>>=1)&&(t+=t))r&1&&(i+=t);return i}});var AT=g((iG,wT)=>{"use strict";var xT=he(),GC=Hu(),IT=Da(),WC=TT(),zC=Qt(),YC=xT(WC),KC=xT("".slice),XC=Math.ceil,ET=function(a){return function(e,t,i){var r=IT(zC(e)),s=GC(t),n=r.length,o=i===void 0?" ":IT(i),u,l;return s<=n||o===""?r:(u=s-n,l=YC(o,XC(u/o.length)),l.length>u&&(l=KC(l,0,u)),a?r+l:l+r)}};wT.exports={start:ET(!1),end:ET(!0)}});var RT=g((rG,PT)=>{"use strict";var JC=bi();PT.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(JC)});var kT=g(()=>{"use strict";var ZC=de(),eB=AT().start,tB=RT();ZC({target:"String",proto:!0,forced:tB},{padStart:function(e){return eB(this,e,arguments.length>1?arguments[1]:void 0)}})});var $T=g((nG,LT)=>{"use strict";kT();var iB=Gt();LT.exports=iB("String","padStart")});var DT=g((oG,MT)=>{"use strict";var rB=$T();MT.exports=rB});var BT=g((uG,CT)=>{"use strict";var aB=DT();CT.exports=aB});var _p="2.0.136-beta.0";var Le=(r=>(r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused",r))(Le||{}),At=(v=>(v.MPEG="MPEG",v.DASH="DASH",v.DASH_SEP="DASH_SEP",v.DASH_SEP_VK="DASH_SEP",v.DASH_WEBM="DASH_WEBM",v.DASH_WEBM_AV1="DASH_WEBM_AV1",v.DASH_STREAMS="DASH_STREAMS",v.DASH_WEBM_VK="DASH_WEBM",v.DASH_ONDEMAND="DASH_ONDEMAND",v.DASH_ONDEMAND_VK="DASH_ONDEMAND",v.DASH_LIVE="DASH_LIVE",v.DASH_LIVE_CMAF="DASH_LIVE_CMAF",v.DASH_LIVE_WEBM="DASH_LIVE_WEBM",v.HLS="HLS",v.HLS_ONDEMAND="HLS_ONDEMAND",v.HLS_JS="HLS",v.HLS_LIVE="HLS_LIVE",v.HLS_LIVE_CMAF="HLS_LIVE_CMAF",v.WEB_RTC_LIVE="WEB_RTC_LIVE",v))(At||{});var Ys=(r=>(r.NOT_AVAILABLE="NOT_AVAILABLE",r.AVAILABLE="AVAILABLE",r.CONNECTING="CONNECTING",r.CONNECTED="CONNECTED",r))(Ys||{}),pu=(i=>(i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic",i))(pu||{});var hu=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(hu||{}),Ks=(i=>(i.TRAFFIC_SAVING="traffic_saving",i.HIGH_QUALITY="high_quality",i.UNKNOWN="unknown",i))(Ks||{});var ME=O(Ye(),1);import{assertNever as Vf,assertNonNullable as hA,isNonNullable as tn,ValueSubject as Qu,Subject as fA,Subscription as mA,merge as bA,observableFrom as gA,fromEvent as Mf,map as Df,tap as Cf,filterChanged as SA,isNullable as Gu,ErrorCategory as Bf}from"@vkontakte/videoplayer-shared/es2018";var $f=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 rn=class{constructor(e){this.connection$=new Qu(void 0);this.castState$=new Qu("NOT_AVAILABLE");this.errorEvent$=new fA;this.realCastState$=new Qu("NOT_AVAILABLE");this.subscription=new mA;this.isDestroyed=!1;var s;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");let t="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${t}`}),e.isDisabled||!t)return;let i=tn((s=window.chrome)==null?void 0:s.cast),r=!!window.__onGCastApiAvailable;i?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&!this.isDestroyed&&this.initializeCastApi()},r||$f("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:Bf.NETWORK,message:"Script loading failed!"})))}connect(){var e;(e=cast.framework.CastContext.getInstance())==null||e.requestSession()}disconnect(){var e,t;(t=(e=cast.framework.CastContext.getInstance())==null?void 0:e.getCurrentSession())==null||t.endSession(!0)}stopMedia(){return new Promise((e,t)=>{var i,r,s;(s=(r=(i=cast.framework.CastContext.getInstance())==null?void 0:i.getCurrentSession())==null?void 0:r.getMediaSession())==null||s.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){tn(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();Gu(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();Gu(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(Mf(i,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(r=>{var s,n,o;switch(r.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(o=(n=(s=i.getCurrentSession())==null?void 0:s.getMediaSession())==null?void 0:n.media)==null?void 0:o.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return Vf(r.sessionState)}})).add(bA(Mf(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(Cf(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),Df(r=>r.castState)),gA([i.getCastState()])).pipe(SA(),Df(vA),Cf(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{var o,u;let s=r==="CONNECTED",n=tn(this.connection$.getValue());if(s&&!n){let l=i.getCurrentSession();hA(l);let c=l.getCastDevice(),d=(u=(o=l.getMediaSession())==null?void 0:o.media)==null?void 0:u.contentId;(Gu(d)||d===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:l,castDevice:c}))}else!s&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(r==="CONNECTED"?tn(this.connection$.getValue())?"CONNECTED":"AVAILABLE":r)}))}initializeCastApi(){var r;let e,t,i;try{e=cast.framework.CastContext.getInstance(),t=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,i=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(s){return}try{e.setOptions({receiverApplicationId:(r=this.params.receiverApplicationId)!=null?r:t,autoJoinPolicy:i}),this.initListeners()}catch(s){this.errorEvent$.next({id:"ChromecastInitializer",category:Bf.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:s})}}},vA=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 Vf(a)}};var jd=O(Ye(),1),hE=O(er(),1),fE=O(vl(),1);var NS=O($n(),1);import{assertNever as $S}from"@vkontakte/videoplayer-shared/es2018";var le=(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:$S(t)}return a},zt=(a,e)=>{var t;switch(e){case 0:return NaN;case 1:{let i=new URL(a);return Number(i.searchParams.get("playback_shift"))}case 2:{let i=new URL(a);return Number((t=i.searchParams.get("offset_p"))!=null?t:0)}default:$S(e)}};var $=(a,e,t=!1)=>{let i=a.getTransition();(t||!i||i.to===e)&&a.setState(e)};import{isNonNullable as P$,Subject as Mn,merge as MS}from"@vkontakte/videoplayer-shared/es2018";var q=class{constructor(e){this.transitionStarted$=new Mn;this.transitionEnded$=new Mn;this.transitionUpdated$=new Mn;this.forceChanged$=new Mn;this.stateChangeStarted$=MS(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=MS(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||P$(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 R$}from"@vkontakte/videoplayer-shared/es2018";var DS=a=>{switch(a){case"MPEG":case"DASH":case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":case"HLS":case"HLS_ONDEMAND":return!1;case"DASH_LIVE":case"DASH_LIVE_CMAF":case"HLS_LIVE":case"HLS_LIVE_CMAF":case"DASH_LIVE_WEBM":case"WEB_RTC_LIVE":return!0;default:return R$(a)}};import{assertNever as cr,assertNonNullable as Ei,debounce as CS,ErrorCategory as BS,fromEvent as xi,isNonNullable as VS,map as _S,merge as OS,observableFrom as k$,Subject as L$,Subscription as sc,timeout as $$,getHighestQuality as M$}from"@vkontakte/videoplayer-shared/es2018";var D$=5,C$=5,B$=500,FS=7e3,ga=class{constructor(e){this.subscription=new sc;this.loadMediaTimeoutSubscription=new sc;this.videoState=new q("stopped");this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(s)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.stop());return}if(!t){if((r==null?void 0:r.to)!=="paused"&&s.state==="requested"&&e!=="stopped"){this.seek(s.position/1e3);return}switch(i){case"ready":{switch(e){case"playing":case"paused":case"ready":break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:cr(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:cr(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:cr(e)}break}default:cr(i)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(DS(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 sc;this.subscription.add(e),this.subscription.add(OS(this.videoState.stateChangeStarted$.pipe(_S(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe(_S(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 L$;e.add(r.pipe(CS(B$)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add(xi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(n=>{this.logRemoteEvent(n);let o=n.value;this.params.output.position$.next(o),(this.params.desiredState.seekState.getState().state==="applying"||Math.abs(o-s)>D$)&&r.next(o),s=o})),e.add(xi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(xi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(xi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t(xi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),r=>{this.logRemoteEvent(r);let{remotePlayer:s}=this.params.connection,n=r.value,o=this.params.output.isBuffering$.getValue(),u=n===chrome.cast.media.PlayerState.BUFFERING;switch(o!==u&&this.params.output.isBuffering$.next(u),n){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&s.duration-s.currentTime<C$&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),$(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:cr(n)}}),t(xi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t(xi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});let i=OS(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,k$(["init"])).pipe(CS(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"),$(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),$(this.params.desiredState.playbackState,"playing"));let i=this.params.output.isLive$.getValue();this.params.output.duration$.next(i?0:t.duration),this.params.output.position$.next(i?0:t.currentTime),this.params.desiredState.seekState.setState({state:"none"})}}prepare(){let e=this.params.format;this.log({message:`[prepare] format: ${e}`});let t=this.createMediaInfo(e),i=this.createLoadRequest(t);this.loadMedia(i)}handleRemotePause(){let e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="paused"||e==="playing")&&(this.videoState.setState("paused"),$(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="playing"||e==="paused")&&(this.videoState.setState("playing"),$(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){var t;let e=this.videoState.getTransition();(e==null?void 0:e.to)==="ready"&&this.videoState.setState("ready"),((t=this.params.desiredState.playbackState.getTransition())==null?void 0:t.to)==="ready"&&$(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){var r,s;let t=this.params.output.volume$.getValue(),i={volume:(r=e.volume)!=null?r:t.volume,muted:(s=e.muted)!=null?s:t.muted};(i.volume!==t.volume||i.muted!==i.muted)&&this.params.output.volume$.next(i)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:i}=this.params.connection;t.currentTime=e,i.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){var l;let t=this.params.source,i,r,s;switch(e){case"MPEG":{let c=t[e];Ei(c);let d=M$(Object.keys(c));Ei(d);let f=c[d];Ei(f),i=f,r="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let c=t[e];Ei(c),i=c.url,r="application/x-mpegurl",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":{let c=t[e];Ei(c),i=c.url,r="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let c=t[e];Ei(c),i=c.url,r="application/dash+xml",s=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let c=t[e];Ei(c),i=le(c.url),r="application/x-mpegurl",s=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let c="Unsupported format for Chromecast",d=new Error(c);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:BS.VIDEO_PIPELINE,message:c,thrown:d}),d}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return cr(e)}let n=new chrome.cast.media.MediaInfo((l=this.params.meta.videoId)!=null?l:i,r);n.contentUrl=i,n.streamType=s,n.metadata=new chrome.cast.media.GenericMediaMetadata;let{title:o,subtitle:u}=this.params.meta;return VS(o)&&(n.metadata.title=o),VS(u)&&(n.metadata.subtitle=u),n}createLoadRequest(e){let t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;let i=this.params.desiredState.seekState.getState();return i.state==="applying"||i.state==="requested"?t.currentTime=this.params.output.isLive$.getValue()?0:i.position/1e3:t.currentTime=0,t}loadMedia(e){let t=this.params.connection.session.loadMedia(e),i=new Promise((r,s)=>{this.loadMediaTimeoutSubscription.add($$(FS).subscribe(()=>s(`timeout(${FS})`)))});(0,NS.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:BS.VIDEO_PIPELINE,message:s,thrown:r})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var wc=O(Ye(),1);import{clearVideoElement as qS}from"@vkontakte/videoplayer-shared/es2018";import{clearVideoElement as V$}from"@vkontakte/videoplayer-shared/es2018";var US=a=>{try{a.pause(),a.playbackRate=0,V$(a),a.remove()}catch(e){console.error(e)}};import{fromEvent as _$,Subscription as O$}from"@vkontakte/videoplayer-shared/es2018";var nc=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)}},oc=window.WeakMap?new WeakMap:new nc,uc=window.WeakMap?new WeakMap:new Map,F$=(a,e=20)=>{let t=0;return _$(a,"ratechange").subscribe(i=>{t++,t>=e&&(a.currentTime=a.currentTime,t=0)})},Me=(a,{audioVideoSyncRate:e,disableYandexPiP:t})=>{let i=a.querySelector("video"),r=!!i;i?qS(i):(i=document.createElement("video"),a.appendChild(i)),oc.set(i,r);let s=new O$;return s.add(F$(i,e)),uc.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},De=a=>{let e=uc.get(a);e==null||e.unsubscribe(),uc.delete(a);let t=oc.get(a);oc.delete(a),t?qS(a):US(a)};var cc=O(dr(),1);import{assertNonNullable as va,isNonNullable as gt,isNullable as W$,fromEvent as pr,merge as YS,observableFrom as KS,filterChanged as XS,map as ya,Subject as JS,Subscription as z$,ValueSubject as Y$,ErrorCategory as K$}from"@vkontakte/videoplayer-shared/es2018";import{isNonNullable as lc,isNullable as Q$,Subscription as G$}from"@vkontakte/videoplayer-shared/es2018";var Dn=(a,e,t,{equal:i=(n,o)=>n===o,changed$:r,onError:s}={})=>{let n=a.getState(),o=e(),u=Q$(r),l=new G$;return r&&l.add(r.subscribe(c=>{let d=a.getState();i(c,d)&&a.setState(c)},s)),i(o,n)||(t(n),u&&a.setState(n)),l.add(a.stateChangeStarted$.subscribe(c=>{t(c.to),u&&a.setState(c.to)},s)),l},bt=(a,e,t)=>Dn(e,()=>a.loop,i=>{lc(i)&&(a.loop=i)},{onError:t}),Ce=(a,e,t,i)=>Dn(e,()=>({muted:a.muted,volume:a.volume}),r=>{lc(r)&&(a.muted=r.muted,a.volume=r.volume)},{equal:(r,s)=>r===s||(r==null?void 0:r.muted)===(s==null?void 0:s.muted)&&(r==null?void 0:r.volume)===(s==null?void 0:s.volume),changed$:t,onError:i}),Ke=(a,e,t,i)=>Dn(e,()=>a.playbackRate,r=>{lc(r)&&(a.playbackRate=r)},{changed$:t,onError:i}),Sa=Dn;var X$=a=>["__",a.language,a.label].join("|"),J$=(a,e)=>{if(a.id===e)return!0;let[t,i,r]=e.split("|");return a.language===i&&a.label===r},dc=class a{constructor(e){this.available$=new JS;this.current$=new Y$(void 0);this.error$=new JS;this.subscription=new z$;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:K$.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:s})};this.subscription.add(this.available$.subscribe(i.availableTextTracks$)),this.subscription.add(this.current$.subscribe(i.currentTextTrack$)),this.subscription.add(this.error$.subscribe(i.error$)),this.subscription.add(Sa(t.internalTextTracks,()=>(0,cc.default)(this.internalTracks),s=>{gt(s)&&this.setInternal(s)},{equal:(s,n)=>gt(s)&>(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(ya(s=>s.filter(({type:n})=>n==="internal"))),onError:r})),this.subscription.add(Sa(t.externalTextTracks,()=>(0,cc.default)(this.externalTracks),s=>{gt(s)&&this.setExternal(s)},{equal:(s,n)=>gt(s)&>(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(ya(s=>s.filter(({type:n})=>n==="external"))),onError:r})),this.subscription.add(Sa(t.currentTextTrack,()=>{if(this.video)return;let s=this.htmlTextTracksAsArray().find(({mode:n})=>n==="showing");return s&&this.htmlTextTrackToITextTrack(s).id},s=>this.select(s),{changed$:this.current$,onError:r})),this.subscription.add(Sa(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){va(this.video);let{textTracks:e}=this.video;this.subscription.add(pr(e,"addtrack").subscribe(()=>{let i=this.current$.getValue();i&&this.select(i)})),this.subscription.add(YS(pr(e,"addtrack"),pr(e,"removetrack"),KS(["init"])).pipe(ya(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),XS((i,r)=>i.length===r.length&&i.every(({id:s},n)=>s===r[n].id))).subscribe(this.available$)),this.subscription.add(YS(pr(e,"change"),KS(["init"])).pipe(ya(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),ya(i=>i&&this.htmlTextTrackToITextTrack(i).id),XS()).subscribe(this.current$));let t=i=>{var r,s;return this.applyCueSettings((s=(r=i.target)==null?void 0:r.activeCues)!=null?s:null)};this.subscription.add(pr(e,"addtrack").subscribe(i=>{var s,n;(s=i.track)==null||s.addEventListener("cuechange",t);let r=o=>{var l,c,d,f,p;let u=(c=(l=o.target)==null?void 0:l.cues)!=null?c:null;u&&u.length&&(this.applyCueSettings((f=(d=o.target)==null?void 0:d.cues)!=null?f:null),(p=o.target)==null||p.removeEventListener("cuechange",r))};(n=i.track)==null||n.addEventListener("cuechange",r)})),this.subscription.add(pr(e,"removetrack").subscribe(i=>{var r;(r=i.track)==null||r.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;let t=this.cueSettings.getState();for(let i of Array.from(e)){let r=i;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){va(this.video);let t=[...this.video.textTracks];return e?t:t.filter(a.isHealthyTrack)}htmlTextTrackToITextTrack(e){var o,u,l,c,d;let{language:t,label:i}=e,r=e.id?e.id:X$(e),s=this.externalTracks.has(r),n=(l=s?(o=this.externalTracks.get(r))==null?void 0:o.isAuto:(u=this.internalTracks.get(r))==null?void 0:u.isAuto)!=null?l:r.includes("auto");return s?{id:r,type:"external",isAuto:n,language:t,label:i,url:(c=this.externalTracks.get(r))==null?void 0:c.url}:{id:r,type:"internal",isAuto:n,language:t,label:i,url:(d=this.internalTracks.get(r))==null?void 0:d.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(i=>i.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){let t=[...this.externalTracks];e.filter(({id:i,language:r,isAuto:s})=>!this.internalTracks.has(i)&&!t.some(([,n])=>n.language===r&&n.isAuto===s)).forEach(i=>this.attach(i)),Array.from(this.internalTracks).filter(([i])=>!e.find(r=>r.id===i)).forEach(([,i])=>this.detach(i))}select(e){va(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(W$(e)||!J$(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){va(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){va(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)}},Xe=dc;var wi=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 ZS=a=>{let e=a;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e==null?void 0:e.parentNode;return e!=null?e:void 0},pc=a=>{let e=ZS(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},ev=a=>{let e=ZS(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)};import{fromEvent as Ae,map as St,merge as Nn,filterChanged as uv,isNonNullable as lv,Subject as oM,filter as fc,mapTo as mc,combine as uM,once as lM,shareReplay as Pe,throttle as cM,ErrorCategory as dM,ValueSubject as cv,Subscription as pM}from"@vkontakte/videoplayer-shared/es2018";var Z$=3,tv=(a,e,t=Z$)=>{let i=0,r=0;for(let s=0;s<a.length;s++){let n=a.start(s),o=a.end(s);if(n<=e&&e<=o){if(i=n,r=o,!t)return{from:i,to:r};for(let u=s-1;u>=0;u--)a.end(u)+t>=i&&(i=a.start(u));for(let u=s+1;u<a.length;u++)a.start(u)-t<=r&&(r=a.end(u))}}return{from:i,to:r}};var Cn=class{constructor(){this._isMiuiBrowser=!1}get current(){return this._current}get isChrome(){return this.current==="Chrome"}get isFirefox(){return this.current==="Firefox"}get isSafari(){return this.current==="Safari"}get isOpera(){return this.current==="Opera"}get isEdge(){return this.current==="Edge"}get isYandex(){return this.current==="Yandex"}get isSamsungBrowser(){return this.current==="SamsungBrowser"}get currentVersion(){return this._current_version}get chromeVersion(){return this._chromeVersion}get firefoxVersion(){return this._firefoxVersion}get safariVersion(){return this._safariVersion}get operaVersion(){return this._operaVersion}get edgeVersion(){return this._edgeVersion}get yandexVersion(){return this._yandexVersion}get isMiuiBrowser(){return this._isMiuiBrowser}detect(){let{userAgent:e}=navigator;try{let t=/yabrowser/i.test(e)?"Yandex":void 0,i=/samsungbrowser/i.test(e)?"SamsungBrowser":void 0,r=/chrome|crios/i.test(e)?"Chrome":void 0,s=/chromium/i.test(e)?"Chromium":void 0,n=/firefox|fxios/i.test(e)?"Firefox":void 0,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||s||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],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 iv=O(Ye(),1);var Ta=()=>{var a,e;return/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test((a=navigator.appVersion)!=null?a:navigator.userAgent)||((e=navigator==null?void 0:navigator.userAgentData)==null?void 0:e.mobile)};var Bn=class{constructor(e){this._highEntropyValues={};this._displayChecker=e}get current(){return this._current}get isIOS(){let e=["iPhone","iPad","iPod"];return this._highEntropyValues.platform==="iOS"||(0,iv.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=Ta()}catch(t){console.error(t)}this.detectDevice(e),this.detectHighEntropyValues(),this.isIOS&&this.detectIOSVersion()}async detectHighEntropyValues(){let{userAgentData:e}=navigator;if(e!=null&&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,o=/webOS|BlackBerry|IEMobile|Opera Mini/i.test(e)?"RestMobile":void 0;this._current=t||i||r||s||o||n||"Desktop"}catch(t){console.error(t)}}detectIOSVersion(){try{if(this._highEntropyValues.platformVersion){let s=this._highEntropyValues.platformVersion.split(".").slice(0,2).join("."),n=parseFloat(s);this._iosVersion=n;return}let{userAgent:e}=window.navigator,t=e.match(/OS (\d+(_\d+)?)/i);if(!t)return;let i=t[1].replace(/_/g,".");if(!i)return;let r=parseFloat(i);if(isNaN(r))return;this._iosVersion=r}catch(e){console.error(e)}}};var Vn=class{get isTouch(){return typeof this._maxTouchPoints=="number"?this._maxTouchPoints>1:"ontouchstart"in window}get maxTouchPoints(){return this._maxTouchPoints}get height(){return this._height}get width(){return this._width}get screenHeight(){return this._screenHeight}get screenWidth(){return this._screenWidth}get pixelRatio(){return this._pixelRatio}get isHDR(){return this._isHdr}get colorDepth(){return this._colorDepth}detect(){var t;let{maxTouchPoints:e}=navigator;try{this._maxTouchPoints=e!=null?e:0,this._isHdr=!!((t=matchMedia("(dynamic-range: high)"))!=null&&t.matches),this._colorDepth=screen.colorDepth}catch(i){console.error(i)}try{this._pixelRatio=window.devicePixelRatio||1,this._height=screen.height,this._width=screen.width,this._height=screen.height,this._screenHeight=this._height*this._pixelRatio,this._screenWidth=this._width*this._pixelRatio}catch(i){console.error(i)}}};var je=()=>window.ManagedMediaSource||window.MediaSource,hr=()=>{var a,e;return!!(window.ManagedMediaSource&&((e=(a=window.ManagedSourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},rv=()=>{var a,e;return!!(window.MediaSource&&((e=(a=window.SourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},_n=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var eM=document.createElement("video"),tM='video/mp4; codecs="avc1.42000a,mp4a.40.2"',iM='video/mp4; codecs="hev1.1.6.L93.B0"',av='video/webm; codecs="vp09.00.10.08"',sv='video/webm; codecs="av01.0.00M.08"',rM='audio/mp4; codecs="mp4a.40.2"',aM='audio/webm; codecs="opus"',nv,sM=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:sv}}),window.navigator.mediaCapabilities.decodingInfo({...a,video:{...a.video,contentType:av}})]);nv={DASH_WEBM_AV1:e,DASH_WEBM:t}};sM().catch(a=>{console.log(eM),console.error(a)});var On=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 nv}get supportedCodecs(){return Object.keys(this._codecs).filter(e=>this._codecs[e])}get nativeHlsSupported(){return this._nativeHlsSupported}detect(){var e,t,i,r,s,n,o,u,l,c,d,f,p,h,m,b,S,y,v,I;this._video=document.createElement("video");try{this._protocols={mms:hr(),mse:rv(),hls:!!((t=(e=this._video).canPlayType)!=null&&t.call(e,"application/x-mpegurl")||(r=(i=this._video).canPlayType)!=null&&r.call(i,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},this._containers={mp4:!!((n=(s=this._video).canPlayType)!=null&&n.call(s,"video/mp4")),webm:!!((u=(o=this._video).canPlayType)!=null&&u.call(o,"video/webm")),cmaf:!0};let E=!!((c=(l=je())==null?void 0:l.isTypeSupported)!=null&&c.call(l,tM)),A=!!((f=(d=je())==null?void 0:d.isTypeSupported)!=null&&f.call(d,iM)),M=!!((h=(p=je())==null?void 0:p.isTypeSupported)!=null&&h.call(p,rM));this._codecs={h264:E,h265:A,vp9:!!((b=(m=je())==null?void 0:m.isTypeSupported)!=null&&b.call(m,av)),av1:!!((y=(S=je())==null?void 0:S.isTypeSupported)!=null&&y.call(S,sv)),aac:M,opus:!!((I=(v=je())==null?void 0:v.isTypeSupported)!=null&&I.call(v,aM)),mpeg:(E||A)&&M},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(){var t;if(!this._video)return;if(this._video.pause(),this._video.currentTime=0,this._video.removeAttribute("src"),this._video.src="",this._video.load(),this._video.remove){this._video.remove(),this._video=null;return}this._video.parentNode&&this._video.parentNode.removeChild(this._video);let e=this._video.cloneNode(!1);(t=this._video.parentNode)==null||t.replaceChild(e,this._video),this._video=null}};var ov="audio/mpeg",Fn=class{supportMp3(){return this._codecs.mp3&&this._containers.mpeg}detect(){var e,t,i,r;this._audio=document.createElement("audio");try{this._containers={mpeg:!!((t=(e=this._audio).canPlayType)!=null&&t.call(e,ov))},this._codecs={mp3:!!((r=(i=je())==null?void 0:i.isTypeSupported)!=null&&r.call(i,ov))}}catch(s){console.error(s)}try{this.destroyAudioElement()}catch(s){console.error("Error destroying audio element:",s)}}destroyAudioElement(){var t;if(!this._audio)return;if(this._audio.pause(),this._audio.currentTime=0,this._audio.removeAttribute("src"),this._audio.src="",this._audio.load(),this._audio.remove){this._audio.remove(),this._audio=null;return}this._audio.parentNode&&this._audio.parentNode.removeChild(this._audio);let e=this._audio.cloneNode(!1);(t=this._audio.parentNode)==null||t.replaceChild(e,this._audio),this._audio=null}};import{ValueSubject as nM}from"@vkontakte/videoplayer-shared/es2018";var hc=class{constructor(){this.isInited$=new nM(!1);this._displayChecker=new Vn,this._deviceChecker=new Bn(this._displayChecker),this._browserChecker=new Cn,this._videoChecker=new On(this._deviceChecker,this._browserChecker),this._audioChecker=new Fn,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)}},N=new hc;var Be=a=>{let e=R=>Ae(a,R).pipe(mc(void 0),Pe(1)),t=new pM,i=()=>t.unsubscribe(),r=Nn(Ae(a,"progress"),Ae(a,"timeupdate")).pipe(St(()=>tv(a.buffered,a.currentTime)),Pe(1)),s=N.browser.isSafari?uM({play:e("play").pipe(lM()),playing:e("playing")}).pipe(mc(void 0),Pe(1)):e("playing"),n=Ae(a,"volumechange").pipe(St(()=>({muted:a.muted,volume:a.volume})),Pe(1)),o=Ae(a,"ratechange").pipe(St(()=>a.playbackRate),Pe(1)),u=Ae(a,"error").pipe(fc(()=>!!(a.error||a.played.length)),St(()=>{var V;let R=a.error;return{id:R?`MediaError#${R.code}`:"HtmlVideoError",category:dM.VIDEO_PIPELINE,message:R?R.message:"Error event from HTML video element",thrown:(V=a.error)!=null?V:void 0}}),Pe(1)),l=Ae(a,"timeupdate").pipe(St(()=>a.currentTime),Pe(1)),c=["waiting","seeking","seeked","timeupdate"],d=new oM,f=.3,p;t.add(Nn(...c.map(R=>Ae(a,R))).subscribe(R=>{let V=a.currentTime;a.loop&&lv(p)&&lv(V)&&p>=a.duration-f&&V<=f&&d.next(p),p=V}));let h=e("pause").pipe(fc(()=>!a.error&&p!==a.duration),Pe(1)),m=Ae(a,"enterpictureinpicture").pipe(Pe(1)),b=Ae(a,"leavepictureinpicture").pipe(Pe(1)),S=new cv(ev(a));t.add(m.subscribe(()=>S.next(!0))),t.add(b.subscribe(()=>S.next(!1)));let y=new cv(pc(a)),v=Ae(a,"fullscreenchange").pipe(Pe(1));t.add(v.pipe(St(()=>pc(a))).subscribe(y));let I=.1,E=1e3,A=Ae(a,"timeupdate").pipe(St(R=>a.duration-a.currentTime<I),uv(),Pe(1)),M=Nn(A.pipe(fc(R=>!a.loop&&R)),Ae(a,"ended")).pipe(cM(E),mc(void 0),Pe(1)),P=Nn(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(R=>Ae(a,R)),A.pipe(St(R=>({type:R?"ended":"unknown"})))).pipe(St(R=>N.browser.isFirefox&&R.type==="ended"?a.readyState<2:a.readyState<3),uv(),Pe(1));return{playing$:s,pause$:h,canplay$:e("canplay"),ended$:M,looped$:d,error$:u,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:l,durationChange$:Ae(a,"durationchange").pipe(St(()=>a.duration),Pe(1)),isBuffering$:P,currentBuffer$:r,volumeState$:n,playbackRateState$:o,inPiP$:S,inFullscreen$:y,enterPip$:m,leavePip$:b,destroy:i}};import{VideoQuality as Yt}from"@vkontakte/videoplayer-shared/es2018";var Kt=a=>{switch(a){case"mobile":return Yt.Q_144P;case"lowest":return Yt.Q_240P;case"low":return Yt.Q_360P;case"sd":case"medium":return Yt.Q_480P;case"hd":case"high":return Yt.Q_720P;case"fullhd":case"full":return Yt.Q_1080P;case"quadhd":case"quad":return Yt.Q_1440P;case"ultrahd":case"ultra":return Yt.Q_2160P}};var ke=O(ot(),1),Sc=O(Ye(),1),Ai=O(er(),1);import{isNonNullable as X,isNullable as Qn,now as Av,isHigher as Gn,isHigherOrEqual as mr,isInvariantQuality as Wn,isLowerOrEqual as br,videoSizeToQuality as Pv,assertNotEmptyArray as zn,assertNonNullable as Rv}from"@vkontakte/videoplayer-shared/es2018";var bc=!1,Lt={},gv=a=>{bc=a},Sv=()=>{Lt={}},vv=a=>{a(Lt)},Ia=(a,e)=>{var t;bc&&(Lt.meta=(t=Lt.meta)!=null?t:{},Lt.meta[a]=e)},Re=class{constructor(e){this.name=e}next(e){var i,r;if(!bc)return;Lt.series=(i=Lt.series)!=null?i:{};let t=(r=Lt.series[this.name])!=null?r:[];t.push([Date.now(),e]),Lt.series[this.name]=t}};import{isHigher as TM,isHigherOrEqual as XU,isLower as yv,isLowerOrEqual as JU,isNonNullable as Un,isNullable as IM,videoHeightToQuality as qn}from"@vkontakte/videoplayer-shared/es2018";function gc(a,e,t){return!a.max&&a.min===e?"high_quality":!a.min&&a.max===t?"traffic_saving":"unknown"}function Hn(a,e,t){return!!a&&gc(a,e,t)==="high_quality"}function fr(a,e,t){return IM(a)||Un(a.min)&&Un(a.max)&&yv(a.max,a.min)||Un(a.min)&&e&&TM(a.min,e)||Un(a.max)&&t&&yv(a.max,t)}function Tv({limits:a,highestAvailableHeight:e,lowestAvailableHeight:t}){return fr({max:a!=null&&a.max?qn(a.max):void 0,min:a!=null&&a.min?qn(a.min):void 0},e?qn(e):void 0,t?qn(t):void 0)}var kv=new Re("best_bitrate"),Yn=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t;var gr=a=>(e,t)=>a*(Number(e.bitrate)-Number(t.bitrate)),Xt=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=Av()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},Kn='Assertion "ABR Tracks is empty array" failed',jn=new WeakMap,Iv=new WeakMap,Ev=new WeakMap,Ea=(a,e,t,i)=>{var u;let r=[...e].sort(gr(1)),s=[...t].sort(gr(1)),n=s.filter(l=>X(l.bitrate)&&X(a.bitrate)?a.bitrate/l.bitrate>i:!0),o=(u=(0,ke.default)(s,Math.round(s.length*r.indexOf(a)/(r.length+1))))!=null?u:(0,ke.default)(s,-1);return o&&(0,Sc.default)(n,o)?o:n.length?(0,ke.default)(n,-1):(0,ke.default)(s,0)},xa=(a,e,t,i)=>{var u;let r=jn.get(e);r||(r=[...e].sort(gr(1)),jn.set(e,r));let s=jn.get(t);s||(s=[...t].sort(gr(1)),jn.set(t,s));let n=Ev.get(a);n||(n=s.filter(l=>X(l.bitrate)&&X(a.bitrate)?a.bitrate/l.bitrate>i:!0),Ev.set(a,n));let o=(u=(0,ke.default)(s,Math.round(s.length*r.indexOf(a)/(r.length+1))))!=null?u:(0,ke.default)(s,-1);return o&&(0,Sc.default)(n,o)?o:n.length?(0,ke.default)(n,-1):(0,ke.default)(s,0)},xv=a=>"quality"in a,Xn=(a,e,t,i)=>{var n;let r=X((n=i==null?void 0:i.last)==null?void 0:n.bitrate)&&X(t==null?void 0:t.bitrate)&&i.last.bitrate<t.bitrate?a.trackCooldownIncreaseQuality:a.trackCooldownDecreaseQuality,s=t&&i&&i.history[t.id]&&Av()-i.history[t.id]<=r&&(!i.last||t.id!==i.last.id);if(t!=null&&t.id&&i&&!s&&i.recordSelection(t),s&&(i!=null&&i.last)){let o=i.last;i==null||i.recordSwitch(o);let u=xv(o)?"video":"audio",l=xv(o)?o.quality:o.bitrate;return e({message:`
|
|
8
8
|
[last ${u} selected] ${l}
|
|
9
|
-
`}),o}return i==null||i.recordSwitch(t),t},
|
|
9
|
+
`}),o}return i==null||i.recordSwitch(t),t},EM=(a,e)=>Math.log(e)/Math.log(a),Lv=({tuning:a,container:e,limits:t,panelSize:i})=>{let r=a.containerSizeFactor;if(i)return{containerSizeLimit:i,containerSizeFactor:r};if(a.usePixelRatio&&N.display.pixelRatio){let s=N.display.pixelRatio;if(a.pixelRatioMultiplier)r*=a.pixelRatioMultiplier*(s-1)+1;else{let n=a.pixelRatioLogBase,[o=0,u=0,l=0]=a.pixelRatioLogCoefficients,c=EM(n,o*s+u)+l;Number.isFinite(c)&&(r*=c)}}return Hn(t,a.highQualityLimit,a.trafficSavingLimit)&&(r*=2),{containerSizeLimit:a.limitByContainer&&e&&e.width>0&&e.height>0?{width:e.width*r,height:e.height*r}:void 0,containerSizeFactor:r}},wv=new WeakMap,vt=(a,{container:e,estimatedThroughput:t,tuning:i,limits:r,reserve:s=0,forwardBufferHealth:n,playbackRate:o,current:u,history:l,visible:c,droppedVideoMaxQualityLimit:d,stallsVideoMaxQualityLimit:f,stallsPredictedThroughput:p,abrLogger:h,panelSize:m})=>{var _,Y,J,T,k;zn(a,Kn);let{containerSizeFactor:b,containerSizeLimit:S}=Lv({container:e,tuning:i,limits:r,panelSize:m}),y=i.considerPlaybackRate&&X(o)?o:1,v=wv.get(a);v||(v=a.filter(x=>!Wn(x.quality)).sort((x,w)=>Gn(x.quality,w.quality)?-1:1),wv.set(a,v));let I=(_=(0,ke.default)(v,-1))==null?void 0:_.quality,E=(Y=(0,ke.default)(v,0))==null?void 0:Y.quality,A=fr(r,E,I),M=y*Yn(n!=null?n:.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),L={},P=null;for(let x of v){let w=!0;if(S)if(x.size)w=x.size.width<=S.width&&x.size.height<=S.height;else{let Ne=S&&Pv(S);w=Ne?br(x.quality,Ne):!0}if(!w){L[x.quality]="FitsContainer";continue}let B=p||t,ne=X(B)&&isFinite(B)&&X(x.bitrate)?B-s>=x.bitrate*M:!0,Fe=Hn(r,i.highQualityLimit,i.trafficSavingLimit)&&(r==null?void 0:r.min)===x.quality;if(!ne&&!Fe){L[x.quality]="FitsThroughput";continue}if(i.lazyQualitySwitch&&X(i.minBufferToSwitchUp)&&u&&!Wn(u.quality)&&(n!=null?n:0)<i.minBufferToSwitchUp&&Gn(x.quality,u.quality)){L[x.quality]="Buffer";continue}if(!!d&&mr(x.quality,d)&&!Fe){L[x.quality]="DroppedFramesLimit";continue}if(!!f&&mr(x.quality,f)&&!Fe){L[x.quality]="StallsLimit";continue}let Se=A||(Qn(r==null?void 0:r.max)||br(x.quality,r.max))&&(Qn(r==null?void 0:r.min)||mr(x.quality,r.min)),ve=X(c)&&!c?br(x.quality,i.backgroundVideoQualityLimit):!0;if(!Se||!ve){L[x.quality]="FitsQualityLimits";continue}P||(P=x)}P&&P.bitrate&&kv.next(P.bitrate);let R=(J=P!=null?P:(0,ke.default)(v,-1))!=null?J:a[0],V=l==null?void 0:l.last,D=Xn(i,h,R,l);return X(l)&&D.quality!==(V==null?void 0:V.quality)&&h({message:`
|
|
10
10
|
[VIDEO TRACKS ABR]
|
|
11
11
|
[available video tracks]
|
|
12
|
-
${
|
|
12
|
+
${a.map(x=>{var w,B;return`{ id: ${x.id}, quality: ${x.quality}, bitrate: ${x.bitrate}, size: ${(w=x.size)==null?void 0:w.width}:${(B=x.size)==null?void 0:B.height} }`}).join(`
|
|
13
13
|
`)}
|
|
14
14
|
|
|
15
15
|
[tuning]
|
|
16
|
-
${(0,
|
|
16
|
+
${(0,Ai.default)(i!=null?i:{}).map(([x,w])=>`${x}: ${w}`).join(`
|
|
17
17
|
`)}
|
|
18
18
|
|
|
19
19
|
[limit params]
|
|
20
|
-
containerSizeFactor: ${
|
|
21
|
-
containerSizeLimit: ${(
|
|
20
|
+
containerSizeFactor: ${b},
|
|
21
|
+
containerSizeLimit: ${(T=S==null?void 0:S.width)!=null?T:0} x ${(k=S==null?void 0:S.height)!=null?k:0},
|
|
22
22
|
estimatedThroughput: ${t},
|
|
23
23
|
stallsPredictedThroughput: ${p},
|
|
24
|
-
reserve: ${
|
|
24
|
+
reserve: ${s},
|
|
25
25
|
playbackRate: ${o},
|
|
26
|
-
playbackRateFactor: ${
|
|
26
|
+
playbackRateFactor: ${y},
|
|
27
27
|
forwardBufferHealth: ${n},
|
|
28
|
-
bitrateFactor: ${
|
|
28
|
+
bitrateFactor: ${M},
|
|
29
29
|
minBufferToSwitchUp: ${i.minBufferToSwitchUp},
|
|
30
|
-
droppedVideoMaxQualityLimit: ${
|
|
31
|
-
stallsVideoMaxQualityLimit: ${
|
|
32
|
-
limitsAreInvalid: ${
|
|
30
|
+
droppedVideoMaxQualityLimit: ${d},
|
|
31
|
+
stallsVideoMaxQualityLimit: ${f},
|
|
32
|
+
limitsAreInvalid: ${A},
|
|
33
33
|
maxQualityLimit: ${r==null?void 0:r.max},
|
|
34
34
|
minQualityLimit: ${r==null?void 0:r.min},
|
|
35
35
|
|
|
36
36
|
[limited video tracks]
|
|
37
|
-
${(0,
|
|
37
|
+
${(0,Ai.default)(L).map(([x,w])=>`${x}: ${w}`).join(`
|
|
38
38
|
`)||"All tracks are available"}
|
|
39
39
|
|
|
40
|
-
[best video track] ${
|
|
41
|
-
[selected video track] ${
|
|
42
|
-
`}),
|
|
40
|
+
[best video track] ${P==null?void 0:P.quality}
|
|
41
|
+
[selected video track] ${D==null?void 0:D.quality}
|
|
42
|
+
`}),D},Jn=(a,{container:e,estimatedThroughput:t,tuning:i,limits:r,reserve:s=0,forwardBufferHealth:n,playbackRate:o,current:u,history:l,visible:c,droppedVideoMaxQualityLimit:d,stallsVideoMaxQualityLimit:f,stallsPredictedThroughput:p,abrLogger:h,panelSize:m})=>{var Y,J,T,k,x;zn(a,Kn);let{containerSizeFactor:b,containerSizeLimit:S}=Lv({container:e,tuning:i,limits:r,panelSize:m}),y=i.considerPlaybackRate&&X(o)?o:1,v=a.filter(w=>!Wn(w.quality)).sort((w,B)=>Gn(w.quality,B.quality)?-1:1),I=(Y=(0,ke.default)(v,-1))==null?void 0:Y.quality,E=(J=(0,ke.default)(v,0))==null?void 0:J.quality,A=fr(r,E,I),M=y*Yn(n!=null?n:.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),L={},R=v.filter(w=>{let B=!0;if(S)if(w.size)B=w.size.width<=S.width&&w.size.height<=S.height;else{let xt=S&&Pv(S);B=xt?br(w.quality,xt):!0}if(!B)return L[w.quality]="FitsContainer",!1;let ne=p||t,Fe=X(ne)&&isFinite(ne)&&X(w.bitrate)?ne-s>=w.bitrate*M:!0,ie=Hn(r,i.highQualityLimit,i.trafficSavingLimit)&&(r==null?void 0:r.min)===w.quality;if(!Fe&&!ie)return L[w.quality]="FitsThroughput",!1;if(i.lazyQualitySwitch&&X(i.minBufferToSwitchUp)&&u&&!Wn(u.quality)&&(n!=null?n:0)<i.minBufferToSwitchUp&&Gn(w.quality,u.quality))return L[w.quality]="Buffer",!1;if(!!d&&mr(w.quality,d)&&!ie)return L[w.quality]="DroppedFramesLimit",!1;if(!!f&&mr(w.quality,f)&&!ie)return L[w.quality]="StallsLimit",!1;let ve=A||(Qn(r==null?void 0:r.max)||br(w.quality,r.max))&&(Qn(r==null?void 0:r.min)||mr(w.quality,r.min)),Ne=X(c)&&!c?br(w.quality,i.backgroundVideoQualityLimit):!0;return!ve||!Ne?(L[w.quality]="FitsQualityLimits",!1):!0})[0];R&&R.bitrate&&kv.next(R.bitrate);let V=(T=R!=null?R:(0,ke.default)(v,-1))!=null?T:a[0],D=l==null?void 0:l.last,_=Xn(i,h,V,l);return X(l)&&_.quality!==(D==null?void 0:D.quality)&&h({message:`
|
|
43
43
|
[VIDEO TRACKS ABR]
|
|
44
44
|
[available video tracks]
|
|
45
|
-
${
|
|
45
|
+
${a.map(w=>{var B,ne;return`{ id: ${w.id}, quality: ${w.quality}, bitrate: ${w.bitrate}, size: ${(B=w.size)==null?void 0:B.width}:${(ne=w.size)==null?void 0:ne.height} }`}).join(`
|
|
46
46
|
`)}
|
|
47
47
|
|
|
48
48
|
[tuning]
|
|
49
|
-
${(0,
|
|
49
|
+
${(0,Ai.default)(i!=null?i:{}).map(([w,B])=>`${w}: ${B}`).join(`
|
|
50
50
|
`)}
|
|
51
51
|
|
|
52
52
|
[limit params]
|
|
53
|
-
containerSizeFactor: ${
|
|
54
|
-
containerSizeLimit: ${(
|
|
53
|
+
containerSizeFactor: ${b},
|
|
54
|
+
containerSizeLimit: ${(k=S==null?void 0:S.width)!=null?k:0} x ${(x=S==null?void 0:S.height)!=null?x:0},
|
|
55
55
|
estimatedThroughput: ${t},
|
|
56
56
|
stallsPredictedThroughput: ${p},
|
|
57
|
-
reserve: ${
|
|
57
|
+
reserve: ${s},
|
|
58
58
|
playbackRate: ${o},
|
|
59
|
-
playbackRateFactor: ${
|
|
59
|
+
playbackRateFactor: ${y},
|
|
60
60
|
forwardBufferHealth: ${n},
|
|
61
|
-
bitrateFactor: ${
|
|
61
|
+
bitrateFactor: ${M},
|
|
62
62
|
minBufferToSwitchUp: ${i.minBufferToSwitchUp},
|
|
63
|
-
droppedVideoMaxQualityLimit: ${
|
|
64
|
-
stallsVideoMaxQualityLimit: ${
|
|
65
|
-
limitsAreInvalid: ${
|
|
63
|
+
droppedVideoMaxQualityLimit: ${d},
|
|
64
|
+
stallsVideoMaxQualityLimit: ${f},
|
|
65
|
+
limitsAreInvalid: ${A},
|
|
66
66
|
maxQualityLimit: ${r==null?void 0:r.max},
|
|
67
67
|
minQualityLimit: ${r==null?void 0:r.min},
|
|
68
68
|
|
|
69
69
|
[limited video tracks]
|
|
70
|
-
${(0,
|
|
70
|
+
${(0,Ai.default)(L).map(([w,B])=>`${w}: ${B}`).join(`
|
|
71
71
|
`)||"All tracks are available"}
|
|
72
72
|
|
|
73
|
-
[best video track] ${
|
|
74
|
-
[selected video track] ${
|
|
75
|
-
`}),
|
|
73
|
+
[best video track] ${R==null?void 0:R.quality}
|
|
74
|
+
[selected video track] ${_==null?void 0:_.quality}
|
|
75
|
+
`}),_},Zn=(a,e,t,{estimatedThroughput:i,tuning:r,playbackRate:s,forwardBufferHealth:n,history:o,abrLogger:u,stallsPredictedThroughput:l})=>{zn(t,Kn);let c=r.considerPlaybackRate&&X(s)?s:1,d=[...t].sort(gr(-1)),f=a.bitrate;Rv(f);let p=c*Yn(n!=null?n:.5,r.bitrateAudioFactorAtEmptyBuffer,r.bitrateAudioFactorAtFullBuffer),h,m=Ea(a,e,t,r.minVideoAudioRatio),b=l||i;X(b)&&isFinite(b)&&(h=d.find(v=>X(v.bitrate)&&X(m==null?void 0:m.bitrate)?b-f>=v.bitrate*p&&v.bitrate>=m.bitrate:!1)),h||(h=m);let S=o==null?void 0:o.last,y=h&&Xn(r,u,h,o);return X(o)&&(y==null?void 0:y.bitrate)!==(S==null?void 0:S.bitrate)&&u({message:`
|
|
76
76
|
[AUDIO TRACKS ABR]
|
|
77
77
|
[available audio tracks]
|
|
78
|
-
${t.map(
|
|
78
|
+
${t.map(v=>`{ id: ${v.id}, bitrate: ${v.bitrate} }`).join(`
|
|
79
79
|
`)}
|
|
80
80
|
|
|
81
81
|
[tuning]
|
|
82
|
-
${(0,
|
|
82
|
+
${(0,Ai.default)(r!=null?r:{}).map(([v,I])=>`${v}: ${I}`).join(`
|
|
83
83
|
`)}
|
|
84
84
|
|
|
85
85
|
[limit params]
|
|
86
86
|
estimatedThroughput: ${i},
|
|
87
87
|
stallsPredictedThroughput: ${l},
|
|
88
|
-
reserve: ${
|
|
89
|
-
playbackRate: ${
|
|
90
|
-
playbackRateFactor: ${
|
|
88
|
+
reserve: ${f},
|
|
89
|
+
playbackRate: ${s},
|
|
90
|
+
playbackRateFactor: ${c},
|
|
91
91
|
forwardBufferHealth: ${n},
|
|
92
92
|
bitrateFactor: ${p},
|
|
93
93
|
minBufferToSwitchUp: ${r.minBufferToSwitchUp},
|
|
94
94
|
|
|
95
|
-
[selected audio track] ${
|
|
96
|
-
`}),
|
|
95
|
+
[selected audio track] ${y==null?void 0:y.id}
|
|
96
|
+
`}),y},eo=(a,e,t,{estimatedThroughput:i,tuning:r,playbackRate:s,forwardBufferHealth:n,history:o,abrLogger:u,stallsPredictedThroughput:l})=>{zn(t,Kn);let c=r.considerPlaybackRate&&X(s)?s:1,d=Iv.get(t);d||(d=[...t].sort(gr(-1)),Iv.set(t,d));let f=a.bitrate;Rv(f);let p=c*Yn(n!=null?n:.5,r.bitrateAudioFactorAtEmptyBuffer,r.bitrateAudioFactorAtFullBuffer),h,m=xa(a,e,t,r.minVideoAudioRatio),b=l||i;X(b)&&isFinite(b)&&(h=d.find(v=>X(v.bitrate)&&X(m==null?void 0:m.bitrate)?b-f>=v.bitrate*p&&v.bitrate>=m.bitrate:!1)),h||(h=m);let S=o==null?void 0:o.last,y=h&&Xn(r,u,h,o);return X(o)&&(y==null?void 0:y.bitrate)!==(S==null?void 0:S.bitrate)&&u({message:`
|
|
97
97
|
[AUDIO TRACKS ABR]
|
|
98
98
|
[available audio tracks]
|
|
99
|
-
${t.map(
|
|
99
|
+
${t.map(v=>`{ id: ${v.id}, bitrate: ${v.bitrate} }`).join(`
|
|
100
100
|
`)}
|
|
101
101
|
|
|
102
102
|
[tuning]
|
|
103
|
-
${(0,
|
|
103
|
+
${(0,Ai.default)(r!=null?r:{}).map(([v,I])=>`${v}: ${I}`).join(`
|
|
104
104
|
`)}
|
|
105
105
|
|
|
106
106
|
[limit params]
|
|
107
107
|
estimatedThroughput: ${i},
|
|
108
108
|
stallsPredictedThroughput: ${l},
|
|
109
|
-
reserve: ${
|
|
110
|
-
playbackRate: ${
|
|
111
|
-
playbackRateFactor: ${
|
|
109
|
+
reserve: ${f},
|
|
110
|
+
playbackRate: ${s},
|
|
111
|
+
playbackRateFactor: ${c},
|
|
112
112
|
forwardBufferHealth: ${n},
|
|
113
113
|
bitrateFactor: ${p},
|
|
114
114
|
minBufferToSwitchUp: ${r.minBufferToSwitchUp},
|
|
115
115
|
|
|
116
|
-
[selected audio track] ${
|
|
117
|
-
`}),v};var Fe=s=>new URL(s).hostname;import{assertNever as Cy,assertNonNullable as Vy,combine as C$,debounce as V$,ErrorCategory as Oy,filter as _y,filterChanged as O$,isNonNullable as Qd,map as Pu,merge as Fy,observableFrom as _$,once as F$,Subscription as N$,ValueSubject as Gd,videoQualityToHeight as Ny,videoSizeToQuality as U$}from"@vkontakte/videoplayer-shared/es2018";var Ly=N(Ot(),1);var Ay=N(gt(),1),wy=s=>{if(s instanceof DOMException&&(0,Ay.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"))},at=async(s,e)=>{let t=s.muted;try{await s.play()}catch(i){if(!wy(i))return!1;if(e&&e(),t)return console.warn(i),!1;s.muted=!0;try{await s.play()}catch(r){return wy(r)&&(s.muted=!1,console.warn(r)),!1}}return!0};import{isNonNullable as wu,isNullable as g$,assertNonNullable as $a}from"@vkontakte/videoplayer-shared/es2018";var ky=N(nr(),1);import{isNonNullable as Py,assertNonNullable as Eu,now as m$}from"@vkontakte/videoplayer-shared/es2018";function Be(){return m$()}function qd(s){return Be()-s}function jd(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 Ry(s,e,t){let i=(...r)=>{t.apply(null,r),s.removeEventListener(e,i)};s.addEventListener(e,i)}function Qr(s,e,t,i){let r=window.XMLHttpRequest,a,n,o,u=!1,l=0,d,c,h=!1,p="arraybuffer",f=7e3,m=2e3,g=()=>{if(u)return;Eu(d);let L=qd(d),R;if(L<m){R=m-L,setTimeout(g,R);return}m*=2,m>f&&(m=f),n&&n.abort(),n=new r,E()},S=L=>(a=L,C),v=L=>(c=L,C),y=()=>(p="json",C),I=()=>{if(!u){if(--l>=0){g(),i&&i();return}u=!0,c&&c(),t&&t()}},T=L=>(h=L,C),E=()=>{d=Be(),n=new r,n.open("get",s);let L=0,R,Q=0,U=()=>(Eu(d),Math.max(d,Math.max(R||0,Q||0)));if(a&&n.addEventListener("progress",A=>{let F=Be();a.updateChunk&&A.loaded>L&&(a.updateChunk(U(),A.loaded-L),L=A.loaded,R=F)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>I())),n.addEventListener("load",()=>{if(u)return;Eu(n);let A=n.status;if(A>=200&&A<300){let{response:F,responseType:k}=n,x=F==null?void 0:F.byteLength;if(typeof x=="number"&&a){let $=x-L;$&&a.updateChunk&&a.updateChunk(U(),$)}k==="json"&&(!F||!(0,ky.default)(F).length)?I():(c&&c(),e(F))}else I()}),n.addEventListener("error",()=>{I()}),h){let A=()=>{Eu(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(Q=Be(),n.removeEventListener("readystatechange",A))};n.addEventListener("readystatechange",A)}return n.responseType=p,n.send(),C},C={withBitrateReporting:S,withParallel:T,withJSONResponse:y,withRetryCount:L=>(l=L,C),withRetryInterval:(L,R)=>(Py(L)&&(m=L),Py(R)&&(f=R),C),withTimeout:L=>(o=L,C),withFinally:v,send:E,abort:()=>{n&&(n.abort(),n=void 0),u=!0,c&&c()}};return C}var La=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 My=N(nr(),1);var Ba=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=Be(),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=Be()-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=Qr(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=Be()}_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=Be();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,My.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 S$}from"@vkontakte/videoplayer-shared/es2018";var Au=1e4,Hd=3;var v$=6e4,y$=10,T$=1,I$=500,Da=class{constructor(e){this.paused=!1;this.autoQuality=!0;this.autoQualityLimits=void 0;this.buffering=!0;this.destroyed=!1;this.videoPlayStarted=!1;this.lowLatency=!1;this.bitrate=0;this.manifest=[];this.sourceBuffer=0;this.bufferStates=[];this.sourceJitter=-1;this.waitingForFirstBufferAfterSrcChange=!1;this.params=e,this.soundProhibitedEvent$=new S$,this.chunkRateEstimator=new La(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=jd(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=jd(e),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){let e=this.params.videoElement,t=0,i=e.buffered.length;return i!==0&&(t=e.buffered.end(i-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){let{videoElement:e,logger:t}=this.params;e.addEventListener("error",()=>{var r,a;!!e.error&&!this.destroyed&&(t(`Video element error: ${(r=e.error)==null?void 0:r.code}, details: ${(a=e.error)==null?void 0:a.message}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{let i=this._getBufferSizeSec();!this.paused&&i<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(i+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){let{logger:e,videoElement:t}=this.params,i=t.buffered.length,r;i!==0&&!this.waitingForFirstBufferAfterSrcChange&&(r=t.buffered.start(i-1),t.currentTime<r&&(e("Fixup stall"),t.currentTime=r))}_selectQuality(e){let{videoElement:t}=this.params,i,r,a,n=t&&1.62*(j.display.pixelRatio||1)*t.offsetHeight||520;for(let o=0;o<this.manifest.length;++o){a=this.manifest[o];let{max:u,min:l}=this.autoQualityLimits||{};!my({limits:this.autoQualityLimits,highestAvailableHeight:this.manifest[0].video.height,lowestAvailableHeight:(0,Ly.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||wu(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){let{logger:i,videoElement:r,playerCallback:a}=this.params;this.mediaSource=new window.MediaSource,i("setting video src"),r.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,r.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});let n=()=>{Ry(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 Ba(Hd,Au,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:i,playerCallback:r}=this.params,a=!1,n=null,o=null,u=null,l=null,d=!1,c=()=>{let I=a&&(!d||d===this.rep);return I||t("Not running!"),I},h=(I,T,E)=>{u&&u.abort(),u=Qr(this.urlResolver.resolve(I,!1),T,E,()=>this._retryCallback()).withTimeout(Au).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Hd).withFinally(()=>{u=null}).send()},p=(I,T,E)=>{$a(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(I,!1),T,E,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},f=I=>{let T=i.playbackRate;i.playbackRate!==I&&(t(`Playback rate switch: ${T}=>${I}`),i.playbackRate=I)},m=I=>{this.lowLatency=I,t(`lowLatency changed to ${I}`),g()},g=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)f(1);else{let I=this._getBufferSizeSec();if(this.bufferStates.length<5){f(1);return}let E=Be()-1e4,O=0;for(let w=0;w<this.bufferStates.length;w++){let P=this.bufferStates[w];I=Math.min(I,P.buf),P.ts<E&&O++}this.bufferStates.splice(0,O),t(`update playback rate; minBuffer=${I} drop=${O} jitter=${this.sourceJitter}`);let B=I-T$;this.sourceJitter>=0?B-=this.sourceJitter/2:this.sourceJitter-=1,B>3?f(1.15):B>1?f(1.1):B>.3?f(1.05):f(1)}},S=I=>{let T,E=()=>T&&T.start?T.start.length:0,O=A=>T.start[A]/1e3,B=A=>T.dur[A]/1e3,w=A=>T.fragIndex+A,P=(A,F)=>({chunkIdx:w(A),startTS:O(A),dur:B(A),discontinuity:F}),C=()=>{let A=0;if(T&&T.dur){let F=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,k=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,x=F;this.sourceJitter>1&&(x+=this.sourceJitter-1);let $=T.dur.length-1;for(;$>=0&&(x-=T.dur[$],!(x<=0));--$);A=Math.min($,T.dur.length-1-k),A=Math.max(A,0)}return P(A,!0)},L=A=>{let F=E();if(!(F<=0)){if(wu(A)){for(let k=0;k<F;k++)if(O(k)>A)return P(k)}return C()}},R=A=>{let F=E(),k=A?A.chunkIdx+1:0,x=k-T.fragIndex;if(!(F<=0)){if(!A||x<0||x-F>y$)return t(`Resync: offset=${x} bChunks=${F} chunk=`+JSON.stringify(A)),C();if(!(x>=F))return P(k-T.fragIndex,!1)}},Q=(A,F,k)=>{l&&l.abort(),l=Qr(this.urlResolver.resolve(A,!0,this.lowLatency),F,k,()=>this._retryCallback()).withTimeout(Au).withRetryCount(Hd).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(A,F)=>{Q(I,k=>{if(!c())return;T=k;let x=!!T.lowLatency;x!==this.lowLatency&&m(x);let $=0;for(let oe=0;oe<T.dur.length;++oe)$+=T.dur[oe];$>0&&($a(this.filesFetcher),this.filesFetcher.optimizeForSegDuration($/T.dur.length)),r({name:"index",zeroTime:T.zeroTime,shiftDuration:T.shiftDuration}),this.sourceJitter=T.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,T.jitter/1e3)):1,A(L(F))},()=>this._handleNetworkError())},nextChunk:R}},v=()=>{a=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),$a(this.filesFetcher),this.filesFetcher.abortAll()};return d={start:I=>{let{videoElement:T,logger:E}=this.params,O=S(e.jidxUrl),B,w,P,C,L=0,R,Q,U,A=()=>{R&&(clearTimeout(R),R=void 0);let K=Math.max(I$,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),ye=L+K,Te=Be(),Ie=Math.min(1e4,ye-Te);L=Te;let Ve=()=>{l||c()&&O.seek(()=>{c()&&(L=Be(),F(),A())})};Ie>0?R=window.setTimeout(()=>{this.paused?A():Ve()},Ie):Ve()},F=()=>{let K;for(;K=O.nextChunk(C);)C=K,Ce(K);let ye=O.nextChunk(P);if(ye){if(P&&ye.discontinuity){E("Detected discontinuity; restarting playback"),this.paused?A():(v(),this._initPlayerWith(e));return}oe(ye)}else A()},k=(K,ye)=>{if(!c()||!this.sourceBuffer)return;let Te,Ie,Ve,Tt=At=>{window.setTimeout(()=>{c()&&k(K,ye)},At)};if(this.sourceBuffer.updating)E("Source buffer is updating; delaying appendBuffer"),Tt(100);else{let At=Be(),qt=T.currentTime;!this.paused&&T.buffered.length>1&&Q===qt&&At-U>500&&(E("Stall suspected; trying to fix"),this._fixupStall()),Q!==qt&&(Q=qt,U=At);let Xt=this._getBufferSizeSec();if(Xt>30)E(`Buffered ${Xt} seconds; delaying appendBuffer`),Tt(2e3);else try{this.sourceBuffer.appendBuffer(K),this.videoPlayStarted?(this.bufferStates.push({ts:At,buf:Xt}),g(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),ye&&ye()}catch(Ai){if(Ai.name==="QuotaExceededError")E("QuotaExceededError; delaying appendBuffer"),Ve=this.sourceBuffer.buffered.length,Ve!==0&&(Te=this.sourceBuffer.buffered.start(0),Ie=qt,Ie-Te>4&&this.sourceBuffer.remove(Te,Ie-3)),Tt(1e3);else throw Ai}}},x=()=>{w&&B&&(E([`Appending chunk, sz=${w.byteLength}:`,JSON.stringify(P)]),k(w,function(){w=null,F()}))},$=K=>e.fragUrlTemplate.replace("%%id%%",K.chunkIdx),oe=K=>{c()&&p($(K),(ye,Te)=>{if(c()){if(Te/=1e3,w=ye,P=K,n=K.startTS,Te){let Ie=Math.min(10,K.dur/Te);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*Ie:Ie}x()}},()=>this._handleNetworkError())},Ce=K=>{c()&&($a(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve($(K),!1)))},se=K=>{c()&&(e.cachedHeader=K,k(K,()=>{B=!0,x()}))};a=!0,O.seek(K=>{if(c()){if(L=Be(),!K){A();return}C=K,!g$(I)||K.startTS>I?oe(K):(P=K,F())}},I),e.cachedHeader?se(e.cachedHeader):h(e.headerUrl,se,()=>this._handleNetworkError())},stop:v,getTimestampSec:()=>n},d}_switchToQuality(e){let{logger:t,playerCallback:i}=this.params,r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),wu(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,$a(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return wu(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,i=c=>{if(!this.autoQuality)return;let h,p,f;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&c<this.bitrate&&(p=this._getBufferSizeSec(),f=c/this.bitrate,p>10&&f>.8||p>15&&f>.5||p>20&&f>.3)){e(`Not switching: buffer=${Math.floor(p)}; bitrate=${this.bitrate}; newRate=${Math.floor(c)}`);return}h=this._selectQuality(c),h?this._switchToQuality(h):e(`Could not find quality by bitrate ${c}`)},a={updateChunk:(h,p)=>{let f=Be();if(this.chunkRateEstimator.addInterval(h,f,p)){let g=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:p,duration:f-h,speed:g}),!0}},get:()=>{let h=this.chunkRateEstimator.getBitRate();return h?h*.85:0}},n=-1/0,o,u=!0,l=()=>{let c=a.get();if(c&&o&&this.autoQuality){if(u&&c>o&&qd(n)<3e4)return;i(c)}u=this.autoQuality};return{updateChunk:(c,h)=>{let p=a.updateChunk(c,h);return p&&l(),p},notifySwitch:c=>{let h=Be();c<o&&(n=h),o=c}}}_fetchManifest(e,t,i){this.manifestRequest=Qr(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(Au).withRetryCount(this.params.config.manifestRetryMaxCount).withRetryInterval(this.params.config.manifestRetryInterval,this.params.config.manifestRetryMaxInterval).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(){let{videoElement:e}=this.params;at(e,()=>{this.soundProhibitedEvent$.next()}).then(t=>{t||(this.params.liveOffset.pause(),this.params.videoState.setState("paused"))})}_handleManifestUpdate(e){let{logger:t,playerCallback:i,videoElement:r}=this.params,a=n=>{let o=[];return n!=null&&n.length?(n.forEach((u,l)=>{var d,c;u.video&&r.canPlayType(u.codecs).replace(/no/,"")&&((c=(d=window.MediaSource)==null?void 0:d.isTypeSupported)!=null&&c.call(d,u.codecs))&&(u.index=l,o.push(u))}),o.sort(function(u,l){return u.video&&l.video?l.video.height-u.video.height:l.bitrate-u.bitrate}),o):(i({name:"error",type:"empty_manifest"}),[])};this.manifest=a(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),i({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},v$))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var Dy=N(Ji(),1);import{debounce as x$,filter as By,fromEvent as E$,interval as w$,isHigher as A$,isInvariantQuality as P$,isLower as k$,merge as R$,Subject as $y,Subscription as M$}from"@vkontakte/videoplayer-shared/es2018";var zd=class{constructor(){this.onDroopedVideoFramesLimit$=new $y;this.subscription=new M$;this.playing=!1;this.tracks=[];this.forceChecker$=new $y;this.isForceCheckCounter=0;this.prevTotalVideoFrames=0;this.prevDroppedVideoFrames=0;this.limitCounts={};this.handleChangeVideoQuality=()=>{let e=this.tracks.find(({size:t})=>(t==null?void 0:t.height)===this.video.videoHeight&&(t==null?void 0:t.width)===this.video.videoWidth);e&&!P$(e.quality)&&this.onChangeQuality(e.quality)};this.checkDroppedFrames=()=>{var n;let{totalVideoFrames:e,droppedVideoFrames:t}=this.video.getVideoPlaybackQuality(),i=e-this.prevTotalVideoFrames,r=t-this.prevDroppedVideoFrames,a=1-(i-r)/i;!isNaN(a)&&a>0&&this.log({message:`[dropped]. current dropped percent: ${a}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(a)&&a>=this.droppedFramesChecker.percentLimit&&A$(this.currentQuality,this.droppedFramesChecker.minQualityBanLimit)&&(this.limitCounts[this.currentQuality]=((n=this.limitCounts[this.currentQuality])!=null?n:0)+1,this.maxQualityLimit=this.getMaxQualityLimit(this.currentQuality),this.currentTimer&&window.clearTimeout(this.currentTimer),this.currentTimer=window.setTimeout(()=>this.maxQualityLimit=this.getMaxQualityLimit(),this.droppedFramesChecker.qualityUpWaitingTime),this.onDroopedVideoFramesLimitTrigger()),this.savePrevFrameCounts(e,t)}}connect(e){this.log=e.logger.createComponentLog("DroppedFramesManager"),this.video=e.video,this.isAuto=e.isAuto,this.tracks=e.tracks,this.droppedFramesChecker=e.droppedFramesChecker,this.subscription.add(e.playing$.subscribe(()=>this.playing=!0)),this.subscription.add(e.pause$.subscribe(()=>this.playing=!1)),this.isEnabled&&this.subscribe()}destroy(){this.currentTimer&&window.clearTimeout(this.currentTimer),this.subscription.unsubscribe()}get droppedVideoMaxQualityLimit(){return this.maxQualityLimit}subscribe(){this.subscription.add(E$(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=w$(this.droppedFramesChecker.checkTime).pipe(By(()=>this.playing),By(()=>{let r=!!this.isForceCheckCounter;return r&&(this.isForceCheckCounter-=1),!r})),t=this.forceChecker$.pipe(x$(this.droppedFramesChecker.checkTime)),i=R$(e,t);this.subscription.add(i.subscribe(this.checkDroppedFrames))}onChangeQuality(e){this.currentQuality=e;let{totalVideoFrames:t,droppedVideoFrames:i}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,i),this.isForceCheckCounter=this.droppedFramesChecker.tickCountAfterQualityChange,this.forceChecker$.next()}onDroopedVideoFramesLimitTrigger(){this.isAuto.getState()&&(this.log({message:`[onDroopedVideoFramesLimit]. maxQualityLimit: ${this.maxQualityLimit}`}),this.onDroopedVideoFramesLimit$.next())}getMaxQualityLimit(e){var i,r;let t=(r=(i=(0,Dy.default)(this.limitCounts).filter(([,a])=>a>=this.droppedFramesChecker.countLimit).sort(([a],[n])=>k$(a,n)?-1:1))==null?void 0:i[0])==null?void 0:r[0];return e!=null?e:t}get isEnabled(){return this.droppedFramesChecker.enabled&&this.isDroppedFramesCheckerSupport}get isDroppedFramesCheckerSupport(){return!!this.video&&typeof this.video.getVideoPlaybackQuality=="function"}savePrevFrameCounts(e,t){this.prevTotalVideoFrames=e,this.prevDroppedVideoFrames=t}},Gr=zd;import{map as L$,Observable as B$}from"@vkontakte/videoplayer-shared/es2018";import{fromEvent as $$}from"@vkontakte/videoplayer-shared/es2018";var Ca=()=>{var s;return!!((s=window.documentPictureInPicture)!=null&&s.window)||!!document.pictureInPictureElement};var D$=(s,e)=>new B$(t=>{if(!window.IntersectionObserver)return;let i={root:null},r=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||Ca()))},{...i,...e});r.observe(s);let a=$$(document,"visibilitychange").pipe(L$(n=>!document.hidden||Ca())).subscribe(n=>t.next(n));return()=>{r.unobserve(s),a.unsubscribe()}}),Et=D$;var q$=["paused","playing","ready"],j$=["paused","playing","ready"],Va=class{constructor(e){this.subscription=new N$;this.videoState=new G("stopped");this.representations$=new Gd([]);this.droppedFramesManager=new Gr;this.maxSeekBackTime$=new Gd(1/0);this.zeroTime$=new Gd(void 0);this.liveOffset=new or;this._dashCb=e=>{var t,i,r,a;switch(e.name){case"buffering":{let n=e.isBuffering;this.params.output.isBuffering$.next(n);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,category:Oy.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{let n=e.manifest,o=[];for(let u of n){let l=(t=u.name)!=null?t:u.index.toString(10),d=(i=Bi(u.name))!=null?i:U$(u.video),c=u.bitrate/1e3,h={...u.video};if(!d)continue;let p={id:l,quality:d,bitrate:c,size:h};o.push({track:p,representation:u})}this.representations$.next(o),this.params.output.availableVideoTracks$.next(o.map(({track:u})=>u)),((r=this.videoState.getTransition())==null?void 0:r.to)==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let n=e.quality,o=(a=this.representations$.getValue().find(({representation:u})=>u===n))==null?void 0:a.track;this.params.output.hostname$.next(new URL(n.headerUrl,this.params.source.url).hostname),Qd(o)&&this.params.output.currentVideoTrack$.next(o);break}case"bandwidth":{let{size:n,duration:o}=e;this.params.dependencies.throughputEstimator.addRawSpeed(n,o);break}case"index":{this.maxSeekBackTime$.next(e.shiftDuration||0),this.zeroTime$.next(e.zeroTime);break}}};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; seekState: ${JSON.stringify(a)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"));return}if(t)return;let n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if((0,Wd.default)(j$,e)&&(n||o)){this.prepare();return}if((r==null?void 0:r.to)!=="paused"&&a.state==="requested"&&(0,Wd.default)(q$,e)){this.seek(a.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(Se(this.params.source.url));return;case"manifest_ready":this.videoState.startTransitionTo("ready"),this.prepare();break;case"ready":if(i==="paused")this.videoState.setState("paused");else if(i==="playing"){this.videoState.startTransitionTo("playing");let u=r==null?void 0:r.from;u&&u==="ready"&&this.dash.catchUp(),this.dash.play()}return;case"playing":i==="paused"&&(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.dash.pause());return;case"paused":if(i==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.dash.play(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let u=this.liveOffset.getTotalOffset();u>=this.maxSeekBackTime$.getValue()&&(u=0,this.liveOffset.resetTo(u)),this.liveOffset.resume(),this.params.output.position$.next(-u/1e3),this.dash.reinit(Se(this.params.source.url,u))}return;default:return Cy(e)}};this.textTracksManager=new xt(e.source.url),this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=r=>{e.output.error$.next({id:"DashLiveProvider",category:Oy.WTF,message:"DashLiveProvider internal logic error",thrown:r})};this.subscription.add(Fy(this.videoState.stateChangeStarted$.pipe(Pu(r=>({transition:r,type:"start"}))),this.videoState.stateChangeEnded$.pipe(Pu(r=>({transition:r,type:"end"})))).subscribe(({transition:r,type:a})=>{this.log({message:`[videoState change] ${a}: ${JSON.stringify(r)}`})})),this.video=tt(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(Fe(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=st(this.video);this.subscription.add(()=>i.destroy()),this.subscription.add(this.representations$.pipe(Pu(r=>r.map(({track:a})=>a)),_y(r=>!!r.length),F$()).subscribe(r=>this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:r}))),this.subscription.add(i.canplay$.subscribe(()=>{var r;((r=this.videoState.getTransition())==null?void 0:r.to)==="ready"&&this.videoState.setState("ready")},t)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused")},t)).add(i.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.videoState.setState("playing")},t)).add(i.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(O$(),Pu(r=>-r/1e3)).subscribe(this.params.output.duration$)).add(C$({zeroTime:this.zeroTime$.pipe(_y(Qd)),position:i.timeUpdate$}).subscribe(({zeroTime:r,position:a})=>this.params.output.liveTime$.next(r+a*1e3),t)).add(zt(this.video,this.params.desiredState.isLooped,t)).add(rt(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(It(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(Et(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:r,min:a}})=>{this.dash.setAutoQualityLimits({max:r&&Ny(r),min:a&&Ny(a)}),this.params.output.autoVideoTrackLimits$.next({max:r,min:a})})).add(this.videoState.stateChangeEnded$.subscribe(r=>{var a;switch(r.to){case"stopped":this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState("stopped");break;case"manifest_ready":case"ready":((a=this.params.desiredState.playbackState.getTransition())==null?void 0:a.to)==="ready"&&this.params.desiredState.playbackState.setState("ready");break;case"paused":this.params.desiredState.playbackState.setState("paused");break;case"playing":this.params.desiredState.playbackState.setState("playing");break;default:return Cy(r.to)}},t)).add(Fy(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,_$(["init"])).pipe(V$(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),it(this.video)}createLiveDashPlayer(){let e=new Da({videoElement:this.video,videoState:this.videoState,playbackState:this.params.desiredState.playbackState,liveOffset:this.liveOffset,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode,manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){var l,d,c,h,p,f;let e=this.representations$.getValue(),t=(d=(l=this.params.desiredState.videoTrack.getTransition())==null?void 0:l.to)!=null?d:this.params.desiredState.videoTrack.getState(),i=(h=(c=this.params.desiredState.autoVideoTrackSwitching.getTransition())==null?void 0:c.to)!=null?h:this.params.desiredState.autoVideoTrackSwitching.getState(),r=!i&&Qd(t)?t:Wt(e.map(({track:m})=>m),{container:this.video.getBoundingClientRect(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),a=r==null?void 0:r.id,n=this.params.desiredState.videoTrack.getTransition(),o=(p=this.params.desiredState.videoTrack.getState())==null?void 0:p.id,u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(r&&(n||a!==o)&&this.setVideoTrack(r),u&&this.setAutoQuality(i),n||u||a!==o){let m=(f=e.find(({track:g})=>g.id===a))==null?void 0:f.representation;Vy(m,"Representations missing"),this.dash.startPlay(m,i)}}setVideoTrack(e){var i;let t=(i=this.representations$.getValue().find(({track:r})=>r.id===e.id))==null?void 0:i.representation;Vy(t,`No such representation ${e.id}`),this.dash.switchByName(t.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),r=t==="paused"&&i==="paused",a=-e,n=a<=this.maxSeekBackTime$.getValue()?a:0;this.params.output.position$.next(e/1e3),this.dash.reinit(Se(this.params.source.url,n)),r&&this.dash.pause(),this.liveOffset.resetTo(n,r)}};var Uy=Va;var ex=N(gt(),1);var $e=(s,e)=>{let t=0;for(let i=0;i<s.length;i++){let r=s.start(i)*1e3,a=s.end(i)*1e3;r<=e&&e<=a&&(t=a)}return Math.max(t-e,0)};import{assertNever as wC,assertNonNullable as AC,debounce as PC,ErrorCategory as XI,filter as Dp,filterChanged as el,fromEvent as kC,isNonNullable as JI,isNullable as RC,map as Cp,merge as tl,observableFrom as Vp,once as ZI,Subscription as MC}from"@vkontakte/videoplayer-shared/es2018";var ku=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}},Wr=class extends ku{constructor(){super(),this.listeners||ku.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)}},Oa=class{constructor(){Object.defineProperty(this,"signal",{value:new Wr,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch(r){typeof document!="undefined"?document.createEvent?(t=document.createEvent("Event"),t.initEvent("abort",!1,!1)):(t=document.createEventObject(),t.type="abort"):t={type:"abort",bubbles:!1,cancelable:!1}}let i=e;if(i===void 0)if(typeof document=="undefined")i=new Error("This operation was aborted"),i.name="AbortError";else try{i=new DOMException("signal is aborted without reason")}catch(r){i=new Error("This operation was aborted"),i.name="AbortError"}this.signal.reason=i,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol!="undefined"&&Symbol.toStringTag&&(Oa.prototype[Symbol.toStringTag]="AbortController",Wr.prototype[Symbol.toStringTag]="AbortSignal");function Ru(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 Yd(s){typeof s=="function"&&(s={fetch:s});let{fetch:e,Request:t=e.Request,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r=!1}=s;if(!Ru({fetch:e,Request:t,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r}))return{fetch:e,Request:a};let a=t;(a&&!a.prototype.hasOwnProperty("signal")||r)&&(a=function(l,d){let c;d&&d.signal&&(c=d.signal,delete d.signal);let h=new t(l,d);return c&&Object.defineProperty(h,"signal",{writable:!1,enumerable:!1,configurable:!0,value:c}),h},a.prototype=t.prototype);let n=e;return{fetch:(u,l)=>{let d=a&&a.prototype.isPrototypeOf(u)?u.signal:l?l.signal:void 0;if(d){let c;try{c=new DOMException("Aborted","AbortError")}catch(p){c=new Error("Aborted"),c.name="AbortError"}if(d.aborted)return Promise.reject(c);let h=new Promise((p,f)=>{d.addEventListener("abort",()=>f(c),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([h,n(u,l)])}return n(u,l)},Request:a}}var H$=()=>"fetch"in window,_a=H$()&&Ru({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),qy=_a?Yd({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,wt=_a?qy.fetch:window.fetch,Vj=_a?qy.Request:window.Request,ae=_a?Oa:window.AbortController,Oj=_a?Wr:window.AbortSignal;var kp=N(Fa(),1);var kT=N(PT(),1);import{ErrorCategory as Ua}from"@vkontakte/videoplayer-shared/es2018";var Mu=s=>{if(!s)return{id:"EmptyResponse",category:Ua.PARSER,message:"Empty response"};if(s.length<=2&&s.match(/^\d+$/))return{id:`UVError#${s}`,category:Ua.NETWORK,message:`UV Error ${s}`};let e=(0,kT.default)(s).substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:Ua.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:Ua.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:Ua.PARSER,message:"Response is valid XML, but parser failed"}};var Ne=(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 wp,assertNonNullable as ss,combine as as,ErrorCategory as Ft,filter as Qu,filterChanged as Tn,flattenObject as In,fromEvent as Ti,getTraceSubscriptionMethod as oC,interval as Ap,isNonNullable as xn,isNullable as zI,map as ns,merge as pr,now as Pp,Subject as Gu,Subscription as QI,tap as uC,throttle as lC,ValueSubject as he}from"@vkontakte/videoplayer-shared/es2018";var $u=N(gt(),1),ts=N(Ot(),1),Du=N(Fa(),1);var RD=(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)},MD=s=>window.clearTimeout(s),RT=s=>typeof s=="function"&&(s==null?void 0:s.toString().endsWith("{ [native code] }")),MT=!RT(window.requestIdleCallback)||!RT(window.cancelIdleCallback),Yr=MT?RD:window.requestIdleCallback,Yt=MT?MD:window.cancelIdleCallback;var CI=N(eu(),1);import{assertNever as LD,ErrorCategory as LT,Subject as BT}from"@vkontakte/videoplayer-shared/es2018";var BD=18,$T=!1;try{$T=j.browser.isSafari&&!!j.browser.safariVersion&&j.browser.safariVersion<=BD}catch(s){console.error(s)}var tp=class{constructor(e){this.bufferFull$=new BT;this.error$=new BT;this.queue=[];this.currentTask=null;this.destroyed=!1;this.abortRequested=!1;this.completeTask=()=>{var e;try{if(this.currentTask){let t=(e=this.currentTask.signal)==null?void 0:e.aborted;this.currentTask.callback(!t),this.currentTask=null}this.queue.length&&this.pull()}catch(t){this.error$.next({id:"BufferTaskQueueUnknown",category:LT.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(i=>{let r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(r=>{let a={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(a),this.pull()})}async abort(e){return new Promise(t=>{let i,r=a=>{this.abortRequested=!1,t(a)};$T&&e?i={operation:"safariAbort",init:e,callback:r}:i={operation:"abort",callback:r};for(let{callback:a}of this.queue)a(!1);this.abortRequested=!0,i&&(this.queue=[i]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){var r;if((this.buffer.updating||this.currentTask||this.destroyed)&&!this.abortRequested)return;let e=this.queue.shift();if(!e)return;if((r=e.signal)!=null&&r.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(a){a instanceof DOMException&&a.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):a instanceof DOMException&&a.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:LT.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:a}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){let{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:LD(t)}}},DT=tp;var Kr=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 Ci,assertNonNullable as nt,ErrorCategory as Si,fromEvent as vp,getExponentialDelay as yp,isNonNullable as es,isNullable as Ue,now as Bu,once as Y0,Subject as K0,Subscription as X0,ValueSubject as dr}from"@vkontakte/videoplayer-shared/es2018";var X=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let i=this.readUint32();this.type=this.readString(4),this.size32=i<=e.buffer.byteLength-e.byteOffset?i:NaN;let r=this.size32?this.size32-8:void 0,a=e.byteOffset+this.cursor;this.size64=0,this.usertype=0,this.content=new DataView(e.buffer,a,r)}get id(){return this.type}get size(){return this.size32}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t="ascii"){let r=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,r}readUint8(){let e=this.source.getUint8(this.cursor);return this.cursor+=1,e}readUint16(){let e=this.source.getUint16(this.cursor);return this.cursor+=2,e}readUint32(){let e=this.source.getUint32(this.cursor);return this.cursor+=4,e}readUint64(){let e=this.source.getBigInt64(this.cursor);return this.cursor+=8,e}};var Xr=class extends X{};var qa=class extends X{constructor(t,i){super(t,i);this.ondemandPrefix="ondemandlivejson";this.ondemandDataReceivedKey="t-in";this.ondemandDataPreparedKey="t-out";let r=this.content.byteOffset,a=r+this.content.byteLength,n=new TextDecoder("ascii").decode(this.content.buffer.slice(r,a)).split(this.ondemandPrefix)[1],o=JSON.parse(n);this.serverDataReceivedTimestamp=o[this.ondemandDataReceivedKey],this.serverDataPreparedTime=o[this.ondemandDataPreparedKey]}};var ja=class extends X{constructor(e,t){super(e,t),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let i=this.size-this.cursor;for(;i;){let r=this.readString(4);this.compatibleBrands.push(r),i-=4}}};var Ha=class extends X{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ue=class extends X{constructor(e,t){super(e,t);let i=this.readUint32();this.version=i>>>24,this.flags=i&16777215}};var za=class extends ue{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.timescale=this.readUint32(),this.duration=this.readUint32(),this.rate=this.readUint32(),this.volume=this.readUint16()}};var Qa=class extends X{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ga=class extends X{constructor(e,t){super(e,t),this.data=this.content}};var lr=class extends ue{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e,t){super(e,t),this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let i=0;i<this.referenceCount;i++){let r=this.readUint32(),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 Wa=class extends X{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ya=class extends X{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ka=class extends ue{constructor(e,t){switch(super(e,t),this.readUint8()){case 0:this.stereoMode=0;break;case 1:this.stereoMode=1;break;case 2:this.stereoMode=2;break;case 3:this.stereoMode=3;break;case 4:this.stereoMode=4;break}this.cursor+=1}};var Xa=class extends ue{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var Ja=class extends ue{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var Za=class extends X{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var en=class extends ue{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.trackId=this.readUint32(),this.cursor+=4,this.duration=this.readUint32(),this.cursor+=8,this.layer=this.readUint16(),this.alternateGroup=this.readUint16(),this.cursor+=2,this.cursor+=2,this.matrix=[[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()]],this.width=this.readUint32(),this.height=this.readUint32()}};var tn=class extends X{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var rn=class extends X{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var sn=class extends ue{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var an=class extends X{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var nn=class extends ue{constructor(e,t){super(e,t),this.trackId=this.readUint32(),this.flags&1&&(this.baseDataOffset=this.readUint64()),this.flags&2&&(this.sampleDescriptionIndex=this.readUint32()),this.flags&8&&(this.defaultSampleDuration=this.readUint32()),this.flags&16&&(this.defaultSampleSize=this.readUint32()),this.flags&32&&(this.defaultSampleFlags=this.readUint32())}};var on=class extends ue{constructor(t,i){super(t,i);this.baseMediaDecodeTime32=0;this.baseMediaDecodeTime64=BigInt(0);this.version===1?this.baseMediaDecodeTime64=this.readUint64():this.baseMediaDecodeTime32=this.readUint32()}get baseMediaDecodeTime(){return this.version===1?this.baseMediaDecodeTime64:this.baseMediaDecodeTime32}};var un=class extends ue{constructor(t,i){super(t,i);this.sampleDuration=[];this.sampleSize=[];this.sampleFlags=[];this.sampleCompositionTimeOffset=[];this.optionalFields=0;this.sampleCount=this.readUint32(),this.flags&1&&(this.dataOffset=this.readUint32()),this.flags&4&&(this.firstSampleFlags=this.readUint32());for(let r=0;r<this.sampleCount;r++)this.flags&256&&this.sampleDuration.push(this.readUint32()),this.flags&512&&this.sampleSize.push(this.readUint32()),this.flags&1024&&this.sampleFlags.push(this.readUint32()),this.flags&2048&&this.sampleCompositionTimeOffset.push(this.readUint32())}};var ln=class extends X{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var cn=class extends ue{constructor(e,t){super(e,t),this.entryCount=this.readUint32(),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+8,this.content.byteLength-8))}};var dn=class extends X{constructor(e,t){super(e,t),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+78,this.content.byteLength-78))}};var DD={ftyp:ja,moov:Ha,mvhd:za,moof:Qa,mdat:Ga,sidx:lr,trak:Wa,mdia:Za,mfhd:sn,tkhd:en,traf:an,tfhd:nn,tfdt:on,trun:un,minf:tn,sv3d:Ya,st3d:Ka,prhd:Xa,proj:rn,equi:Ja,uuid:qa,stbl:ln,stsd:cn,avc1:dn,unknown:Xr},bi=class s{constructor(e={}){this.options={offset:0,...e}}parse(e){let t=[],i=this.options.offset;for(;i<e.byteLength;)try{let a=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+i+4,4)),n=this.createBox(a,new DataView(e.buffer,e.byteOffset+i));if(!n.size)break;t.push(n),i+=n.size}catch(r){break}return t}createBox(e,t){let i=DD[e];return i?new i(t,new s):new Xr(t,new s)}};var Di=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{var i,r,a;(a=(i=this.index)[r=t.type])!=null||(i[r]=[]),this.index[t.type].push(t),t.children.length>0&&this.indexBoxLevel(t.children)})}find(e){return this.index[e]&&this.index[e][0]?this.index[e][0]:null}findAll(e){return this.index[e]||[]}};var VD=new TextDecoder("ascii"),OD=s=>VD.decode(new DataView(s.buffer,s.byteOffset+4,4))==="ftyp",_D=s=>{let e=new lr(s,new bi),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})},FD=(s,e)=>{let i=new bi().parse(s),r=new Di(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)},ND=s=>{let t=new bi().parse(s),i=new Di(t),r={},a=i.findAll("uuid");return a.length?a[a.length-1]:r},UD=s=>{var r;let t=new bi().parse(s);return(r=new Di(t).find("sidx"))==null?void 0:r.timescale},qD=(s,e)=>{let i=new bi().parse(s),a=new Di(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,h)=>c+h,0):l=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+l)/e*1e3},jD=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 bi().parse(s),r=new Di(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},CT={validateData:OD,parseInit:jD,getIndexRange:()=>{},parseSegments:_D,parseFeedableSegmentChunk:FD,getChunkEndTime:qD,getServerLatencyTimestamps:ND,getTimescaleFromIndex:UD};var hn=N(gt(),1);import{assertNonNullable as rp,isNonNullable as FT,isNullable as zD}from"@vkontakte/videoplayer-shared/es2018";import{assertNever as HD}from"@vkontakte/videoplayer-shared/es2018";var VT={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"}},OT=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=pn(s,t),r=i in VT,a=r?VT[i].type:"binary",n=s.getUint8(t),o=0;n&128?o=1:n&64?o=2:n&32?o=3:n&16?o=4:n&8?o=5:n&4?o=6:n&2?o=7:n&1&&(o=8);let u=new DataView(s.buffer,s.byteOffset+t+1,o-1),l=n&255>>o,d=pn(u),c=l*2**((o-1)*8)+d,h=t+o,p;return h+c>s.byteLength?p=new DataView(s.buffer,s.byteOffset+h):p=new DataView(s.buffer,s.byteOffset+h,c),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:a,tagHeaderSize:h,tagSize:h+c,value:p,valueSize:c}},pn=(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},_t=(s,e)=>{switch(e){case"int":return s.getInt8(0);case"uint":return pn(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:HD(e)}},cr=(s,e)=>{let t=0;for(;t<s.byteLength;){let i=new DataView(s.buffer,s.byteOffset+t),r=OT(i);if(!e(r))return;r.type==="master"&&cr(r.value,e),t=r.value.byteOffset-s.byteOffset+r.valueSize}},_T=s=>{if(s.getUint32(0)!==440786851)return!1;let e,t,i,r=OT(s);return cr(r.value,({tag:a,type:n,value:o})=>(a===17143?e=_t(o,n):a===17026?t=_t(o,n):a===17029&&(i=_t(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)};var NT=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],QD=[231,22612,22743,167,171,163,160,175],GD=s=>{let e,t,i,r,a=!1,n=!1,o=!1,u,l,d=!1,c=0;return cr(s,({tag:h,type:p,value:f,valueSize:m})=>{if(h===21419){let g=_t(f,p);l=pn(g)}else h!==21420&&(l=void 0);return h===408125543?(e=f.byteOffset,t=f.byteOffset+m):h===357149030?a=!0:h===290298740?n=!0:h===2807729?i=_t(f,p):h===17545?r=_t(f,p):h===21420&&l===475249515?u=_t(f,p):h===374648427?cr(f,({tag:g,type:S,value:v})=>g===30321?(d=_t(v,S)===1,!1):!0):a&&n&&(0,hn.default)(NT,h)&&(o=!0),!o}),rp(e,"Failed to parse webm Segment start"),rp(t,"Failed to parse webm Segment end"),rp(r,"Failed to parse webm Segment duration"),i=i!=null?i:1e6,{segmentStart:Math.round(e/1e9*i*1e3),segmentEnd:Math.round(t/1e9*i*1e3),timeScale:i,segmentDuration:Math.round(r/1e9*i*1e3),cuesSeekPosition:u,is3dVideo:d,stereoMode:c,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},WD=s=>{if(zD(s.cuesSeekPosition))return;let e=s.segmentStart+s.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},YD=(s,e)=>{let t=!1,i=!1,r=o=>FT(o.time)&&FT(o.position),a=[],n;return cr(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=_t(l,u));break;case 183:break;case 241:n&&(n.position=_t(l,u));break;default:t&&(0,hn.default)(NT,o)&&(i=!0)}return!(t&&i)}),n&&r(n)&&a.push(n),a.map((o,u)=>{let{time:l,position:d}=o,c=a[u+1];return{status:"none",time:{from:l,to:c?c.time:e.segmentDuration},byte:{from:e.segmentStart+d,to:c?e.segmentStart+c.position-1:e.segmentEnd-1}}})},KD=s=>{let e=0,t=!1;try{cr(s,i=>i.tag===524531317?i.tagSize<=s.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):(0,hn.default)(QD,i.tag)?(e+i.tagSize<=s.byteLength&&(e+=i.tagSize,t||(t=(0,hn.default)([163,160,175],i.tag))),!0):!1)}catch(i){}return e>0&&e<=s.byteLength&&t?new DataView(s.buffer,s.byteOffset,e):null},UT={validateData:_T,parseInit:GD,getIndexRange:WD,parseSegments:YD,parseFeedableSegmentChunk:KD};var fn=s=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(s);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return UT;case"mp4":return CT}}throw new ReferenceError(`Unsupported mime type ${s}`)};var bp=N(lp(),1),MI=N(Ji(),1),LI=N(cp(),1),BI=N(Ot(),1),gp=N(nr(),1);var II=N(gt(),1),Zr=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,II.default)(["6E","7A","F4"],o)}}return!1};import{isNonNullable as G0,isNullable as kI}from"@vkontakte/videoplayer-shared/es2018";var Lu=s=>{if(s.includes("/")){let e=s.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(s)};var xI=s=>{var e;try{let t=z0(),i=s.match(t),{groups:r}=i!=null?i:{};if(r){let a={};if(r.extensions){let u=r.extensions.toLowerCase().match(/(?:[0-9a-wy-z](?:-[a-z0-9]{2,8})+)/g);Array.from(u||[]).forEach(l=>{a[l[0]]=l.slice(2)})}let n=(e=r.variants)==null?void 0:e.split(/-/).filter(u=>u!==""),o={extlang:r.extlang,langtag:r.langtag,language:r.language,privateuse:r.privateuse||r.privateuse2,region:r.region,script:r.script,extensions:a,variants:n};return Object.keys(o).forEach(u=>{let l=o[u];(typeof l=="undefined"||l==="")&&delete o[u]}),o}return null}catch(t){return null}};function z0(){let s="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",d=`^(?:(?<langtag>${`
|
|
118
|
-
(?<language>${`(?:[a-z]{2,3}(?:-${
|
|
116
|
+
[selected audio track] ${y==null?void 0:y.id}
|
|
117
|
+
`}),y};var Te=a=>new URL(a).hostname;import{assertNever as Uv,assertNonNullable as qv,combine as jM,debounce as QM,ErrorCategory as Hv,filter as jv,filterChanged as GM,isNonNullable as Ec,map as ao,merge as Qv,observableFrom as WM,once as zM,Subscription as YM,ValueSubject as xc,videoQualityToHeight as Gv,videoSizeToQuality as KM}from"@vkontakte/videoplayer-shared/es2018";var _v=O(ot(),1);var Mv=O(Ye(),1),$v=a=>{if(a instanceof DOMException&&(0,Mv.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"))},Ve=async(a,e)=>{let t=a.muted;try{await a.play()}catch(i){if(!$v(i))return!1;if(e&&e(),t)return console.warn(i),!1;a.muted=!0;try{await a.play()}catch(r){return $v(r)&&(a.muted=!1,console.warn(r)),!1}}return!0};import{isNonNullable as io,isNullable as AM,assertNonNullable as Pa}from"@vkontakte/videoplayer-shared/es2018";var Cv=O(dr(),1);import{isNonNullable as Dv,assertNonNullable as to,now as xM}from"@vkontakte/videoplayer-shared/es2018";function fe(){return xM()}function vc(a){return fe()-a}function yc(a){let e=a.split("/"),t=e.slice(0,e.length-1).join("/"),i=/^([a-z]+:)?\/\//i,r=n=>i.test(n);return{resolve:(n,o,u=!1)=>{r(n)||(n.startsWith("/")||(n="/"+n),n=t+n);let l=n.indexOf("?")>-1?"&":"?";return u&&(n+=l+"lowLat=1",l="&"),o&&(n+=l+"_rnd="+Math.floor(999999999*Math.random())),n}}}function Bv(a,e,t){let i=(...r)=>{t.apply(null,r),a.removeEventListener(e,i)};a.addEventListener(e,i)}function Sr(a,e,t,i){let r=window.XMLHttpRequest,s,n,o,u=!1,l=0,c,d,f=!1,p="arraybuffer",h=7e3,m=2e3,b=()=>{if(u)return;to(c);let D=vc(c),_;if(D<m){_=m-D,setTimeout(b,_);return}m*=2,m>h&&(m=h),n&&n.abort(),n=new r,A()},S=D=>(s=D,V),y=D=>(d=D,V),v=()=>(p="json",V),I=()=>{if(!u){if(--l>=0){b(),i&&i();return}u=!0,d&&d(),t&&t()}},E=D=>(f=D,V),A=()=>{c=fe(),n=new r,n.open("get",a);let D=0,_,Y=0,J=()=>(to(c),Math.max(c,Math.max(_||0,Y||0)));if(s&&n.addEventListener("progress",T=>{let k=fe();s.updateChunk&&T.loaded>D&&(s.updateChunk(J(),T.loaded-D),D=T.loaded,_=k)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>I())),n.addEventListener("load",()=>{if(u)return;to(n);let T=n.status;if(T>=200&&T<300){let{response:k,responseType:x}=n,w=k==null?void 0:k.byteLength;if(typeof w=="number"&&s){let B=w-D;B&&s.updateChunk&&s.updateChunk(J(),B)}x==="json"&&(!k||!(0,Cv.default)(k).length)?I():(d&&d(),e(k))}else I()}),n.addEventListener("error",()=>{I()}),f){let T=()=>{to(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(Y=fe(),n.removeEventListener("readystatechange",T))};n.addEventListener("readystatechange",T)}return n.responseType=p,n.send(),V},V={withBitrateReporting:S,withParallel:E,withJSONResponse:v,withRetryCount:D=>(l=D,V),withRetryInterval:(D,_)=>(Dv(D)&&(m=D),Dv(_)&&(h=_),V),withTimeout:D=>(o=D,V),withFinally:y,send:A,abort:()=>{n&&(n.abort(),n=void 0),u=!0,d&&d()}};return V}var wa=class{constructor(e){this.intervals=[];this.currentRate=0;this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,i){return{start:e,end:t,bytes:i}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;let e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-500;if(t-e>2e3){let i=0,r=0;for(;this.intervals.length>0;){let s=this.intervals[0];if(s.end<=t)i+=s.end-s.start,r+=s.bytes,this.intervals.splice(0,1);else{if(s.start>=t)break;{let n=t-s.start,o=s.end-s.start;i+=n;let u=s.bytes*n/o;r+=u,s.start=t,s.bytes-=u}}}if(r>0&&i>0){let s=r*8/(i/1e3);return this._updateRate(s),this.logger(`rate updated, new=${Math.round(s/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(r)}/${Math.round(i)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,i){return this.intervals.push(this._createInterval(e,t,i)),this._joinIntervals(),this.intervals.length>100&&(this.logger(`too many intervals (${this.intervals.length}); will merge`,{type:"warn"}),this._doMergeIntervals(this.intervals[1],this.intervals[0]),this.intervals.splice(0,1)),this._flushIntervals()}getBitRate(){return this.currentRate}};var Vv=O(dr(),1);var Aa=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=fe(),r=u=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=u,e._errorCB?e._errorCB(u):(this.limitCompleteCount(),this.completeRequests[t]=e)},s=u=>{e._complete=1,e._responseData=u,e._downloadTime=fe()-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=Sr(t,s,()=>r("error"),o),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(n),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=fe()}_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=fe();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,Vv.default)(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,i,r){let s={};return s.send=()=>{let n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=i,n._retryCB=r,n._finallyCB=s._finallyCB,n._error||n._complete?(this._removeFromActive(e),setTimeout(()=>{n._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(n._responseData,n._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),i(n._errorMsg)),s._finallyCB&&s._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{let o=this.pendingQueue.indexOf(e);o!==-1&&this.pendingQueue.splice(o,1),this.logger(`Request not prefetched, starting new request, url=${e}${o===-1?"":"; removed pending"}`),this._sendRequest(s,e)}},s._cb=t,s._errorCB=i,s._retryCB=r,s.abort=function(){s.request&&s.request.abort()},s.withFinally=n=>(s._finallyCB=n,s),s}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}};import{Subject as PM}from"@vkontakte/videoplayer-shared/es2018";var ro=1e4,Tc=3;var RM=6e4,kM=10,LM=1,$M=500,Ra=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 PM,this.chunkRateEstimator=new wa(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=yc(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=yc(e),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){let e=this.params.videoElement,t=0,i=e.buffered.length;return i!==0&&(t=e.buffered.end(i-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){let{videoElement:e,logger:t}=this.params;e.addEventListener("error",()=>{var r,s;!!e.error&&!this.destroyed&&(t(`Video element error: ${(r=e.error)==null?void 0:r.code}, details: ${(s=e.error)==null?void 0:s.message}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{let i=this._getBufferSizeSec();!this.paused&&i<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(i+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){let{logger:e,videoElement:t}=this.params,i=t.buffered.length,r;i!==0&&!this.waitingForFirstBufferAfterSrcChange&&(r=t.buffered.start(i-1),t.currentTime<r&&(e("Fixup stall"),t.currentTime=r))}_selectQuality(e){let{videoElement:t}=this.params,i,r,s,n=t&&1.62*(N.display.pixelRatio||1)*t.offsetHeight||520;for(let o=0;o<this.manifest.length;++o){s=this.manifest[o];let{max:u,min:l}=this.autoQualityLimits||{};!Tv({limits:this.autoQualityLimits,highestAvailableHeight:this.manifest[0].video.height,lowestAvailableHeight:(0,_v.default)(this.manifest,-1).video.height})&&(u&&s.video.height>u||l&&s.video.height<l)||(s.bitrate<e&&n>Math.min(s.video.height,s.video.width)?(!r||s.bitrate>r.bitrate)&&(r=s):(!i||i.bitrate>s.bitrate)&&(i=s))}return r||i}shouldPlay(){if(this.paused)return!1;let t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||io(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=()=>{Bv(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 Aa(Tc,ro,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:i,playerCallback:r}=this.params,s=!1,n=null,o=null,u=null,l=null,c=!1,d=()=>{let I=s&&(!c||c===this.rep);return I||t("Not running!"),I},f=(I,E,A)=>{u&&u.abort(),u=Sr(this.urlResolver.resolve(I,!1),E,A,()=>this._retryCallback()).withTimeout(ro).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Tc).withFinally(()=>{u=null}).send()},p=(I,E,A)=>{Pa(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(I,!1),E,A,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},h=I=>{let E=i.playbackRate;i.playbackRate!==I&&(t(`Playback rate switch: ${E}=>${I}`),i.playbackRate=I)},m=I=>{this.lowLatency=I,t(`lowLatency changed to ${I}`),b()},b=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)h(1);else{let I=this._getBufferSizeSec();if(this.bufferStates.length<5){h(1);return}let A=fe()-1e4,M=0;for(let P=0;P<this.bufferStates.length;P++){let R=this.bufferStates[P];I=Math.min(I,R.buf),R.ts<A&&M++}this.bufferStates.splice(0,M),t(`update playback rate; minBuffer=${I} drop=${M} jitter=${this.sourceJitter}`);let L=I-LM;this.sourceJitter>=0?L-=this.sourceJitter/2:this.sourceJitter-=1,L>3?h(1.15):L>1?h(1.1):L>.3?h(1.05):h(1)}},S=I=>{let E,A=()=>E&&E.start?E.start.length:0,M=T=>E.start[T]/1e3,L=T=>E.dur[T]/1e3,P=T=>E.fragIndex+T,R=(T,k)=>({chunkIdx:P(T),startTS:M(T),dur:L(T),discontinuity:k}),V=()=>{let T=0;if(E&&E.dur){let k=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,x=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,w=k;this.sourceJitter>1&&(w+=this.sourceJitter-1);let B=E.dur.length-1;for(;B>=0&&(w-=E.dur[B],!(w<=0));--B);T=Math.min(B,E.dur.length-1-x),T=Math.max(T,0)}return R(T,!0)},D=T=>{let k=A();if(!(k<=0)){if(io(T)){for(let x=0;x<k;x++)if(M(x)>T)return R(x)}return V()}},_=T=>{let k=A(),x=T?T.chunkIdx+1:0,w=x-E.fragIndex;if(!(k<=0)){if(!T||w<0||w-k>kM)return t(`Resync: offset=${w} bChunks=${k} chunk=`+JSON.stringify(T)),V();if(!(w>=k))return R(x-E.fragIndex,!1)}},Y=(T,k,x)=>{l&&l.abort(),l=Sr(this.urlResolver.resolve(T,!0,this.lowLatency),k,x,()=>this._retryCallback()).withTimeout(ro).withRetryCount(Tc).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(T,k)=>{Y(I,x=>{if(!d())return;E=x;let w=!!E.lowLatency;w!==this.lowLatency&&m(w);let B=0;for(let ne=0;ne<E.dur.length;++ne)B+=E.dur[ne];B>0&&(Pa(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(B/E.dur.length)),r({name:"index",zeroTime:E.zeroTime,shiftDuration:E.shiftDuration}),this.sourceJitter=E.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,E.jitter/1e3)):1,T(D(k))},()=>this._handleNetworkError())},nextChunk:_}},y=()=>{s=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),Pa(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:I=>{let{videoElement:E,logger:A}=this.params,M=S(e.jidxUrl),L,P,R,V,D=0,_,Y,J,T=()=>{_&&(clearTimeout(_),_=void 0);let W=Math.max($M,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),ge=D+W,Se=fe(),ve=Math.min(1e4,ge-Se);D=Se;let Ne=()=>{l||d()&&M.seek(()=>{d()&&(D=fe(),k(),T())})};ve>0?_=window.setTimeout(()=>{this.paused?T():Ne()},ve):Ne()},k=()=>{let W;for(;W=M.nextChunk(V);)V=W,Fe(W);let ge=M.nextChunk(R);if(ge){if(R&&ge.discontinuity){A("Detected discontinuity; restarting playback"),this.paused?T():(y(),this._initPlayerWith(e));return}ne(ge)}else T()},x=(W,ge)=>{if(!d()||!this.sourceBuffer)return;let Se,ve,Ne,xt=Ot=>{window.setTimeout(()=>{d()&&x(W,ge)},Ot)};if(this.sourceBuffer.updating)A("Source buffer is updating; delaying appendBuffer"),xt(100);else{let Ot=fe(),ni=E.currentTime;!this.paused&&E.buffered.length>1&&Y===ni&&Ot-J>500&&(A("Stall suspected; trying to fix"),this._fixupStall()),Y!==ni&&(Y=ni,J=Ot);let Ni=this._getBufferSizeSec();if(Ni>30)A(`Buffered ${Ni} seconds; delaying appendBuffer`),xt(2e3);else try{this.sourceBuffer.appendBuffer(W),this.videoPlayStarted?(this.bufferStates.push({ts:Ot,buf:Ni}),b(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),ge&&ge()}catch(Nr){if(Nr.name==="QuotaExceededError")A("QuotaExceededError; delaying appendBuffer"),Ne=this.sourceBuffer.buffered.length,Ne!==0&&(Se=this.sourceBuffer.buffered.start(0),ve=ni,ve-Se>4&&this.sourceBuffer.remove(Se,ve-3)),xt(1e3);else throw Nr}}},w=()=>{P&&L&&(A([`Appending chunk, sz=${P.byteLength}:`,JSON.stringify(R)]),x(P,function(){P=null,k()}))},B=W=>e.fragUrlTemplate.replace("%%id%%",W.chunkIdx),ne=W=>{d()&&p(B(W),(ge,Se)=>{if(d()){if(Se/=1e3,P=ge,R=W,n=W.startTS,Se){let ve=Math.min(10,W.dur/Se);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*ve:ve}w()}},()=>this._handleNetworkError())},Fe=W=>{d()&&(Pa(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(B(W),!1)))},ie=W=>{d()&&(e.cachedHeader=W,x(W,()=>{L=!0,w()}))};s=!0,M.seek(W=>{if(d()){if(D=fe(),!W){T();return}V=W,!AM(I)||W.startTS>I?ne(W):(R=W,k())}},I),e.cachedHeader?ie(e.cachedHeader):f(e.headerUrl,ie,()=>this._handleNetworkError())},stop:y,getTimestampSec:()=>n},c}_switchToQuality(e){let{logger:t,playerCallback:i}=this.params,r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),io(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,Pa(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return io(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,i=d=>{if(!this.autoQuality)return;let f,p,h;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&d<this.bitrate&&(p=this._getBufferSizeSec(),h=d/this.bitrate,p>10&&h>.8||p>15&&h>.5||p>20&&h>.3)){e(`Not switching: buffer=${Math.floor(p)}; bitrate=${this.bitrate}; newRate=${Math.floor(d)}`);return}f=this._selectQuality(d),f?this._switchToQuality(f):e(`Could not find quality by bitrate ${d}`)},s={updateChunk:(f,p)=>{let h=fe();if(this.chunkRateEstimator.addInterval(f,h,p)){let b=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:p,duration:h-f,speed:b}),!0}},get:()=>{let f=this.chunkRateEstimator.getBitRate();return f?f*.85:0}},n=-1/0,o,u=!0,l=()=>{let d=s.get();if(d&&o&&this.autoQuality){if(u&&d>o&&vc(n)<3e4)return;i(d)}u=this.autoQuality};return{updateChunk:(d,f)=>{let p=s.updateChunk(d,f);return p&&l(),p},notifySwitch:d=>{let f=fe();d<o&&(n=f),o=d}}}_fetchManifest(e,t,i){this.manifestRequest=Sr(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(ro).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;Ve(e,()=>{this.soundProhibitedEvent$.next()}).then(t=>{t||(this.params.liveOffset.pause(),this.params.videoState.setState("paused"))})}_handleManifestUpdate(e){let{logger:t,playerCallback:i,videoElement:r}=this.params,s=n=>{let o=[];return n!=null&&n.length?(n.forEach((u,l)=>{var c,d;u.video&&r.canPlayType(u.codecs).replace(/no/,"")&&((d=(c=window.MediaSource)==null?void 0:c.isTypeSupported)!=null&&d.call(c,u.codecs))&&(u.index=l,o.push(u))}),o.sort(function(u,l){return u.video&&l.video?l.video.height-u.video.height:l.bitrate-u.bitrate}),o):(i({name:"error",type:"empty_manifest"}),[])};this.manifest=s(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),i({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},RM))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var Nv=O(er(),1);import{debounce as MM,filter as Ov,fromEvent as DM,interval as CM,isHigher as BM,isInvariantQuality as VM,isLower as _M,merge as OM,Subject as Fv,Subscription as FM}from"@vkontakte/videoplayer-shared/es2018";var Ic=class{constructor(){this.onDroopedVideoFramesLimit$=new Fv;this.subscription=new FM;this.playing=!1;this.tracks=[];this.forceChecker$=new Fv;this.isForceCheckCounter=0;this.prevTotalVideoFrames=0;this.prevDroppedVideoFrames=0;this.limitCounts={};this.handleChangeVideoQuality=()=>{let e=this.tracks.find(({size:t})=>(t==null?void 0:t.height)===this.video.videoHeight&&(t==null?void 0:t.width)===this.video.videoWidth);e&&!VM(e.quality)&&this.onChangeQuality(e.quality)};this.checkDroppedFrames=()=>{var n;let{totalVideoFrames:e,droppedVideoFrames:t}=this.video.getVideoPlaybackQuality(),i=e-this.prevTotalVideoFrames,r=t-this.prevDroppedVideoFrames,s=1-(i-r)/i;!isNaN(s)&&s>0&&this.log({message:`[dropped]. current dropped percent: ${s}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(s)&&s>=this.droppedFramesChecker.percentLimit&&BM(this.currentQuality,this.droppedFramesChecker.minQualityBanLimit)&&(this.limitCounts[this.currentQuality]=((n=this.limitCounts[this.currentQuality])!=null?n:0)+1,this.maxQualityLimit=this.getMaxQualityLimit(this.currentQuality),this.currentTimer&&window.clearTimeout(this.currentTimer),this.currentTimer=window.setTimeout(()=>this.maxQualityLimit=this.getMaxQualityLimit(),this.droppedFramesChecker.qualityUpWaitingTime),this.onDroopedVideoFramesLimitTrigger()),this.savePrevFrameCounts(e,t)}}connect(e){this.log=e.logger.createComponentLog("DroppedFramesManager"),this.video=e.video,this.isAuto=e.isAuto,this.tracks=e.tracks,this.droppedFramesChecker=e.droppedFramesChecker,this.subscription.add(e.playing$.subscribe(()=>this.playing=!0)),this.subscription.add(e.pause$.subscribe(()=>this.playing=!1)),this.isEnabled&&this.subscribe()}destroy(){this.currentTimer&&window.clearTimeout(this.currentTimer),this.subscription.unsubscribe()}get droppedVideoMaxQualityLimit(){return this.maxQualityLimit}subscribe(){this.subscription.add(DM(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=CM(this.droppedFramesChecker.checkTime).pipe(Ov(()=>this.playing),Ov(()=>{let r=!!this.isForceCheckCounter;return r&&(this.isForceCheckCounter-=1),!r})),t=this.forceChecker$.pipe(MM(this.droppedFramesChecker.checkTime)),i=OM(e,t);this.subscription.add(i.subscribe(this.checkDroppedFrames))}onChangeQuality(e){this.currentQuality=e;let{totalVideoFrames:t,droppedVideoFrames:i}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,i),this.isForceCheckCounter=this.droppedFramesChecker.tickCountAfterQualityChange,this.forceChecker$.next()}onDroopedVideoFramesLimitTrigger(){this.isAuto.getState()&&(this.log({message:`[onDroopedVideoFramesLimit]. maxQualityLimit: ${this.maxQualityLimit}`}),this.onDroopedVideoFramesLimit$.next())}getMaxQualityLimit(e){var i,r;let t=(r=(i=(0,Nv.default)(this.limitCounts).filter(([,s])=>s>=this.droppedFramesChecker.countLimit).sort(([s],[n])=>_M(s,n)?-1:1))==null?void 0:i[0])==null?void 0:r[0];return e!=null?e:t}get isEnabled(){return this.droppedFramesChecker.enabled&&this.isDroppedFramesCheckerSupport}get isDroppedFramesCheckerSupport(){return!!this.video&&typeof this.video.getVideoPlaybackQuality=="function"}savePrevFrameCounts(e,t){this.prevTotalVideoFrames=e,this.prevDroppedVideoFrames=t}},vr=Ic;import{map as NM,Observable as UM}from"@vkontakte/videoplayer-shared/es2018";import{fromEvent as qM}from"@vkontakte/videoplayer-shared/es2018";var ka=()=>{var a;return!!((a=window.documentPictureInPicture)!=null&&a.window)||!!document.pictureInPictureElement};var HM=(a,e)=>new UM(t=>{if(!window.IntersectionObserver)return;let i={root:null},r=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||ka()))},{...i,...e});r.observe(a);let s=qM(document,"visibilitychange").pipe(NM(n=>!document.hidden||ka())).subscribe(n=>t.next(n));return()=>{r.unobserve(a),s.unsubscribe()}}),Je=HM;var XM=["paused","playing","ready"],JM=["paused","playing","ready"],La=class{constructor(e){this.subscription=new YM;this.videoState=new q("stopped");this.representations$=new xc([]);this.droppedFramesManager=new vr;this.maxSeekBackTime$=new xc(1/0);this.zeroTime$=new xc(void 0);this.liveOffset=new wi;this._dashCb=e=>{var t,i,r,s;switch(e.name){case"buffering":{let n=e.isBuffering;this.params.output.isBuffering$.next(n);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,category:Hv.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{let n=e.manifest,o=[];for(let u of n){let l=(t=u.name)!=null?t:u.index.toString(10),c=(i=Kt(u.name))!=null?i:KM(u.video),d=u.bitrate/1e3,f={...u.video};if(!c)continue;let p={id:l,quality:c,bitrate:d,size:f};o.push({track:p,representation:u})}this.representations$.next(o),this.params.output.availableVideoTracks$.next(o.map(({track:u})=>u)),((r=this.videoState.getTransition())==null?void 0:r.to)==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let n=e.quality,o=(s=this.representations$.getValue().find(({representation:u})=>u===n))==null?void 0:s.track;this.params.output.hostname$.next(new URL(n.headerUrl,this.params.source.url).hostname),Ec(o)&&this.params.output.currentVideoTrack$.next(o);break}case"bandwidth":{let{size:n,duration:o}=e;this.params.dependencies.throughputEstimator.addRawSpeed(n,o);break}case"index":{this.maxSeekBackTime$.next(e.shiftDuration||0),this.zeroTime$.next(e.zeroTime);break}}};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; seekState: ${JSON.stringify(s)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"));return}if(t)return;let n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if((0,wc.default)(JM,e)&&(n||o)){this.prepare();return}if((r==null?void 0:r.to)!=="paused"&&s.state==="requested"&&(0,wc.default)(XM,e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(le(this.params.source.url));return;case"manifest_ready":this.videoState.startTransitionTo("ready"),this.prepare();break;case"ready":if(i==="paused")this.videoState.setState("paused");else if(i==="playing"){this.videoState.startTransitionTo("playing");let u=r==null?void 0:r.from;u&&u==="ready"&&this.dash.catchUp(),this.dash.play()}return;case"playing":i==="paused"&&(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.dash.pause());return;case"paused":if(i==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.dash.play(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let u=this.liveOffset.getTotalOffset();u>=this.maxSeekBackTime$.getValue()&&(u=0,this.liveOffset.resetTo(u)),this.liveOffset.resume(),this.params.output.position$.next(-u/1e3),this.dash.reinit(le(this.params.source.url,u))}return;default:return Uv(e)}};this.textTracksManager=new Xe(e.source.url),this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=r=>{e.output.error$.next({id:"DashLiveProvider",category:Hv.WTF,message:"DashLiveProvider internal logic error",thrown:r})};this.subscription.add(Qv(this.videoState.stateChangeStarted$.pipe(ao(r=>({transition:r,type:"start"}))),this.videoState.stateChangeEnded$.pipe(ao(r=>({transition:r,type:"end"})))).subscribe(({transition:r,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(r)}`})})),this.video=Me(e.container,e.tuning),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.subscription.add(this.dash.soundProhibitedEvent$.subscribe(this.params.output.soundProhibitedEvent$)),this.params.output.duration$.next(1/0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(Te(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);let i=Be(this.video);this.subscription.add(()=>i.destroy()),this.subscription.add(this.representations$.pipe(ao(r=>r.map(({track:s})=>s)),jv(r=>!!r.length),zM()).subscribe(r=>this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:r}))),this.subscription.add(i.canplay$.subscribe(()=>{var r;((r=this.videoState.getTransition())==null?void 0:r.to)==="ready"&&this.videoState.setState("ready")},t)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused")},t)).add(i.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.videoState.setState("playing")},t)).add(i.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(GM(),ao(r=>-r/1e3)).subscribe(this.params.output.duration$)).add(jM({zeroTime:this.zeroTime$.pipe(jv(Ec)),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(Ce(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(Ke(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(Je(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:r,min:s}})=>{this.dash.setAutoQualityLimits({max:r&&Gv(r),min:s&&Gv(s)}),this.params.output.autoVideoTrackLimits$.next({max:r,min:s})})).add(this.videoState.stateChangeEnded$.subscribe(r=>{var s;switch(r.to){case"stopped":this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState("stopped");break;case"manifest_ready":case"ready":((s=this.params.desiredState.playbackState.getTransition())==null?void 0:s.to)==="ready"&&this.params.desiredState.playbackState.setState("ready");break;case"paused":this.params.desiredState.playbackState.setState("paused");break;case"playing":this.params.desiredState.playbackState.setState("playing");break;default:return Uv(r.to)}},t)).add(Qv(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,WM(["init"])).pipe(QM(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),De(this.video)}createLiveDashPlayer(){let e=new Ra({videoElement:this.video,videoState:this.videoState,playbackState:this.params.desiredState.playbackState,liveOffset:this.liveOffset,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode,manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){var l,c,d,f,p,h;let e=this.representations$.getValue(),t=(c=(l=this.params.desiredState.videoTrack.getTransition())==null?void 0:l.to)!=null?c:this.params.desiredState.videoTrack.getState(),i=(f=(d=this.params.desiredState.autoVideoTrackSwitching.getTransition())==null?void 0:d.to)!=null?f:this.params.desiredState.autoVideoTrackSwitching.getState(),r=!i&&Ec(t)?t:vt(e.map(({track:m})=>m),{container:this.video.getBoundingClientRect(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),s=r==null?void 0:r.id,n=this.params.desiredState.videoTrack.getTransition(),o=(p=this.params.desiredState.videoTrack.getState())==null?void 0:p.id,u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(r&&(n||s!==o)&&this.setVideoTrack(r),u&&this.setAutoQuality(i),n||u||s!==o){let m=(h=e.find(({track:b})=>b.id===s))==null?void 0:h.representation;qv(m,"Representations missing"),this.dash.startPlay(m,i)}}setVideoTrack(e){var i;let t=(i=this.representations$.getValue().find(({track:r})=>r.id===e.id))==null?void 0:i.representation;qv(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(le(this.params.source.url,n)),r&&this.dash.pause(),this.liveOffset.resetTo(n,r)}};var Wv=La;var fI=O(Ye(),1);var me=(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 FB,assertNonNullable as NB,debounce as UB,ErrorCategory as dI,filter as od,filterChanged as Do,fromEvent as qB,isNonNullable as pI,isNullable as HB,map as ud,merge as Co,observableFrom as ld,once as hI,Subscription as jB}from"@vkontakte/videoplayer-shared/es2018";var{NativeAbortSignal:I1,NativeAbortController:E1}=function(a){return{NativeAbortSignal:a.AbortSignal,NativeAbortController:a.AbortController}}(typeof self!="undefined"?self:global);function zv(a){let e;try{e=new Event("abort")}catch(t){typeof document!="undefined"?document.createEvent?(e=document.createEvent("Event"),e.initEvent("abort",!1,!1)):(e=document.createEventObject(),e.type="abort"):e={type:"abort",bubbles:!1,cancelable:!1}}return e.reason=a,e}function Yv(a){if(a===void 0)if(typeof document=="undefined")a=new Error("This operation was aborted"),a.name="AbortError";else try{a=new DOMException("signal is aborted without reason"),Object.defineProperty(a,"name",{value:"AbortError"})}catch(e){a=new Error("This operation was aborted"),a.name="AbortError"}return a}var so=class{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,i){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:i})}removeEventListener(e,t){if(!(e in this.listeners))return;let i=this.listeners[e];for(let r=0,s=i.length;r<s;r++)if(i[r].callback===t){i.splice(r,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;let i=this.listeners[e.type].slice();for(let r=0,s=i.length;r<s;r++){let n=i[r];try{n.callback.call(this,e)}catch(o){Promise.resolve().then(()=>{throw o})}n.options&&n.options.once&&this.removeEventListener(e.type,n.callback)}return!e.defaultPrevented}},yr=class extends so{constructor(){super(),this.listeners||so.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 Pi;return setTimeout(()=>t.abort(new DOMException(`This signal is timeout in ${e}ms`,"TimeoutError")),e),t.signal}static any(e){let t=new Pi;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}},Pi=class{constructor(){Object.defineProperty(this,"signal",{value:new yr,writable:!0,configurable:!0})}abort(e){let t=Yv(e),i=zv(t);this.signal.reason=t,this.signal.dispatchEvent(i)}toString(){return"[object AbortController]"}};typeof Symbol!="undefined"&&Symbol.toStringTag&&(Pi.prototype[Symbol.toStringTag]="AbortController",yr.prototype[Symbol.toStringTag]="AbortSignal");function no(a){return a.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof a.Request=="function"&&!a.Request.prototype.hasOwnProperty("signal")||!a.AbortController}function Ac(a){typeof a=="function"&&(a={fetch:a});let{fetch:e,Request:t=e.Request,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r=!1}=a;if(!no({fetch:e,Request:t,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r}))return{fetch:e,Request:s};let s=t;(s&&!s.prototype.hasOwnProperty("signal")||r)&&(s=function(l,c){let d;c&&c.signal&&(d=c.signal,delete c.signal);let f=new t(l,c);return d&&Object.defineProperty(f,"signal",{writable:!1,enumerable:!1,configurable:!0,value:d}),f},s.prototype=t.prototype);let n=e;return{fetch:(u,l)=>{let c=s&&s.prototype.isPrototypeOf(u)?u.signal:l?l.signal:void 0;if(c){let d;try{d=new DOMException("Aborted","AbortError")}catch(p){d=new Error("Aborted"),d.name="AbortError"}if(c.aborted)return Promise.reject(d);let f=new Promise((p,h)=>{c.addEventListener("abort",()=>h(d),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([f,n(u,l)])}return n(u,l)},Request:s}}var ZM=()=>"fetch"in window,$a=ZM()&&no({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),Kv=$a?Ac({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,Ze=$a?Kv.fetch:window.fetch,D1=$a?Kv.Request:window.Request,Z=$a?Pi:window.AbortController,C1=$a?yr:window.AbortSignal;var td=O(Ma(),1);var Vy=O(By(),1);import{ErrorCategory as Ca}from"@vkontakte/videoplayer-shared/es2018";var oo=a=>{if(!a)return{id:"EmptyResponse",category:Ca.PARSER,message:"Empty response"};if(a.length<=2&&a.match(/^\d+$/))return{id:`UVError#${a}`,category:Ca.NETWORK,message:`UV Error ${a}`};let e=(0,Vy.default)(a).substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:Ca.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:Ca.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:Ca.PARSER,message:"Response is valid XML, but parser failed"}};var Ie=(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 Jc,assertNonNullable as Lr,combine as $r,ErrorCategory as ct,filter as wo,filterChanged as ps,flattenObject as hs,fromEvent as Bt,getTraceSubscriptionMethod as TB,interval as Zc,isNonNullable as fs,isNullable as sI,map as Mr,merge as Mi,now as ed,Subject as Ao,Subscription as nI,tap as IB,throttle as EB,ValueSubject as ae}from"@vkontakte/videoplayer-shared/es2018";var po=O(Ye(),1),$i=O(ot(),1),ho=O(Ma(),1);var OD=(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)},FD=a=>window.clearTimeout(a),_y=a=>typeof a=="function"&&(a==null?void 0:a.toString().endsWith("{ [native code] }")),Oy=!_y(window.requestIdleCallback)||!_y(window.cancelIdleCallback),Tr=Oy?OD:window.requestIdleCallback,yt=Oy?FD:window.cancelIdleCallback;var YT=O($n(),1);import{assertNever as ND,ErrorCategory as Fy,Subject as Ny}from"@vkontakte/videoplayer-shared/es2018";var UD=18,Uy=!1;try{Uy=N.browser.isSafari&&!!N.browser.safariVersion&&N.browser.safariVersion<=UD}catch(a){console.error(a)}var Mc=class{constructor(e){this.bufferFull$=new Ny;this.error$=new Ny;this.queue=[];this.currentTask=null;this.destroyed=!1;this.abortRequested=!1;this.completeTask=()=>{var e;try{if(this.currentTask){let t=(e=this.currentTask.signal)==null?void 0:e.aborted;this.currentTask.callback(!t),this.currentTask=null}this.queue.length&&this.pull()}catch(t){this.error$.next({id:"BufferTaskQueueUnknown",category:Fy.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(i=>{let r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(r=>{let s={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(s),this.pull()})}async abort(e){return new Promise(t=>{let i,r=s=>{this.abortRequested=!1,t(s)};Uy&&e?i={operation:"safariAbort",init:e,callback:r}:i={operation:"abort",callback:r};for(let{callback:s}of this.queue)s(!1);this.abortRequested=!0,i&&(this.queue=[i]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){var r;if((this.buffer.updating||this.currentTask||this.destroyed)&&!this.abortRequested)return;let e=this.queue.shift();if(!e)return;if((r=e.signal)!=null&&r.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(s){s instanceof DOMException&&s.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):s instanceof DOMException&&s.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:Fy.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:s}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){let{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:ND(t)}}},qy=Mc;var Ir=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 Zt,assertNonNullable as _e,ErrorCategory as Mt,fromEvent as Gc,getExponentialDelay as Wc,isNonNullable as Pr,isNullable as Ee,now as co,once as lB,Subject as cB,Subscription as dB,ValueSubject as Li}from"@vkontakte/videoplayer-shared/es2018";var Hy=O(ot(),1);var uo=a=>a.valid,Q=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let i=this.readUint32();this.type=this.readString(4),i===1&&(this.cursor+=8);let r=e.byteOffset+this.cursor,s;i===0?(this.size=void 0,this.valid=!1,s=void 0):i===1?(this.size=void 0,this.valid=!1,s=void 0):i>e.byteLength?(this.size=i,this.valid=!1,s=Math.min(i-this.cursor,e.byteLength-this.cursor)):(this.size=i,this.valid=!0,s=i-this.cursor),this.content=new DataView(e.buffer,r,s)}get id(){return this.type}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t="ascii"){let r=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,r}readUint8(){let e=this.source.getUint8(this.cursor);return this.cursor+=1,e}readUint16(){let e=this.source.getUint16(this.cursor);return this.cursor+=2,e}readUint32(){let e=this.source.getUint32(this.cursor);return this.cursor+=4,e}readUint64(){let e=this.source.getBigInt64(this.cursor);return this.cursor+=8,e}};var Er=class extends Q{};import{assertNever as qD}from"@vkontakte/videoplayer-shared/es2018";var Ba=class extends Q{constructor(e,t){if(super(e,t),!this.valid)return;let i=this.readString(16),r=new DataView(this.content.buffer,this.content.byteOffset+16,this.content.byteLength-16);this.userData=this.parseData(i,r)}parseData(e,t){switch(e){case"ondemandlivejson":{let i=new TextDecoder("ascii").decode(t),r=JSON.parse(i);return{received:r["t-in"],prepared:r["t-out"]}}default:qD(e)}}};var Va=class extends Q{constructor(e,t){if(super(e,t),!this.valid)return;this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let i=new DataView(this.content.buffer,this.content.byteOffset+8,this.content.byteLength-8);for(let r=0;r<i.byteLength;r+=4){let s=this.readString(4);this.compatibleBrands.push(s)}}};var _a=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var re=class extends Q{constructor(e,t){if(super(e,t),!this.valid)return;let i=this.readUint32();this.version=i>>>24,this.flags=i&16777215,this.content=new DataView(this.content.buffer,this.content.byteOffset+4,this.content.byteLength-4)}};var Oa=class extends re{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 Fa=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Na=class extends Q{constructor(e,t){super(e,t),this.data=this.content}};var Ri=class extends re{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,o=this.readUint32();r=this.readUint32();let u=r>>>28,l=r<<3>>>3;this.segments.push({referenceType:s,referencedSize:n,subsegmentDuration:o,SAPType:u,SAPDeltaTime:l})}}}};var Ua=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var qa=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ha=class extends re{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 ja=class extends re{constructor(e,t){super(e,t),this.valid&&(this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32())}};var Qa=class extends re{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 Ga=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Wa=class extends re{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 za=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ya=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ka=class extends re{constructor(e,t){super(e,t),this.valid&&(this.sequenceNumber=this.readUint32())}};var Xa=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ja=class extends re{constructor(e,t){super(e,t),this.trackId=this.readUint32(),this.flags&1&&(this.baseDataOffset=this.readUint64()),this.flags&2&&(this.sampleDescriptionIndex=this.readUint32()),this.flags&8&&(this.defaultSampleDuration=this.readUint32()),this.flags&16&&(this.defaultSampleSize=this.readUint32()),this.flags&32&&(this.defaultSampleFlags=this.readUint32())}};var Za=class extends re{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 es=class extends re{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 ts=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var is=class extends re{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 rs=class extends Q{constructor(e,t){super(e,t),this.valid&&(this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+78,this.content.byteLength-78)))}};var jD={ftyp:Va,moov:_a,mvhd:Oa,moof:Fa,mdat:Na,sidx:Ri,trak:Ua,mdia:Ga,mfhd:Ka,tkhd:Wa,traf:Xa,tfhd:Ja,tfdt:Za,trun:es,minf:za,sv3d:qa,st3d:Ha,prhd:ja,proj:Ya,equi:Qa,uuid:Ba,stbl:ts,stsd:is,avc1:rs,unknown:Er},$t=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(o){if(!(o instanceof RangeError))throw o}if(!n||!uo(n))break;t.push(n),i+=n.size}return t}createBox(e,t){let i=jD[e];return i?new i(t,new a):new Er(t,new a)}};var Jt=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{var i,r,s;uo(t)&&((s=(i=this.index)[r=t.type])!=null||(i[r]=[]),this.index[t.type].push(t),t.children.length>0&&this.indexBoxLevel(t.children))})}find(e){return this.index[e]&&this.index[e][0]?this.index[e][0]:null}findAll(e){return this.index[e]||[]}};var GD=new TextDecoder("ascii"),WD=a=>GD.decode(new DataView(a.buffer,a.byteOffset+4,4))==="ftyp",zD=a=>{let e=new Ri(a,new $t),t=e.earliestPresentationTime/e.timescale*1e3,i=a.byteOffset+a.byteLength+e.firstOffset;return e.segments.map(s=>{if(s.referenceType!==0)throw new Error("Unsupported multilevel sidx");let n=s.subsegmentDuration/e.timescale*1e3,o={status:"none",time:{from:t,to:t+n},byte:{from:i,to:i+s.referencedSize-1}};return t+=n,i+=s.referencedSize,o})},YD=(a,e)=>{let i=new $t().parse(a),r=new Jt(i),s=r.findAll("moof"),n=e?r.findAll("uuid"):r.findAll("mdat");if(!(n.length&&s.length))return null;let o=s[0],u=n[n.length-1],l=o.source.byteOffset,d=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(a.buffer,l,d)},KD=a=>{let t=new $t().parse(a),i=new Jt(t),r={},s=i.findAll("uuid"),n=(0,Hy.default)(s,-1);return n?{serverDataReceivedTimestamp:n.userData.received,serverDataPreparedTime:n.userData.received}:r},XD=a=>{var r;let t=new $t().parse(a);return(r=new Jt(t).find("sidx"))==null?void 0:r.timescale},JD=(a,e)=>{let i=new $t().parse(a),s=new Jt(i).findAll("traf"),n=s[s.length-1].children.find(d=>d.type==="tfhd"),o=s[s.length-1].children.find(d=>d.type==="tfdt"),u=s[s.length-1].children.find(d=>d.type==="trun"),l=0;return u.sampleDuration.length?l=u.sampleDuration.reduce((d,f)=>d+f,0):l=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+l)/e*1e3},ZD=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 $t().parse(a),r=new Jt(i);if(r.find("sv3d")){e.is3dVideo=!0;let n=r.find("st3d");n&&(e.stereoMode=n.stereoMode);let o=r.find("prhd");o&&(e.projectionData.pose.yaw=o.poseYawDegrees,e.projectionData.pose.pitch=o.posePitchDegrees,e.projectionData.pose.roll=o.poseRollDegrees);let u=r.find("equi");u&&(e.projectionData.bounds.top=u.projectionBoundsTop,e.projectionData.bounds.right=u.projectionBoundsRight,e.projectionData.bounds.bottom=u.projectionBoundsBottom,e.projectionData.bounds.left=u.projectionBoundsLeft)}return e},jy={validateData:WD,parseInit:ZD,getIndexRange:()=>{},parseSegments:zD,parseFeedableSegmentChunk:YD,getChunkEndTime:JD,getServerLatencyTimestamps:KD,getTimescaleFromIndex:XD};var ns=O(Ye(),1);import{assertNonNullable as Dc,isNonNullable as zy,isNullable as tC}from"@vkontakte/videoplayer-shared/es2018";import{assertNever as eC}from"@vkontakte/videoplayer-shared/es2018";var Qy={440786851:{type:"master"},17030:{type:"uint"},17143:{type:"uint"},17138:{type:"uint"},17139:{type:"uint"},17026:{type:"string"},17031:{type:"uint"},17029:{type:"uint"},236:{type:"binary"},408125543:{type:"master"},290298740:{type:"master"},19899:{type:"master"},21419:{type:"binary"},21420:{type:"uint"},357149030:{type:"master"},2807729:{type:"uint"},17545:{type:"float"},374648427:{type:"master"},174:{type:"master"},224:{type:"master"},30320:{type:"master"},30321:{type:"uint"},30322:{type:"master"},272869232:{type:"master"},524531317:{type:"master"},231:{type:"uint"},22612:{type:"master"},22743:{type:"uint"},167:{type:"uint"},171:{type:"uint"},163:{type:"binary"},160:{type:"master"},175:{type:"binary"},423732329:{type:"master"},307544935:{type:"master"},475249515:{type:"master"},187:{type:"master"},179:{type:"uint"},183:{type:"master"},247:{type:"uint"},241:{type:"uint"},240:{type:"uint"},178:{type:"uint"},21368:{type:"uint"},234:{type:"uint"},219:{type:"master"},150:{type:"uint"}},Gy=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=ss(a,t),r=i in Qy,s=r?Qy[i].type:"binary",n=a.getUint8(t),o=0;n&128?o=1:n&64?o=2:n&32?o=3:n&16?o=4:n&8?o=5:n&4?o=6:n&2?o=7:n&1&&(o=8);let u=new DataView(a.buffer,a.byteOffset+t+1,o-1),l=n&255>>o,c=ss(u),d=l*2**((o-1)*8)+c,f=t+o,p;return f+d>a.byteLength?p=new DataView(a.buffer,a.byteOffset+f):p=new DataView(a.buffer,a.byteOffset+f,d),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:s,tagHeaderSize:f,tagSize:f+d,value:p,valueSize:d}},ss=(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},ut=(a,e)=>{switch(e){case"int":return a.getInt8(0);case"uint":return ss(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:eC(e)}},ki=(a,e)=>{let t=0;for(;t<a.byteLength;){let i=new DataView(a.buffer,a.byteOffset+t),r=Gy(i);if(!e(r))return;r.type==="master"&&ki(r.value,e),t=r.value.byteOffset-a.byteOffset+r.valueSize}},Wy=a=>{if(a.getUint32(0)!==440786851)return!1;let e,t,i,r=Gy(a);return ki(r.value,({tag:s,type:n,value:o})=>(s===17143?e=ut(o,n):s===17026?t=ut(o,n):s===17029&&(i=ut(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)};var Yy=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],iC=[231,22612,22743,167,171,163,160,175],rC=a=>{let e,t,i,r,s=!1,n=!1,o=!1,u,l,c=!1,d=0;return ki(a,({tag:f,type:p,value:h,valueSize:m})=>{if(f===21419){let b=ut(h,p);l=ss(b)}else f!==21420&&(l=void 0);return f===408125543?(e=h.byteOffset,t=h.byteOffset+m):f===357149030?s=!0:f===290298740?n=!0:f===2807729?i=ut(h,p):f===17545?r=ut(h,p):f===21420&&l===475249515?u=ut(h,p):f===374648427?ki(h,({tag:b,type:S,value:y})=>b===30321?(c=ut(y,S)===1,!1):!0):s&&n&&(0,ns.default)(Yy,f)&&(o=!0),!o}),Dc(e,"Failed to parse webm Segment start"),Dc(t,"Failed to parse webm Segment end"),Dc(r,"Failed to parse webm Segment duration"),i=i!=null?i:1e6,{segmentStart:Math.round(e/1e9*i*1e3),segmentEnd:Math.round(t/1e9*i*1e3),timeScale:i,segmentDuration:Math.round(r/1e9*i*1e3),cuesSeekPosition:u,is3dVideo:c,stereoMode:d,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},aC=a=>{if(tC(a.cuesSeekPosition))return;let e=a.segmentStart+a.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},sC=(a,e)=>{let t=!1,i=!1,r=o=>zy(o.time)&&zy(o.position),s=[],n;return ki(a,({tag:o,type:u,value:l})=>{switch(o){case 475249515:t=!0;break;case 187:n&&r(n)&&s.push(n),n={};break;case 179:n&&(n.time=ut(l,u));break;case 183:break;case 241:n&&(n.position=ut(l,u));break;default:t&&(0,ns.default)(Yy,o)&&(i=!0)}return!(t&&i)}),n&&r(n)&&s.push(n),s.map((o,u)=>{let{time:l,position:c}=o,d=s[u+1];return{status:"none",time:{from:l,to:d?d.time:e.segmentDuration},byte:{from:e.segmentStart+c,to:d?e.segmentStart+d.position-1:e.segmentEnd-1}}})},nC=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,ns.default)(iC,i.tag)?(e+i.tagSize<=a.byteLength&&(e+=i.tagSize,t||(t=(0,ns.default)([163,160,175],i.tag))),!0):!1)}catch(i){}return e>0&&e<=a.byteLength&&t?new DataView(a.buffer,a.byteOffset,e):null},Ky={validateData:Wy,parseInit:rC,getIndexRange:aC,parseSegments:sC,parseFeedableSegmentChunk:nC};var Tt=a=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(a);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return Ky;case"mp4":return jy}}throw new ReferenceError(`Unsupported mime type ${a}`)};var It=a=>a instanceof DOMException&&(a.name==="AbortError"||a.code===20);var Nc=O(vT(),1),UT=O(er(),1),qT=O(BT(),1),HT=O(ot(),1),Uc=O(dr(),1);var VT=O(Ye(),1),Fc=a=>{let e=a.split("."),[t,...i]=e;if(!t)return!1;switch(t){case"av01":{let[r,s,n]=i;return!!(n&&parseInt(n,10)>8)}case"vp09":{let[r,s,n]=i;return!!(r&&parseInt(r,10)>=2&&n&&parseInt(n,10)>8)}case"avc1":{let r=i[0];if(!r||r.length!==6)return!1;let[s,n]=r.toUpperCase(),o=s+n;return(0,VT.default)(["6E","7A","F4"],o)}}return!1};import{isNonNullable as nB,isNullable as FT}from"@vkontakte/videoplayer-shared/es2018";var _T=a=>{if(a.includes("/")){let e=a.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(a)};var OT=a=>{var e;try{let t=sB(),i=a.match(t),{groups:r}=i!=null?i:{};if(r){let s={};if(r.extensions){let u=r.extensions.toLowerCase().match(/(?:[0-9a-wy-z](?:-[a-z0-9]{2,8})+)/g);Array.from(u||[]).forEach(l=>{s[l[0]]=l.slice(2)})}let n=(e=r.variants)==null?void 0:e.split(/-/).filter(u=>u!==""),o={extlang:r.extlang,langtag:r.langtag,language:r.language,privateuse:r.privateuse||r.privateuse2,region:r.region,script:r.script,extensions:s,variants:n};return Object.keys(o).forEach(u=>{let l=o[u];(typeof l=="undefined"||l==="")&&delete o[u]}),o}return null}catch(t){return null}};function sB(){let a="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",c=`^(?:(?<langtag>${`
|
|
118
|
+
(?<language>${`(?:[a-z]{2,3}(?:-${a})?|[a-z]{4}|[a-z]{5,8})`})
|
|
119
119
|
(-(?<script>[a-z]{4}))?
|
|
120
120
|
(-(?<region>(?:[a-z]{2}|[0-9]{3})))?
|
|
121
121
|
(?<variants>(?:-(?:[a-z0-9]{5,8}|[0-9][a-z0-9]{3}))*)
|
|
122
122
|
(?<extensions>(?:-[0-9a-wy-z](?:-[a-z0-9]{2,8})+)*)
|
|
123
123
|
(?:-(?<privateuse>(?:${e})))?
|
|
124
|
-
`})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(d,"i")}var pp=N(Ot(),1);import{videoSizeToQuality as Q0}from"@vkontakte/videoplayer-shared/es2018";var EI=({id:s,width:e,height:t,bitrate:i,fps:r,quality:a,streamId:n})=>{var u;let o=(u=a?Bi(a):void 0)!=null?u:Q0({width:e,height:t});return o&&{id:s,quality:o,bitrate:i,size:{width:e,height:t},fps:r,streamId:n}},wI=({id:s,bitrate:e})=>({id:s,bitrate:e}),AI=({language:s,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:s,label:e}),PI=({language:s,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:s,label:e}),hp=({id:s,language:e,label:t,codecs:i,isDefault:r})=>({id:s,language:e,label:t,codec:(0,pp.default)(i.split("."),0),isDefault:r}),fp=({id:s,language:e,label:t,hdr:i,codecs:r})=>({id:s,language:e,hdr:i,label:t,codec:(0,pp.default)(r.split("."),0)}),mp=s=>"url"in s,Je=s=>s.type==="template",mn=s=>s instanceof DOMException&&(s.name==="AbortError"||s.code===20);var RI=s=>{if(!(s!=null&&s.startsWith("P")))return;let e=(n,o)=>{let u=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(u)?0:u)*o},i=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(s),r=(i==null?void 0:i[1])==="-"?-1:1,a={days:e(i==null?void 0:i[5],r),hours:e(i==null?void 0:i[6],r),minutes:e(i==null?void 0:i[7],r),seconds:e(i==null?void 0:i[8],r)};return a.days*24*60*60*1e3+a.hours*60*60*1e3+a.minutes*60*1e3+a.seconds*1e3},gi=(s,e)=>{let t=s;t=(0,bp.default)(t,"$$","$");let i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[r,a]of(0,MI.default)(i)){let n=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=(0,bp.default)(t,n,(o,u)=>kI(a)?o:kI(u)?a:(0,LI.default)(a,parseInt(u,10),"0"))}return t},$I=(s,e)=>{var w,P,C,L,R,Q,U,A,F,k,x,$,oe,Ce,se,K,ye,Te,Ie,Ve,Tt,At,qt,Xt,Ai,bs,gs,Ss,vs,ys,Ts,Is,xs,Es,ws,As,Ps,ks,Rs,Ms,Ls,Bs,$s,Ds,Cs,Vs,Os,_s,Fs,Ns,Us,qs,js,Hs,zs,Qs,Gs,Ws,Ys,Ks,Xs;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(ce=>{var _,je;return(je=(_=ce.textContent)==null?void 0:_.trim())!=null?je:""}),o=(w=(0,BI.default)(n,0))!=null?w:"",u=a.getAttribute("type")==="dynamic",l=a.getAttribute("availabilityStartTime"),d=a.getAttribute("publishTime"),c=a.getElementsByTagName("vk:Attrs")[0],h=c==null?void 0:c.getElementsByTagName("vk:XLatestSegmentPublishTime")[0].textContent,p=c==null?void 0:c.getElementsByTagName("vk:XStreamIsLive")[0].textContent,f=c==null?void 0:c.getElementsByTagName("vk:XStreamIsUnpublished")[0].textContent,m=c==null?void 0:c.getElementsByTagName("vk:XPlaybackDuration")[0].textContent,g;u&&(g={availabilityStartTime:l?new Date(l).getTime():0,publishTime:d?new Date(d).getTime():0,latestSegmentPublishTime:h?new Date(h).getTime():0,streamIsAlive:p==="yes",streamIsUnpublished:f==="yes"});let S,v=a.getAttribute("mediaPresentationDuration"),y=[...a.getElementsByTagName("Period")],I=y.reduce((ce,_)=>({...ce,[_.id]:_.children}),{}),T=y.reduce((ce,_)=>({...ce,[_.id]:_.getAttribute("duration")}),{});v?S=RI(v):(0,gp.default)(T).filter(ce=>ce).length&&!u?S=(0,gp.default)(T).reduce((ce,_)=>{var je;return ce+((je=RI(_))!=null?je:0)},0):m&&(S=parseInt(m,10));let E=0,O=(C=(P=a.getAttribute("profiles"))==null?void 0:P.split(","))!=null?C:[];for(let ce of y.map(_=>_.id))for(let _ of I[ce]){let je=(L=_.getAttribute("id"))!=null?L:"id"+(E++).toString(10),Pt=(R=_.getAttribute("mimeType"))!=null?R:"",ji=(Q=_.getAttribute("codecs"))!=null?Q:"",Hi=(U=_.getAttribute("contentType"))!=null?U:Pt==null?void 0:Pt.split("/")[0],kl=(F=(A=_.getAttribute("profiles"))==null?void 0:A.split(","))!=null?F:[],Js=(x=xI((k=_.getAttribute("lang"))!=null?k:""))!=null?x:{},Jt=(Ce=(oe=($=_.querySelector("Label"))==null?void 0:$.textContent)==null?void 0:oe.trim())!=null?Ce:void 0,Rl=_.querySelectorAll("Representation"),Ml=_.querySelector("SegmentTemplate"),Ll=(K=(se=_.querySelector("Role"))==null?void 0:se.getAttribute("value"))!=null?K:void 0,ut=Hi,H={id:je,language:Js.language,isDefault:Ll==="main",label:Jt,codecs:ji,hdr:ut==="video"&&Zr(ji),mime:Pt,representations:[]};for(let V of Rl){let we=(ye=V.getAttribute("lang"))!=null?ye:void 0,kt=(Ie=(Te=Jt!=null?Jt:_.getAttribute("label"))!=null?Te:V.getAttribute("label"))!=null?Ie:void 0,Zt=(At=(Tt=(Ve=V.querySelector("BaseURL"))==null?void 0:Ve.textContent)==null?void 0:Tt.trim())!=null?At:"",He=new URL(Zt||o,e).toString(),Ae=(qt=V.getAttribute("mimeType"))!=null?qt:Pt,ei=(Ai=(Xt=V.getAttribute("codecs"))!=null?Xt:ji)!=null?Ai:"",ti;if(Hi==="text"){let Pe=V.getAttribute("id")||"",ii=((bs=Js.privateuse)==null?void 0:bs.includes("x-auto"))||Pe.includes("_auto"),ze=V.querySelector("SegmentTemplate");if(ze){let Rt={representationId:(gs=V.getAttribute("id"))!=null?gs:void 0,bandwidth:(Ss=V.getAttribute("bandwidth"))!=null?Ss:void 0},ri=parseInt((vs=V.getAttribute("bandwidth"))!=null?vs:"",10)/1e3,si=(Ts=parseInt((ys=ze.getAttribute("startNumber"))!=null?ys:"",10))!=null?Ts:1,lt=parseInt((Is=ze.getAttribute("timescale"))!=null?Is:"",10),zi=(xs=ze.querySelectorAll("SegmentTimeline S"))!=null?xs:[],ct=ze.getAttribute("media");if(!ct)continue;let ai=[],ni=0,oi="",dt=0,Mt=si,ee=0;for(let de of zi){let Qe=parseInt((Es=de.getAttribute("d"))!=null?Es:"",10),ne=parseInt((ws=de.getAttribute("r"))!=null?ws:"",10)||0,ke=parseInt((As=de.getAttribute("t"))!=null?As:"",10);ee=Number.isFinite(ke)?ke:ee;let Ge=Qe/lt*1e3,Re=ee/lt*1e3;for(let me=0;me<ne+1;me++){let Me=gi(ct,{...Rt,segmentNumber:Mt.toString(10),segmentTime:(ee+me*Qe).toString(10)}),pt=(Re!=null?Re:0)+me*Ge,Bt=pt+Ge;Mt++,ai.push({time:{from:pt,to:Bt},url:Me})}ee+=(ne+1)*Qe,ni+=(ne+1)*Ge}dt=ee/lt*1e3,oi=gi(ct,{...Rt,segmentNumber:Mt.toString(10),segmentTime:ee.toString(10)});let Lt={time:{from:dt,to:1/0},url:oi},xe={type:"template",baseUrl:He,segmentTemplateUrl:ct,initUrl:"",totalSegmentsDurationMs:ni,segments:ai,nextSegmentBeyondManifest:Lt,timescale:lt};ti={id:Pe,kind:"text",segmentReference:xe,profiles:[],duration:S,bitrate:ri,mime:"",codecs:"",width:0,height:0,isAuto:ii}}else ti={id:Pe,isAuto:ii,kind:"text",url:He}}else{let Pe=(ks=(Ps=V.getAttribute("contentType"))!=null?Ps:Ae==null?void 0:Ae.split("/")[0])!=null?ks:Hi,ii=(Ms=(Rs=_.getAttribute("profiles"))==null?void 0:Rs.split(","))!=null?Ms:[],ze=parseInt((Ls=V.getAttribute("width"))!=null?Ls:"",10),Rt=parseInt((Bs=V.getAttribute("height"))!=null?Bs:"",10),ri=parseInt(($s=V.getAttribute("bandwidth"))!=null?$s:"",10)/1e3,si=(Ds=V.getAttribute("frameRate"))!=null?Ds:"",lt=(Cs=V.getAttribute("quality"))!=null?Cs:void 0,zi=si?Lu(si):void 0,ct=(Vs=V.getAttribute("id"))!=null?Vs:"id"+(E++).toString(10),ai=Pe==="video"?`${Rt}p`:Pe==="audio"?`${ri}Kbps`:ei,ni=`${ct}@${ai}`,oi=[...O,...kl,...ii],dt,Mt=V.querySelector("SegmentBase"),ee=(Os=V.querySelector("SegmentTemplate"))!=null?Os:Ml;if(Mt){let xe=(Fs=(_s=V.querySelector("SegmentBase Initialization"))==null?void 0:_s.getAttribute("range"))!=null?Fs:"",[de,Qe]=xe.split("-").map(Me=>parseInt(Me,10)),ne={from:de,to:Qe},ke=(Ns=V.querySelector("SegmentBase"))==null?void 0:Ns.getAttribute("indexRange"),[Ge,Re]=ke?ke.split("-").map(Me=>parseInt(Me,10)):[],me=ke?{from:Ge,to:Re}:void 0;dt={type:"byteRange",url:He,initRange:ne,indexRange:me}}else if(ee){let xe={representationId:(Us=V.getAttribute("id"))!=null?Us:void 0,bandwidth:(qs=V.getAttribute("bandwidth"))!=null?qs:void 0},de=parseInt((js=ee.getAttribute("timescale"))!=null?js:"",10),Qe=(Hs=ee.getAttribute("initialization"))!=null?Hs:"",ne=ee.getAttribute("media"),ke=(Qs=parseInt((zs=ee.getAttribute("startNumber"))!=null?zs:"",10))!=null?Qs:1,Ge=gi(Qe,xe);if(!ne)throw new ReferenceError("No media attribute in SegmentTemplate");let Re=(Gs=ee.querySelectorAll("SegmentTimeline S"))!=null?Gs:[],me=[],Me=0,pt="",Bt=0;if(Re.length){let ui=ke,pe=0;for(let ht of Re){let be=parseInt((Ws=ht.getAttribute("d"))!=null?Ws:"",10),We=parseInt((Ys=ht.getAttribute("r"))!=null?Ys:"",10)||0,li=parseInt((Ks=ht.getAttribute("t"))!=null?Ks:"",10);pe=Number.isFinite(li)?li:pe;let Qi=be/de*1e3,Gi=pe/de*1e3;for(let ci=0;ci<We+1;ci++){let $l=gi(ne,{...xe,segmentNumber:ui.toString(10),segmentTime:(pe+ci*be).toString(10)}),Zs=(Gi!=null?Gi:0)+ci*Qi,Dl=Zs+Qi;ui++,me.push({time:{from:Zs,to:Dl},url:$l})}pe+=(We+1)*be,Me+=(We+1)*Qi}Bt=pe/de*1e3,pt=gi(ne,{...xe,segmentNumber:ui.toString(10),segmentTime:pe.toString(10)})}else if(G0(S)){let pe=parseInt((Xs=ee.getAttribute("duration"))!=null?Xs:"",10)/de*1e3,ht=Math.ceil(S/pe),be=0;for(let We=1;We<ht;We++){let li=gi(ne,{...xe,segmentNumber:We.toString(10),segmentTime:be.toString(10)});me.push({time:{from:be,to:be+pe},url:li}),be+=pe}Bt=be,pt=gi(ne,{...xe,segmentNumber:ht.toString(10),segmentTime:be.toString(10)})}let Bl={time:{from:Bt,to:1/0},url:pt};dt={type:"template",baseUrl:He,segmentTemplateUrl:ne,initUrl:Ge,totalSegmentsDurationMs:Me,segments:me,nextSegmentBeyondManifest:Bl,timescale:de}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Pe||!Ae)continue;let Lt={video:"video",audio:"audio",text:"text"}[Pe];if(!Lt)continue;ut||(ut=Lt),ti={id:ni,kind:Lt,segmentReference:dt,profiles:oi,duration:S,bitrate:ri,mime:Ae,codecs:ei,width:ze,height:Rt,fps:zi,quality:lt}}H.language||(H.language=we),H.label||(H.label=kt),H.mime||(H.mime=Ae),H.codecs||(H.codecs=ei),H.hdr||(H.hdr=ut==="video"&&Zr(ei)),H.representations.push(ti)}if(ut){let V=r[ut].find(we=>we.id===H.id);if(V&&H.representations.every(we=>Je(we.segmentReference)))for(let we of V.representations){let kt=H.representations.find(Ae=>Ae.id===we.id),Zt=kt==null?void 0:kt.segmentReference,He=we.segmentReference;He.segments.push(...Zt.segments),He.nextSegmentBeyondManifest=Zt.nextSegmentBeyondManifest}else r[ut].push(H)}}return{duration:S,streams:r,baseUrls:n,live:g}};import{isNonNullable as DI}from"@vkontakte/videoplayer-shared/es2018";var q=(s,e)=>DI(s)&&DI(e)&&s.readyState==="open"&&W0(s,e);function W0(s,e){for(let t=0;t<s.activeSourceBuffers.length;++t)if(s.activeSourceBuffers[t]===e)return!0;return!1}var bn=class{constructor(e,t,i,{fetcher:r,tuning:a,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new dr(0);this.currentLowLatencySegmentLength$=new dr(0);this.currentSegmentLength$=new dr(0);this.onLastSegment$=new dr(!1);this.fullyBuffered$=new dr(!1);this.playingRepresentation$=new dr(void 0);this.playingRepresentationInit$=new dr(void 0);this.error$=new K0;this.gaps=[];this.subscription=new X0;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new ae;this.switchAbortController=new ae;this.destroyAbortController=new ae;this.bufferLimit=1/0;this.failedDownloads=0;this.baseUrls=[];this.baseUrlsIndex=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.lastDataObtainedTimestampMs=0;this.loadByteRangeSegmentsTimeoutId=0;this.startWith=Ci(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);nt(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new DT(this.sourceBuffer),this.subscription.add(vp(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:Si.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o!=null||(o={id:"SegmentEjection",category:Si.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),this.error$.next(o)})),this.subscription.add(vp(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:Si.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o||!q(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,Kr(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=this.getForwardBufferDuration(o),d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,n*2,l<d).catch(c=>{this.handleAsyncError(c,"pruneBuffer")})})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);let i=this.initData.get(t.id),r=this.segments.get(t.id),a=this.parsedInitData.get(t.id);nt(i,"No init buffer for starting representation"),nt(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=Ci(this.destroyAbortController.signal,async function*(e,t=!1){if(!q(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);nt(i,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if(Ue(a)||Ue(r)?yield this.loadInit(i,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),nt(r,"No segments for starting representation"),a=this.initData.get(e),!(!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer||!q(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();es(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=Ci(this.destroyAbortController.signal,async function*(e,t=!1){if(!q(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);nt(i,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if(Ue(a)||Ue(r)?yield this.loadInit(i,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),nt(r,"No segments for starting representation"),a=this.initData.get(e),!(!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer||!q(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();es(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=Ci(this.destroyAbortController.signal,async function*(e){var u,l;let t=(u=(0,Du.default)(e,d=>d.representations))!=null?u:[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let d of this.representations.keys()){let c=t.find(f=>f.id===d);c&&this.representations.set(d,c);let h=this.representations.get(d);if(!h||!Je(h.segmentReference))return;let p=this.getActualLiveStartingSegments(h.segmentReference);this.segments.set(h.id,p)}let i=(l=this.switchingToRepresentationId)!=null?l:this.downloadingRepresentationId,r=this.representations.get(i);nt(r);let a=this.segments.get(i);nt(a,"No segments for starting representation");let n=this.initData.get(i);if(nt(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer))return;let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(a,r),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));var d;this.fetcher=r,this.tuning=a,this.compatibilityMode=u,this.forwardBufferTarget=a.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!(l!=null&&l.live),this.baseUrls=(d=l==null?void 0:l.baseUrls)!=null?d:[],this.initData=new Map(i.map(c=>[c.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(c=>[c.id,c])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchToWithPreviousAbort(e,t=!1){!q(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new ae,Ci(this.switchAbortController.signal,async function*(i,r=!1){this.switchingToRepresentationId=i;let a=this.representations.get(i);nt(a,`No such representation ${i}`);let n=this.segments.get(i),o=this.initData.get(i);if(Ue(o)||Ue(n)?yield this.loadInit(a,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(i),nt(n,"No segments for starting representation"),o=this.initData.get(i),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer||!q(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(o,this.downloadAbortController.signal),r)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=i,yield this.dropBuffer();else{let u=this.getCurrentPosition();es(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(){!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 ae,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(Ue(e)||Ue(this.downloadingRepresentationId)||Ue(this.playingRepresentationId)||Ue(this.sourceBuffer)||!q(this.mediaSource,this.sourceBuffer)||es(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(nt(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;let r=i.find(d=>e>=d.time.from&&e<d.time.to);es(r)&&isFinite(r.time.from)&&isFinite(r.time.to)&&this.currentSegmentLength$.next((r==null?void 0:r.time.to)-r.time.from);let a=e,n=100;if(this.playingRepresentationId!==this.downloadingRepresentationId){let d=this.getForwardBufferDuration(e),c=r?r.time.to+n:-1/0;r&&r.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&d>=r.time.to-e+n&&(a=c)}if(isFinite(this.bufferLimit)&&Kr(this.sourceBuffer.buffered)>=this.bufferLimit){let d=this.getForwardBufferDuration(e),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,d<c).catch(h=>{this.handleAsyncError(h,"pruneBuffer")});return}let u=[];if(!this.activeSegments.size&&(u=this.selectForwardBufferSegments(i,t.segmentReference.type,a),u.length)){let d="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if((0,$u.default)(u,r))d="high";else{let c=(0,ts.default)(u,0);c&&c.time.from-r.time.to>=this.forwardBufferTarget/2&&(d="low")}this.loadSegments(u,t,d).catch(c=>{this.handleAsyncError(c,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&r&&r.status==="fed"&&!u.length&&this.getForwardBufferDuration(e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let l=(0,ts.default)(i,-1);!this.isLive&&l&&(this.fullyBuffered$.next(l.time.to-e-this.getForwardBufferDuration(e)<n),this.onLastSegment$.next(e-l.time.from>0))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let i=0,r=this.isLive?this.liveInitialAdditionalOffset:0;for(let a of e)Math.trunc(a.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:a.time.from+r}),i=a.time.to;es(t.duration)&&t.duration-i>0&&!this.isLive&&this.gaps.push({representation:t.id,from:i,to:t.duration})}getActualLiveStartingSegments(e){let t=e.segments,i=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,r=[],a=0,n=t.length-1;do r.unshift(t[n]),a+=t[n].time.to-t[n].time.from,n--;while(a<i&&n>=0);return this.liveInitialAdditionalOffset=a-i,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){let t=(0,Du.default)(e==null?void 0:e.streams[this.kind],r=>r.representations).find(r=>r.id===this.downloadingRepresentationId);if(!t)return;let i=this.segments.get(t.id);if(i!=null&&i.length)return{from:i[0].time.from,to:i[i.length-1].time.to}}updateLive(e){var i,r,a,n;let t=(i=(0,Du.default)(e==null?void 0:e.streams[this.kind],o=>o.representations))!=null?i:[];if(![...this.segments.values()].every(o=>!o.length))for(let o of t){if(!o||!Je(o.segmentReference))return;let u=o.segmentReference.segments.map(p=>({...p,status:"none",size:void 0})),l=100,d=(r=this.segments.get(o.id))!=null?r:[],c=(n=(a=(0,ts.default)(d,-1))==null?void 0:a.time.to)!=null?n:0,h=u==null?void 0:u.findIndex(p=>c>=p.time.from+l&&c<=p.time.to+l);if(h===-1){this.liveUpdateSegmentIndex=0;let p=this.getActualLiveStartingSegments(o.segmentReference);this.segments.set(o.id,p)}else{let p=u.slice(h+1);this.segments.set(o.id,[...d,...p])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;nt(e);let t=this.segments.get(e);if(t!=null&&t.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}updateLowLatencyLiveIfNeeded(e){var i;let t=0;for(let r of this.representations.values()){let a=r.segmentReference;if(!Je(a))return;let n=(i=this.segments.get(r.id))!=null?i:[],o=n.find(l=>Math.floor(l.time.from)===Math.floor(e.time.from));if(o&&!isFinite(o.time.to)&&(o.time.to=e.time.to,t=o.time.to-o.time.from),!!!n.find(l=>Math.floor(l.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let l=Math.round(e.time.to*a.timescale/1e3).toString(10),d=gi(a.segmentTemplateUrl,{segmentTime:l});n.push({status:"none",time:{from:e.time.to,to:1/0},url:d})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){var a,n,o;let t=(n=(a=this.switchingToRepresentationId)!=null?a:this.downloadingRepresentationId)!=null?n:this.playingRepresentationId;if(!t)return;let i=this.segments.get(t);if(!i)return;let r=i.find(u=>u.time.from<=e&&u.time.to>=e);return(o=r==null?void 0:r.time.from)!=null?o:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)==null||e.destroy(),this.gapDetectionIdleCallback&&Yt&&Yt(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&Yt&&Yt(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}this.sourceBuffer=null,this.downloadAbortController.abort(),this.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,i){return this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){let i=e.findIndex(r=>t>=r.time.from&&t<r.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=i),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,i){let r=this.getForwardBufferDuration(i),a=e.findIndex(({status:h,time:{from:p,to:f}},m)=>{let g=p<=i&&f>=i,S=p>i||g||m===0&&i===0,v=Math.min(this.forwardBufferTarget,this.bufferLimit),y=this.preloadOnly&&p<=i+v||r<v&&f-p>=v||f<=i+v;return(h==="none"||h==="partially_ejected"&&S&&y&&this.sourceBuffer&&q(this.mediaSource,this.sourceBuffer)&&!(Ne(this.sourceBuffer.buffered,p)&&Ne(this.sourceBuffer.buffered,f)))&&S&&y});if(a===-1)return[];if(t!=="byteRange")return e.slice(a,a+1);let n=e,o=0,u=0,l=[],d=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,c=this.preloadOnly?this.forwardBufferTarget:0;for(let h=a;h<n.length&&(o<=d||u<=c);h++){let p=n[h];if(o+=p.byte.to+1-p.byte.from,u+=p.time.to+1-p.time.from,p.status==="none"||p.status==="partially_ejected")l.push(p);else break}return l}async loadSegments(e,t,i="auto"){Je(t.segmentReference)?await this.loadTemplateSegment(e[0],t,i):await this.loadByteRangeSegments(e,t,i)}async loadTemplateSegment(e,t,i="auto"){e.status="downloading";let r={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(r);let{range:a,url:n,signal:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await Ci(o,async function*(){let d=yp(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,d))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let d=await this.fetcher.fetch(n,{range:a,signal:o,onProgress:u,priority:i,isLowLatency:this.isActiveLowLatency()});if(this.lastDataObtainedTimestampMs=Bu(),!d)return;let c=new DataView(d),h=fn(t.mime);if(!isFinite(r.segment.time.to)){let m=t.segmentReference.timescale;r.segment.time.to=h.getChunkEndTime(c,m)}u&&r.feedingBytes&&l?await Promise.all(l):await this.sourceBufferTaskQueue.append(c,o);let{serverDataReceivedTimestamp:p,serverDataPreparedTime:f}=h.getServerLatencyTimestamps(c);p&&f&&this.currentLiveSegmentServerLatency$.next(f-p),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(d){this.abortActiveSegments([e]),mn(d)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}updateRepresentationsBaseUrlIfNeeded(){if(!this.tuning.dash.enableBaseUrlSupport||!this.baseUrls.length||this.failedDownloads<=this.tuning.dash.maxSegmentRetryCount)return;this.baseUrlsIndex=(this.baseUrlsIndex+1)%this.baseUrls.length;let e=this.baseUrls[this.baseUrlsIndex];for(let t of this.representations.values())Je(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}async loadByteRangeSegments(e,t,i="auto"){if(!e.length)return;for(let u of e)u.status="downloading",this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:r,url:a,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(await Ci(n,async function*(){let u=yp(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),vp(window,"online").pipe(Y0()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(a,{range:r,onProgress:o,signal:n,priority:i}),this.lastDataObtainedTimestampMs=Bu(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),mn(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(Je(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:(0,ts.default)(e,0).byte.from,to:(0,ts.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=Bu(),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:Si.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!Je(t.segmentReference))throw new Error("Representation is not template type");let i=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&i.searchParams.set("low-latency","yes");let r=i.toString(),{signal:a}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,d)=>{if(!a.aborted)try{this.lastDataObtainedTimestampMs=Bu();let c=this.onSomeTemplateDataLoaded({dataView:l,loaded:d,signal:a,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(c)}catch(c){this.error$.next({id:"SegmentFeeding",category:Si.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,$u.default)(e,t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:a}){if(!this.activeSegments.size||!q(this.mediaSource,this.sourceBuffer))return;let n=this.representations.get(t);if(n)for(let o of this.activeSegments){let{segment:u}=o;if(o.representationId===t){if(a.aborted){r();continue}if(o.loadedBytes=i,o.loadedBytes>o.feedingBytes){let l=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),d=fn(n.mime).parseFeedableSegmentChunk(l,this.isLive);d!=null&&d.byteLength&&(u.status="partially_fed",o.feedingBytes+=d.byteLength,await this.sourceBufferTaskQueue.append(d),o.fedBytes+=d.byteLength)}}}}async onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:a,onSegmentAppendFailed:n}){if(!this.activeSegments.size||!q(this.mediaSource,this.sourceBuffer))return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){let{segment:l}=u;if(u.representationId!==t)continue;if(a.aborted){await n();continue}let d=l.byte.from-i,c=l.byte.to-i,h=c-d+1,p=d<r,f=c<=r;if(!p)continue;let m=fn(o.mime);if(l.status==="downloading"&&f){l.status="downloaded";let g=new DataView(e.buffer,e.byteOffset+d,h);await this.sourceBufferTaskQueue.append(g,a)&&!a.aborted?this.onSegmentFullyAppended(u,t):await n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(l.status==="downloading"||l.status==="partially_fed")&&(u.loadedBytes=Math.min(h,r-d),u.loadedBytes>u.feedingBytes)){let g=new DataView(e.buffer,e.byteOffset+d+u.feedingBytes,u.loadedBytes-u.feedingBytes),S=u.loadedBytes===h?g:m.parseFeedableSegmentChunk(g);S!=null&&S.byteLength&&(l.status="partially_fed",u.feedingBytes+=S.byteLength,await this.sourceBufferTaskQueue.append(S,a)&&!a.aborted?(u.fedBytes+=S.byteLength,u.fedBytes===h&&this.onSegmentFullyAppended(u,t)):await n())}}}onSegmentFullyAppended(e,t){var i;if(!(Ue(this.sourceBuffer)||!q(this.mediaSource,this.sourceBuffer))){!this.isLive&&j.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(Ne(this.sourceBuffer.buffered,e.segment.time.from,100)&&Ne(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:Si.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",mp(e.segment)&&(e.segment.size=e.fedBytes);for(let r of this.representations.values())if(r.id!==t)for(let a of(i=this.segments.get(r.id))!=null?i:[])a.status==="fed"&&Math.round(a.time.from)===Math.round(e.segment.time.from)&&Math.round(a.time.to)===Math.round(e.segment.time.to)&&(a.status="none");this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}}abortSegment(e){e.status==="partially_fed"?e.status="partially_ejected":e.status!=="partially_ejected"&&(e.status="none");for(let t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[r,a]of this.initData.entries()){let n=a instanceof Promise;t||(t=n),a===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let i=this.representations.get(e);i&&(this.initLoadIdleCallback=Yr(()=>(0,CI.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?Ci(this.destroyAbortController.signal,async function*(){let o=yp(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,fn(e.mime),r)).then(async o=>{if(!o)return;let{init:u,dataView:l,segments:d}=o,c=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,c);let h=d;this.isLive&&Je(e.segmentReference)&&(h=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,h),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:Si.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n}async dropBuffer(){for(let e of this.segments.values())for(let t of e)t.status="none";await this.pruneBuffer(0,1/0,!0)}async pruneBuffer(e,t,i=!1){if(!this.sourceBuffer||!q(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||Ue(e))return!1;let r=[],a=0,n=u=>{u.sort((d,c)=>d.from-c.from);let l=[u[0]];for(let d=1;d<u.length;d++){let{from:c,to:h}=u[d],p=l[l.length-1];p.to>=c?p.to=Math.max(p.to,h):l.push(u[d])}return l},o=u=>{var d;if(a>=t)return r;r.push({...u.time}),r=n(r);let l=mp(u)?(d=u.size)!=null?d:0:u.byte.to-u.byte.from;a+=l};for(let u of this.segments.values())for(let l of u){let d=l.time.to<=e-this.tuning.dash.bufferPruningSafeZone,c=l.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(d||c)&&l.status==="fed"&&o(l)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let l=this.sourceBuffer.buffered.start(u)*1e3,d=this.sourceBuffer.buffered.end(u)*1e3,c=0;for(let h of this.segments.values())for(let p of h)(0,$u.default)(["none","partially_ejected"],p.status)&&Math.round(p.time.from)<=Math.round(l)&&Math.round(p.time.to)>=Math.round(d)&&c++;if(c===this.segments.size){let h={time:{from:l,to:d},url:"",status:"none"};o(h)}}if(r.length&&i){let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let l of this.segments.values())for(let d of l)d.time.from>=e+u&&d.status==="fed"&&o(d)}return r.length?(await Promise.all(r.map(l=>this.sourceBufferTaskQueue.remove(l.from,l.to)))).reduce((l,d)=>l||d,!1):!1}async abortBuffer(){if(!this.sourceBuffer||!q(this.mediaSource,this.sourceBuffer))return!1;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;return this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!q(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}getForwardBufferDuration(e=this.getCurrentPosition()){return!this.sourceBuffer||!q(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||Ue(e)?0:$e(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!(!this.sourceBuffer||!q(this.mediaSource,this.sourceBuffer))){if(this.tuning.useRefactoredSearchGap)for(let i=0;i<this.sourceBuffer.buffered.length;i++)this.gaps=this.gaps.filter(r=>this.sourceBuffer&&(Math.round(r.from)<Math.round(this.sourceBuffer.buffered.start(i)*1e3)||Math.round(r.to)>Math.round(this.sourceBuffer.buffered.end(i)*1e3)));for(let i of t){let r={representation:e,from:i.time.from,to:i.time.to};for(let a=0;a<this.sourceBuffer.buffered.length;a++){let n=this.sourceBuffer.buffered.start(a)*1e3,o=this.sourceBuffer.buffered.end(a)*1e3;if(!(o<=i.time.from||n>=i.time.to)){if(n<=i.time.from&&o>=i.time.to){r=void 0;break}o>i.time.from&&o<i.time.to&&(r.from=o),n<i.time.to&&n>i.time.from&&(r.to=n)}}r&&r.to-r.from>1&&!this.gaps.some(a=>r&&a.from===r.from&&a.to===r.to)&&this.gaps.push(r)}}}detectGapsWhenIdle(e,t){if(!(this.gapDetectionIdleCallback||!this.sourceBuffer||!q(this.mediaSource,this.sourceBuffer))){if(!this.tuning.useRefactoredSearchGap)for(let i=0;i<this.sourceBuffer.buffered.length;i++)this.gaps=this.gaps.filter(r=>this.sourceBuffer&&(Math.round(r.from)<Math.round(this.sourceBuffer.buffered.start(i)*1e3)||Math.round(r.to)>Math.round(this.sourceBuffer.buffered.end(i)*1e3)));this.gapDetectionIdleCallback=Yr(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:Si.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if(Ue(this.sourceBuffer)||!q(this.mediaSource,this.sourceBuffer)||Ue(this.playingRepresentationId))return;let e=[];for(let i=0;i<this.sourceBuffer.buffered.length;i++){let r=Math.floor(this.sourceBuffer.buffered.start(i)*1e3),a=Math.ceil(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:r,to:a})}let t=100;for(let i of this.segments.values())for(let r of i){let{status:a}=r;if(a!=="fed"&&a!=="partially_ejected")continue;let n=Math.floor(r.time.from),o=Math.ceil(r.time.to),u=e.some(d=>d.from-t<=n&&d.to+t>=o),l=e.filter(d=>n>=d.from&&n<d.to-t||o>d.from+t&&o<=d.to);u||(l.length===1?r.status="partially_ejected":this.gaps.some(d=>d.from===r.time.from||d.to===r.time.to)?r.status="partially_ejected":r.status="none")}}handleAsyncError(e,t){this.error$.next({id:t,category:Si.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}};var Vi=s=>{let e=new URL(s);return e.searchParams.set("quic","1"),e.toString()};var Cu=s=>{var a;let e=s.get("X-Delivery-Type"),t=s.get("X-Reused"),i=e===null?"http1":e!=null?e:void 0,r=t===null?void 0:(a={1:!0,0:!1}[t])!=null?a:void 0;return{type:i,reused:r}};import{abortable as gn,assertNever as VI,fromEvent as OI,merge as J0,now as Sn,Subscription as Z0,Subject as _I,ValueSubject as Tp,flattenObject as is,ErrorCategory as vn}from"@vkontakte/videoplayer-shared/es2018";var Vu=s=>{let e=new URL(s);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var _u=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:a=!1}){this.lastConnectionType$=new Tp(void 0);this.lastConnectionReused$=new Tp(void 0);this.lastRequestFirstBytes$=new Tp(void 0);this.recoverableError$=new _I;this.error$=new _I;this.abortAllController=new ae;this.subscription=new Z0;this.fetchManifest=gn(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=Vi(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=Vu(i));let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(Ou);return r?(t.log("success",is({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(r.headers),r.text()):(t.error("error",is({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=gn(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:a="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1}={}){var C,L;let l=e,d=new Headers,c=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{d.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let R=new URL(l,location.href);R.searchParams.append("bytes",`${i.from}-${i.to}`),l=R.toString();break}default:VI(t)}this.requestQuic&&(l=Vi(l));let h=this.abortAllController.signal,p;if(n){let R=new ae;if(p=J0(OI(this.abortAllController.signal,"abort"),OI(n,"abort")).subscribe(()=>{try{R.abort()}catch(Q){Ou(Q)}}),this.subscription.add(p),this.abortAllController.signal.aborted||n.aborted)try{R.abort()}catch(Q){Ou(Q)}h=R.signal}let f=Sn();c.log("startRequest",is({url:l,priority:a,rangeMethod:t,range:i,isLowLatency:u,requestStartedAt:f}));let m=yield this.doFetch(l,{priority:a,headers:d,signal:h}),g=Sn();if(!m)return c.error("error",{message:"No response in request"}),c.end(),p==null||p.unsubscribe(),null;if((C=this.throughputEstimator)==null||C.addRawRtt(g-f),!m.ok||!m.body){p==null||p.unsubscribe();let R=`Fetch error ${m.status}: ${m.statusText}`;return c.error("error",{message:R}),c.end(),Promise.reject(new Error(`Fetch error ${m.status}: ${m.statusText}`))}if(this.onHeadersReceived(m.headers),!r&&!o){p==null||p.unsubscribe();let R=Sn(),Q={requestStartedAt:f,requestEndedAt:R,duration:R-f};return c.log("endRequest",is(Q)),c.end(),m.arrayBuffer()}let[S,v]=m.body.tee(),y=S.getReader();o&&((L=this.throughputEstimator)==null||L.trackStream(v,u));let I=0,T=new Uint8Array(0),E=!1,O=R=>{p==null||p.unsubscribe(),E=!0,Ou(R)},B=gn(h,async function*({done:R,value:Q}){if(I===0&&this.lastRequestFirstBytes$.next(Sn()-f),h.aborted){p==null||p.unsubscribe();return}if(!R&&Q){let U=new Uint8Array(T.length+Q.length);U.set(T),U.set(Q,T.length),T=U,I+=Q.byteLength,r==null||r(new DataView(T.buffer),I),yield y==null?void 0:y.read().then(B,O)}}.bind(this));yield y==null?void 0:y.read().then(B,O),p==null||p.unsubscribe();let w=Sn(),P={failed:E,requestStartedAt:f,requestEndedAt:w,duration:w-f};return E?(c.error("endRequest",is(P)),c.end(),null):(c.log("endRequest",is(P)),c.end(),T.buffer)}.bind(this));this.fetchByteRangeRepresentation=gn(this.abortAllController.signal,async function*(e,t,i){var S;if(e.type!=="byteRange")return null;let{from:r,to:a}=e.initRange,n=r,o=a,u=!1,l,d;e.indexRange&&(l=e.indexRange.from,d=e.indexRange.to,u=a+1===l,u&&(n=Math.min(l,r),o=Math.max(d,a))),n=Math.min(n,0);let c=yield this.fetch(e.url,{range:{from:n,to:o},priority:i,measureThroughput:!1});if(!c)return null;let h=new DataView(c,r-n,a-n+1);if(!t.validateData(h))throw new Error("Invalid media file");let p=t.parseInit(h),f=(S=e.indexRange)!=null?S:t.getIndexRange(p);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 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,p,f);return{init:p,dataView:new DataView(c),segments:g}}.bind(this));this.fetchTemplateRepresentation=gn(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}=Cu(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,t,i="auto"){var a,n;let{type:r}=e;switch(r){case"byteRange":return(a=await this.fetchByteRangeRepresentation(e,t,i))!=null?a:null;case"template":return(n=await this.fetchTemplateRepresentation(e,i))!=null?n:null;default:VI(r)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}async doFetch(e,t){let i=await wt(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:vn.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:vn.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:vn.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:vn.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${a})`,category:vn.FATAL})}}},Ou=s=>{if(!mn(s))throw s};var vi=(s,e,t)=>t*e+(1-t)*s,Ip=(s,e)=>s.reduce((t,i)=>t+i,0)/e,FI=(s,e,t,i)=>{let r=0,a=t,n=Ip(s,e),o=e<i?e:i;for(let u=0;u<o;u++)s[a]>n?r++:r--,a=(s.length+a-1)%s.length;return Math.abs(r)===o};import{isNullable as eC,ValueSubject as NI}from"@vkontakte/videoplayer-shared/es2018";var Oi=class{constructor(e){this.prevReported=void 0;this.pastMeasures=[];this.takenMeasures=0;this.measuresCursor=0;var i;this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new NI(e.initial),this.debounced$=new NI(e.initial);let t=(i=e.label)!=null?i:"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 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)&&(eC(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 Fu=class extends Oi{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=vi(this.slow,e,this.params.emaAlphaSlow),this.fast=vi(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var Nu=class extends Oi{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=Ip(this.pastMeasures,this.takenMeasures);this.emaSmoothed=vi(this.emaSmoothed,e,this.params.emaAlpha);let i=FI(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}};var Uu=class extends Oi{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?vi(this.smoothed,t,this.params.emaAlpha):t}};var yi=class{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new Fu({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new Nu({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 Uu({initial:e,label:"liveEdgeDelay",...t})}};var rs=(s,e)=>{s&&s.playbackRate!==e&&(s.playbackRate=e)};import{isNullable as tC,ValueSubject as iC}from"@vkontakte/videoplayer-shared/es2018";var yn=class s{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==null?void 0:e.streams.text)}seekLive(e){this.processStreams(e)}maintain(e=this.getCurrentPosition()){var t;if(!tC(e))for(let i of this.representations)for(let r of i){let a=r.segmentReference,n=a.segments.length,o=a.segments[0].time.from,u=a.segments[n-1].time.to;if(e<o||e>u)continue;let l=a.segments.find(d=>d.time.from<=e&&d.time.to>=e);!l||((t=this.currentSegment)==null?void 0:t.time.from)===l.time.from&&this.currentSegment.time.to===l.time.to||(this.currentSegment=l,this.currentRepresentation$.next({...r,label:"Live Text",language:"ru",isAuto:!0,url:new URL(l.url,a.baseUrl).toString()}))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e!=null?e:[]){let i=s.filterRepresentations(t.representations);if(i){this.representations[this.representationsCursor]=i,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!(e!=null&&e.some(t=>s.filterRepresentations(t.representations)))}static filterRepresentations(e){return e==null?void 0:e.filter(t=>t.kind==="text"&&"segmentReference"in t&&Je(t.segmentReference))}};var ju=N(Ot(),1);import{assertNever as Hu}from"@vkontakte/videoplayer-shared/es2018";var UI=(s,{useManagedMediaSource:e,useOldMSEDetection:t})=>{let{containers:i,protocols:r,codecs:a,nativeHlsSupported:n}=j.video,o=(a.h264||a.h265)&&a.aac,u=r.mse&&(!t||!!window.MediaStreamTrack)||r.mms&&e;return s.filter(l=>{switch(l){case"DASH_SEP":return u&&i.mp4&&o;case"DASH_WEBM":return u&&i.webm&&a.vp9&&a.opus;case"DASH_WEBM_AV1":return u&&i.webm&&a.av1&&a.opus;case"DASH_STREAMS":return u&&(i.mp4&&o||i.webm&&(a.vp9||a.av1)&&(a.opus||a.aac));case"DASH_LIVE":return u&&i.mp4&&o;case"DASH_LIVE_CMAF":return u&&i.mp4&&o&&i.cmaf;case"DASH_ONDEMAND":return u&&i.mp4&&o;case"HLS":case"HLS_ONDEMAND":case"HLS_LIVE":case"HLS_LIVE_CMAF":return n;case"MPEG":return i.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return r.webrtc&&r.ws&&a.h264&&(i.mp4||i.webm);default:return Hu(l)}})},qu=s=>{let{webmDecodingInfo:e}=j.video,t="DASH_WEBM",i="DASH_WEBM_AV1";switch(s){case"vp9":return[t,i];case"av1":return[i,t];case"none":return[];case"smooth":return e?e[i].smooth?[i,t]:e[t].smooth?[t,i]:[i,t]:[t,i];case"power_efficient":return e?e[i].powerEfficient?[i,t]:e[t].powerEfficient?[t,i]:[i,t]:[t,i];default:Hu(s)}return[t,i]},qI=({webmCodec:s,androidPreferredFormat:e,preferMultiStream:t})=>{let i=[...t?["DASH_STREAMS"]:[],...qu(s),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],r=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(j.device.isAndroid)switch(e){case"mpeg":return["MPEG",...i,"HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...i,"MPEG"];case"dash":return[...i,"HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return[...r,"MPEG",...qu(s),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...qu(s),"MPEG",...r,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...qu(s),...r,"HLS","HLS_ONDEMAND"];default:Hu(e)}return j.video.nativeHlsSupported?[...i,"HLS","HLS_ONDEMAND","MPEG"]:[...i,"HLS","HLS_ONDEMAND","MPEG"]},jI=({androidPreferredFormat:s,preferCMAF:e,preferWebRTC:t})=>{let i=e?["DASH_LIVE_CMAF","DASH_LIVE"]:["DASH_LIVE","DASH_LIVE_CMAF"],r=e?["HLS_LIVE_CMAF","HLS_LIVE"]:["HLS_LIVE","HLS_LIVE_CMAF"],a=[...i,...r],n=[...r,...i],o,u=j.device.isMac&&j.browser.isSafari;if(j.device.isAndroid)switch(s){case"dash":case"dash_any_mpeg":case"dash_any_webm":case"dash_sep":{o=a;break}case"hls":case"mpeg":{o=n;break}default:Hu(s)}else j.video.nativeHlsSupported&&!u?o=n:u?o=e?["DASH_LIVE_CMAF","HLS_LIVE_CMAF","HLS_LIVE","DASH_LIVE"]:["HLS_LIVE","DASH_LIVE","DASH_LIVE_CMAF","HLS_LIVE_CMAF"]:o=a;return t?["WEB_RTC_LIVE",...o]:[...o,"WEB_RTC_LIVE"]},xp=s=>s?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],zu=s=>{if(s.size===0)return;if(s.size===1){let t=s.values().next();return(0,ju.default)(t.value.split("."),0)}for(let t of s){let i=(0,ju.default)(t.split("."),0);if(i==="opus"||i==="vp09"||i==="av01")return i}let e=s.values().next();return(0,ju.default)(e.value.split("."),0)};var cC=["timeupdate","progress","play","seeked","stalled","waiting"],dC=["timeupdate","progress","loadeddata","playing","seeked"];var Wu=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new QI;this.representationSubscription=new QI;this.state$=new G("none");this.currentVideoRepresentation$=new he(void 0);this.currentVideoRepresentationInit$=new he(void 0);this.currentAudioRepresentation$=new he(void 0);this.currentVideoSegmentLength$=new he(0);this.currentAudioSegmentLength$=new he(0);this.error$=new Gu;this.lastConnectionType$=new he(void 0);this.lastConnectionReused$=new he(void 0);this.lastRequestFirstBytes$=new he(void 0);this.currentLiveTextRepresentation$=new he(null);this.isLive$=new he(!1);this.isActiveLive$=new he(!1);this.isLowLatency$=new he(!1);this.liveDuration$=new he(0);this.liveSeekableDuration$=new he(0);this.liveAvailabilityStartTime$=new he(0);this.liveStreamStatus$=new he(void 0);this.bufferLength$=new he(0);this.liveLatency$=new he(void 0);this.liveLoadBufferLength$=new he(0);this.livePositionFromPlayer$=new he(0);this.currentStallDuration$=new he(0);this.videoLastDataObtainedTimestamp$=new he(0);this.fetcherRecoverableError$=new Gu;this.fetcherError$=new Gu;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new Gu;this.gapWatchdogActive=!1;this.destroyController=new ae;this.initManifest=wp(this.destroyController.signal,async function*(e,t,i){var r;this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=Se(t,i,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),(r=this.manifest)!=null&&r.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:Ft.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=wp(this.destroyController.signal,async function*(){var n,o;this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(u=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:Ft.NETWORK,message:"Failed to load manifest",thrown:u})});if(!e)return null;let t=null;try{t=$I(e!=null?e:"",this.manifestUrlString)}catch(u){let l=(n=Mu(e))!=null?n:{id:"ManifestParsing",category:Ft.PARSER,message:"Failed to parse MPD manifest",thrown:u};this.error$.next(l)}if(!t)return null;let i=(u,l,d)=>{var c,h,p,f;return!!((h=(c=this.element)==null?void 0:c.canPlayType)!=null&&h.call(c,l)&&((f=(p=vt())==null?void 0:p.isTypeSupported)!=null&&f.call(p,`${l}; codecs="${d}"`))||u==="text")};if(t.live){this.isLive$.next(!!t.live);let{availabilityStartTime:u,latestSegmentPublishTime:l,streamIsUnpublished:d,streamIsAlive:c}=t.live,h=((o=t.duration)!=null?o:0)/1e3;this.liveSeekableDuration$.next(-1*h),this.liveDuration$.next((l-u)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let p="active";c||(p=d?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(p)}let r={text:t.streams.text,video:[],audio:[]};for(let u of["video","audio"]){let d=t.streams[u].filter(({mime:p,codecs:f})=>i(u,p,f)),c=new Set(d.map(({codecs:p})=>p)),h=zu(c);if(h&&(r[u]=d.filter(({codecs:p})=>p.startsWith(h))),u==="video"){let p=this.tuning.preferHDR,f=r.video.some(g=>g.hdr),m=r.video.some(g=>!g.hdr);j.display.isHDR&&p&&f?r.video=r.video.filter(g=>g.hdr):m&&(r.video=r.video.filter(g=>!g.hdr))}}let a={...t,streams:r};return this.tracer.log("updateManifestEnd",In(a)),a}.bind(this));this.initRepresentations=wp(this.destroyController.signal,async function*(e,t,i){var h;this.tracer.log("initRepresentationsStart",In({initialVideo:e,initialAudio:t,sourceHls:i})),ss(this.manifest),ss(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let r=p=>{this.representationSubscription.add(Ti(p,"error").pipe(Qu(f=>{var m;return!!((m=this.element)!=null&&m.played.length)})).subscribe(f=>{this.error$.next({id:"VideoSource",category:Ft.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:f})}))};this.source=this.tuning.useManagedMediaSource?nu():new MediaSource;let a=document.createElement("source");if(r(a),a.src=URL.createObjectURL(this.source),this.element.appendChild(a),this.tuning.useManagedMediaSource&&Ur())if(i){let p=document.createElement("source");r(p),p.type="application/x-mpegurl",p.src=i.url,this.element.appendChild(p)}else this.element.disableRemotePlayback=!0;this.isActiveLive$.next(this.isLive$.getValue());let n={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),manifest:this.manifest},o=this.manifest.streams.video.reduce((p,f)=>[...p,...f.representations],[]);if(this.videoBufferManager=new bn("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],xn(t)){let p=this.manifest.streams.audio.reduce((f,m)=>[...f,...m.representations],[]);this.audioBufferManager=new bn("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}yn.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new yn(this.manifest.streams.text,n)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$));let u=()=>{var p;(p=this.stallWatchdogSubscription)==null||p.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add(pr(...dC.map(p=>Ti(this.element,p))).pipe(ns(p=>this.element?$e(this.element.buffered,this.element.currentTime*1e3):0),Tn(),uC(p=>{p>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add(pr(Ti(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe(Tn()).subscribe(f=>this.liveStreamEndTimestamp=Pp())),this.subscription.add(Ti(this.element,"pause").subscribe(()=>{this.livePauseWatchdogSubscription=Ap(1e3).subscribe(f=>{let m=Mi(this.manifestUrlString,2);this.manifestUrlString=Se(this.manifestUrlString,m+1e3,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add(Ti(this.element,"play").subscribe(f=>{var m;return(m=this.livePauseWatchdogSubscription)==null?void 0:m.unsubscribe()})),this.representationSubscription.add(as({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(ns(({isActiveLive:f,isLowLatency:m})=>f&&m),Tn()).subscribe(f=>{this.isManualDecreasePlaybackInLive()||rs(this.element,1)})),this.representationSubscription.add(as({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(Qu(({bufferLength:f,isActiveLive:m,isLowLatency:g})=>m&&g&&!!f)).subscribe(({bufferLength:f})=>this.liveBuffer.next(f))),this.representationSubscription.add(this.videoBufferManager.currentLowLatencySegmentLength$.subscribe(f=>{if(!this.isActiveLive$.getValue()&&!this.isLowLatency$.getValue()&&!f)return;let m=this.liveSeekableDuration$.getValue()-f/1e3;this.liveSeekableDuration$.next(Math.max(m,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+f/1e3)})),this.representationSubscription.add(as({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(Qu(({isLive:f})=>f),Tn((f,m)=>m.bufferLength<f.bufferLength),ns(({rtt:f,bufferLength:m,segmentServerLatency:g})=>{let S=Mi(this.manifestUrlString,2);return(f/2+m+g+S)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(as({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:f,isActiveLive:m,isLowLatency:g})=>{if(!g||!m)return;let S=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,v=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,y=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,I=f-S;if(this.isManualDecreasePlaybackInLive())return;let T=1;Math.abs(I)>v&&(T=1+Math.sign(I)*y),rs(this.element,T)})),this.representationSubscription.add(this.bufferLength$.subscribe(f=>{var g,S;let m=0;if(f){let v=((S=(g=this.element)==null?void 0:g.currentTime)!=null?S:0)*1e3;m=Math.min(...this.bufferManagers.map(I=>{var T,E;return(E=(T=I.getLiveSegmentsToLoadState(this.manifest))==null?void 0:T.to)!=null?E:v}))-v}this.liveLoadBufferLength$.getValue()!==m&&this.liveLoadBufferLength$.next(m)}));let p=0;this.representationSubscription.add(as({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(lC(1e3)).subscribe(async({liveLoadBufferLength:f,bufferLength:m})=>{if(!this.element||this.isUpdatingLive)return;let g=this.element.playbackRate,S=Mi(this.manifestUrlString,2),v=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,y=Math.min(v,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*g),I=this.tuning.dashCmafLive.normalizedActualBufferOffset*g,T=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*g,E=isFinite(f)?f:m,O=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),B=v<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(B);let w="none";if(O?w="active_low_latency":this.isLowLatency$.getValue()&&B?(this.bufferManagers.forEach(P=>P.proceedLowLatencyLive()),w="active_low_latency"):S!==0&&E<y?w="live_forward_buffering":E<y+T&&(w="live_with_target_offset"),isFinite(f)&&(p=f>p?f:p),w==="live_forward_buffering"||w==="live_with_target_offset"){let P=p-(y+I),C=this.normolizeLiveOffset(Math.trunc(S+P/g)),L=Math.abs(C-S),R=0;!f||L<=this.tuning.dashCmafLive.offsetCalculationError?R=S:C>0&&L>this.tuning.dashCmafLive.offsetCalculationError&&(R=C),this.manifestUrlString=Se(this.manifestUrlString,R,2)}(w==="live_with_target_offset"||w==="live_forward_buffering")&&(p=0,await this.updateLive())},f=>{this.error$.next({id:"updateLive",category:Ft.VIDEO_PIPELINE,thrown:f,message:"Failed to update live with subscription"})}))}let l=pr(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe(ns(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),d=pr(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe(ns(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue()))),c=as({allBuffersFull:l,someBufferEnded:d}).pipe(Tn(),ns(({allBuffersFull:p,someBufferEnded:f})=>p&&f),Qu(p=>p));if(this.representationSubscription.add(pr(this.forceEnded$,c).subscribe(()=>{var p;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(f=>!f.updating))try{(p=this.source)==null||p.endOfStream()}catch(f){this.error$.next({id:"EndOfStream",category:Ft.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:f})}})),this.representationSubscription.add(pr(...this.bufferManagers.map(p=>p.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.representationSubscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.representationSubscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.liveTextManager&&this.representationSubscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$)),this.source.readyState!=="open"){let p=this.tuning.dash.sourceOpenTimeout>=0;yield new Promise(f=>{var m;p&&(this.timeoutSourceOpenId=setTimeout(()=>{var g;if(((g=this.source)==null?void 0:g.readyState)==="open"){f();return}this.error$.next({id:"OpenOfStream",category:Ft.VIDEO_PIPELINE,message:"Failed to open MediaSource",thrown:new Error("Timeout reject when wait sourceopen event"),traceAsLog:!0})},this.tuning.dash.sourceOpenTimeout)),(m=this.source)==null||m.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),f()},{once:!0})})}if(!this.isLive$.getValue()){let p=[(h=this.manifest.duration)!=null?h:0,...(0,kp.default)((0,kp.default)([...this.manifest.streams.audio,...this.manifest.streams.video],f=>f.representations),f=>{let m=[];return f.duration&&m.push(f.duration),Je(f.segmentReference)&&f.segmentReference.totalSegmentsDurationMs&&m.push(f.segmentReference.totalSegmentsDurationMs),m})];this.source.duration=Math.max(...p)/1e3}this.audioBufferManager&&xn(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")}.bind(this));this.tick=()=>{var t,i,r,a;if(!this.element||!this.videoBufferManager||((t=this.source)==null?void 0:t.readyState)!=="open")return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),(i=this.audioBufferManager)==null||i.maintain(e),(r=this.liveTextManager)==null||r.maintain(e),(this.videoBufferManager.gaps.length||(a=this.audioBufferManager)!=null&&a.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=Ap(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),n=>{this.error$.next({id:"GapWatchdog",category:Ft.WTF,message:"Error handling gaps",thrown:n})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.fetcher=new _u({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.subscription.add(this.fetcher.recoverableError$.subscribe(this.fetcherRecoverableError$)),this.subscription.add(this.fetcher.error$.subscribe(this.fetcherError$)),this.liveBuffer=yi.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator}),this.initTracerSubscription()}async seekLive(e){var r,a,n;ss(this.element);let t=this.liveStreamStatus$.getValue()!=="active"?Pp()-this.liveStreamEndTimestamp:0,i=this.normolizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=Se(this.manifestUrlString,i,2),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await((r=this.videoBufferManager)==null?void 0:r.seekLive(this.manifest.streams.video)),await((a=this.audioBufferManager)==null?void 0:a.seekLive(this.manifest.streams.audio)),(n=this.liveTextManager)==null||n.seekLive(this.manifest.streams.text))}initBuffer(){ss(this.element),this.state$.setState("running"),this.subscription.add(pr(...cC.map(e=>Ti(this.element,e)),Ti(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:Ft.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(Ti(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(Ti(this.element,"waiting").subscribe(()=>{var t;this.element&&this.element.readyState===2&&!this.element.seeking&&Ne(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{var p,f,m,g,S,v,y,I,T,E,O;if(!this.element||((p=this.source)==null?void 0:p.readyState)!=="open")return;let i=this.currentStallDuration$.getValue();i+=50,this.currentStallDuration$.next(i);let r={timeInWaiting:i},a=Pp(),n=100,o=(m=(f=this.videoBufferManager)==null?void 0:f.lastDataObtainedTimestamp)!=null?m:0;this.videoLastDataObtainedTimestamp$.next(o);let u=(S=(g=this.audioBufferManager)==null?void 0:g.lastDataObtainedTimestamp)!=null?S:0,l=(y=(v=this.videoBufferManager)==null?void 0:v.getForwardBufferDuration())!=null?y:0,d=(T=(I=this.audioBufferManager)==null?void 0:I.getForwardBufferDuration())!=null?T:0,c=l<n&&a-o>this.tuning.dash.crashOnStallTWithoutDataTimeout,h=this.audioBufferManager&&d<n&&a-u>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((c||h)&&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 B=this.normolizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(B).catch(w=>{this.error$.next({id:"stallIntervalCallback",category:Ft.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:w})}),r.liveLastOffset=B}else{let B=this.element.currentTime*1e3;(E=this.videoBufferManager)==null||E.maintain(B),(O=this.audioBufferManager)==null||O.maintain(B),r.position=B}this.tracer.log("stallIntervalCallback",In(r))};(t=this.stallWatchdogSubscription)==null||t.unsubscribe(),this.stallWatchdogSubscription=Ap(50).subscribe(e,i=>{this.error$.next({id:"StallWatchdogCallback",category:Ft.NETWORK,message:"Can't restore DASH after stall.",thrown:i})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,i=!1){let r={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return this.tuning.useNewSwitchTo?this.currentStallDuration$.getValue()>0?r==null?void 0:r.switchToWithPreviousAbort(t,i):r==null?void 0:r.switchTo(t,i):r==null?void 0:r.switchToOld(t,i)}async seek(e,t){var r,a,n,o,u;ss(this.element),ss(this.videoBufferManager);let i;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?i=e:i=Math.max((r=this.videoBufferManager.findSegmentStartTime(e))!=null?r:e,(n=(a=this.audioBufferManager)==null?void 0:a.findSegmentStartTime(e))!=null?n:e),this.warmUpMediaSourceIfNeeded(i),Ne(this.element.buffered,i)||await Promise.all([this.videoBufferManager.abort(),(o=this.audioBufferManager)==null?void 0:o.abort()]),!(zI(this.element)||zI(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),(u=this.audioBufferManager)==null||u.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",In({requestedPosition:e,forcePrecise:t,position:i})))}warmUpMediaSourceIfNeeded(e=(t=>(t=this.element)==null?void 0:t.currentTime)()){var i;xn(this.element)&&xn(this.source)&&xn(e)&&((i=this.source)==null?void 0:i.readyState)==="ended"&&this.element.duration*1e3-e>this.tuning.dash.seekBiasInTheEnd&&this.bufferManagers.forEach(r=>r.warmUpMediaSource())}get isStreamEnded(){var e;return((e=this.source)==null?void 0:e.readyState)==="ended"}stop(){var e,t,i;this.tracer.log("stop"),(e=this.element)==null||e.querySelectorAll("source").forEach(r=>{URL.revokeObjectURL(r.src),r.remove()}),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(t=this.videoBufferManager)==null||t.destroy(),this.videoBufferManager=null,(i=this.audioBufferManager)==null||i.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){var e;return(e=this.manifest)==null?void 0:e.streams}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){var e;this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),((e=this.source)==null?void 0:e.readyState)==="open"&&Array.from(this.source.sourceBuffers).every(t=>!t.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=oC(this.tracer.error.bind(this.tracer));this.subscription.add(this.error$.subscribe(e("error")))}isManualDecreasePlaybackInLive(){if(!this.element||!this.isLive$.getValue())return!1;let e=1-this.element.playbackRate;return Number(e.toFixed(2))>Number(this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup.toFixed(2))}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){var e,t;this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&((e=this.bufferManagers)==null||e.forEach(i=>i.updateLive(this.manifest)),(t=this.liveTextManager)==null||t.updateLive(this.manifest)),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getDebugBufferState();if(!e)return;let t=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),i={isJumpGapAfterSeekLive:this.isJumpGapAfterSeekLive,isActiveLowLatency:t,initialCurrentTime:this.element.currentTime};this.isJumpGapAfterSeekLive&&!t&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let r=this.element.currentTime*1e3,a=[],n=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let o of this.bufferManagers)for(let u of o.gaps)o.playingRepresentation$.getValue()===u.representation&&u.from-n<=r&&u.to+n>r&&(this.element.duration*1e3-u.to<this.tuning.endGapTolerance?a.push(1/0):a.push(u.to));if(a.length){let o=Math.max(...a)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,o===1/0?this.forceEnded$.next():(this.element.currentTime=o/1e3,i={...i,gapEnds:a,jumpTo:o,resultCurrentTime:this.element.currentTime},this.tracer.log("jumpGap",In(i)))}}};var Yu=class{constructor(e,t){this.fov=e,this.orientation=t}};var Ku=class{constructor(e,t){this.rotating=!1;this.fading=!1;this.lastTickTS=0;this.lastCameraTurnTS=0;this.fadeStartSpeed=null;this.fadeTime=0;this.camera=e,this.options=t,this.rotationSpeed={x:0,y:0,z:0},this.fadeCorrection=1/(this.options.speedFadeTime/1e3)**2}turnCamera(e=0,t=0,i=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+i)}pointCameraTo(e=0,t=0,i=0){t=this.limitCameraRotationY(t);let r=e-this.camera.orientation.x,a=t-this.camera.orientation.y,n=i-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=i,this.lastCameraTurn={x:r,y:a,z:n},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,i){this.rotationSpeed.x=e!=null?e:this.rotationSpeed.x,this.rotationSpeed.y=t!=null?t:this.rotationSpeed.y,this.rotationSpeed.z=i!=null?i:this.rotationSpeed.z}startRotation(){this.rotating=!0}stopRotation(e=!1){e?(this.setRotationSpeed(0,0,0),this.fadeStartSpeed=null):this.startFading(this.rotationSpeed.x,this.rotationSpeed.y,this.rotationSpeed.z),this.rotating=!1}onCameraRelease(){if(this.lastCameraTurn&&this.lastCameraTurnTS){let e=Date.now()-this.lastCameraTurnTS;if(e<this.options.speedFadeThreshold){let t=(1-e/this.options.speedFadeThreshold)*this.options.rotationSpeedCorrection;this.startFading(this.lastCameraTurn.x*t,this.lastCameraTurn.y*t,this.lastCameraTurn.z*t)}}}startFading(e,t,i){this.setRotationSpeed(e,t,i),this.fadeStartSpeed={...this.rotationSpeed},this.fading=!0}stopFading(){this.fadeStartSpeed=null,this.fading=!0,this.fadeTime=0}limitCameraRotationY(e){return Math.max(-this.options.maxYawAngle,Math.min(e,this.options.maxYawAngle))}tick(e){if(!this.lastTickTS){this.lastTickTS=e,this.lastCameraTurnTS=Date.now();return}let t=e-this.lastTickTS,i=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i);else if(this.fading&&this.fadeStartSpeed){let r=-this.fadeCorrection*(this.fadeTime/1e3)**2+1;this.setRotationSpeed(this.fadeStartSpeed.x*r,this.fadeStartSpeed.y*r,this.fadeStartSpeed.z*r),r>0?this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}};var WI=`attribute vec2 a_vertex;
|
|
124
|
+
`})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(c,"i")}var NT=a=>{if(!(a!=null&&a.startsWith("P")))return;let e=(n,o)=>{let u=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(u)?0:u)*o},i=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(a),r=(i==null?void 0:i[1])==="-"?-1:1,s={days:e(i==null?void 0:i[5],r),hours:e(i==null?void 0:i[6],r),minutes:e(i==null?void 0:i[7],r),seconds:e(i==null?void 0:i[8],r)};return s.days*24*60*60*1e3+s.hours*60*60*1e3+s.minutes*60*1e3+s.seconds*1e3},lt=(a,e)=>{let t=a;t=(0,Nc.default)(t,"$$","$");let i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[r,s]of(0,UT.default)(i)){let n=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=(0,Nc.default)(t,n,(o,u)=>FT(s)?o:FT(u)?s:(0,qT.default)(s,parseInt(u,10),"0"))}return t},lo=(a,e)=>{var P,R,V,D,_,Y,J,T,k,x,w,B,ne,Fe,ie,W,ge,Se,ve,Ne,xt,Ot,ni,Ni,Nr,Jd,Zd,ep,tp,ip,rp,ap,sp,np,op,up,lp,cp,dp,pp,hp,fp,mp,bp,gp,Sp,vp,yp,Tp,Ip,Ep,xp,wp,Ap,Pp,Rp,kp,Lp,$p,Mp,Dp;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(et=>{var te,oi;return(oi=(te=et.textContent)==null?void 0:te.trim())!=null?oi:""}),o=(P=(0,HT.default)(n,0))!=null?P:"",u=s.getAttribute("type")==="dynamic",l=s.getAttribute("availabilityStartTime"),c=s.getAttribute("publishTime"),d=s.getElementsByTagName("vk:Attrs")[0],f=d==null?void 0:d.getElementsByTagName("vk:XLatestSegmentPublishTime")[0].textContent,p=d==null?void 0:d.getElementsByTagName("vk:XStreamIsLive")[0].textContent,h=d==null?void 0:d.getElementsByTagName("vk:XStreamIsUnpublished")[0].textContent,m=d==null?void 0:d.getElementsByTagName("vk:XPlaybackDuration")[0].textContent,b;u&&(b={availabilityStartTime:l?new Date(l).getTime():0,publishTime:c?new Date(c).getTime():0,latestSegmentPublishTime:f?new Date(f).getTime():0,streamIsAlive:p==="yes",streamIsUnpublished:h==="yes"});let S,y=s.getAttribute("mediaPresentationDuration"),v=[...s.getElementsByTagName("Period")],I=v.reduce((et,te)=>({...et,[te.id]:te.children}),{}),E=v.reduce((et,te)=>({...et,[te.id]:te.getAttribute("duration")}),{});y?S=NT(y):(0,Uc.default)(E).filter(et=>et).length&&!u?S=(0,Uc.default)(E).reduce((et,te)=>{var oi;return et+((oi=NT(te))!=null?oi:0)},0):m&&(S=parseInt(m,10));let A=0,M=(V=(R=s.getAttribute("profiles"))==null?void 0:R.split(","))!=null?V:[];for(let et of v.map(te=>te.id))for(let te of I[et]){let oi=(D=te.getAttribute("id"))!=null?D:"id"+(A++).toString(10),Ur=(_=te.getAttribute("mimeType"))!=null?_:"",ou=(Y=te.getAttribute("codecs"))!=null?Y:"",uu=(J=te.getAttribute("contentType"))!=null?J:Ur==null?void 0:Ur.split("/")[0],DE=(k=(T=te.getAttribute("profiles"))==null?void 0:T.split(","))!=null?k:[],Cp=(w=OT((x=te.getAttribute("lang"))!=null?x:""))!=null?w:{},Vs=(Fe=(ne=(B=te.querySelector("Label"))==null?void 0:B.textContent)==null?void 0:ne.trim())!=null?Fe:void 0,CE=te.querySelectorAll("Representation"),BE=te.querySelector("SegmentTemplate"),VE=(W=(ie=te.querySelector("Role"))==null?void 0:ie.getAttribute("value"))!=null?W:void 0,Ui=uu,ce={id:oi,language:Cp.language,isDefault:VE==="main",label:Vs,codecs:ou,hdr:Ui==="video"&&Fc(ou),mime:Ur,representations:[]};for(let ee of CE){let Ft=(ge=ee.getAttribute("lang"))!=null?ge:void 0,qr=(ve=(Se=Vs!=null?Vs:te.getAttribute("label"))!=null?Se:ee.getAttribute("label"))!=null?ve:void 0,_s=(Ot=(xt=(Ne=ee.querySelector("BaseURL"))==null?void 0:Ne.textContent)==null?void 0:xt.trim())!=null?Ot:"",ui=new URL(_s||o,e).toString(),Nt=(ni=ee.getAttribute("mimeType"))!=null?ni:Ur,Os=(Nr=(Ni=ee.getAttribute("codecs"))!=null?Ni:ou)!=null?Nr:"",Fs;if(uu==="text"){let Ut=ee.getAttribute("id")||"",Ns=((Jd=Cp.privateuse)==null?void 0:Jd.includes("x-auto"))||Ut.includes("_auto"),li=ee.querySelector("SegmentTemplate");if(li){let Hr={representationId:(Zd=ee.getAttribute("id"))!=null?Zd:void 0,bandwidth:(ep=ee.getAttribute("bandwidth"))!=null?ep:void 0},Us=parseInt((tp=ee.getAttribute("bandwidth"))!=null?tp:"",10)/1e3,qs=(rp=parseInt((ip=li.getAttribute("startNumber"))!=null?ip:"",10))!=null?rp:1,qi=parseInt((ap=li.getAttribute("timescale"))!=null?ap:"",10),lu=(sp=li.querySelectorAll("SegmentTimeline S"))!=null?sp:[],Hi=li.getAttribute("media");if(!Hi)continue;let Hs=[],js=0,Qs="",ji=0,jr=qs,we=0;for(let tt of lu){let ci=parseInt((np=tt.getAttribute("d"))!=null?np:"",10),ze=parseInt((op=tt.getAttribute("r"))!=null?op:"",10)||0,qt=parseInt((up=tt.getAttribute("t"))!=null?up:"",10);we=Number.isFinite(qt)?qt:we;let di=ci/qi*1e3,Ht=we/qi*1e3;for(let pt=0;pt<ze+1;pt++){let jt=lt(Hi,{...Hr,segmentNumber:jr.toString(10),segmentTime:(we+pt*ci).toString(10)}),Qi=(Ht!=null?Ht:0)+pt*di,Gr=Qi+di;jr++,Hs.push({time:{from:Qi,to:Gr},url:jt})}we+=(ze+1)*ci,js+=(ze+1)*di}ji=we/qi*1e3,Qs=lt(Hi,{...Hr,segmentNumber:jr.toString(10),segmentTime:we.toString(10)});let Qr={time:{from:ji,to:1/0},url:Qs},wt={type:"template",baseUrl:ui,segmentTemplateUrl:Hi,initUrl:"",totalSegmentsDurationMs:js,segments:Hs,nextSegmentBeyondManifest:Qr,timescale:qi};Fs={id:Ut,kind:"text",segmentReference:wt,profiles:[],duration:S,bitrate:Us,mime:"",codecs:"",width:0,height:0,isAuto:Ns}}else Fs={id:Ut,isAuto:Ns,kind:"text",url:ui}}else{let Ut=(cp=(lp=ee.getAttribute("contentType"))!=null?lp:Nt==null?void 0:Nt.split("/")[0])!=null?cp:uu,Ns=(pp=(dp=te.getAttribute("profiles"))==null?void 0:dp.split(","))!=null?pp:[],li=parseInt((hp=ee.getAttribute("width"))!=null?hp:"",10),Hr=parseInt((fp=ee.getAttribute("height"))!=null?fp:"",10),Us=parseInt((mp=ee.getAttribute("bandwidth"))!=null?mp:"",10)/1e3,qs=(bp=ee.getAttribute("frameRate"))!=null?bp:"",qi=(gp=ee.getAttribute("quality"))!=null?gp:void 0,lu=qs?_T(qs):void 0,Hi=(Sp=ee.getAttribute("id"))!=null?Sp:"id"+(A++).toString(10),Hs=Ut==="video"?`${Hr}p`:Ut==="audio"?`${Us}Kbps`:Os,js=`${Hi}@${Hs}`,Qs=[...M,...DE,...Ns],ji,jr=ee.querySelector("SegmentBase"),we=(vp=ee.querySelector("SegmentTemplate"))!=null?vp:BE;if(jr){let wt=(Tp=(yp=ee.querySelector("SegmentBase Initialization"))==null?void 0:yp.getAttribute("range"))!=null?Tp:"",[tt,ci]=wt.split("-").map(jt=>parseInt(jt,10)),ze={from:tt,to:ci},qt=(Ip=ee.querySelector("SegmentBase"))==null?void 0:Ip.getAttribute("indexRange"),[di,Ht]=qt?qt.split("-").map(jt=>parseInt(jt,10)):[],pt=qt?{from:di,to:Ht}:void 0;ji={type:"byteRange",url:ui,initRange:ze,indexRange:pt}}else if(we){let wt={representationId:(Ep=ee.getAttribute("id"))!=null?Ep:void 0,bandwidth:(xp=ee.getAttribute("bandwidth"))!=null?xp:void 0},tt=parseInt((wp=we.getAttribute("timescale"))!=null?wp:"",10),ci=(Ap=we.getAttribute("initialization"))!=null?Ap:"",ze=we.getAttribute("media"),qt=(Rp=parseInt((Pp=we.getAttribute("startNumber"))!=null?Pp:"",10))!=null?Rp:1,di=lt(ci,wt);if(!ze)throw new ReferenceError("No media attribute in SegmentTemplate");let Ht=(kp=we.querySelectorAll("SegmentTimeline S"))!=null?kp:[],pt=[],jt=0,Qi="",Gr=0;if(Ht.length){let Gs=qt,it=0;for(let Gi of Ht){let ht=parseInt((Lp=Gi.getAttribute("d"))!=null?Lp:"",10),pi=parseInt(($p=Gi.getAttribute("r"))!=null?$p:"",10)||0,Ws=parseInt((Mp=Gi.getAttribute("t"))!=null?Mp:"",10);it=Number.isFinite(Ws)?Ws:it;let cu=ht/tt*1e3,du=it/tt*1e3;for(let zs=0;zs<pi+1;zs++){let OE=lt(ze,{...wt,segmentNumber:Gs.toString(10),segmentTime:(it+zs*ht).toString(10)}),Bp=(du!=null?du:0)+zs*cu,FE=Bp+cu;Gs++,pt.push({time:{from:Bp,to:FE},url:OE})}it+=(pi+1)*ht,jt+=(pi+1)*cu}Gr=it/tt*1e3,Qi=lt(ze,{...wt,segmentNumber:Gs.toString(10),segmentTime:it.toString(10)})}else if(nB(S)){let it=parseInt((Dp=we.getAttribute("duration"))!=null?Dp:"",10)/tt*1e3,Gi=Math.ceil(S/it),ht=0;for(let pi=1;pi<Gi;pi++){let Ws=lt(ze,{...wt,segmentNumber:pi.toString(10),segmentTime:ht.toString(10)});pt.push({time:{from:ht,to:ht+it},url:Ws}),ht+=it}Gr=ht,Qi=lt(ze,{...wt,segmentNumber:Gi.toString(10),segmentTime:ht.toString(10)})}let _E={time:{from:Gr,to:1/0},url:Qi};ji={type:"template",baseUrl:ui,segmentTemplateUrl:ze,initUrl:di,totalSegmentsDurationMs:jt,segments:pt,nextSegmentBeyondManifest:_E,timescale:tt}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Ut||!Nt)continue;let Qr={video:"video",audio:"audio",text:"text"}[Ut];if(!Qr)continue;Ui||(Ui=Qr),Fs={id:js,kind:Qr,segmentReference:ji,profiles:Qs,duration:S,bitrate:Us,mime:Nt,codecs:Os,width:li,height:Hr,fps:lu,quality:qi}}ce.language||(ce.language=Ft),ce.label||(ce.label=qr),ce.mime||(ce.mime=Nt),ce.codecs||(ce.codecs=Os),ce.hdr||(ce.hdr=Ui==="video"&&Fc(Os)),ce.representations.push(Fs)}if(Ui){let ee=r[Ui].find(Ft=>Ft.id===ce.id);if(ee&&ce.representations.every(Ft=>Ft.segmentReference.type==="template"))for(let Ft of ee.representations){let qr=ce.representations.find(Nt=>Nt.id===Ft.id),_s=qr==null?void 0:qr.segmentReference,ui=Ft.segmentReference;ui.segments.push(..._s.segments),ui.nextSegmentBeyondManifest=_s.nextSegmentBeyondManifest}else r[Ui].push(ce)}}return{duration:S,streams:r,baseUrls:n,live:b}};var qc=O(ot(),1);import{videoSizeToQuality as oB}from"@vkontakte/videoplayer-shared/es2018";var jT=({id:a,width:e,height:t,bitrate:i,fps:r,quality:s,streamId:n})=>{var u;let o=(u=s?Kt(s):void 0)!=null?u:oB({width:e,height:t});return o&&{id:a,quality:o,bitrate:i,size:{width:e,height:t},fps:r,streamId:n}},QT=({id:a,bitrate:e})=>({id:a,bitrate:e}),GT=({language:a,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),WT=({language:a,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),Hc=({id:a,language:e,label:t,codecs:i,isDefault:r})=>({id:a,language:e,label:t,codec:(0,qc.default)(i.split("."),0),isDefault:r}),jc=({id:a,language:e,label:t,hdr:i,codecs:r})=>({id:a,language:e,hdr:i,label:t,codec:(0,qc.default)(r.split("."),0)}),Qc=a=>"url"in a,Qe=a=>a.type==="template";import{isNonNullable as zT}from"@vkontakte/videoplayer-shared/es2018";var F=(a,e)=>zT(a)&&zT(e)&&a.readyState==="open"&&uB(a,e);function uB(a,e){for(let t=0;t<a.activeSourceBuffers.length;++t)if(a.activeSourceBuffers[t]===e)return!0;return!1}var os=class{constructor(e,t,i,{fetcher:r,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new Li(0);this.currentLowLatencySegmentLength$=new Li(0);this.currentSegmentLength$=new Li(0);this.onLastSegment$=new Li(!1);this.fullyBuffered$=new Li(!1);this.playingRepresentation$=new Li(void 0);this.playingRepresentationInit$=new Li(void 0);this.error$=new cB;this.gaps=[];this.subscription=new dB;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new Z;this.switchAbortController=new Z;this.destroyAbortController=new Z;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=Zt(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 qy(this.sourceBuffer),this.subscription.add(Gc(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:Mt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o!=null||(o={id:"SegmentEjection",category:Mt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),this.error$.next(o)})),this.subscription.add(Gc(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:Mt.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o||!F(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,Ir(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=this.getForwardBufferDuration(o),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,n*2,l<c).catch(d=>{this.handleAsyncError(d,"pruneBuffer")})})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);let i=this.initData.get(t.id),r=this.segments.get(t.id),s=this.parsedInitData.get(t.id);_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=Zt(this.destroyAbortController.signal,async function*(e,t=!1){if(!F(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(Ee(s)||Ee(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||!F(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();Pr(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=Zt(this.destroyAbortController.signal,async function*(e,t=!1){if(!F(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(Ee(s)||Ee(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||!F(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();Pr(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=Zt(this.destroyAbortController.signal,async function*(e){var u,l;let t=(u=(0,ho.default)(e,c=>c.representations))!=null?u:[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let c of this.representations.keys()){let d=t.find(h=>h.id===c);d&&this.representations.set(c,d);let f=this.representations.get(c);if(!f||!Qe(f.segmentReference))return;let p=this.getActualLiveStartingSegments(f.segmentReference);this.segments.set(f.id,p)}let i=(l=this.switchingToRepresentationId)!=null?l:this.downloadingRepresentationId,r=this.representations.get(i);_e(r);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))return;let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(s,r),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));var c;this.fetcher=r,this.tuning=s,this.compatibilityMode=u,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!(l!=null&&l.live),this.baseUrls=(c=l==null?void 0:l.baseUrls)!=null?c:[],this.initData=new Map(i.map(d=>[d.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(d=>[d.id,d])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchToWithPreviousAbort(e,t=!1){!F(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new Z,Zt(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),o=this.initData.get(i);if(Ee(o)||Ee(n)?yield this.loadInit(s,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(i),_e(n,"No segments for starting representation"),o=this.initData.get(i),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer||!F(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();Pr(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(){!Ee(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 Z,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(Ee(e)||Ee(this.downloadingRepresentationId)||Ee(this.playingRepresentationId)||Ee(this.sourceBuffer)||!F(this.mediaSource,this.sourceBuffer)||Pr(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(_e(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;let r=i.find(c=>e>=c.time.from&&e<c.time.to);Pr(r)&&isFinite(r.time.from)&&isFinite(r.time.to)&&this.currentSegmentLength$.next((r==null?void 0:r.time.to)-r.time.from);let s=e,n=100;if(this.playingRepresentationId!==this.downloadingRepresentationId){let c=this.getForwardBufferDuration(e),d=r?r.time.to+n:-1/0;r&&r.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&c>=r.time.to-e+n&&(s=d)}if(isFinite(this.bufferLimit)&&Ir(this.sourceBuffer.buffered)>=this.bufferLimit){let c=this.getForwardBufferDuration(e),d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,c<d).catch(f=>{this.handleAsyncError(f,"pruneBuffer")});return}let u=[];if(!this.activeSegments.size&&(u=this.selectForwardBufferSegments(i,t.segmentReference.type,s),u.length)){let c="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if((0,po.default)(u,r))c="high";else{let d=(0,$i.default)(u,0);d&&d.time.from-r.time.to>=this.forwardBufferTarget/2&&(c="low")}this.loadSegments(u,t,c).catch(d=>{this.handleAsyncError(d,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&r&&r.status==="fed"&&!u.length&&this.getForwardBufferDuration(e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let l=(0,$i.default)(i,-1);!this.isLive&&l&&(this.fullyBuffered$.next(l.time.to-e-this.getForwardBufferDuration(e)<n),this.onLastSegment$.next(e-l.time.from>0))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let i=0,r=this.isLive?this.liveInitialAdditionalOffset:0;for(let s of e)Math.trunc(s.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:s.time.from+r}),i=s.time.to;Pr(t.duration)&&t.duration-i>0&&!this.isLive&&this.gaps.push({representation:t.id,from:i,to:t.duration})}getActualLiveStartingSegments(e){let t=e.segments,i=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,r=[],s=0,n=t.length-1;do r.unshift(t[n]),s+=t[n].time.to-t[n].time.from,n--;while(s<i&&n>=0);return this.liveInitialAdditionalOffset=s-i,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){let t=(0,ho.default)(e==null?void 0:e.streams[this.kind],r=>r.representations).find(r=>r.id===this.downloadingRepresentationId);if(!t)return;let i=this.segments.get(t.id);if(i!=null&&i.length)return{from:i[0].time.from,to:i[i.length-1].time.to}}updateLive(e){var i,r,s,n;let t=(i=(0,ho.default)(e==null?void 0:e.streams[this.kind],o=>o.representations))!=null?i:[];if(![...this.segments.values()].every(o=>!o.length))for(let o of t){if(!o||!Qe(o.segmentReference))return;let u=o.segmentReference.segments.map(p=>({...p,status:"none",size:void 0})),l=100,c=(r=this.segments.get(o.id))!=null?r:[],d=(n=(s=(0,$i.default)(c,-1))==null?void 0:s.time.to)!=null?n:0,f=u==null?void 0:u.findIndex(p=>d>=p.time.from+l&&d<=p.time.to+l);if(f===-1){this.liveUpdateSegmentIndex=0;let p=this.getActualLiveStartingSegments(o.segmentReference);this.segments.set(o.id,p)}else{let p=u.slice(f+1);this.segments.set(o.id,[...c,...p])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;_e(e);let t=this.segments.get(e);if(t!=null&&t.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}calculateDurationFromSegments(){var t;if(!this.playingRepresentationId)return 0;let e=this.segments.get(this.playingRepresentationId);return(e?(t=(0,$i.default)(e,-1))==null?void 0:t.time.to:0)||0}updateLowLatencyLiveIfNeeded(e){var i;let t=0;for(let r of this.representations.values()){let s=r.segmentReference;if(!Qe(s))return;let n=(i=this.segments.get(r.id))!=null?i:[],o=n.find(l=>Math.floor(l.time.from)===Math.floor(e.time.from));if(o&&!isFinite(o.time.to)&&(o.time.to=e.time.to,t=o.time.to-o.time.from),!!!n.find(l=>Math.floor(l.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let l=Math.round(e.time.to*s.timescale/1e3).toString(10),c=lt(s.segmentTemplateUrl,{segmentTime:l});n.push({status:"none",time:{from:e.time.to,to:1/0},url:c})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){var s,n,o;let t=(n=(s=this.switchingToRepresentationId)!=null?s:this.downloadingRepresentationId)!=null?n:this.playingRepresentationId;if(!t)return;let i=this.segments.get(t);if(!i)return;let r=i.find(u=>u.time.from<=e&&u.time.to>=e);return(o=r==null?void 0:r.time.from)!=null?o:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)==null||e.destroy(),this.gapDetectionIdleCallback&&yt&&yt(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&yt&&yt(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}this.sourceBuffer=null,this.downloadAbortController.abort(),this.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,i){return this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){let i=e.findIndex(r=>t>=r.time.from&&t<r.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=i),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,i){let r=this.getForwardBufferDuration(i),s=e.findIndex(({status:f,time:{from:p,to:h}},m)=>{let b=p<=i&&h>=i,S=p>i||b||m===0&&i===0,y=Math.min(this.forwardBufferTarget,this.bufferLimit),v=this.preloadOnly&&p<=i+y||r<y&&h-p>=y||h<=i+y;return(f==="none"||f==="partially_ejected"&&S&&v&&this.sourceBuffer&&F(this.mediaSource,this.sourceBuffer)&&!(Ie(this.sourceBuffer.buffered,p)&&Ie(this.sourceBuffer.buffered,h)))&&S&&v});if(s===-1)return[];if(t!=="byteRange")return e.slice(s,s+1);let n=e,o=0,u=0,l=[],c=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,d=this.preloadOnly?this.forwardBufferTarget:0;for(let f=s;f<n.length&&(o<=c||u<=d);f++){let p=n[f];if(o+=p.byte.to+1-p.byte.from,u+=p.time.to+1-p.time.from,p.status==="none"||p.status==="partially_ejected")l.push(p);else break}return l}async loadSegments(e,t,i="auto"){Qe(t.segmentReference)?await this.loadTemplateSegment(e[0],t,i):await this.loadByteRangeSegments(e,t,i)}async loadTemplateSegment(e,t,i="auto"){e.status="downloading";let r={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(r);let{range:s,url:n,signal:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await Zt(o,async function*(){let c=Wc(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,c))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let c=await this.fetcher.fetch(n,{range:s,signal:o,onProgress:u,priority:i,isLowLatency:this.isActiveLowLatency(),bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation});if(this.lastDataObtainedTimestampMs=co(),!c)return;let d=new DataView(c),f=Tt(t.mime);if(!isFinite(r.segment.time.to)){let m=t.segmentReference.timescale;r.segment.time.to=f.getChunkEndTime(d,m)}u&&r.feedingBytes&&l?await Promise.all(l):await this.sourceBufferTaskQueue.append(d,o);let{serverDataReceivedTimestamp:p,serverDataPreparedTime:h}=f.getServerLatencyTimestamps(d);p&&h&&this.currentLiveSegmentServerLatency$.next(h-p),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(c){this.abortActiveSegments([e]),It(c)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}updateRepresentationsBaseUrlIfNeeded(){if(!this.tuning.dash.enableBaseUrlSupport||!this.baseUrls.length||this.failedDownloads<=this.tuning.dash.maxSegmentRetryCount)return;this.baseUrlsIndex=(this.baseUrlsIndex+1)%this.baseUrls.length;let e=this.baseUrls[this.baseUrlsIndex];for(let t of this.representations.values())Qe(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}async loadByteRangeSegments(e,t,i="auto"){if(!e.length)return;for(let u of e)u.status="downloading",this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:r,url:s,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(await Zt(n,async function*(){let u=Wc(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),Gc(window,"online").pipe(lB()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(s,{range:r,onProgress:o,signal:n,priority:i,bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation}),this.lastDataObtainedTimestampMs=co(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),It(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(Qe(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:(0,$i.default)(e,0).byte.from,to:(0,$i.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:i,range:r,signal:s,onProgress:async(o,u)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=co(),await this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:Mt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!Qe(t.segmentReference))throw new Error("Representation is not template type");let i=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&i.searchParams.set("low-latency","yes");let r=i.toString(),{signal:s}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,c)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=co();let d=this.onSomeTemplateDataLoaded({dataView:l,loaded:c,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(d)}catch(d){this.error$.next({id:"SegmentFeeding",category:Mt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}:void 0;return{url:r,signal:s,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,po.default)(e,t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:s}){if(!this.activeSegments.size||!F(this.mediaSource,this.sourceBuffer))return;let n=this.representations.get(t);if(n)for(let o of this.activeSegments){let{segment:u}=o;if(o.representationId===t){if(s.aborted){r();continue}if(o.loadedBytes=i,o.loadedBytes>o.feedingBytes){let l=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),c=Tt(n.mime).parseFeedableSegmentChunk(l,this.isLive);c!=null&&c.byteLength&&(u.status="partially_fed",o.feedingBytes+=c.byteLength,await this.sourceBufferTaskQueue.append(c),o.fedBytes+=c.byteLength)}}}}async onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size||!F(this.mediaSource,this.sourceBuffer))return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){let{segment:l}=u;if(u.representationId!==t)continue;if(s.aborted){await n();continue}let c=l.byte.from-i,d=l.byte.to-i,f=d-c+1,p=c<r,h=d<=r;if(!p)continue;let m=Tt(o.mime);if(l.status==="downloading"&&h){l.status="downloaded";let b=new DataView(e.buffer,e.byteOffset+c,f);await this.sourceBufferTaskQueue.append(b,s)&&!s.aborted?this.onSegmentFullyAppended(u,t):await n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(l.status==="downloading"||l.status==="partially_fed")&&(u.loadedBytes=Math.min(f,r-c),u.loadedBytes>u.feedingBytes)){let b=new DataView(e.buffer,e.byteOffset+c+u.feedingBytes,u.loadedBytes-u.feedingBytes),S=u.loadedBytes===f?b:m.parseFeedableSegmentChunk(b);S!=null&&S.byteLength&&(l.status="partially_fed",u.feedingBytes+=S.byteLength,await this.sourceBufferTaskQueue.append(S,s)&&!s.aborted?(u.fedBytes+=S.byteLength,u.fedBytes===f&&this.onSegmentFullyAppended(u,t)):await n())}}}onSegmentFullyAppended(e,t){var i;if(!(Ee(this.sourceBuffer)||!F(this.mediaSource,this.sourceBuffer))){!this.isLive&&N.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(Ie(this.sourceBuffer.buffered,e.segment.time.from,100)&&Ie(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:Mt.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",Qc(e.segment)&&(e.segment.size=e.fedBytes);for(let r of this.representations.values())if(r.id!==t)for(let s of(i=this.segments.get(r.id))!=null?i:[])s.status==="fed"&&Math.round(s.time.from)===Math.round(e.segment.time.from)&&Math.round(s.time.to)===Math.round(e.segment.time.to)&&(s.status="none");this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}}abortSegment(e){e.status==="partially_fed"?e.status="partially_ejected":e.status!=="partially_ejected"&&(e.status="none");for(let t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[r,s]of this.initData.entries()){let n=s instanceof Promise;t||(t=n),s===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let i=this.representations.get(e);i&&(this.initLoadIdleCallback=Tr(()=>(0,YT.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?Zt(this.destroyAbortController.signal,async function*(){let o=Wc(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,Tt(e.mime),r)).then(async o=>{if(!o)return;let{init:u,dataView:l,segments:c}=o,d=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,d);let f=c;this.isLive&&Qe(e.segmentReference)&&(f=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,f),u&&this.parsedInitData.set(e.id,u)}).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:Mt.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||!F(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||Ee(e))return!1;let r=[],s=0,n=u=>{u.sort((c,d)=>c.from-d.from);let l=[u[0]];for(let c=1;c<u.length;c++){let{from:d,to:f}=u[c],p=l[l.length-1];p.to>=d?p.to=Math.max(p.to,f):l.push(u[c])}return l},o=u=>{var c;if(s>=t)return r;r.push({...u.time}),r=n(r);let l=Qc(u)?(c=u.size)!=null?c:0:u.byte.to-u.byte.from;s+=l};for(let u of this.segments.values())for(let l of u){let c=l.time.to<=e-this.tuning.dash.bufferPruningSafeZone,d=l.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(c||d)&&l.status==="fed"&&o(l)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let l=this.sourceBuffer.buffered.start(u)*1e3,c=this.sourceBuffer.buffered.end(u)*1e3,d=0;for(let f of this.segments.values())for(let p of f)(0,po.default)(["none","partially_ejected"],p.status)&&Math.round(p.time.from)<=Math.round(l)&&Math.round(p.time.to)>=Math.round(c)&&d++;if(d===this.segments.size){let f={time:{from:l,to:c},url:"",status:"none"};o(f)}}if(r.length&&i){let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let l of this.segments.values())for(let c of l)c.time.from>=e+u&&c.status==="fed"&&o(c)}return r.length?(await Promise.all(r.map(l=>this.sourceBufferTaskQueue.remove(l.from,l.to)))).reduce((l,c)=>l||c,!1):!1}async abortBuffer(){if(!this.sourceBuffer||!F(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||!F(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||!F(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||Ee(e)?0:me(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!(!this.sourceBuffer||!F(this.mediaSource,this.sourceBuffer))){if(this.tuning.useRefactoredSearchGap)for(let i=0;i<this.sourceBuffer.buffered.length;i++)this.gaps=this.gaps.filter(r=>this.sourceBuffer&&(Math.round(r.from)<Math.round(this.sourceBuffer.buffered.start(i)*1e3)||Math.round(r.to)>Math.round(this.sourceBuffer.buffered.end(i)*1e3)));for(let i of t){let r={representation:e,from:i.time.from,to:i.time.to};for(let s=0;s<this.sourceBuffer.buffered.length;s++){let n=this.sourceBuffer.buffered.start(s)*1e3,o=this.sourceBuffer.buffered.end(s)*1e3;if(!(o<=i.time.from||n>=i.time.to)){if(n<=i.time.from&&o>=i.time.to){r=void 0;break}o>i.time.from&&o<i.time.to&&(r.from=o),n<i.time.to&&n>i.time.from&&(r.to=n)}}r&&r.to-r.from>1&&!this.gaps.some(s=>r&&s.from===r.from&&s.to===r.to)&&this.gaps.push(r)}}}detectGapsWhenIdle(e,t){if(!(this.gapDetectionIdleCallback||!this.sourceBuffer||!F(this.mediaSource,this.sourceBuffer))){if(!this.tuning.useRefactoredSearchGap)for(let i=0;i<this.sourceBuffer.buffered.length;i++)this.gaps=this.gaps.filter(r=>this.sourceBuffer&&(Math.round(r.from)<Math.round(this.sourceBuffer.buffered.start(i)*1e3)||Math.round(r.to)>Math.round(this.sourceBuffer.buffered.end(i)*1e3)));this.gapDetectionIdleCallback=Tr(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:Mt.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if(Ee(this.sourceBuffer)||!F(this.mediaSource,this.sourceBuffer)||Ee(this.playingRepresentationId))return;let e=[];for(let i=0;i<this.sourceBuffer.buffered.length;i++){let r=Math.floor(this.sourceBuffer.buffered.start(i)*1e3),s=Math.ceil(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:r,to:s})}let t=100;for(let i of this.segments.values())for(let r of i){let{status:s}=r;if(s!=="fed"&&s!=="partially_ejected")continue;let n=Math.floor(r.time.from),o=Math.ceil(r.time.to),u=e.some(c=>c.from-t<=n&&c.to+t>=o),l=e.filter(c=>n>=c.from&&n<c.to-t||o>c.from+t&&o<=c.to);u||(l.length===1?r.status="partially_ejected":this.gaps.some(c=>c.from===r.time.from||c.to===r.time.to)?r.status="partially_ejected":r.status="none")}}handleAsyncError(e,t){this.error$.next({id:t,category:Mt.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}};var ei=a=>{let e=new URL(a);return e.searchParams.set("quic","1"),e.toString()};var fo=a=>{var s;let e=a.get("X-Delivery-Type"),t=a.get("X-Reused"),i=e===null?"http1":e!=null?e:void 0,r=t===null?void 0:(s={1:!0,0:!1}[t])!=null?s:void 0;return{type:i,reused:r}};import{abortable as us,assertNever as KT,fromEvent as XT,merge as pB,now as ls,Subscription as hB,Subject as JT,ValueSubject as zc,flattenObject as Rr,ErrorCategory as cs}from"@vkontakte/videoplayer-shared/es2018";var mo=a=>{let e=new URL(a);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var go=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:s=!1}){this.lastConnectionType$=new zc(void 0);this.lastConnectionReused$=new zc(void 0);this.lastRequestFirstBytes$=new zc(void 0);this.recoverableError$=new JT;this.error$=new JT;this.abortAllController=new Z;this.subscription=new hB;this.fetchManifest=us(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=ei(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=mo(i));let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(bo);return r?(t.log("success",Rr({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(r.headers),r.text()):(t.error("error",Rr({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=us(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:s="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1,bufferOptimisation:l=!1}={}){var _,Y,J;let c=e,d=new Headers,f=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{d.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let T=new URL(c,location.href);T.searchParams.append("bytes",`${i.from}-${i.to}`),c=T.toString();break}default:KT(t)}this.requestQuic&&(c=ei(c));let p=this.abortAllController.signal,h;if(n){let T=new Z;if(h=pB(XT(this.abortAllController.signal,"abort"),XT(n,"abort")).subscribe(()=>{try{T.abort()}catch(k){bo(k)}}),this.subscription.add(h),this.abortAllController.signal.aborted||n.aborted)try{T.abort()}catch(k){bo(k)}p=T.signal}let m=ls();f.log("startRequest",Rr({url:c,priority:s,rangeMethod:t,range:i,isLowLatency:u,requestStartedAt:m}));let b=yield this.doFetch(c,{priority:s,headers:d,signal:p}),S=ls();if(!b)return f.error("error",{message:"No response in request"}),f.end(),h==null||h.unsubscribe(),null;if((_=this.throughputEstimator)==null||_.addRawRtt(S-m),!b.ok||!b.body){h==null||h.unsubscribe();let T=`Fetch error ${b.status}: ${b.statusText}`;return f.error("error",{message:T}),f.end(),Promise.reject(new Error(`Fetch error ${b.status}: ${b.statusText}`))}if(this.onHeadersReceived(b.headers),!r&&!o){h==null||h.unsubscribe();let T=ls(),k={requestStartedAt:m,requestEndedAt:T,duration:T-m};return f.log("endRequest",Rr(k)),f.end(),b.arrayBuffer()}let y=b.body;if(o){let T;[y,T]=b.body.tee(),(Y=this.throughputEstimator)==null||Y.trackStream(T,u)}let v=y.getReader(),I,E=parseInt((J=b.headers.get("content-length"))!=null?J:"",10);Number.isFinite(E)&&(I=E),!I&&i&&(I=i.to-i.from+1);let A=0,M=I?new Uint8Array(I):new Uint8Array(0),L=!1,P=T=>{h==null||h.unsubscribe(),L=!0,bo(T)},R=us(p,async function*({done:T,value:k}){if(A===0&&this.lastRequestFirstBytes$.next(ls()-m),p.aborted){h==null||h.unsubscribe();return}if(!T&&k){if(l&&I)M.set(k,A),A+=k.byteLength;else{let x=new Uint8Array(M.length+k.length);x.set(M),x.set(k,M.length),M=x,A+=k.byteLength}r==null||r(new DataView(M.buffer),A),yield v==null?void 0:v.read().then(R,P)}}.bind(this));yield v==null?void 0:v.read().then(R,P),h==null||h.unsubscribe();let V=ls(),D={failed:L,requestStartedAt:m,requestEndedAt:V,duration:V-m};return L?(f.error("endRequest",Rr(D)),f.end(),null):(f.log("endRequest",Rr(D)),f.end(),M.buffer)}.bind(this));this.fetchByteRangeRepresentation=us(this.abortAllController.signal,async function*(e,t,i){var S;if(e.type!=="byteRange")return null;let{from:r,to:s}=e.initRange,n=r,o=s,u=!1,l,c;e.indexRange&&(l=e.indexRange.from,c=e.indexRange.to,u=s+1===l,u&&(n=Math.min(l,r),o=Math.max(c,s))),n=Math.min(n,0);let d=yield this.fetch(e.url,{range:{from:n,to:o},priority:i,measureThroughput:!1});if(!d)return null;let f=new DataView(d,r-n,s-n+1);if(!t.validateData(f))throw new Error("Invalid media file");let p=t.parseInit(f),h=(S=e.indexRange)!=null?S:t.getIndexRange(p);if(!h)throw new ReferenceError("No way to load representation index");let m;if(u)m=new DataView(d,h.from-n,h.to-h.from+1);else{let y=yield this.fetch(e.url,{range:h,priority:i,measureThroughput:!1});if(!y)return null;m=new DataView(y)}let b=t.parseSegments(m,p,h);return{init:p,dataView:new DataView(d),segments:b}}.bind(this));this.fetchTemplateRepresentation=us(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}=fo(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,t,i="auto"){var s,n;let{type:r}=e;switch(r){case"byteRange":return(s=await this.fetchByteRangeRepresentation(e,t,i))!=null?s:null;case"template":return(n=await this.fetchTemplateRepresentation(e,i))!=null?n:null;default:KT(r)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}async doFetch(e,t){let i=await Ze(e,t);if(i.ok)return i;let r=await i.text(),s=parseInt(r);if(!isNaN(s))switch(s){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:cs.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:cs.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:cs.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:cs.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${s})`,category:cs.FATAL})}}},bo=a=>{if(!It(a))throw a};var Dt=(a,e,t)=>t*e+(1-t)*a,Yc=(a,e)=>a.reduce((t,i)=>t+i,0)/e,ZT=(a,e,t,i)=>{let r=0,s=t,n=Yc(a,e),o=e<i?e:i;for(let u=0;u<o;u++)a[s]>n?r++:r--,s=(a.length+s-1)%a.length;return Math.abs(r)===o};import{isNullable as fB,ValueSubject as eI}from"@vkontakte/videoplayer-shared/es2018";var ti=class{constructor(e){this.prevReported=void 0;this.pastMeasures=[];this.takenMeasures=0;this.measuresCursor=0;var i;this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new eI(e.initial),this.debounced$=new eI(e.initial);let t=(i=e.label)!=null?i:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new Re(`raw_${t}`),this.smoothedSeries$=new Re(`smoothed_${t}`),this.reportedSeries$=new Re(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,i=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=(this.pastMeasures[o]-this.smoothed)**2,i++);this.takenMeasures=i,t/=i;let r=Math.sqrt(t),s=this.smoothed+this.params.deviationFactor*r,n=this.smoothed-this.params.deviationFactor*r;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>s||this.smoothed<n)&&(fB(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 So=class extends ti{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=Dt(this.slow,e,this.params.emaAlphaSlow),this.fast=Dt(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var vo=class extends ti{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=Yc(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Dt(this.emaSmoothed,e,this.params.emaAlpha);let i=ZT(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}};var yo=class extends ti{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?Dt(this.smoothed,t,this.params.emaAlpha):t}};var Ct=class{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new So({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new vo({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 yo({initial:e,label:"liveEdgeDelay",...t})}};var kr=(a,e)=>{a&&a.playbackRate!==e&&(a.playbackRate=e)};import{isNullable as mB,ValueSubject as bB}from"@vkontakte/videoplayer-shared/es2018";var ds=class a{constructor(e,t){this.currentRepresentation$=new bB(null);this.maxRepresentations=4;this.representationsCursor=0;this.representations=[];this.currentSegment=null;this.getCurrentPosition=t.getCurrentPosition,this.processStreams(e)}updateLive(e){this.processStreams(e==null?void 0:e.streams.text)}seekLive(e){this.processStreams(e)}maintain(e=this.getCurrentPosition()){var t;if(!mB(e))for(let i of this.representations)for(let r of i){let s=r.segmentReference,n=s.segments.length,o=s.segments[0].time.from,u=s.segments[n-1].time.to;if(e<o||e>u)continue;let l=s.segments.find(c=>c.time.from<=e&&c.time.to>=e);!l||((t=this.currentSegment)==null?void 0:t.time.from)===l.time.from&&this.currentSegment.time.to===l.time.to||(this.currentSegment=l,this.currentRepresentation$.next({...r,label:"Live Text",language:"ru",isAuto:!0,url:new URL(l.url,s.baseUrl).toString()}))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e!=null?e:[]){let i=a.filterRepresentations(t.representations);if(i){this.representations[this.representationsCursor]=i,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!(e!=null&&e.some(t=>a.filterRepresentations(t.representations)))}static filterRepresentations(e){return e==null?void 0:e.filter(t=>t.kind==="text"&&"segmentReference"in t&&Qe(t.segmentReference))}};var Io=O(ot(),1);import{assertNever as Eo}from"@vkontakte/videoplayer-shared/es2018";var tI=(a,{useManagedMediaSource:e,useOldMSEDetection:t})=>{let{containers:i,protocols:r,codecs:s,nativeHlsSupported:n}=N.video,o=(s.h264||s.h265)&&s.aac,u=r.mse&&(!t||!!window.MediaStreamTrack)||r.mms&&e;return a.filter(l=>{switch(l){case"DASH_SEP":return u&&i.mp4&&o;case"DASH_WEBM":return u&&i.webm&&s.vp9&&s.opus;case"DASH_WEBM_AV1":return u&&i.webm&&s.av1&&s.opus;case"DASH_STREAMS":return u&&(i.mp4&&o||i.webm&&(s.vp9||s.av1)&&(s.opus||s.aac));case"DASH_LIVE":return u&&i.mp4&&o;case"DASH_LIVE_CMAF":return u&&i.mp4&&o&&i.cmaf;case"DASH_ONDEMAND":return u&&i.mp4&&o;case"HLS":case"HLS_ONDEMAND":case"HLS_LIVE":case"HLS_LIVE_CMAF":return n;case"MPEG":return i.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return r.webrtc&&r.ws&&s.h264&&(i.mp4||i.webm);default:return Eo(l)}})},To=a=>{let{webmDecodingInfo:e}=N.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:Eo(a)}return[t,i]},iI=({webmCodec:a,androidPreferredFormat:e,preferMultiStream:t})=>{let i=[...t?["DASH_STREAMS"]:[],...To(a),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],r=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(N.device.isAndroid)switch(e){case"mpeg":return["MPEG",...i,"HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...i,"MPEG"];case"dash":return[...i,"HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return[...r,"MPEG",...To(a),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...To(a),"MPEG",...r,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...To(a),...r,"HLS","HLS_ONDEMAND"];default:Eo(e)}return N.video.nativeHlsSupported?[...i,"HLS","HLS_ONDEMAND","MPEG"]:[...i,"HLS","HLS_ONDEMAND","MPEG"]},rI=({androidPreferredFormat:a,preferCMAF:e,preferWebRTC:t})=>{let i=e?["DASH_LIVE_CMAF","DASH_LIVE"]:["DASH_LIVE","DASH_LIVE_CMAF"],r=e?["HLS_LIVE_CMAF","HLS_LIVE"]:["HLS_LIVE","HLS_LIVE_CMAF"],s=[...i,...r],n=[...r,...i],o,u=N.device.isMac&&N.browser.isSafari;if(N.device.isAndroid)switch(a){case"dash":case"dash_any_mpeg":case"dash_any_webm":case"dash_sep":{o=s;break}case"hls":case"mpeg":{o=n;break}default:Eo(a)}else N.video.nativeHlsSupported&&!u?o=n:u?o=e?["DASH_LIVE_CMAF","HLS_LIVE_CMAF","HLS_LIVE","DASH_LIVE"]:["HLS_LIVE","DASH_LIVE","DASH_LIVE_CMAF","HLS_LIVE_CMAF"]:o=s;return t?["WEB_RTC_LIVE",...o]:[...o,"WEB_RTC_LIVE"]},Kc=a=>a?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],xo=a=>{if(a.size===0)return;if(a.size===1){let t=a.values().next();return(0,Io.default)(t.value.split("."),0)}for(let t of a){let i=(0,Io.default)(t.split("."),0);if(i==="opus"||i==="vp09"||i==="av01")return i}let e=a.values().next();return(0,Io.default)(e.value.split("."),0)};var xB=["timeupdate","progress","play","seeked","stalled","waiting"],wB=["timeupdate","progress","loadeddata","playing","seeked"];var Po=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new nI;this.representationSubscription=new nI;this.state$=new q("none");this.currentVideoRepresentation$=new ae(void 0);this.currentVideoRepresentationInit$=new ae(void 0);this.currentAudioRepresentation$=new ae(void 0);this.currentVideoSegmentLength$=new ae(0);this.currentAudioSegmentLength$=new ae(0);this.error$=new Ao;this.lastConnectionType$=new ae(void 0);this.lastConnectionReused$=new ae(void 0);this.lastRequestFirstBytes$=new ae(void 0);this.currentLiveTextRepresentation$=new ae(null);this.isLive$=new ae(!1);this.isActiveLive$=new ae(!1);this.isLowLatency$=new ae(!1);this.liveDuration$=new ae(0);this.liveSeekableDuration$=new ae(0);this.liveAvailabilityStartTime$=new ae(0);this.liveStreamStatus$=new ae(void 0);this.bufferLength$=new ae(0);this.liveLatency$=new ae(void 0);this.liveLoadBufferLength$=new ae(0);this.livePositionFromPlayer$=new ae(0);this.currentStallDuration$=new ae(0);this.videoLastDataObtainedTimestamp$=new ae(0);this.fetcherRecoverableError$=new Ao;this.fetcherError$=new Ao;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new Ao;this.gapWatchdogActive=!1;this.destroyController=new Z;this.initManifest=Jc(this.destroyController.signal,async function*(e,t,i){var r;this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=le(t,i,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),(r=this.manifest)!=null&&r.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:ct.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=Jc(this.destroyController.signal,async function*(){var n,o;this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(u=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:ct.NETWORK,message:"Failed to load manifest",thrown:u})});if(!e)return null;let t=null;try{t=lo(e!=null?e:"",this.manifestUrlString)}catch(u){let l=(n=oo(e))!=null?n:{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,c)=>{var d,f,p,h;return!!((f=(d=this.element)==null?void 0:d.canPlayType)!=null&&f.call(d,l)&&((h=(p=je())==null?void 0:p.isTypeSupported)!=null&&h.call(p,`${l}; codecs="${c}"`))||u==="text")};if(t.live){this.isLive$.next(!!t.live);let{availabilityStartTime:u,latestSegmentPublishTime:l,streamIsUnpublished:c,streamIsAlive:d}=t.live,f=((o=t.duration)!=null?o:0)/1e3;this.liveSeekableDuration$.next(-1*f),this.liveDuration$.next((l-u)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let p="active";d||(p=c?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(p)}let r={text:t.streams.text,video:[],audio:[]};for(let u of["video","audio"]){let c=t.streams[u].filter(({mime:p,codecs:h})=>i(u,p,h)),d=new Set(c.map(({codecs:p})=>p)),f=xo(d);if(f&&(r[u]=c.filter(({codecs:p})=>p.startsWith(f))),u==="video"){let p=this.tuning.preferHDR,h=r.video.some(b=>b.hdr),m=r.video.some(b=>!b.hdr);N.display.isHDR&&p&&h?r.video=r.video.filter(b=>b.hdr):m&&(r.video=r.video.filter(b=>!b.hdr))}}let s={...t,streams:r};return this.tracer.log("updateManifestEnd",hs(s)),s}.bind(this));this.initRepresentations=Jc(this.destroyController.signal,async function*(e,t,i){var f;this.tracer.log("initRepresentationsStart",hs({initialVideo:e,initialAudio:t,sourceHls:i})),Lr(this.manifest),Lr(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let r=p=>{this.representationSubscription.add(Bt(p,"error").pipe(wo(h=>{var m;return!!((m=this.element)!=null&&m.played.length)})).subscribe(h=>{this.error$.next({id:"VideoSource",category:ct.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=this.tuning.useManagedMediaSource?_n():new MediaSource;let s=document.createElement("source");if(r(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&hr())if(i){let p=document.createElement("source");r(p),p.type="application/x-mpegurl",p.src=i.url,this.element.appendChild(p)}else this.element.disableRemotePlayback=!0;this.isActiveLive$.next(this.isLive$.getValue());let n={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),manifest:this.manifest},o=this.manifest.streams.video.reduce((p,h)=>[...p,...h.representations],[]);if(this.videoBufferManager=new os("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],fs(t)){let p=this.manifest.streams.audio.reduce((h,m)=>[...h,...m.representations],[]);this.audioBufferManager=new os("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}ds.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new ds(this.manifest.streams.text,n)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$));let u=()=>{var p;(p=this.stallWatchdogSubscription)==null||p.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add(Mi(...wB.map(p=>Bt(this.element,p))).pipe(Mr(p=>this.element?me(this.element.buffered,this.element.currentTime*1e3):0),ps(),IB(p=>{p>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add(Mi(Bt(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe(ps()).subscribe(h=>this.liveStreamEndTimestamp=ed())),this.subscription.add(Bt(this.element,"pause").subscribe(()=>{this.livePauseWatchdogSubscription=Zc(1e3).subscribe(h=>{let m=zt(this.manifestUrlString,2);this.manifestUrlString=le(this.manifestUrlString,m+1e3,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add(Bt(this.element,"play").subscribe(h=>{var m;return(m=this.livePauseWatchdogSubscription)==null?void 0:m.unsubscribe()})),this.representationSubscription.add($r({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(Mr(({isActiveLive:h,isLowLatency:m})=>h&&m),ps()).subscribe(h=>{this.isManualDecreasePlaybackInLive()||kr(this.element,1)})),this.representationSubscription.add($r({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(wo(({bufferLength:h,isActiveLive:m,isLowLatency:b})=>m&&b&&!!h)).subscribe(({bufferLength:h})=>this.liveBuffer.next(h))),this.representationSubscription.add(this.videoBufferManager.currentLowLatencySegmentLength$.subscribe(h=>{if(!this.isActiveLive$.getValue()&&!this.isLowLatency$.getValue()&&!h)return;let m=this.liveSeekableDuration$.getValue()-h/1e3;this.liveSeekableDuration$.next(Math.max(m,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+h/1e3)})),this.representationSubscription.add($r({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(wo(({isLive:h})=>h),ps((h,m)=>m.bufferLength<h.bufferLength),Mr(({rtt:h,bufferLength:m,segmentServerLatency:b})=>{let S=zt(this.manifestUrlString,2);return(h/2+m+b+S)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add($r({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:h,isActiveLive:m,isLowLatency:b})=>{if(!b||!m)return;let S=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,y=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,v=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,I=h-S;if(this.isManualDecreasePlaybackInLive())return;let E=1;Math.abs(I)>y&&(E=1+Math.sign(I)*v),kr(this.element,E)})),this.representationSubscription.add(this.bufferLength$.subscribe(h=>{var b,S;let m=0;if(h){let y=((S=(b=this.element)==null?void 0:b.currentTime)!=null?S:0)*1e3;m=Math.min(...this.bufferManagers.map(I=>{var E,A;return(A=(E=I.getLiveSegmentsToLoadState(this.manifest))==null?void 0:E.to)!=null?A:y}))-y}this.liveLoadBufferLength$.getValue()!==m&&this.liveLoadBufferLength$.next(m)}));let p=0;this.representationSubscription.add($r({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(EB(1e3)).subscribe(async({liveLoadBufferLength:h,bufferLength:m})=>{if(!this.element||this.isUpdatingLive)return;let b=this.element.playbackRate,S=zt(this.manifestUrlString,2),y=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,v=Math.min(y,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*b),I=this.tuning.dashCmafLive.normalizedActualBufferOffset*b,E=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*b,A=isFinite(h)?h:m,M=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),L=y<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(L);let P="none";if(M?P="active_low_latency":this.isLowLatency$.getValue()&&L?(this.bufferManagers.forEach(R=>R.proceedLowLatencyLive()),P="active_low_latency"):S!==0&&A<v?P="live_forward_buffering":A<v+E&&(P="live_with_target_offset"),isFinite(h)&&(p=h>p?h:p),P==="live_forward_buffering"||P==="live_with_target_offset"){let R=p-(v+I),V=this.normolizeLiveOffset(Math.trunc(S+R/b)),D=Math.abs(V-S),_=0;!h||D<=this.tuning.dashCmafLive.offsetCalculationError?_=S:V>0&&D>this.tuning.dashCmafLive.offsetCalculationError&&(_=V),this.manifestUrlString=le(this.manifestUrlString,_,2)}(P==="live_with_target_offset"||P==="live_forward_buffering")&&(p=0,await this.updateLive())},h=>{this.error$.next({id:"updateLive",category:ct.VIDEO_PIPELINE,thrown:h,message:"Failed to update live with subscription"})}))}let l=Mi(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe(Mr(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),c=Mi(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe(Mr(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue()))),d=$r({allBuffersFull:l,someBufferEnded:c}).pipe(ps(),Mr(({allBuffersFull:p,someBufferEnded:h})=>p&&h),wo(p=>p));if(this.representationSubscription.add(Mi(this.forceEnded$,d).subscribe(()=>{var p;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(h=>!h.updating))try{(p=this.source)==null||p.endOfStream()}catch(h){this.error$.next({id:"EndOfStream",category:ct.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:h})}})),this.representationSubscription.add(Mi(...this.bufferManagers.map(p=>p.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.representationSubscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.representationSubscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.liveTextManager&&this.representationSubscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$)),this.source.readyState!=="open"){let p=this.tuning.dash.sourceOpenTimeout>=0;yield new Promise(h=>{var m;p&&(this.timeoutSourceOpenId=setTimeout(()=>{var b;if(((b=this.source)==null?void 0:b.readyState)==="open"){h();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)),(m=this.source)==null||m.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),h()},{once:!0})})}if(!this.isLive$.getValue()){let p=[(f=this.manifest.duration)!=null?f:0,...(0,td.default)((0,td.default)([...this.manifest.streams.audio,...this.manifest.streams.video],h=>h.representations),h=>{let m=[];return h.duration&&m.push(h.duration),Qe(h.segmentReference)&&h.segmentReference.totalSegmentsDurationMs&&m.push(h.segmentReference.totalSegmentsDurationMs),m})];this.source.duration=Math.max(...p)/1e3}this.audioBufferManager&&fs(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")}.bind(this));this.tick=()=>{var t,i,r,s;if(!this.element||!this.videoBufferManager||((t=this.source)==null?void 0:t.readyState)!=="open")return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),(i=this.audioBufferManager)==null||i.maintain(e),(r=this.liveTextManager)==null||r.maintain(e),(this.videoBufferManager.gaps.length||(s=this.audioBufferManager)!=null&&s.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=Zc(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),n=>{this.error$.next({id:"GapWatchdog",category:ct.WTF,message:"Error handling gaps",thrown:n})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.fetcher=new go({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.subscription.add(this.fetcher.recoverableError$.subscribe(this.fetcherRecoverableError$)),this.subscription.add(this.fetcher.error$.subscribe(this.fetcherError$)),this.liveBuffer=Ct.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator}),this.initTracerSubscription()}async seekLive(e){var r,s,n;Lr(this.element);let t=this.liveStreamStatus$.getValue()!=="active"?ed()-this.liveStreamEndTimestamp:0,i=this.normolizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=le(this.manifestUrlString,i,2),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await((r=this.videoBufferManager)==null?void 0:r.seekLive(this.manifest.streams.video)),await((s=this.audioBufferManager)==null?void 0:s.seekLive(this.manifest.streams.audio)),(n=this.liveTextManager)==null||n.seekLive(this.manifest.streams.text))}initBuffer(){Lr(this.element),this.state$.setState("running"),this.subscription.add(Mi(...xB.map(e=>Bt(this.element,e)),Bt(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:ct.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(Bt(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(Bt(this.element,"waiting").subscribe(()=>{var t;this.element&&this.element.readyState===2&&!this.element.seeking&&Ie(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{var p,h,m,b,S,y,v,I,E,A,M;if(!this.element||((p=this.source)==null?void 0:p.readyState)!=="open")return;let i=this.currentStallDuration$.getValue();i+=50,this.currentStallDuration$.next(i);let r={timeInWaiting:i},s=ed(),n=100,o=(m=(h=this.videoBufferManager)==null?void 0:h.lastDataObtainedTimestamp)!=null?m:0;this.videoLastDataObtainedTimestamp$.next(o);let u=(S=(b=this.audioBufferManager)==null?void 0:b.lastDataObtainedTimestamp)!=null?S:0,l=(v=(y=this.videoBufferManager)==null?void 0:y.getForwardBufferDuration())!=null?v:0,c=(E=(I=this.audioBufferManager)==null?void 0:I.getForwardBufferDuration())!=null?E:0,d=l<n&&s-o>this.tuning.dash.crashOnStallTWithoutDataTimeout,f=this.audioBufferManager&&c<n&&s-u>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((d||f)&&i>this.tuning.dash.crashOnStallTWithoutDataTimeout||i>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${i} ms`);if(this.isLive$.getValue()&&i%2e3===0){let L=this.normolizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(L).catch(P=>{this.error$.next({id:"stallIntervalCallback",category:ct.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:P})}),r.liveLastOffset=L}else{let L=this.element.currentTime*1e3;(A=this.videoBufferManager)==null||A.maintain(L),(M=this.audioBufferManager)==null||M.maintain(L),r.position=L}this.tracer.log("stallIntervalCallback",hs(r))};(t=this.stallWatchdogSubscription)==null||t.unsubscribe(),this.stallWatchdogSubscription=Zc(50).subscribe(e,i=>{this.error$.next({id:"StallWatchdogCallback",category:ct.NETWORK,message:"Can't restore DASH after stall.",thrown:i})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,i=!1){let r={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return this.tuning.useNewSwitchTo?this.currentStallDuration$.getValue()>0?r==null?void 0:r.switchToWithPreviousAbort(t,i):r==null?void 0:r.switchTo(t,i):r==null?void 0:r.switchToOld(t,i)}async seek(e,t){var r,s,n,o,u;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((r=this.videoBufferManager.findSegmentStartTime(e))!=null?r:e,(n=(s=this.audioBufferManager)==null?void 0:s.findSegmentStartTime(e))!=null?n:e),this.warmUpMediaSourceIfNeeded(i),Ie(this.element.buffered,i)||await Promise.all([this.videoBufferManager.abort(),(o=this.audioBufferManager)==null?void 0:o.abort()]),!(sI(this.element)||sI(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),(u=this.audioBufferManager)==null||u.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",hs({requestedPosition:e,forcePrecise:t,position:i})))}warmUpMediaSourceIfNeeded(e=(t=>(t=this.element)==null?void 0:t.currentTime)()){var i;fs(this.element)&&fs(this.source)&&fs(e)&&((i=this.source)==null?void 0:i.readyState)==="ended"&&this.element.duration*1e3-e>this.tuning.dash.seekBiasInTheEnd&&this.bufferManagers.forEach(r=>r.warmUpMediaSource())}get isStreamEnded(){var e;return((e=this.source)==null?void 0:e.readyState)==="ended"}stop(){var e,t,i;this.tracer.log("stop"),(e=this.element)==null||e.querySelectorAll("source").forEach(r=>{URL.revokeObjectURL(r.src),r.remove()}),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(t=this.videoBufferManager)==null||t.destroy(),this.videoBufferManager=null,(i=this.audioBufferManager)==null||i.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){var e;return(e=this.manifest)==null?void 0:e.streams}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){var e;this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),((e=this.source)==null?void 0:e.readyState)==="open"&&Array.from(this.source.sourceBuffers).every(t=>!t.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=TB(this.tracer.error.bind(this.tracer));this.subscription.add(this.error$.subscribe(e("error")))}isManualDecreasePlaybackInLive(){if(!this.element||!this.isLive$.getValue())return!1;let e=1-this.element.playbackRate;return Number(e.toFixed(2))>Number(this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup.toFixed(2))}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){var e,t;this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&((e=this.bufferManagers)==null||e.forEach(i=>i.updateLive(this.manifest)),(t=this.liveTextManager)==null||t.updateLive(this.manifest)),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getDebugBufferState();if(!e)return;let t=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),i={isJumpGapAfterSeekLive:this.isJumpGapAfterSeekLive,isActiveLowLatency:t,initialCurrentTime:this.element.currentTime};this.isJumpGapAfterSeekLive&&!t&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let r=this.element.currentTime*1e3,s=[],n=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let o of this.bufferManagers)for(let u of o.gaps)o.playingRepresentation$.getValue()===u.representation&&u.from-n<=r&&u.to+n>r&&(this.element.duration*1e3-u.to<this.tuning.endGapTolerance?s.push(1/0):s.push(u.to));if(s.length){let o=Math.max(...s)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,o===1/0?this.forceEnded$.next():(this.element.currentTime=o/1e3,i={...i,gapEnds:s,jumpTo:o,resultCurrentTime:this.element.currentTime},this.tracer.log("jumpGap",hs(i)))}}calculateDurationFromSegments(){var e,t;return Math.max(((e=this.videoBufferManager)==null?void 0:e.calculateDurationFromSegments())||0,((t=this.audioBufferManager)==null?void 0:t.calculateDurationFromSegments())||0)}};var Ro=class{constructor(e,t){this.fov=e,this.orientation=t}};var ko=class{constructor(e,t){this.rotating=!1;this.fading=!1;this.lastTickTS=0;this.lastCameraTurnTS=0;this.fadeStartSpeed=null;this.fadeTime=0;this.camera=e,this.options=t,this.rotationSpeed={x:0,y:0,z:0},this.fadeCorrection=1/(this.options.speedFadeTime/1e3)**2}turnCamera(e=0,t=0,i=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+i)}pointCameraTo(e=0,t=0,i=0){t=this.limitCameraRotationY(t);let r=e-this.camera.orientation.x,s=t-this.camera.orientation.y,n=i-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=i,this.lastCameraTurn={x:r,y:s,z:n},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,i){this.rotationSpeed.x=e!=null?e:this.rotationSpeed.x,this.rotationSpeed.y=t!=null?t:this.rotationSpeed.y,this.rotationSpeed.z=i!=null?i:this.rotationSpeed.z}startRotation(){this.rotating=!0}stopRotation(e=!1){e?(this.setRotationSpeed(0,0,0),this.fadeStartSpeed=null):this.startFading(this.rotationSpeed.x,this.rotationSpeed.y,this.rotationSpeed.z),this.rotating=!1}onCameraRelease(){if(this.lastCameraTurn&&this.lastCameraTurnTS){let e=Date.now()-this.lastCameraTurnTS;if(e<this.options.speedFadeThreshold){let t=(1-e/this.options.speedFadeThreshold)*this.options.rotationSpeedCorrection;this.startFading(this.lastCameraTurn.x*t,this.lastCameraTurn.y*t,this.lastCameraTurn.z*t)}}}startFading(e,t,i){this.setRotationSpeed(e,t,i),this.fadeStartSpeed={...this.rotationSpeed},this.fading=!0}stopFading(){this.fadeStartSpeed=null,this.fading=!0,this.fadeTime=0}limitCameraRotationY(e){return Math.max(-this.options.maxYawAngle,Math.min(e,this.options.maxYawAngle))}tick(e){if(!this.lastTickTS){this.lastTickTS=e,this.lastCameraTurnTS=Date.now();return}let t=e-this.lastTickTS,i=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i);else if(this.fading&&this.fadeStartSpeed){let r=-this.fadeCorrection*(this.fadeTime/1e3)**2+1;this.setRotationSpeed(this.fadeStartSpeed.x*r,this.fadeStartSpeed.y*r,this.fadeStartSpeed.z*r),r>0?this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}};var uI=`attribute vec2 a_vertex;
|
|
125
125
|
attribute vec2 a_texel;
|
|
126
126
|
|
|
127
127
|
varying vec2 v_texel;
|
|
@@ -132,7 +132,7 @@ void main(void) {
|
|
|
132
132
|
// save texel vector to pass to fragment shader
|
|
133
133
|
v_texel = a_texel;
|
|
134
134
|
}
|
|
135
|
-
`;var
|
|
135
|
+
`;var lI=`#ifdef GL_ES
|
|
136
136
|
precision highp float;
|
|
137
137
|
precision highp int;
|
|
138
138
|
#else
|
|
@@ -175,13 +175,6 @@ void main(void) {
|
|
|
175
175
|
// sample using new coordinates
|
|
176
176
|
gl_FragColor = texture2D(u_texture, tc);
|
|
177
177
|
}
|
|
178
|
-
`;var os=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 Yu(this.params.fov,this.params.orientation),this.cameraRotationManager=new Ku(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(WI,this.gl.VERTEX_SHADER),i=this.createShader(YI,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,i),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){let e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,i=1,r=this.frameHeight/(this.frameWidth/this.viewportWidth);return r>this.viewportHeight?t=this.viewportHeight/r:i=r/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-i,t,-i,t,i,-t,i]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){let e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,i=this.camera.fov.x/360/2,r=this.camera.fov.y/180/2,a=e-i,n=t-r,o=e+i,u=t-r,l=e+i,d=t+r,c=e-i,h=t+r;return[a,n,o,u,l,d,c,h]}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 fC,now as En,once as mC,Subscription as bC,ValueSubject as Rp,isNonNullable as gC,safeStorage as Mp,filterChanged as SC}from"@vkontakte/videoplayer-shared/es2018";var Xu="stalls_manager_metrics",Lp="stalls_manager_abr_params",KI="stalls_manager_default_tuning_abr_params",Bp=class{constructor(){this.isSeeked$=new Rp(!1);this.isBuffering$=new Rp(!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 bC;this.severeStallOccurred$=new Rp(!1)}init(e){this.currentStallDuration$=e.currentStallDuration$,this.videoLastDataObtainedTimestamp$=e.videoLastDataObtainedTimestamp$,this.throughput$=e.throughput$,this.rtt$=e.rtt$,this.tuning=e.tuning,this.abrParams=e.abrParams,this.resetStoredAbrParamsIfNeeded(),this.subscribe(e)}get videoMaxQualityLimit(){return this.maxQualityLimit}get predictedThroughput(){return this.predictedThroughputWithoutData}get abrTuningParams(){let e=this.tuning.enabled?this.getStoredData(Lp):{};return{...this.abrParams,...e}}set lastVideoTrackSelected(e){var t;((t=this.lastUniqueVideoTrackSelected)==null?void 0:t.id)!==e.id&&(this.lastUniqueVideoTrackSelected=e,this.lastUniqueVideoTrackSelectedTimestamp=En(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe(),this.currentStallDuration$.getValue()!==0&&this.updateStallData();let e=(En()-this.providerStartWatchingTimestamp-this.sumStallsDuration)/1e3,t=this.sumStallsDuration;this.addStallInfoToHistory(e,t),this.updateStoredAbrParams()}resetStoredAbrParamsIfNeeded(){let{bitrateFactorAtEmptyBuffer:e,bitrateFactorAtFullBuffer:t,containerSizeFactor:i}={...this.getStoredData(KI)},{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:a,containerSizeFactor:n}={...this.abrParams};this.tuning.enabled&&e===r&&t===a&&i===n||(this.removeStoredData(Lp),this.setStoredData(KI,{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:a,containerSizeFactor:n}))}updateStoredAbrParams(){let e=[],t=this.getStoredData(Xu,"[]");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(Xu,[]),this.setStoredData(Lp,r)}calculateOptimalAbrParams(e,t){let{targetStallsDurationPerTvt:i,deviationStallsDurationPerTvt:r,criticalStallsDurationPerTvt:a,abrAdjustingSpeed:n,significantTvt:o,stallsMetricsHistoryLength:u}=this.tuning,l=n*Math.min(t/(o*u),1),d=this.abrTuningParams;return e<i-r?d={bitrateFactorAtEmptyBuffer:Math.max(d.bitrateFactorAtEmptyBuffer-l,this.abrParams.minBitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.max(d.bitrateFactorAtFullBuffer-l,this.abrParams.minBitrateFactorAtFullBuffer),containerSizeFactor:Math.min(d.containerSizeFactor+l,this.abrParams.maxContainerSizeFactor)}:e>i+r&&(d={bitrateFactorAtEmptyBuffer:Math.min(d.bitrateFactorAtEmptyBuffer+l,this.abrParams.maxBitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.min(d.bitrateFactorAtFullBuffer+l,this.abrParams.maxBitrateFactorAtFullBuffer),containerSizeFactor:Math.max(d.containerSizeFactor-l,this.abrParams.minContainerSizeFactor)}),e>a&&(d={bitrateFactorAtEmptyBuffer:Math.max(d.bitrateFactorAtEmptyBuffer,this.abrParams.bitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.max(d.bitrateFactorAtFullBuffer,this.abrParams.bitrateFactorAtFullBuffer),containerSizeFactor:Math.min(d.containerSizeFactor,this.abrParams.containerSizeFactor)}),d}getStoredData(e,t="{}"){var i;return JSON.parse((i=Mp.get(e))!=null?i:t)}setStoredData(e,t){Mp.set(e,JSON.stringify(t))}removeStoredData(e){Mp.remove(e)}addStallInfoToHistory(e,t){if(e<this.tuning.minTvtToBeCounted||e>this.tuning.maxTvtToBeCounted||e*1e3<t)return;let i=this.getStoredData(Xu,"[]"),r=t/e,a=i.length?vi(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(Xu,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(mC()).subscribe(t=>this.providerStartWatchingTimestamp=En())),this.subscription.add(this.currentStallDuration$.pipe(SC()).subscribe(t=>{let{stallDurationNoDataBeforeQualityDecrease:i,stallCountBeforeQualityDecrease:r,resetQualityRestrictionTimeout:a,ignoreStallsOnSeek:n}=this.tuning;if(fC(this.lastUniqueVideoTrackSelected)||n&&this.isSeeked$.getValue())return;let o=this.rtt$.getValue(),u=this.throughput$.getValue(),l=this.videoLastDataObtainedTimestamp$.getValue(),d=En(),c=r&&this.currentStallsCount>=r,h=i&&d-this.lastUniqueVideoTrackSelectedTimestamp>=i+o&&d-l>=i+o&&t>=i;(c||h)&&(this.severeStallOccurred$.next(!0),window.clearTimeout(this.qualityRestrictionTimer),this.maxQualityLimit=this.lastUniqueVideoTrackSelected.quality,gC(this.lastUniqueVideoTrackSelected.bitrate)&&u>this.lastUniqueVideoTrackSelected.bitrate&&(this.predictedThroughputWithoutData=this.lastUniqueVideoTrackSelected.bitrate)),!t&&En()-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}))}},Ju=Bp;import{combine as vC,map as yC,observeElementSize as TC,Subscription as IC,ValueSubject as $p,noop as xC}from"@vkontakte/videoplayer-shared/es2018";var Zu=class{constructor(){this.subscription=new IC;this.pipSize$=new $p(void 0);this.videoSize$=new $p(void 0);this.elementSize$=new $p(void 0);this.pictureInPictureWindowRemoveEventListener=xC}connect({observableVideo:e,video:t}){let i=r=>{let a=r.target;this.pipSize$.next({width:a.width,height:a.height})};this.subscription.add(TC(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(vC({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(yC(({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 hr=class{constructor(e){this.subscription=new MC;this.videoState=new G("stopped");this.observableVideo=null;this.droppedFramesManager=new Gr;this.stallsManager=new Ju;this.elementSizeManager=new Zu;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new $i;this.audioTrackSwitchHistory=new $i;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(r.state==="requested"&&(i==null?void 0:i.to)!=="paused"&&e!=="stopped"&&t!=="stopped"&&this.seek(r.position,r.forcePrecise),t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),M(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"),M(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="ready"&&M(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):t==="playing"&&this.video.paused?this.playIfAllowed():(i==null?void 0:i.to)==="playing"&&M(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&M(this.params.desiredState.playbackState,"paused");return;default:return wC(e)}}};this.init3DScene=e=>{var i,r,a;if(this.scene3D)return;this.scene3D=new os(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((i=e.projectionData)==null?void 0:i.pose.yaw)||0,y:((r=e.projectionData)==null?void 0:r.pose.pitch)||0,z:((a=e.projectionData)==null?void 0:a.pose.roll)||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSizeManager.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.textTracksManager=new xt(e.source.url),this.params=e,this.video=tt(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(Fe(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.player=new Wu({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params;RC(this.observableVideo)&&(this.observableVideo=st(this.video),this.subscription.add(()=>{var n;return(n=this.observableVideo)==null?void 0:n.destroy()}));let i=this.constructor.name,r=n=>{e.error$.next({id:i,category:XI.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(Dp(l=>!!l.length),ZI()).subscribe(l=>{this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:l})}));let n=this.params.desiredState.seekState.stateChangeEnded$.pipe(Cp(l=>l.to.state!=="none"),el());this.stallsManager.init({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$,videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,tuning:this.params.tuning.stallsManager,abrParams:this.params.tuning.autoTrackSelection,isBuffering$:i.isBuffering$,looped$:i.looped$,playing$:i.playing$}),a(i.ended$,e.endedEvent$),a(i.looped$,e.loopedEvent$),a(i.error$,e.error$),a(i.isBuffering$,e.isBuffering$),a(i.currentBuffer$,e.currentBuffer$),a(i.playing$,e.firstFrameEvent$),a(i.canplay$,e.canplay$),a(i.inPiP$,e.inPiP$),a(i.inFullscreen$,e.inFullscreen$),a(i.loadedMetadata$,e.loadedMetadataEvent$),a(this.player.error$,e.error$),a(this.player.fetcherRecoverableError$,e.fetcherRecoverableError$),a(this.player.fetcherError$,e.fetcherError$),a(this.player.lastConnectionType$,e.httpConnectionType$),a(this.player.lastConnectionReused$,e.httpConnectionReused$),a(this.player.isLive$,e.isLive$),a(this.player.lastRequestFirstBytes$.pipe(Dp(JI),ZI()),e.firstBytesEvent$),a(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),a(this.videoState.stateChangeEnded$.pipe(Cp(l=>l.to)),this.params.output.playbackState$),this.subscription.add(i.looped$.subscribe(()=>this.player.warmUpMediaSourceIfNeeded(),r)),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(zt(this.video,t.isLooped,r)),this.subscription.add(rt(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(It(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),a(Et(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),M(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),M(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"),M(t.playbackState,"paused")})),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:l})=>{if(l==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let d=this.player.getStreams();if(AC(d,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let h=[];for(let p of d.audio){h.push(hp(p));let f=[];for(let m of p.representations){let g=wI(m);f.push(g),this.audioTracksMap.set(g,{stream:p,representation:m})}this.audioStreamsMap.set(p,f)}this.params.output.availableAudioStreams$.next(h)}let c=[];for(let h of d.video){c.push(fp(h));let p=[];for(let f of h.representations){let m=EI({...f,streamId:h.id});m&&(p.push(m),this.videoTracksMap.set(m,{stream:h,representation:f}))}this.videoStreamsMap.set(h,p)}this.params.output.availableVideoStreams$.next(c);for(let h of d.text)for(let p of h.representations){let f=AI(h,p);this.textTracksMap.set(f,{stream:h,representation:p})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else l==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r)),this.subscription.add(tl(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$,kC(this.video,"progress")).pipe(Dp(()=>this.videoTracksMap.size>0)).subscribe(async()=>{let l=this.player.state$.getState(),d=this.player.state$.getTransition();if(!(0,ex.default)(["manifest_ready","running"],l)||d)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let c=this.selectVideoAudioRepresentations();if(!c)return;let[h,p]=c,f=[...this.videoTracksMap.keys()].find(g=>{var S;return((S=this.videoTracksMap.get(g))==null?void 0:S.representation.id)===h.id});JI(f)&&(this.stallsManager.lastVideoTrackSelected=f);let m=this.params.desiredState.autoVideoTrackLimits.getTransition();if(m&&this.params.output.autoVideoTrackLimits$.next(m.to),l==="manifest_ready")await this.player.initRepresentations(h.id,p==null?void 0:p.id,this.params.sourceHls);else if(await this.player.switchRepresentation("video",h.id),p){let g=!!t.audioStream.getTransition();await this.player.switchRepresentation("audio",p.id,g)}},r)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:l})=>{this.scene3D&&l&&this.scene3D.pointCameraTo(l.x,l.y)})),this.subscription.add(this.elementSizeManager.subscribe(l=>{this.scene3D&&l&&this.scene3D.setViewportSize(l.width,l.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(el()).subscribe(l=>{let d=[...this.videoTracksMap.entries()].find(([,{representation:f}])=>f.id===l);if(!d){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[c,{stream:h}]=d,p=this.params.desiredState.videoStream.getTransition();p&&p.to&&p.to.id===h.id&&this.params.desiredState.videoStream.setState(p.to),e.currentVideoTrack$.next(c),e.currentVideoStream$.next(fp(h))},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(el()).subscribe(l=>{let d=[...this.audioTracksMap.entries()].find(([,{representation:f}])=>f.id===l);if(!d){e.currentAudioStream$.next(void 0);return}let[c,{stream:h}]=d,p=this.params.desiredState.audioStream.getTransition();p&&p.to&&p.to.id===h.id&&this.params.desiredState.audioStream.setState(p.to),e.currentAudioStream$.next(hp(h))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(l=>{var d,c;if(l!=null&&l.is3dVideo&&((d=this.params.tuning.spherical)!=null&&d.enabled))try{this.init3DScene(l),e.is3DVideo$.next(!0)}catch(h){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${h}`})}else this.destroy3DScene(),(c=this.params.tuning.spherical)!=null&&c.enabled&&e.is3DVideo$.next(!1)},r)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,r)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,r)),this.textTracksManager.connect(this.video,t,e);let o=t.playbackState.stateChangeStarted$.pipe(Cp(({to:l})=>l==="ready"),el());this.subscription.add(tl(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,Vp(["init"])).subscribe(()=>{let l=t.autoVideoTrackSwitching.getState(),c=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:l?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(c)})),this.subscription.add(tl(o,this.player.state$.stateChangeEnded$,Vp(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let u=tl(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Vp(["init"])).pipe(PC(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){var P,C,L,R,Q,U,A,F,k,x,$,oe,Ce;if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?Ma:Ra,t=this.params.tuning.useNewAutoSelectVideoTrack?xu:Iu,i=this.params.tuning.useNewAutoSelectVideoTrack?Wt:Tu,{desiredState:r,output:a}=this.params,n=r.autoVideoTrackSwitching.getState(),o=(P=r.videoTrack.getState())==null?void 0:P.id,l=[...this.videoTracksMap.keys()].find(({id:se})=>se===o),d=a.currentVideoTrack$.getValue(),c=((R=(L=r.videoStream.getState())!=null?L:l&&((C=this.videoTracksMap.get(l))==null?void 0:C.stream))!=null?R:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!c)return;let h=[...this.videoStreamsMap.keys()].find(({id:se})=>se===c.id),p=h&&this.videoStreamsMap.get(h);if(!p)return;let f=$e(this.video.buffered,this.video.currentTime*1e3),m;this.player.isActiveLive$.getValue()?m=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?m=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:m=n?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let g=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,S=Math.min(f/Math.min(m,g||1/0),1),v=(Q=r.audioStream.getState())!=null?Q:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,y=(U=[...this.audioStreamsMap.keys()].find(({id:se})=>se===(v==null?void 0:v.id)))!=null?U:this.audioStreamsMap.keys().next().value,I=0;if(y){if(l&&!n){let se=e(l,p,(A=this.audioStreamsMap.get(y))!=null?A:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);I=Math.max(I,(F=se==null?void 0:se.bitrate)!=null?F:-1/0)}if(d){let se=e(d,p,(k=this.audioStreamsMap.get(y))!=null?k:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);I=Math.max(I,(x=se==null?void 0:se.bitrate)!=null?x:-1/0)}}let T=i(p,{container:this.elementSizeManager.getValue(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.stallsManager.abrTuningParams,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:I,forwardBufferHealth:S,current:d,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,stallsVideoMaxQualityLimit:this.stallsManager.videoMaxQualityLimit,stallsPredictedThroughput:this.stallsManager.predictedThroughput,abrLogger:this.params.dependencies.abrLogger}),E=n?T!=null?T:l:l!=null?l:T,O=y&&t(E,p,($=this.audioStreamsMap.get(y))!=null?$:[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.stallsManager.abrTuningParams,forwardBufferHealth:S,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),B=(oe=this.videoTracksMap.get(E))==null?void 0:oe.representation,w=O&&((Ce=this.audioTracksMap.get(O))==null?void 0:Ce.representation);if(B&&w)return[B,w];if(B&&!w&&this.audioTracksMap.size===0)return[B,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){at(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),M(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:XI.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),it(this.video),this.tracer.end()}};var wn=class extends hr{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 Op,merge as tx,filter as ix,filterChanged as LC,isNullable as _p,map as rx,ValueSubject as Fp,isNonNullable as BC}from"@vkontakte/videoplayer-shared/es2018";var An=class extends hr{constructor(e){super(e),this.textTracksManager.destroy()}subscribe(){super.subscribe();let e=-1,{output:t,observableVideo:i,desiredState:r,connect:a}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),a(i.timeUpdate$,t.liveBufferTime$),a(this.player.liveSeekableDuration$,t.duration$),a(this.player.liveLatency$,t.liveLatency$);let n=new Fp(1);a(i.playbackRateState$,n),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(r.isLowLatency.stateChangeEnded$.pipe(rx(o=>o.to)).subscribe(this.player.isLowLatency$)).add(Op({liveBufferTime:t.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(rx(({liveBufferTime:o,liveAvailabilityStartTime:u})=>o&&u?o+u:void 0)).subscribe(t.liveTime$)).add(this.player.liveStreamStatus$.pipe(ix(o=>BC(o))).subscribe(o=>t.isLiveEnded$.next(o!=="active"&&t.position$.getValue()===0))).add(Op({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:tx(i.playbackRateState$,new Fp(1))}).pipe(ix(({liveStreamStatus:o,liveDuration:u})=>o==="active"&&!!u)).subscribe(({liveDuration:o,playbackRate:u})=>{let l=t.liveBufferTime$.getValue(),d=t.position$.getValue(),{playbackCatchupSpeedup:c}=this.params.tuning.dashCmafLive.lowLatency;d||u<1-c||this.video.paused||_p(l)||(e=o-l)})).add(Op({time:t.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:tx(i.playbackRateState$,new Fp(1))}).pipe(LC((o,u)=>this.player.liveStreamStatus$.getValue()==="active"?o.liveDuration===u.liveDuration:o.time===u.time)).subscribe(({time:o,liveDuration:u,playbackRate:l})=>{let d=t.position$.getValue(),{playbackCatchupSpeedup:c}=this.params.tuning.dashCmafLive.lowLatency;if(!d&&!this.video.paused&&l>=1-c||_p(o)||_p(u))return;let h=-1*(u-o-e);t.position$.next(Math.min(h,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(o=>{if(o){let u=PI(o);this.params.output.availableTextTracks$.next([u])}}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=Math.trunc(t/1e3<=Math.abs(this.params.output.duration$.getValue())?t:0);this.player.seekLive(i).then(()=>{this.params.output.position$.next(e/1e3)})}};import{assertNever as EV,assertNonNullable as wV,debounce as AV,ErrorCategory as Cx,filter as oh,filterChanged as hl,fromEvent as PV,isNonNullable as Vx,isNullable as kV,map as uh,merge as fl,observableFrom as lh,once as Ox,Subscription as RV}from"@vkontakte/videoplayer-shared/es2018";var ah=N(Fa(),1);import{abortable as th,assertNonNullable as ps,combine as hs,ErrorCategory as Ut,filter as ll,filterChanged as ao,flattenObject as no,fromEvent as Kt,getTraceSubscriptionMethod as fV,interval as ih,isNonNullable as oo,isNullable as $x,map as fs,merge as vr,now as rh,Subject as cl,Subscription as sh,tap as mV,throttle as Dx,ValueSubject as fe}from"@vkontakte/videoplayer-shared/es2018";var al=N(gt(),1),cs=N(Ot(),1),nl=N(Fa(),1);var kx=N(eu(),1);import{assertNever as $C,ErrorCategory as sx,Subject as ax}from"@vkontakte/videoplayer-shared/es2018";var DC=18,nx=!1;try{nx=j.browser.isSafari&&!!j.browser.safariVersion&&j.browser.safariVersion<=DC}catch(s){console.error(s)}var Np=class{constructor(e){this.bufferFull$=new ax;this.error$=new ax;this.queue=[];this.currentTask=null;this.destroyed=!1;this.abortRequested=!1;this.completeTask=()=>{var e;try{if(this.currentTask){let t=(e=this.currentTask.signal)==null?void 0:e.aborted;this.currentTask.callback(!t),this.currentTask=null}this.queue.length&&this.pull()}catch(t){this.error$.next({id:"BufferTaskQueueUnknown",category:sx.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(i=>{let r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(r=>{let a={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(a),this.pull()})}async abort(e){return new Promise(t=>{let i,r=a=>{this.abortRequested=!1,t(a)};nx&&e?i={operation:"safariAbort",init:e,callback:r}:i={operation:"abort",callback:r};for(let{callback:a}of this.queue)a(!1);this.abortRequested=!0,i&&(this.queue=[i]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){var r;if((this.buffer.updating||this.currentTask||this.destroyed)&&!this.abortRequested)return;let e=this.queue.shift();if(!e)return;if((r=e.signal)!=null&&r.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(a){a instanceof DOMException&&a.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):a instanceof DOMException&&a.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:sx.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:a}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){let{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:$C(t)}}},ox=Np;import{abortable as Fi,assertNonNullable as ot,ErrorCategory as gr,fromEvent as Xp,getExponentialDelay as Jp,isNonNullable as ls,isNullable as qe,now as sl,once as aV,Subject as nV,Subscription as oV,ValueSubject as Sr}from"@vkontakte/videoplayer-shared/es2018";var J=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let i=this.readUint32();this.type=this.readString(4),i>e.byteLength-e.byteOffset&&(this.size32=NaN);let r=this.size32?this.size32-8:void 0,a=e.byteOffset+this.cursor;this.size64=0,this.usertype=0,this.content=new DataView(e.buffer,a,r)}get id(){return this.type}get size(){return this.size32}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t="ascii"){let r=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,r}readUint8(){let e=this.source.getUint8(this.cursor);return this.cursor+=1,e}readUint16(){let e=this.source.getUint16(this.cursor);return this.cursor+=2,e}readUint32(){let e=this.source.getUint32(this.cursor);return this.cursor+=4,e}readUint64(){let e=this.source.getBigInt64(this.cursor);return this.cursor+=8,e}};var us=class extends J{};var Pn=class extends J{constructor(t,i){super(t,i);this.ondemandPrefix="ondemandlivejson";this.ondemandDataReceivedKey="t-in";this.ondemandDataPreparedKey="t-out";let r=this.content.byteOffset,a=r+this.content.byteLength,n=new TextDecoder("ascii").decode(this.content.buffer.slice(r,a)).split(this.ondemandPrefix)[1],o=JSON.parse(n);this.serverDataReceivedTimestamp=o[this.ondemandDataReceivedKey],this.serverDataPreparedTime=o[this.ondemandDataPreparedKey]}};var kn=class extends J{constructor(e,t){super(e,t),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let i=this.size-this.cursor;for(;i;){let r=this.readString(4);this.compatibleBrands.push(r),i-=4}}};var Rn=class extends J{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var le=class extends J{constructor(e,t){super(e,t);let i=this.readUint32();this.version=i>>>24,this.flags=i&16777215}};var Mn=class extends le{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.timescale=this.readUint32(),this.duration=this.readUint32(),this.rate=this.readUint32(),this.volume=this.readUint16()}};var Ln=class extends J{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Bn=class extends J{constructor(e,t){super(e,t),this.data=this.content}};var fr=class extends le{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e,t){super(e,t),this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let i=0;i<this.referenceCount;i++){let r=this.readUint32(),a=r>>>31,n=r<<1>>>1,o=this.readUint32();r=this.readUint32();let u=r>>>28,l=r<<3>>>3;this.segments.push({referenceType:a,referencedSize:n,subsegmentDuration:o,SAPType:u,SAPDeltaTime:l})}}};var $n=class extends J{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Dn=class extends J{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Cn=class extends le{constructor(e,t){switch(super(e,t),this.readUint8()){case 0:this.stereoMode=0;break;case 1:this.stereoMode=1;break;case 2:this.stereoMode=2;break;case 3:this.stereoMode=3;break;case 4:this.stereoMode=4;break}this.cursor+=1}};var Vn=class extends le{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var On=class extends le{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var _n=class extends J{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Fn=class extends le{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 Nn=class extends J{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Un=class extends J{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var qn=class extends le{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var jn=class extends J{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Hn=class extends le{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 zn=class extends le{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 Qn=class extends le{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 Gn=class extends J{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Wn=class extends le{constructor(e,t){super(e,t),this.entryCount=this.readUint32(),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+8,this.content.byteLength-8))}};var Yn=class extends J{constructor(e,t){super(e,t),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+78,this.content.byteLength-78))}};var VC={ftyp:kn,moov:Rn,mvhd:Mn,moof:Ln,mdat:Bn,sidx:fr,trak:$n,mdia:_n,mfhd:qn,tkhd:Fn,traf:jn,tfhd:Hn,tfdt:zn,trun:Qn,minf:Nn,sv3d:Dn,st3d:Cn,prhd:Vn,proj:Un,equi:On,uuid:Pn,stbl:Gn,stsd:Wn,avc1:Yn,unknown:us},Ii=class s{constructor(e={}){this.options={offset:0,...e}}parse(e){let t=[],i=this.options.offset;for(;i<e.byteLength;)try{let a=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+i+4,4)),n=this.createBox(a,new DataView(e.buffer,e.byteOffset+i,e.byteLength-i));if(!n.size)break;t.push(n),i+=n.size}catch(r){break}return t}createBox(e,t){let i=VC[e];return i?new i(t,new s):new us(t,new s)}};var _i=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{var i,r,a;(a=(i=this.index)[r=t.type])!=null||(i[r]=[]),this.index[t.type].push(t),t.children.length>0&&this.indexBoxLevel(t.children)})}find(e){return this.index[e]&&this.index[e][0]?this.index[e][0]:null}findAll(e){return this.index[e]||[]}};var _C=new TextDecoder("ascii"),FC=s=>_C.decode(new DataView(s.buffer,s.byteOffset+4,4))==="ftyp",NC=s=>{let e=new fr(s,new Ii),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})},UC=(s,e)=>{let i=new Ii().parse(s),r=new _i(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)},qC=s=>{let t=new Ii().parse(s),i=new _i(t),r={},a=i.findAll("uuid");return a.length?a[a.length-1]:r},jC=s=>{var r;let t=new Ii().parse(s);return(r=new _i(t).find("sidx"))==null?void 0:r.timescale},HC=(s,e)=>{let i=new Ii().parse(s),a=new _i(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,h)=>c+h,0):l=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+l)/e*1e3},zC=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 Ii().parse(s),r=new _i(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},ux={validateData:FC,parseInit:zC,getIndexRange:()=>{},parseSegments:NC,parseFeedableSegmentChunk:UC,getChunkEndTime:HC,getServerLatencyTimestamps:qC,getTimescaleFromIndex:jC};var Xn=N(gt(),1);import{assertNonNullable as qp,isNonNullable as px,isNullable as GC}from"@vkontakte/videoplayer-shared/es2018";import{assertNever as QC}from"@vkontakte/videoplayer-shared/es2018";var lx={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"}},cx=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=Kn(s,t),r=i in lx,a=r?lx[i].type:"binary",n=s.getUint8(t),o=0;n&128?o=1:n&64?o=2:n&32?o=3:n&16?o=4:n&8?o=5:n&4?o=6:n&2?o=7:n&1&&(o=8);let u=new DataView(s.buffer,s.byteOffset+t+1,o-1),l=n&255>>o,d=Kn(u),c=l*2**((o-1)*8)+d,h=t+o,p;return h+c>s.byteLength?p=new DataView(s.buffer,s.byteOffset+h):p=new DataView(s.buffer,s.byteOffset+h,c),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:a,tagHeaderSize:h,tagSize:h+c,value:p,valueSize:c}},Kn=(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},Nt=(s,e)=>{switch(e){case"int":return s.getInt8(0);case"uint":return Kn(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:QC(e)}},mr=(s,e)=>{let t=0;for(;t<s.byteLength;){let i=new DataView(s.buffer,s.byteOffset+t),r=cx(i);if(!e(r))return;r.type==="master"&&mr(r.value,e),t=r.value.byteOffset-s.byteOffset+r.valueSize}},dx=s=>{if(s.getUint32(0)!==440786851)return!1;let e,t,i,r=cx(s);return mr(r.value,({tag:a,type:n,value:o})=>(a===17143?e=Nt(o,n):a===17026?t=Nt(o,n):a===17029&&(i=Nt(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)};var hx=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],WC=[231,22612,22743,167,171,163,160,175],YC=s=>{let e,t,i,r,a=!1,n=!1,o=!1,u,l,d=!1,c=0;return mr(s,({tag:h,type:p,value:f,valueSize:m})=>{if(h===21419){let g=Nt(f,p);l=Kn(g)}else h!==21420&&(l=void 0);return h===408125543?(e=f.byteOffset,t=f.byteOffset+m):h===357149030?a=!0:h===290298740?n=!0:h===2807729?i=Nt(f,p):h===17545?r=Nt(f,p):h===21420&&l===475249515?u=Nt(f,p):h===374648427?mr(f,({tag:g,type:S,value:v})=>g===30321?(d=Nt(v,S)===1,!1):!0):a&&n&&(0,Xn.default)(hx,h)&&(o=!0),!o}),qp(e,"Failed to parse webm Segment start"),qp(t,"Failed to parse webm Segment end"),qp(r,"Failed to parse webm Segment duration"),i=i!=null?i:1e6,{segmentStart:Math.round(e/1e9*i*1e3),segmentEnd:Math.round(t/1e9*i*1e3),timeScale:i,segmentDuration:Math.round(r/1e9*i*1e3),cuesSeekPosition:u,is3dVideo:d,stereoMode:c,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},KC=s=>{if(GC(s.cuesSeekPosition))return;let e=s.segmentStart+s.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},XC=(s,e)=>{let t=!1,i=!1,r=o=>px(o.time)&&px(o.position),a=[],n;return mr(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=Nt(l,u));break;case 183:break;case 241:n&&(n.position=Nt(l,u));break;default:t&&(0,Xn.default)(hx,o)&&(i=!0)}return!(t&&i)}),n&&r(n)&&a.push(n),a.map((o,u)=>{let{time:l,position:d}=o,c=a[u+1];return{status:"none",time:{from:l,to:c?c.time:e.segmentDuration},byte:{from:e.segmentStart+d,to:c?e.segmentStart+c.position-1:e.segmentEnd-1}}})},JC=s=>{let e=0,t=!1;try{mr(s,i=>i.tag===524531317?i.tagSize<=s.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):(0,Xn.default)(WC,i.tag)?(e+i.tagSize<=s.byteLength&&(e+=i.tagSize,t||(t=(0,Xn.default)([163,160,175],i.tag))),!0):!1)}catch(i){}return e>0&&e<=s.byteLength&&t?new DataView(s.buffer,s.byteOffset,e):null},fx={validateData:dx,parseInit:YC,getIndexRange:KC,parseSegments:XC,parseFeedableSegmentChunk:JC};var Jn=s=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(s);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return fx;case"mp4":return ux}}throw new ReferenceError(`Unsupported mime type ${s}`)};var Wp=N(lp(),1),Ex=N(Ji(),1),wx=N(cp(),1),Ax=N(Ot(),1),Yp=N(nr(),1);import{isNonNullable as iV,isNullable as Ix}from"@vkontakte/videoplayer-shared/es2018";var mx=s=>{var e;try{let t=ZC(),i=s.match(t),{groups:r}=i!=null?i:{};if(r){let a={};if(r.extensions){let u=r.extensions.toLowerCase().match(/(?:[0-9a-wy-z](?:-[a-z0-9]{2,8})+)/g);Array.from(u||[]).forEach(l=>{a[l[0]]=l.slice(2)})}let n=(e=r.variants)==null?void 0:e.split(/-/).filter(u=>u!==""),o={extlang:r.extlang,langtag:r.langtag,language:r.language,privateuse:r.privateuse||r.privateuse2,region:r.region,script:r.script,extensions:a,variants:n};return Object.keys(o).forEach(u=>{let l=o[u];(typeof l=="undefined"||l==="")&&delete o[u]}),o}return null}catch(t){return null}};function ZC(){let s="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",d=`^(?:(?<langtag>${`
|
|
179
|
-
|
|
180
|
-
(-(?<script>[a-z]{4}))?
|
|
181
|
-
(-(?<region>(?:[a-z]{2}|[0-9]{3})))?
|
|
182
|
-
(?<variants>(?:-(?:[a-z0-9]{5,8}|[0-9][a-z0-9]{3}))*)
|
|
183
|
-
(?<extensions>(?:-[0-9a-wy-z](?:-[a-z0-9]{2,8})+)*)
|
|
184
|
-
(?:-(?<privateuse>(?:${e})))?
|
|
185
|
-
`})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(d,"i")}var Hp=N(Ot(),1);import{videoSizeToQuality as eV,throttleFn as tV}from"@vkontakte/videoplayer-shared/es2018";var bx=({id:s,width:e,height:t,bitrate:i,fps:r,quality:a,streamId:n})=>{var u;let o=(u=a?Bi(a):void 0)!=null?u:eV({width:e,height:t});return o&&{id:s,quality:o,bitrate:i,size:{width:e,height:t},fps:r,streamId:n}},gx=({id:s,bitrate:e})=>({id:s,bitrate:e}),Sx=({language:s,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:s,label:e}),vx=({language:s,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:s,label:e}),zp=({id:s,language:e,label:t,codecs:i,isDefault:r})=>({id:s,language:e,label:t,codec:(0,Hp.default)(i.split("."),0),isDefault:r}),Qp=({id:s,language:e,label:t,hdr:i,codecs:r})=>({id:s,language:e,hdr:i,label:t,codec:(0,Hp.default)(r.split("."),0)}),Gp=s=>"url"in s,Ze=s=>s.type==="template",Zn=s=>s instanceof DOMException&&(s.name==="AbortError"||s.code===20);var yx=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},br=(s,e)=>{for(let t of s)if(e(t))return t;return null},Tx=s=>{let e=!1,t=tV(()=>{e=!0},s);return()=>{try{return t(),e}finally{e=!1}}};var xx=s=>{if(!(s!=null&&s.startsWith("P")))return;let e=(n,o)=>{let u=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(u)?0:u)*o},i=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(s),r=(i==null?void 0:i[1])==="-"?-1:1,a={days:e(i==null?void 0:i[5],r),hours:e(i==null?void 0:i[6],r),minutes:e(i==null?void 0:i[7],r),seconds:e(i==null?void 0:i[8],r)};return a.days*24*60*60*1e3+a.hours*60*60*1e3+a.minutes*60*1e3+a.seconds*1e3},xi=(s,e)=>{let t=s;t=(0,Wp.default)(t,"$$","$");let i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[r,a]of(0,Ex.default)(i)){let n=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=(0,Wp.default)(t,n,(o,u)=>Ix(a)?o:Ix(u)?a:(0,wx.default)(a,parseInt(u,10),"0"))}return t},Px=(s,e)=>{var w,P,C,L,R,Q,U,A,F,k,x,$,oe,Ce,se,K,ye,Te,Ie,Ve,Tt,At,qt,Xt,Ai,bs,gs,Ss,vs,ys,Ts,Is,xs,Es,ws,As,Ps,ks,Rs,Ms,Ls,Bs,$s,Ds,Cs,Vs,Os,_s,Fs,Ns,Us,qs,js,Hs,zs,Qs,Gs,Ws,Ys,Ks,Xs;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(ce=>{var _,je;return(je=(_=ce.textContent)==null?void 0:_.trim())!=null?je:""}),o=(w=(0,Ax.default)(n,0))!=null?w:"",u=a.getAttribute("type")==="dynamic",l=a.getAttribute("availabilityStartTime"),d=a.getAttribute("publishTime"),c=a.getElementsByTagName("vk:Attrs")[0],h=c==null?void 0:c.getElementsByTagName("vk:XLatestSegmentPublishTime")[0].textContent,p=c==null?void 0:c.getElementsByTagName("vk:XStreamIsLive")[0].textContent,f=c==null?void 0:c.getElementsByTagName("vk:XStreamIsUnpublished")[0].textContent,m=c==null?void 0:c.getElementsByTagName("vk:XPlaybackDuration")[0].textContent,g;u&&(g={availabilityStartTime:l?new Date(l).getTime():0,publishTime:d?new Date(d).getTime():0,latestSegmentPublishTime:h?new Date(h).getTime():0,streamIsAlive:p==="yes",streamIsUnpublished:f==="yes"});let S,v=a.getAttribute("mediaPresentationDuration"),y=[...a.getElementsByTagName("Period")],I=y.reduce((ce,_)=>({...ce,[_.id]:_.children}),{}),T=y.reduce((ce,_)=>({...ce,[_.id]:_.getAttribute("duration")}),{});v?S=xx(v):(0,Yp.default)(T).filter(ce=>ce).length&&!u?S=(0,Yp.default)(T).reduce((ce,_)=>{var je;return ce+((je=xx(_))!=null?je:0)},0):m&&(S=parseInt(m,10));let E=0,O=(C=(P=a.getAttribute("profiles"))==null?void 0:P.split(","))!=null?C:[];for(let ce of y.map(_=>_.id))for(let _ of I[ce]){let je=(L=_.getAttribute("id"))!=null?L:"id"+(E++).toString(10),Pt=(R=_.getAttribute("mimeType"))!=null?R:"",ji=(Q=_.getAttribute("codecs"))!=null?Q:"",Hi=(U=_.getAttribute("contentType"))!=null?U:Pt==null?void 0:Pt.split("/")[0],kl=(F=(A=_.getAttribute("profiles"))==null?void 0:A.split(","))!=null?F:[],Js=(x=mx((k=_.getAttribute("lang"))!=null?k:""))!=null?x:{},Jt=(Ce=(oe=($=_.querySelector("Label"))==null?void 0:$.textContent)==null?void 0:oe.trim())!=null?Ce:void 0,Rl=_.querySelectorAll("Representation"),Ml=_.querySelector("SegmentTemplate"),Ll=(K=(se=_.querySelector("Role"))==null?void 0:se.getAttribute("value"))!=null?K:void 0,ut=Hi,H={id:je,language:Js.language,isDefault:Ll==="main",label:Jt,codecs:ji,hdr:ut==="video"&&Zr(ji),mime:Pt,representations:[]};for(let V of Rl){let we=(ye=V.getAttribute("lang"))!=null?ye:void 0,kt=(Ie=(Te=Jt!=null?Jt:_.getAttribute("label"))!=null?Te:V.getAttribute("label"))!=null?Ie:void 0,Zt=(At=(Tt=(Ve=V.querySelector("BaseURL"))==null?void 0:Ve.textContent)==null?void 0:Tt.trim())!=null?At:"",He=new URL(Zt||o,e).toString(),Ae=(qt=V.getAttribute("mimeType"))!=null?qt:Pt,ei=(Ai=(Xt=V.getAttribute("codecs"))!=null?Xt:ji)!=null?Ai:"",ti;if(Hi==="text"){let Pe=V.getAttribute("id")||"",ii=((bs=Js.privateuse)==null?void 0:bs.includes("x-auto"))||Pe.includes("_auto"),ze=V.querySelector("SegmentTemplate");if(ze){let Rt={representationId:(gs=V.getAttribute("id"))!=null?gs:void 0,bandwidth:(Ss=V.getAttribute("bandwidth"))!=null?Ss:void 0},ri=parseInt((vs=V.getAttribute("bandwidth"))!=null?vs:"",10)/1e3,si=(Ts=parseInt((ys=ze.getAttribute("startNumber"))!=null?ys:"",10))!=null?Ts:1,lt=parseInt((Is=ze.getAttribute("timescale"))!=null?Is:"",10),zi=(xs=ze.querySelectorAll("SegmentTimeline S"))!=null?xs:[],ct=ze.getAttribute("media");if(!ct)continue;let ai=[],ni=0,oi="",dt=0,Mt=si,ee=0;for(let de of zi){let Qe=parseInt((Es=de.getAttribute("d"))!=null?Es:"",10),ne=parseInt((ws=de.getAttribute("r"))!=null?ws:"",10)||0,ke=parseInt((As=de.getAttribute("t"))!=null?As:"",10);ee=Number.isFinite(ke)?ke:ee;let Ge=Qe/lt*1e3,Re=ee/lt*1e3;for(let me=0;me<ne+1;me++){let Me=xi(ct,{...Rt,segmentNumber:Mt.toString(10),segmentTime:(ee+me*Qe).toString(10)}),pt=(Re!=null?Re:0)+me*Ge,Bt=pt+Ge;Mt++,ai.push({time:{from:pt,to:Bt},url:Me})}ee+=(ne+1)*Qe,ni+=(ne+1)*Ge}dt=ee/lt*1e3,oi=xi(ct,{...Rt,segmentNumber:Mt.toString(10),segmentTime:ee.toString(10)});let Lt={time:{from:dt,to:1/0},url:oi},xe={type:"template",baseUrl:He,segmentTemplateUrl:ct,initUrl:"",totalSegmentsDurationMs:ni,segments:ai,nextSegmentBeyondManifest:Lt,timescale:lt};ti={id:Pe,kind:"text",segmentReference:xe,profiles:[],duration:S,bitrate:ri,mime:"",codecs:"",width:0,height:0,isAuto:ii}}else ti={id:Pe,isAuto:ii,kind:"text",url:He}}else{let Pe=(ks=(Ps=V.getAttribute("contentType"))!=null?Ps:Ae==null?void 0:Ae.split("/")[0])!=null?ks:Hi,ii=(Ms=(Rs=_.getAttribute("profiles"))==null?void 0:Rs.split(","))!=null?Ms:[],ze=parseInt((Ls=V.getAttribute("width"))!=null?Ls:"",10),Rt=parseInt((Bs=V.getAttribute("height"))!=null?Bs:"",10),ri=parseInt(($s=V.getAttribute("bandwidth"))!=null?$s:"",10)/1e3,si=(Ds=V.getAttribute("frameRate"))!=null?Ds:"",lt=(Cs=V.getAttribute("quality"))!=null?Cs:void 0,zi=si?Lu(si):void 0,ct=(Vs=V.getAttribute("id"))!=null?Vs:"id"+(E++).toString(10),ai=Pe==="video"?`${Rt}p`:Pe==="audio"?`${ri}Kbps`:ei,ni=`${ct}@${ai}`,oi=[...O,...kl,...ii],dt,Mt=V.querySelector("SegmentBase"),ee=(Os=V.querySelector("SegmentTemplate"))!=null?Os:Ml;if(Mt){let xe=(Fs=(_s=V.querySelector("SegmentBase Initialization"))==null?void 0:_s.getAttribute("range"))!=null?Fs:"",[de,Qe]=xe.split("-").map(Me=>parseInt(Me,10)),ne={from:de,to:Qe},ke=(Ns=V.querySelector("SegmentBase"))==null?void 0:Ns.getAttribute("indexRange"),[Ge,Re]=ke?ke.split("-").map(Me=>parseInt(Me,10)):[],me=ke?{from:Ge,to:Re}:void 0;dt={type:"byteRange",url:He,initRange:ne,indexRange:me}}else if(ee){let xe={representationId:(Us=V.getAttribute("id"))!=null?Us:void 0,bandwidth:(qs=V.getAttribute("bandwidth"))!=null?qs:void 0},de=parseInt((js=ee.getAttribute("timescale"))!=null?js:"",10),Qe=(Hs=ee.getAttribute("initialization"))!=null?Hs:"",ne=ee.getAttribute("media"),ke=(Qs=parseInt((zs=ee.getAttribute("startNumber"))!=null?zs:"",10))!=null?Qs:1,Ge=xi(Qe,xe);if(!ne)throw new ReferenceError("No media attribute in SegmentTemplate");let Re=(Gs=ee.querySelectorAll("SegmentTimeline S"))!=null?Gs:[],me=[],Me=0,pt="",Bt=0;if(Re.length){let ui=ke,pe=0;for(let ht of Re){let be=parseInt((Ws=ht.getAttribute("d"))!=null?Ws:"",10),We=parseInt((Ys=ht.getAttribute("r"))!=null?Ys:"",10)||0,li=parseInt((Ks=ht.getAttribute("t"))!=null?Ks:"",10);pe=Number.isFinite(li)?li:pe;let Qi=be/de*1e3,Gi=pe/de*1e3;for(let ci=0;ci<We+1;ci++){let $l=xi(ne,{...xe,segmentNumber:ui.toString(10),segmentTime:(pe+ci*be).toString(10)}),Zs=(Gi!=null?Gi:0)+ci*Qi,Dl=Zs+Qi;ui++,me.push({time:{from:Zs,to:Dl},url:$l})}pe+=(We+1)*be,Me+=(We+1)*Qi}Bt=pe/de*1e3,pt=xi(ne,{...xe,segmentNumber:ui.toString(10),segmentTime:pe.toString(10)})}else if(iV(S)){let pe=parseInt((Xs=ee.getAttribute("duration"))!=null?Xs:"",10)/de*1e3,ht=Math.ceil(S/pe),be=0;for(let We=1;We<ht;We++){let li=xi(ne,{...xe,segmentNumber:We.toString(10),segmentTime:be.toString(10)});me.push({time:{from:be,to:be+pe},url:li}),be+=pe}Bt=be,pt=xi(ne,{...xe,segmentNumber:ht.toString(10),segmentTime:be.toString(10)})}let Bl={time:{from:Bt,to:1/0},url:pt};dt={type:"template",baseUrl:He,segmentTemplateUrl:ne,initUrl:Ge,totalSegmentsDurationMs:Me,segments:me,nextSegmentBeyondManifest:Bl,timescale:de}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Pe||!Ae)continue;let Lt={video:"video",audio:"audio",text:"text"}[Pe];if(!Lt)continue;ut||(ut=Lt),ti={id:ni,kind:Lt,segmentReference:dt,profiles:oi,duration:S,bitrate:ri,mime:Ae,codecs:ei,width:ze,height:Rt,fps:zi,quality:lt}}H.language||(H.language=we),H.label||(H.label=kt),H.mime||(H.mime=Ae),H.codecs||(H.codecs=ei),H.hdr||(H.hdr=ut==="video"&&Zr(ei)),H.representations.push(ti)}if(ut){let V=r[ut].find(we=>we.id===H.id);if(V&&H.representations.every(we=>Ze(we.segmentReference)))for(let we of V.representations){let kt=H.representations.find(Ae=>Ae.id===we.id),Zt=kt==null?void 0:kt.segmentReference,He=we.segmentReference;He.segments.push(...Zt.segments),He.nextSegmentBeyondManifest=Zt.nextSegmentBeyondManifest}else r[ut].push(H)}}return{duration:S,streams:r,baseUrls:n,live:g}};import{fromEvent as rV,Subscription as sV}from"@vkontakte/videoplayer-shared/es2018";var il=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 rl=class{constructor(e,t){this.lastUpdateTs=0;this.lastCallTs=0;this.prevRanges=[];this.subscription=new sV;this.mediaSource=e,this.sourceBuffer=t,this.subscription.add(rV(this.sourceBuffer,"updateend").subscribe(()=>this.updateend()))}updateend(){if(!q(this.mediaSource,this.sourceBuffer))return;let{prevRanges:e}=this,t=il(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 eo=class{constructor(e,t,i,{fetcher:r,tuning:a,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new Sr(0);this.currentLowLatencySegmentLength$=new Sr(0);this.currentSegmentLength$=new Sr(0);this.onLastSegment$=new Sr(!1);this.fullyBuffered$=new Sr(!1);this.playingRepresentation$=new Sr(void 0);this.playingRepresentationInit$=new Sr(void 0);this.error$=new nV;this.gaps=[];this.subscription=new oV;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new ae;this.switchAbortController=new ae;this.destroyAbortController=new ae;this.bufferLimit=1/0;this.failedDownloads=0;this.baseUrls=[];this.baseUrlsIndex=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.lastDataObtainedTimestampMs=0;this.loadByteRangeSegmentsTimeoutId=0;this.sourceBufferBufferedDiff=null;this.startWith=Fi(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);ot(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new ox(this.sourceBuffer),this.sourceBufferBufferedDiff=new rl(this.mediaSource,this.sourceBuffer),this.subscription.add(Xp(this.sourceBuffer,"updateend").subscribe(()=>{this.maintain()})),this.subscription.add(Xp(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:gr.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o||!q(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,Kr(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=$e(this.sourceBuffer.buffered,o),d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,n*2,l<d).catch(c=>{this.handleAsyncError(c,"pruneBuffer")})})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);let i=this.initData.get(t.id),r=this.segments.get(t.id),a=this.parsedInitData.get(t.id);ot(i,"No init buffer for starting representation"),ot(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=Fi(this.destroyAbortController.signal,async function*(e,t=!1){if(!q(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);ot(i,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if(qe(a)||qe(r)?yield this.loadInit(i,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),ot(r,"No segments for starting representation"),a=this.initData.get(e),!(!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer||!q(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();ls(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=Fi(this.destroyAbortController.signal,async function*(e,t=!1){if(!q(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);ot(i,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if(qe(a)||qe(r)?yield this.loadInit(i,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),ot(r,"No segments for starting representation"),a=this.initData.get(e),!(!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer||!q(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();ls(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=Fi(this.destroyAbortController.signal,async function*(e){var u,l;let t=(u=(0,nl.default)(e,d=>d.representations))!=null?u:[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let d of this.representations.keys()){let c=t.find(f=>f.id===d);c&&this.representations.set(d,c);let h=this.representations.get(d);if(!h||!Ze(h.segmentReference))return;let p=this.getActualLiveStartingSegments(h.segmentReference);this.segments.set(h.id,p)}let i=(l=this.switchingToRepresentationId)!=null?l:this.downloadingRepresentationId,r=this.representations.get(i);ot(r);let a=this.segments.get(i);ot(a,"No segments for starting representation");let n=this.initData.get(i);if(ot(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer))return;let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(a,r),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));var d;this.fetcher=r,this.tuning=a,this.compatibilityMode=u,this.forwardBufferTarget=a.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!(l!=null&&l.live),this.baseUrls=(d=l==null?void 0:l.baseUrls)!=null?d:[],this.initData=new Map(i.map(c=>[c.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(c=>[c.id,c])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchToWithPreviousAbort(e,t=!1){!q(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new ae,Fi(this.switchAbortController.signal,async function*(i,r=!1){this.switchingToRepresentationId=i;let a=this.representations.get(i);ot(a,`No such representation ${i}`);let n=this.segments.get(i),o=this.initData.get(i);if(qe(o)||qe(n)?yield this.loadInit(a,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(i),ot(n,"No segments for starting representation"),o=this.initData.get(i),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer||!q(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(o,this.downloadAbortController.signal),r)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=i,yield this.dropBuffer();else{let u=this.getCurrentPosition();ls(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(){!qe(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}async abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);return this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new ae,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(qe(e)||qe(this.downloadingRepresentationId)||qe(this.playingRepresentationId)||qe(this.sourceBuffer)||!q(this.mediaSource,this.sourceBuffer)||ls(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(ot(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;let r=i.find(d=>e>=d.time.from&&e<d.time.to);ls(r)&&isFinite(r.time.from)&&isFinite(r.time.to)&&this.currentSegmentLength$.next((r==null?void 0:r.time.to)-r.time.from);let a=e,n=100;if(this.playingRepresentationId!==this.downloadingRepresentationId){let d=$e(this.sourceBuffer.buffered,e),c=r?r.time.to+n:-1/0;r&&r.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&d>=r.time.to-e+n&&(a=c)}if(isFinite(this.bufferLimit)&&Kr(this.sourceBuffer.buffered)>=this.bufferLimit){let d=$e(this.sourceBuffer.buffered,e),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,d<c).catch(h=>{this.handleAsyncError(h,"pruneBuffer")});return}let u=null;if(!this.activeSegments.size&&(u=this.selectForwardBufferSegments(i,t.segmentReference.type,a),u!=null&&u.length)){let d="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if((0,al.default)(u,r))d="high";else{let c=(0,cs.default)(u,0);c&&c.time.from-r.time.to>=this.forwardBufferTarget/2&&(d="low")}this.loadSegments(u,t,d).catch(c=>{this.handleAsyncError(c,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&r&&r.status==="fed"&&!(u!=null&&u.length)&&$e(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let l=(0,cs.default)(i,-1);!this.isLive&&l&&(this.fullyBuffered$.next(l.time.to-e-$e(this.sourceBuffer.buffered,e)<n),this.onLastSegment$.next(e-l.time.from>0))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let i=0,r=this.isLive?this.liveInitialAdditionalOffset:0;for(let a of e)Math.trunc(a.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:a.time.from+r,persistent:!0}),i=a.time.to;ls(t.duration)&&t.duration-i>0&&!this.isLive&&this.gaps.push({representation:t.id,from:i,to:t.duration,persistent:!0})}getActualLiveStartingSegments(e){let t=e.segments,i=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,r=[],a=0,n=t.length-1;do r.unshift(t[n]),a+=t[n].time.to-t[n].time.from,n--;while(a<i&&n>=0);return this.liveInitialAdditionalOffset=a-i,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){let t=(0,nl.default)(e==null?void 0:e.streams[this.kind],r=>r.representations).find(r=>r.id===this.downloadingRepresentationId);if(!t)return;let i=this.segments.get(t.id);if(i!=null&&i.length)return{from:i[0].time.from,to:i[i.length-1].time.to}}updateLive(e){var i,r,a,n;let t=(i=(0,nl.default)(e==null?void 0:e.streams[this.kind],o=>o.representations))!=null?i:[];if(![...this.segments.values()].every(o=>!o.length))for(let o of t){if(!o||!Ze(o.segmentReference))return;let u=o.segmentReference.segments.map(p=>({...p,status:"none",size:void 0})),l=100,d=(r=this.segments.get(o.id))!=null?r:[],c=(n=(a=(0,cs.default)(d,-1))==null?void 0:a.time.to)!=null?n:0,h=u==null?void 0:u.findIndex(p=>c>=p.time.from+l&&c<=p.time.to+l);if(h===-1){this.liveUpdateSegmentIndex=0;let p=this.getActualLiveStartingSegments(o.segmentReference);this.segments.set(o.id,p)}else{let p=u.slice(h+1);this.segments.set(o.id,[...d,...p])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;ot(e);let t=this.segments.get(e);if(t!=null&&t.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}updateLowLatencyLiveIfNeeded(e){let t=0;for(let i of this.representations.values()){let r=i.segmentReference;if(!Ze(r))return;let a=this.segments.get(i.id);if(!a)continue;let n=a.find(u=>Math.floor(u.time.from)===Math.floor(e.time.from));if(n&&!isFinite(n.time.to)&&(n.time.to=e.time.to,t=n.time.to-n.time.from),!!!a.find(u=>Math.floor(u.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let u=Math.round(e.time.to*r.timescale/1e3).toString(10),l=xi(r.segmentTemplateUrl,{segmentTime:u});a.push({status:"none",time:{from:e.time.to,to:1/0},url:l})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){var a,n,o;let t=(n=(a=this.switchingToRepresentationId)!=null?a:this.downloadingRepresentationId)!=null?n:this.playingRepresentationId;if(!t)return;let i=this.segments.get(t);if(!i)return;let r=i.find(u=>u.time.from<=e&&u.time.to>=e);return(o=r==null?void 0:r.time.from)!=null?o:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e,t;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)==null||e.destroy(),(t=this.sourceBufferBufferedDiff)==null||t.destroy(),this.gapDetectionIdleCallback&&Yt&&Yt(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&Yt&&Yt(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(i){if(!(i instanceof DOMException&&i.name==="NotFoundError"))throw i}this.sourceBuffer=null,this.downloadAbortController.abort(),this.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,i){return this.checkEjectedSegments(),this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){if(this.playingRepresentationId!==this.downloadingRepresentationId){let i=e.findIndex(r=>t>=r.time.from&&t<r.time.to);this.liveUpdateSegmentIndex=i}return this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):null}selectForwardBufferSegmentsRecord(e,t,i){let r=this.getForwardBufferDuration(i),a=e.findIndex(({status:h,time:{from:p,to:f}},m)=>{let g=p<=i&&f>=i,S=p>i||g||m===0&&i===0,v=Math.min(this.forwardBufferTarget,this.bufferLimit),y=this.preloadOnly&&p<=i+v||r<v&&f-p>=v||f<=i+v;return(h==="none"||h==="partially_ejected"&&S&&y&&this.sourceBuffer&&q(this.mediaSource,this.sourceBuffer)&&!(Ne(this.sourceBuffer.buffered,p)&&Ne(this.sourceBuffer.buffered,f)))&&S&&y});if(a===-1)return null;if(t!=="byteRange")return e.slice(a,a+1);let n=e,o=0,u=0,l=[],d=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,c=this.preloadOnly?this.forwardBufferTarget:0;for(let h=a;h<n.length&&(o<=d||u<=c);h++){let p=n[h];if(o+=p.byte.to+1-p.byte.from,u+=p.time.to+1-p.time.from,p.status==="none"||p.status==="partially_ejected")l.push(p);else break}return l}async loadSegments(e,t,i="auto"){Ze(t.segmentReference)?await this.loadTemplateSegment(e[0],t,i):await this.loadByteRangeSegments(e,t,i)}async loadTemplateSegment(e,t,i="auto"){e.status="downloading";let r={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(r);let{range:a,url:n,signal:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await Fi(o,async function*(){let d=Jp(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,d))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let d=await this.fetcher.fetch(n,{range:a,signal:o,onProgress:u,priority:i,isLowLatency:this.isActiveLowLatency()});if(this.lastDataObtainedTimestampMs=sl(),!d)return;let c=new DataView(d),h=Jn(t.mime);if(!isFinite(r.segment.time.to)){let m=t.segmentReference.timescale;r.segment.time.to=h.getChunkEndTime(c,m)}u&&r.feedingBytes&&l?await Promise.all(l):await this.sourceBufferTaskQueue.append(c,o);let{serverDataReceivedTimestamp:p,serverDataPreparedTime:f}=h.getServerLatencyTimestamps(c);p&&f&&this.currentLiveSegmentServerLatency$.next(f-p),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(d){this.abortActiveSegments([e]),Zn(d)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}updateRepresentationsBaseUrlIfNeeded(){if(!this.tuning.dash.enableBaseUrlSupport||!this.baseUrls.length||this.failedDownloads<=this.tuning.dash.maxSegmentRetryCount)return;this.baseUrlsIndex=(this.baseUrlsIndex+1)%this.baseUrls.length;let e=this.baseUrls[this.baseUrlsIndex];for(let t of this.representations.values())Ze(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}async loadByteRangeSegments(e,t,i="auto"){if(!e.length)return;for(let u of e)u.status="downloading",this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:r,url:a,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(await Fi(n,async function*(){let u=Jp(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),Xp(window,"online").pipe(aV()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(a,{range:r,onProgress:o,signal:n,priority:i}),this.lastDataObtainedTimestampMs=sl(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),Zn(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(Ze(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:(0,cs.default)(e,0).byte.from,to:(0,cs.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=sl(),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:gr.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!Ze(t.segmentReference))throw new Error("Representation is not template type");let i=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&i.searchParams.set("low-latency","yes");let r=i.toString(),{signal:a}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,d)=>{if(!a.aborted)try{this.lastDataObtainedTimestampMs=sl();let c=this.onSomeTemplateDataLoaded({dataView:l,loaded:d,signal:a,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(c)}catch(c){this.error$.next({id:"SegmentFeeding",category:gr.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,al.default)(e,t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:a}){if(!this.activeSegments.size||!q(this.mediaSource,this.sourceBuffer))return;let n=this.representations.get(t);if(n)for(let o of this.activeSegments){let{segment:u}=o;if(o.representationId===t){if(a.aborted){r();continue}if(o.loadedBytes=i,o.loadedBytes>o.feedingBytes){let l=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),d=Jn(n.mime).parseFeedableSegmentChunk(l,this.isLive);d!=null&&d.byteLength&&(u.status="partially_fed",o.feedingBytes+=d.byteLength,await this.sourceBufferTaskQueue.append(d),o.fedBytes+=d.byteLength)}}}}async onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:a,onSegmentAppendFailed:n}){if(!this.activeSegments.size||!q(this.mediaSource,this.sourceBuffer))return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){if(u.representationId!==t)continue;if(a.aborted){await n();continue}let{segment:l}=u,d=l.byte.from-i,c=l.byte.to-i,h=c-d+1,p=d<r,f=c<=r;if(p){if(l.status==="downloading"&&f){l.status="downloaded";let m=new DataView(e.buffer,e.byteOffset+d,h);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(h,r-d),u.loadedBytes>u.feedingBytes)){let m=new DataView(e.buffer,e.byteOffset+d+u.feedingBytes,u.loadedBytes-u.feedingBytes),g=u.loadedBytes===h?m:Jn(o.mime).parseFeedableSegmentChunk(m);g!=null&&g.byteLength&&(l.status="partially_fed",u.feedingBytes+=g.byteLength,await this.sourceBufferTaskQueue.append(g,a)&&!a.aborted?(u.fedBytes+=g.byteLength,u.fedBytes===h&&this.onSegmentFullyAppended(u,t)):await n())}}}}onSegmentFullyAppended(e,t){if(!(qe(this.sourceBuffer)||!q(this.mediaSource,this.sourceBuffer))){!this.isLive&&j.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(Ne(this.sourceBuffer.buffered,e.segment.time.from,100)&&Ne(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:gr.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",Gp(e.segment)&&(e.segment.size=e.fedBytes);for(let i of this.representations.values()){if(i.id===t)continue;let r=this.segments.get(i.id);if(r)for(let a of r)a.status==="fed"&&Math.round(a.time.from)===Math.round(e.segment.time.from)&&Math.round(a.time.to)===Math.round(e.segment.time.to)&&(a.status="none")}this.isActiveLowLatency()&&this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,e.segment)}}abortSegment(e){e.status==="partially_fed"?e.status="partially_ejected":e.status!=="partially_ejected"&&(e.status="none");for(let t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[r,a]of this.initData.entries()){let n=a instanceof Promise;t||(t=n),a===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let i=this.representations.get(e);i&&(this.initLoadIdleCallback=Yr(()=>(0,kx.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?Fi(this.destroyAbortController.signal,async function*(){let o=Jp(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,Jn(e.mime),r)).then(o=>{if(!o)return;let{init:u,dataView:l,segments:d}=o,c=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,c);let h=d;this.isLive&&Ze(e.segmentReference)&&(h=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,h),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:gr.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n}async dropBuffer(){for(let e of this.segments.values())for(let t of e)t.status="none";await this.pruneBuffer(0,1/0,!0)}async pruneBuffer(e,t,i=!1){if(!this.sourceBuffer||!q(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||qe(e))return!1;this.checkEjectedSegments();let r=[],a=0,n=o=>{var l;if(a>=t)return;r.push({...o.time});let u=Gp(o)?(l=o.size)!=null?l:0:o.byte.to-o.byte.from;a+=u};for(let o of this.segments.values())for(let u of o){let l=u.time.to<=e-this.tuning.dash.bufferPruningSafeZone,d=u.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(l||d)&&u.status==="fed"&&n(u)}for(let o=0;o<this.sourceBuffer.buffered.length;o++){let u=this.sourceBuffer.buffered.start(o)*1e3,l=this.sourceBuffer.buffered.end(o)*1e3,d=0;for(let c of this.segments.values())for(let h of c)(0,al.default)(["none","partially_ejected"],h.status)&&Math.round(h.time.from)<=Math.round(u)&&Math.round(h.time.to)>=Math.round(l)&&d++;if(d===this.segments.size){let c={time:{from:u,to:l},url:"",status:"none"};n(c)}}if(r.length&&i){let o=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let u of this.segments.values())for(let l of u)l.time.from>=e+o&&l.status==="fed"&&n(l)}return r.length?(r=yx(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||!q(this.mediaSource,this.sourceBuffer))return!1;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;return this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!q(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}getBufferedTo(){return!this.sourceBuffer||!q(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length?null:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}getForwardBufferDuration(e=this.getCurrentPosition()){return!this.sourceBuffer||!q(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||qe(e)?0:$e(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!this.sourceBuffer||!q(this.mediaSource,this.sourceBuffer))return;let{buffered:i}=this.sourceBuffer;this.tuning.useRefactoredSearchGap&&(this.gaps=this.gaps.filter(a=>{if(a.persistent)return!0;let n=Math.round(a.from),o=Math.round(a.to);for(let u=0;u<i.length;u++)if(n>=Math.round(i.start(u)*1e3)&&o<=Math.round(i.end(u)*1e3))return!1;return!0}));let r={representation:e,from:t.time.from,to:t.time.to,persistent:!1};for(let a=0;a<i.length;a++){let n=i.start(a)*1e3,o=i.end(a)*1e3;if(!(o<=t.time.from||n>=t.time.to)){if(n<=t.time.from&&o>=t.time.to){r=void 0;break}o>t.time.from&&o<t.time.to&&(r.from=o),n<t.time.to&&n>t.time.from&&(r.to=n)}}r&&r.to-r.from>1&&!this.gaps.some(a=>r&&a.from===r.from&&a.to===r.to)&&this.gaps.push(r)}detectGapsWhenIdle(e,t){if(!(this.gapDetectionIdleCallback||!this.sourceBuffer||!q(this.mediaSource,this.sourceBuffer))){if(!this.tuning.useRefactoredSearchGap)for(let i=0;i<this.sourceBuffer.buffered.length;i++)this.gaps=this.gaps.filter(r=>r.persistent||this.sourceBuffer&&(Math.round(r.from)<Math.round(this.sourceBuffer.buffered.start(i)*1e3)||Math.round(r.to)>Math.round(this.sourceBuffer.buffered.end(i)*1e3)));this.gapDetectionIdleCallback=Yr(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:gr.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if(qe(this.sourceBuffer)||!q(this.mediaSource,this.sourceBuffer)||qe(this.playingRepresentationId)||this.sourceBufferBufferedDiff&&!this.sourceBufferBufferedDiff.wasUpdated())return;let e=il(this.sourceBuffer.buffered),t=100;for(let i of this.segments.values())for(let r of i){let{status:a}=r;if(a!=="fed"&&a!=="partially_ejected")continue;let n=Math.floor(r.time.from),o=Math.ceil(r.time.to),u=!1,l=0;for(let d=0;d<e.length;d+=2){let c=e[d],h=e[d+1];u||(u=c-t<=n&&h+t>=o),(n>=c&&n<h-t||o>c+t&&o<=h)&&(l+=1)}u||(l===1?r.status="partially_ejected":this.gaps.some(d=>d.from===r.time.from||d.to===r.time.to)?r.status="partially_ejected":r.status="none")}}handleAsyncError(e,t){this.error$.next({id:t,category:gr.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}};import{abortable as to,assertNever as Rx,fromEvent as Mx,merge as uV,now as io,Subject as Lx,ValueSubject as Zp,flattenObject as ds,ErrorCategory as ro,SubscriptionRemovable as lV}from"@vkontakte/videoplayer-shared/es2018";var ul=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:a=!1}){this.lastConnectionType$=new Zp(void 0);this.lastConnectionReused$=new Zp(void 0);this.lastRequestFirstBytes$=new Zp(void 0);this.recoverableError$=new Lx;this.error$=new Lx;this.abortAllController=new ae;this.subscription=new lV;this.fetchManifest=to(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=Vi(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=Vu(i));let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(ol);return r?(t.log("success",ds({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(r.headers),r.text()):(t.error("error",ds({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=to(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:a="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1}={}){var L,R,Q;let l=e,d=new Headers,c=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{d.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let U=new URL(l,location.href);U.searchParams.append("bytes",`${i.from}-${i.to}`),l=U.toString();break}default:Rx(t)}this.requestQuic&&(l=Vi(l));let h=this.abortAllController.signal,p;if(n){let U=new ae;if(p=uV(Mx(this.abortAllController.signal,"abort"),Mx(n,"abort")).subscribe(()=>{try{U.abort()}catch(A){ol(A)}}),this.subscription.add(p),this.abortAllController.signal.aborted||n.aborted)try{U.abort()}catch(A){ol(A)}h=U.signal}let f=io();c.log("startRequest",ds({url:l,priority:a,rangeMethod:t,range:i,isLowLatency:u,requestStartedAt:f}));let m=yield this.doFetch(l,{priority:a,headers:d,signal:h}),g=io();if(!m)return c.error("error",{message:"No response in request"}),c.end(),this.unsubscribeAbortSubscription(p),null;if((L=this.throughputEstimator)==null||L.addRawRtt(g-f),!m.ok||!m.body){this.unsubscribeAbortSubscription(p);let U=`Fetch error ${m.status}: ${m.statusText}`;return c.error("error",{message:U}),c.end(),Promise.reject(new Error(`Fetch error ${m.status}: ${m.statusText}`))}if(this.onHeadersReceived(m.headers),!r&&!o){this.unsubscribeAbortSubscription(p);let U=io(),A={requestStartedAt:f,requestEndedAt:U,duration:U-f};return c.log("endRequest",ds(A)),c.end(),m.arrayBuffer()}let S=m.body;if(o){let U;[S,U]=m.body.tee(),(R=this.throughputEstimator)==null||R.trackStream(U,u)}let v=S.getReader(),y,I=parseInt((Q=m.headers.get("content-length"))!=null?Q:"",10);Number.isFinite(I)&&(y=I),!y&&i&&(y=i.to-i.from+1);let T=0,E=y?new Uint8Array(y):new Uint8Array(0),O=!1,B=U=>{this.unsubscribeAbortSubscription(p),O=!0,ol(U)},w=to(h,async function*({done:U,value:A}){if(T===0&&this.lastRequestFirstBytes$.next(io()-f),h.aborted){this.unsubscribeAbortSubscription(p);return}if(!U&&A){if(y)E.set(A,T),T+=A.byteLength;else{let F=new Uint8Array(E.length+A.length);F.set(E),F.set(A,E.length),E=F,T+=A.byteLength}r==null||r(new DataView(E.buffer),T),yield v==null?void 0:v.read().then(w,B)}}.bind(this));yield v==null?void 0:v.read().then(w,B),this.unsubscribeAbortSubscription(p);let P=io(),C={failed:O,requestStartedAt:f,requestEndedAt:P,duration:P-f};return O?(c.error("endRequest",ds(C)),c.end(),null):(c.log("endRequest",ds(C)),c.end(),E.buffer)}.bind(this));this.fetchByteRangeRepresentation=to(this.abortAllController.signal,async function*(e,t,i){var S;if(e.type!=="byteRange")return null;let{from:r,to:a}=e.initRange,n=r,o=a,u=!1,l,d;e.indexRange&&(l=e.indexRange.from,d=e.indexRange.to,u=a+1===l,u&&(n=Math.min(l,r),o=Math.max(d,a))),n=Math.min(n,0);let c=yield this.fetch(e.url,{range:{from:n,to:o},priority:i,measureThroughput:!1});if(!c)return null;let h=new DataView(c,r-n,a-n+1);if(!t.validateData(h))throw new Error("Invalid media file");let p=t.parseInit(h),f=(S=e.indexRange)!=null?S:t.getIndexRange(p);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 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,p,f);return{init:p,dataView:new DataView(c),segments:g}}.bind(this));this.fetchTemplateRepresentation=to(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}=Cu(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,t,i="auto"){var a,n;let{type:r}=e;switch(r){case"byteRange":return(a=await this.fetchByteRangeRepresentation(e,t,i))!=null?a:null;case"template":return(n=await this.fetchTemplateRepresentation(e,i))!=null?n:null;default:Rx(r)}}destroy(){this.abortAllController.abort(),this.tracer.end(),this.subscription.unsubscribe()}async doFetch(e,t){let i=await wt(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:ro.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:ro.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:ro.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:ro.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${a})`,category:ro.FATAL})}}unsubscribeAbortSubscription(e){e&&(e.unsubscribe(),this.subscription.remove(e))}},ol=s=>{if(!Zn(s))throw s};import{isNullable as cV,ValueSubject as dV}from"@vkontakte/videoplayer-shared/es2018";var so=class s{constructor(e,t){this.currentRepresentation$=new dV(null);this.maxRepresentations=4;this.representationsCursor=0;this.representations=[];this.currentSegment=null;this.getCurrentPosition=t.getCurrentPosition,this.processStreams(e)}updateLive(e){this.processStreams(e==null?void 0:e.streams.text)}seekLive(e){this.processStreams(e)}maintain(e=this.getCurrentPosition()){var t;if(!cV(e))for(let i of this.representations)for(let r of i){let a=r.segmentReference,n=a.segments.length,o=a.segments[0].time.from,u=a.segments[n-1].time.to;if(e<o||e>u)continue;let l=a.segments.find(d=>d.time.from<=e&&d.time.to>=e);!l||((t=this.currentSegment)==null?void 0:t.time.from)===l.time.from&&this.currentSegment.time.to===l.time.to||(this.currentSegment=l,this.currentRepresentation$.next({...r,label:"Live Text",language:"ru",isAuto:!0,url:new URL(l.url,a.baseUrl).toString()}))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e!=null?e:[]){let i=s.filterRepresentations(t.representations);if(i){this.representations[this.representationsCursor]=i,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!(e!=null&&e.some(t=>s.filterRepresentations(t.representations)))}static filterRepresentations(e){return e==null?void 0:e.filter(t=>t.kind==="text"&&"segmentReference"in t&&Ze(t.segmentReference))}};var bV=["progress","play","seeked","stalled","waiting"],gV=["timeupdate","progress","loadeddata","playing","seeked"];var dl=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new sh;this.representationSubscription=new sh;this.state$=new G("none");this.currentVideoRepresentation$=new fe(void 0);this.currentVideoRepresentationInit$=new fe(void 0);this.currentAudioRepresentation$=new fe(void 0);this.currentVideoSegmentLength$=new fe(0);this.currentAudioSegmentLength$=new fe(0);this.error$=new cl;this.lastConnectionType$=new fe(void 0);this.lastConnectionReused$=new fe(void 0);this.lastRequestFirstBytes$=new fe(void 0);this.currentLiveTextRepresentation$=new fe(null);this.isLive$=new fe(!1);this.isActiveLive$=new fe(!1);this.isLowLatency$=new fe(!1);this.liveDuration$=new fe(0);this.liveSeekableDuration$=new fe(0);this.liveAvailabilityStartTime$=new fe(0);this.liveStreamStatus$=new fe(void 0);this.bufferLength$=new fe(0);this.liveLatency$=new fe(void 0);this.liveLoadBufferLength$=new fe(0);this.livePositionFromPlayer$=new fe(0);this.currentStallDuration$=new fe(0);this.videoLastDataObtainedTimestamp$=new fe(0);this.fetcherRecoverableError$=new cl;this.fetcherError$=new cl;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new cl;this.gapWatchdogActive=!1;this.destroyController=new ae;this.initManifest=th(this.destroyController.signal,async function*(e,t,i){var r;this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=Se(t,i,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),(r=this.manifest)!=null&&r.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:Ut.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=th(this.destroyController.signal,async function*(){var n,o;this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(u=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:Ut.NETWORK,message:"Failed to load manifest",thrown:u})});if(!e)return null;let t=null;try{t=Px(e!=null?e:"",this.manifestUrlString)}catch(u){let l=(n=Mu(e))!=null?n:{id:"ManifestParsing",category:Ut.PARSER,message:"Failed to parse MPD manifest",thrown:u};this.error$.next(l)}if(!t)return null;let i=(u,l,d)=>{var c,h,p,f;return!!((h=(c=this.element)==null?void 0:c.canPlayType)!=null&&h.call(c,l)&&((f=(p=vt())==null?void 0:p.isTypeSupported)!=null&&f.call(p,`${l}; codecs="${d}"`))||u==="text")};if(t.live){this.isLive$.next(!!t.live);let{availabilityStartTime:u,latestSegmentPublishTime:l,streamIsUnpublished:d,streamIsAlive:c}=t.live,h=((o=t.duration)!=null?o:0)/1e3;this.liveSeekableDuration$.next(-1*h),this.liveDuration$.next((l-u)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let p="active";c||(p=d?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(p)}let r={text:t.streams.text,video:[],audio:[]};for(let u of["video","audio"]){let d=t.streams[u].filter(({mime:p,codecs:f})=>i(u,p,f)),c=new Set(d.map(({codecs:p})=>p)),h=zu(c);if(h&&(r[u]=d.filter(({codecs:p})=>p.startsWith(h))),u==="video"){let p=this.tuning.preferHDR,f=r.video.some(g=>g.hdr),m=r.video.some(g=>!g.hdr);j.display.isHDR&&p&&f?r.video=r.video.filter(g=>g.hdr):m&&(r.video=r.video.filter(g=>!g.hdr))}}let a={...t,streams:r};return this.tracer.log("updateManifestEnd",no(a)),a}.bind(this));this.initRepresentations=th(this.destroyController.signal,async function*(e,t,i){var h;this.tracer.log("initRepresentationsStart",no({initialVideo:e,initialAudio:t,sourceHls:i})),ps(this.manifest),ps(this.element),this.representationSubscription.unsubscribe(),this.representationSubscription=new sh,this.state$.startTransitionTo("representations_ready");let r=p=>{this.representationSubscription.add(Kt(p,"error").pipe(ll(f=>{var m;return!!((m=this.element)!=null&&m.played.length)})).subscribe(f=>{this.error$.next({id:"VideoSource",category:Ut.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:f})}))};this.source=this.tuning.useManagedMediaSource?nu():new MediaSource;let a=document.createElement("source");if(r(a),a.src=URL.createObjectURL(this.source),this.element.appendChild(a),this.tuning.useManagedMediaSource&&Ur())if(i){let p=document.createElement("source");r(p),p.type="application/x-mpegurl",p.src=i.url,this.element.appendChild(p)}else this.element.disableRemotePlayback=!0;this.isActiveLive$.next(this.isLive$.getValue());let n={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),manifest:this.manifest},o=this.manifest.streams.video.reduce((p,f)=>[...p,...f.representations],[]);if(this.videoBufferManager=new eo("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],oo(t)){let p=this.manifest.streams.audio.reduce((f,m)=>[...f,...m.representations],[]);this.audioBufferManager=new eo("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}so.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new so(this.manifest.streams.text,n)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$));let u=()=>{var p;(p=this.stallWatchdogSubscription)==null||p.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add(vr(...gV.map(p=>Kt(this.element,p))).pipe(fs(p=>this.element?$e(this.element.buffered,this.element.currentTime*1e3):0),ao(),mV(p=>{p>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add(vr(Kt(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe(ao()).subscribe(f=>this.liveStreamEndTimestamp=rh())),this.subscription.add(Kt(this.element,"pause").subscribe(()=>{this.livePauseWatchdogSubscription=ih(1e3).subscribe(f=>{let m=Mi(this.manifestUrlString,2);this.manifestUrlString=Se(this.manifestUrlString,m+1e3,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add(Kt(this.element,"play").subscribe(f=>{var m;return(m=this.livePauseWatchdogSubscription)==null?void 0:m.unsubscribe()})),this.representationSubscription.add(hs({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(fs(({isActiveLive:f,isLowLatency:m})=>f&&m),ao()).subscribe(f=>{this.isManualDecreasePlaybackInLive()||rs(this.element,1)})),this.representationSubscription.add(hs({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(ll(({bufferLength:f,isActiveLive:m,isLowLatency:g})=>m&&g&&!!f)).subscribe(({bufferLength:f})=>this.liveBuffer.next(f))),this.representationSubscription.add(this.videoBufferManager.currentLowLatencySegmentLength$.subscribe(f=>{if(!this.isActiveLive$.getValue()&&!this.isLowLatency$.getValue()&&!f)return;let m=this.liveSeekableDuration$.getValue()-f/1e3;this.liveSeekableDuration$.next(Math.max(m,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+f/1e3)})),this.representationSubscription.add(hs({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(ll(({isLive:f})=>f),ao((f,m)=>m.bufferLength<f.bufferLength),fs(({rtt:f,bufferLength:m,segmentServerLatency:g})=>{let S=Mi(this.manifestUrlString,2);return(f/2+m+g+S)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(hs({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:f,isActiveLive:m,isLowLatency:g})=>{if(!g||!m)return;let S=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,v=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,y=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,I=f-S;if(this.isManualDecreasePlaybackInLive())return;let T=1;Math.abs(I)>v&&(T=1+Math.sign(I)*y),rs(this.element,T)})),this.representationSubscription.add(this.bufferLength$.subscribe(f=>{var g,S;let m=0;if(f){let v=((S=(g=this.element)==null?void 0:g.currentTime)!=null?S:0)*1e3;m=Math.min(...this.bufferManagers.map(I=>{var T,E;return(E=(T=I.getLiveSegmentsToLoadState(this.manifest))==null?void 0:T.to)!=null?E:v}))-v}this.liveLoadBufferLength$.getValue()!==m&&this.liveLoadBufferLength$.next(m)}));let p=0;this.representationSubscription.add(hs({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(Dx(1e3)).subscribe(async({liveLoadBufferLength:f,bufferLength:m})=>{if(!this.element||this.isUpdatingLive)return;let g=this.element.playbackRate,S=Mi(this.manifestUrlString,2),v=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,y=Math.min(v,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*g),I=this.tuning.dashCmafLive.normalizedActualBufferOffset*g,T=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*g,E=isFinite(f)?f:m,O=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),B=v<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(B);let w="none";if(O?w="active_low_latency":this.isLowLatency$.getValue()&&B?(this.bufferManagers.forEach(P=>P.proceedLowLatencyLive()),w="active_low_latency"):S!==0&&E<y?w="live_forward_buffering":E<y+T&&(w="live_with_target_offset"),isFinite(f)&&(p=f>p?f:p),w==="live_forward_buffering"||w==="live_with_target_offset"){let P=p-(y+I),C=this.normolizeLiveOffset(Math.trunc(S+P/g)),L=Math.abs(C-S),R=0;!f||L<=this.tuning.dashCmafLive.offsetCalculationError?R=S:C>0&&L>this.tuning.dashCmafLive.offsetCalculationError&&(R=C),this.manifestUrlString=Se(this.manifestUrlString,R,2)}(w==="live_with_target_offset"||w==="live_forward_buffering")&&(p=0,await this.updateLive())},f=>{this.error$.next({id:"updateLive",category:Ut.VIDEO_PIPELINE,thrown:f,message:"Failed to update live with subscription"})}))}let l=vr(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe(fs(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),d=vr(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe(fs(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue()))),c=hs({allBuffersFull:l,someBufferEnded:d}).pipe(ao(),fs(({allBuffersFull:p,someBufferEnded:f})=>p&&f),ll(p=>p));if(this.representationSubscription.add(vr(this.forceEnded$,c).subscribe(()=>{var p;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(f=>!f.updating))try{(p=this.source)==null||p.endOfStream()}catch(f){this.error$.next({id:"EndOfStream",category:Ut.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:f})}})),this.representationSubscription.add(vr(...this.bufferManagers.map(p=>p.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.representationSubscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.representationSubscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.liveTextManager&&this.representationSubscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$)),this.source.readyState!=="open"){let p=this.tuning.dash.sourceOpenTimeout>=0;yield new Promise(f=>{var m;p&&(this.timeoutSourceOpenId=setTimeout(()=>{var g;if(((g=this.source)==null?void 0:g.readyState)==="open"){f();return}this.error$.next({id:"OpenOfStream",category:Ut.VIDEO_PIPELINE,message:"Failed to open MediaSource",thrown:new Error("Timeout reject when wait sourceopen event"),traceAsLog:!0})},this.tuning.dash.sourceOpenTimeout)),(m=this.source)==null||m.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),f()},{once:!0})})}if(!this.isLive$.getValue()){let p=[(h=this.manifest.duration)!=null?h:0,...(0,ah.default)((0,ah.default)([...this.manifest.streams.audio,...this.manifest.streams.video],f=>f.representations),f=>{let m=[];return f.duration&&m.push(f.duration),Ze(f.segmentReference)&&f.segmentReference.totalSegmentsDurationMs&&m.push(f.segmentReference.totalSegmentsDurationMs),m})];this.source.duration=Math.max(...p)/1e3}this.audioBufferManager&&oo(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")}.bind(this));this.tick=()=>{var t,i,r,a;if(!this.element||!this.videoBufferManager||((t=this.source)==null?void 0:t.readyState)!=="open")return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),(i=this.audioBufferManager)==null||i.maintain(e),(r=this.liveTextManager)==null||r.maintain(e),(this.videoBufferManager.gaps.length||(a=this.audioBufferManager)!=null&&a.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=ih(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),n=>{this.error$.next({id:"GapWatchdog",category:Ut.WTF,message:"Error handling gaps",thrown:n})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.fetcher=new ul({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.subscription.add(this.fetcher.recoverableError$.subscribe(this.fetcherRecoverableError$)),this.subscription.add(this.fetcher.error$.subscribe(this.fetcherError$)),this.liveBuffer=yi.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator}),this.initTracerSubscription()}async seekLive(e){var r,a,n;ps(this.element);let t=this.liveStreamStatus$.getValue()!=="active"?rh()-this.liveStreamEndTimestamp:0,i=this.normolizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=Se(this.manifestUrlString,i,2),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await((r=this.videoBufferManager)==null?void 0:r.seekLive(this.manifest.streams.video)),await((a=this.audioBufferManager)==null?void 0:a.seekLive(this.manifest.streams.audio)),(n=this.liveTextManager)==null||n.seekLive(this.manifest.streams.text))}initBuffer(){ps(this.element),this.state$.setState("running");let e=Kt(this.element,"timeupdate");this.tuning.dash.timeupdateEventTickThrottle&&(e=e.pipe(Dx(this.tuning.dash.timeupdateEventTickThrottle))),this.subscription.add(vr(...bV.map(t=>Kt(this.element,t)),Kt(window,"online"),e).subscribe(()=>this.tick(),t=>{this.error$.next({id:"DashVKPlayer",category:Ut.WTF,message:"Internal logic error",thrown:t})})),this.subscription.add(Kt(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(Kt(this.element,"waiting").subscribe(()=>{var i;this.element&&this.element.readyState===HTMLMediaElement.HAVE_CURRENT_DATA&&!this.element.seeking&&Ne(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let t=()=>{var f,m,g,S,v,y,I,T,E,O,B;if(!this.element||((f=this.source)==null?void 0:f.readyState)!=="open")return;let r=this.currentStallDuration$.getValue();r+=50,this.currentStallDuration$.next(r);let a={timeInWaiting:r},n=rh(),o=100,u=(g=(m=this.videoBufferManager)==null?void 0:m.lastDataObtainedTimestamp)!=null?g:0;this.videoLastDataObtainedTimestamp$.next(u);let l=(v=(S=this.audioBufferManager)==null?void 0:S.lastDataObtainedTimestamp)!=null?v:0,d=(I=(y=this.videoBufferManager)==null?void 0:y.getForwardBufferDuration())!=null?I:0,c=(E=(T=this.audioBufferManager)==null?void 0:T.getForwardBufferDuration())!=null?E:0,h=d<o&&n-u>this.tuning.dash.crashOnStallTWithoutDataTimeout,p=this.audioBufferManager&&c<o&&n-l>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((h||p)&&r>this.tuning.dash.crashOnStallTWithoutDataTimeout||r>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${r} ms`);if(this.isLive$.getValue()&&r%2e3===0){let w=this.normolizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(w).catch(P=>{this.error$.next({id:"stallIntervalCallback",category:Ut.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:P})}),a.liveLastOffset=w}else{let w=this.element.currentTime*1e3;(O=this.videoBufferManager)==null||O.maintain(w),(B=this.audioBufferManager)==null||B.maintain(w),a.position=w}this.tracer.log("stallIntervalCallback",no(a))};(i=this.stallWatchdogSubscription)==null||i.unsubscribe(),this.stallWatchdogSubscription=ih(50).subscribe(t,r=>{this.error$.next({id:"StallWatchdogCallback",category:Ut.NETWORK,message:"Can't restore DASH after stall.",thrown:r})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,i=!1){let r={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return this.tuning.useNewSwitchTo?this.currentStallDuration$.getValue()>0?r==null?void 0:r.switchToWithPreviousAbort(t,i):r==null?void 0:r.switchTo(t,i):r==null?void 0:r.switchToOld(t,i)}async seek(e,t){var r,a,n,o,u;ps(this.element),ps(this.videoBufferManager);let i;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?i=e:i=Math.max((r=this.videoBufferManager.findSegmentStartTime(e))!=null?r:e,(n=(a=this.audioBufferManager)==null?void 0:a.findSegmentStartTime(e))!=null?n:e),this.warmUpMediaSourceIfNeeded(i),Ne(this.element.buffered,i)||await Promise.all([this.videoBufferManager.abort(),(o=this.audioBufferManager)==null?void 0:o.abort()]),!($x(this.element)||$x(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),(u=this.audioBufferManager)==null||u.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",no({requestedPosition:e,forcePrecise:t,position:i})))}warmUpMediaSourceIfNeeded(e=(t=>(t=this.element)==null?void 0:t.currentTime)()){var i;oo(this.element)&&oo(this.source)&&oo(e)&&((i=this.source)==null?void 0:i.readyState)==="ended"&&this.element.duration*1e3-e>this.tuning.dash.seekBiasInTheEnd&&this.bufferManagers.forEach(r=>r.warmUpMediaSource())}get isStreamEnded(){var e;return((e=this.source)==null?void 0:e.readyState)==="ended"}stop(){var e,t,i;this.tracer.log("stop"),(e=this.element)==null||e.querySelectorAll("source").forEach(r=>{URL.revokeObjectURL(r.src),r.remove()}),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(t=this.videoBufferManager)==null||t.destroy(),this.videoBufferManager=null,(i=this.audioBufferManager)==null||i.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){var e;return(e=this.manifest)==null?void 0:e.streams}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){var e;this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),((e=this.source)==null?void 0:e.readyState)==="open"&&Array.from(this.source.sourceBuffers).every(t=>!t.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=fV(this.tracer.error.bind(this.tracer));this.subscription.add(this.error$.subscribe(e("error")))}isManualDecreasePlaybackInLive(){return!this.element||!this.isLive$.getValue()?!1:1-this.element.playbackRate>this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){var e,t;this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&((e=this.bufferManagers)==null||e.forEach(i=>i.updateLive(this.manifest)),(t=this.liveTextManager)==null||t.updateLive(this.manifest)),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getBufferedTo();if(e===null)return;let t=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),i=this.isJumpGapAfterSeekLive,r=this.element.currentTime;this.isJumpGapAfterSeekLive&&!t&&this.element.currentTime>e&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let a=this.element.currentTime*1e3,n=null,o=this.element.readyState===HTMLMediaElement.HAVE_METADATA?this.tuning.endGapTolerance:0;for(let u of this.bufferManagers)for(let l of u.gaps)(l.persistent||u.playingRepresentation$.getValue()===l.representation)&&l.from-o<=a&&l.to+o>a&&(this.element.duration*1e3-l.to<this.tuning.endGapTolerance?n=1/0:(n===null||l.to>n)&&(n=l.to));if(n!==null){let u=n+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,u===1/0?this.forceEnded$.next():(this.element.currentTime=u/1e3,this.tracer.log("jumpGap",no({isJumpGapAfterSeekLive:i,isActiveLowLatency:t,initialCurrentTime:r,jumpTo:u,resultCurrentTime:this.element.currentTime})))}}};import{combine as SV,map as vV,observeElementSize as yV,Subscription as TV,ValueSubject as nh,noop as IV}from"@vkontakte/videoplayer-shared/es2018";var pl=class{constructor(){this.subscription=new TV;this.pipSize$=new nh(void 0);this.videoSize$=new nh(void 0);this.elementSize$=new nh(void 0);this.pictureInPictureWindowRemoveEventListener=IV}connect({observableVideo:e,video:t}){let i=r=>{let a=r.target;this.pipSize$.next({width:a.width,height:a.height})};this.subscription.add(yV(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(SV({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(vV(({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 yr=class{constructor(e){this.subscription=new RV;this.videoState=new G("stopped");this.observableVideo=null;this.droppedFramesManager=new Gr;this.stallsManager=new Ju;this.elementSizeManager=new pl;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new $i;this.audioTrackSwitchHistory=new $i;this.selectedRepresentations={audio:null,video:null};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(r.state==="requested"&&(i==null?void 0:i.to)!=="paused"&&e!=="stopped"&&t!=="stopped"&&this.seek(r.position,r.forcePrecise),t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),M(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"),M(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="ready"&&M(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):t==="playing"&&this.video.paused?this.playIfAllowed():(i==null?void 0:i.to)==="playing"&&M(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&M(this.params.desiredState.playbackState,"paused");return;default:return EV(e)}}};this.init3DScene=e=>{var i,r,a;if(this.scene3D)return;this.scene3D=new os(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((i=e.projectionData)==null?void 0:i.pose.yaw)||0,y:((r=e.projectionData)==null?void 0:r.pose.pitch)||0,z:((a=e.projectionData)==null?void 0:a.pose.roll)||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSizeManager.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.textTracksManager=new xt(e.source.url),this.params=e,this.video=tt(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(Fe(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 dl({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params;kV(this.observableVideo)&&(this.observableVideo=st(this.video),this.subscription.add(()=>{var n;return(n=this.observableVideo)==null?void 0:n.destroy()}));let i=this.constructor.name,r=n=>{e.error$.next({id:i,category:Cx.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(oh(c=>!!c.length),Ox()).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(uh(c=>c.to.state!=="none"),hl());this.stallsManager.init({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$,videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,tuning:this.params.tuning.stallsManager,abrParams:this.params.tuning.autoTrackSelection,isBuffering$:i.isBuffering$,looped$:i.looped$,playing$:i.playing$}),a(i.ended$,e.endedEvent$),a(i.looped$,e.loopedEvent$),a(i.error$,e.error$),a(i.isBuffering$,e.isBuffering$),a(i.currentBuffer$,e.currentBuffer$),a(i.playing$,e.firstFrameEvent$),a(i.canplay$,e.canplay$),a(i.inPiP$,e.inPiP$),a(i.inFullscreen$,e.inFullscreen$),a(i.loadedMetadata$,e.loadedMetadataEvent$),a(this.player.error$,e.error$),a(this.player.fetcherRecoverableError$,e.fetcherRecoverableError$),a(this.player.fetcherError$,e.fetcherError$),a(this.player.lastConnectionType$,e.httpConnectionType$),a(this.player.lastConnectionReused$,e.httpConnectionReused$),a(this.player.isLive$,e.isLive$),a(this.player.lastRequestFirstBytes$.pipe(oh(Vx),Ox()),e.firstBytesEvent$),a(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),a(this.videoState.stateChangeEnded$.pipe(uh(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(zt(this.video,t.isLooped,r)),this.subscription.add(rt(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(It(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),a(Et(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),M(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),M(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:c})=>{if(c==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let h=this.player.getStreams();if(wV(h,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let f=[];for(let m of h.audio){f.push(zp(m));let g=[];for(let S of m.representations){let v=gx(S);g.push(v),this.audioTracksMap.set(v,{stream:m,representation:S})}this.audioStreamsMap.set(m,g)}this.params.output.availableAudioStreams$.next(f)}let p=[];for(let f of h.video){p.push(Qp(f));let m=[];for(let g of f.representations){let S=bx({...g,streamId:f.id});S&&(m.push(S),this.videoTracksMap.set(S,{stream:f,representation:g}))}this.videoStreamsMap.set(f,m)}this.params.output.availableVideoStreams$.next(p);for(let f of h.text)for(let m of f.representations){let g=Sx(f,m);this.textTracksMap.set(g,{stream:f,representation:m})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else c==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r));let{vktvAbrThrottle:o}=this.params.tuning.dash,u=o&&Tx(o)||null;this.subscription.add(fl(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$,PV(this.video,"progress")).pipe(oh(()=>this.videoTracksMap.size>0)).subscribe(async()=>{let c=this.player.state$.getState(),h=this.player.state$.getTransition();if(c!=="manifest_ready"&&c!=="running"||h||c==="running"&&u&&!u())return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState()),this.selectVideoAudioRepresentations();let{video:p,audio:f}=this.selectedRepresentations;if(!p)return;let m=br(this.videoTracksMap.keys(),S=>{var v;return((v=this.videoTracksMap.get(S))==null?void 0:v.representation.id)===p.id});Vx(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(p.id,f==null?void 0:f.id,this.params.sourceHls);else if(await this.player.switchRepresentation("video",p.id),f){let S=!!t.audioStream.getTransition();await this.player.switchRepresentation("audio",f.id,S)}},r)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:c})=>{this.scene3D&&c&&this.scene3D.pointCameraTo(c.x,c.y)})),this.subscription.add(this.elementSizeManager.subscribe(c=>{this.scene3D&&c&&this.scene3D.setViewportSize(c.width,c.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(hl()).subscribe(c=>{let h=br(this.videoTracksMap.entries(),([,{representation:g}])=>g.id===c);if(!h){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[p,{stream:f}]=h,m=this.params.desiredState.videoStream.getTransition();m&&m.to&&m.to.id===f.id&&this.params.desiredState.videoStream.setState(m.to),e.currentVideoTrack$.next(p),e.currentVideoStream$.next(Qp(f))},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(hl()).subscribe(c=>{let h=br(this.audioTracksMap.entries(),([,{representation:g}])=>g.id===c);if(!h){e.currentAudioStream$.next(void 0);return}let[p,{stream:f}]=h,m=this.params.desiredState.audioStream.getTransition();m&&m.to&&m.to.id===f.id&&this.params.desiredState.audioStream.setState(m.to),e.currentAudioStream$.next(zp(f))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(c=>{var h,p;if(c!=null&&c.is3dVideo&&((h=this.params.tuning.spherical)!=null&&h.enabled))try{this.init3DScene(c),e.is3DVideo$.next(!0)}catch(f){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${f}`})}else this.destroy3DScene(),(p=this.params.tuning.spherical)!=null&&p.enabled&&e.is3DVideo$.next(!1)},r)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,r)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,r)),this.textTracksManager.connect(this.video,t,e);let l=t.playbackState.stateChangeStarted$.pipe(uh(({to:c})=>c==="ready"),hl());this.subscription.add(fl(l,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,lh(["init"])).subscribe(()=>{let c=t.autoVideoTrackSwitching.getState(),p=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:c?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(p)})),this.subscription.add(fl(l,this.player.state$.stateChangeEnded$,lh(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let d=fl(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,lh(["init"])).pipe(AV(0));this.subscription.add(d.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){var B,w,P,C,L,R,Q,U,A,F,k,x;if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?Ma:Ra,t=this.params.tuning.useNewAutoSelectVideoTrack?xu:Iu,i=this.params.tuning.useNewAutoSelectVideoTrack?Wt:Tu,{desiredState:r,output:a}=this.params,n=r.autoVideoTrackSwitching.getState(),o=(B=r.videoTrack.getState())==null?void 0:B.id,u=br(this.videoTracksMap.keys(),$=>$.id===o),l=a.currentVideoTrack$.getValue(),d=((C=(P=r.videoStream.getState())!=null?P:u&&((w=this.videoTracksMap.get(u))==null?void 0:w.stream))!=null?C:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!d)return;let c=br(this.videoStreamsMap.keys(),$=>$.id===d.id),h=c&&this.videoStreamsMap.get(c);if(!h)return;let p=$e(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(p/Math.min(f,m||1/0),1),S=(L=r.audioStream.getState())!=null?L:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,v=(S==null?void 0:S.id)&&br(this.audioStreamsMap.keys(),$=>$.id===S.id)||this.audioStreamsMap.keys().next().value,y=0;if(v){if(u&&!n){let $=e(u,h,(R=this.audioStreamsMap.get(v))!=null?R:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);y=Math.max(y,(Q=$==null?void 0:$.bitrate)!=null?Q:-1/0)}if(l){let $=e(l,h,(U=this.audioStreamsMap.get(v))!=null?U:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);y=Math.max(y,(A=$==null?void 0:$.bitrate)!=null?A:-1/0)}}let I=u;(n||!I)&&(I=i(h,{container:this.elementSizeManager.getValue(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.stallsManager.abrTuningParams,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:y,forwardBufferHealth:g,current:l,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,stallsVideoMaxQualityLimit:this.stallsManager.videoMaxQualityLimit,stallsPredictedThroughput:this.stallsManager.predictedThroughput,abrLogger:this.params.dependencies.abrLogger}));let T=v&&t(I,h,(F=this.audioStreamsMap.get(v))!=null?F:[],{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}),E=(k=this.videoTracksMap.get(I))==null?void 0:k.representation,O=T&&((x=this.audioTracksMap.get(T))==null?void 0:x.representation);E&&O?(this.selectedRepresentations.video=E,this.selectedRepresentations.audio=O):E&&!O&&this.audioTracksMap.size===0&&(this.selectedRepresentations.video=E,this.selectedRepresentations.audio=null)}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){at(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),M(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Cx.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),it(this.video),this.tracer.end()}};var uo=class extends yr{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 ch,merge as _x,filter as Fx,filterChanged as MV,isNullable as dh,map as Nx,ValueSubject as ph,isNonNullable as LV}from"@vkontakte/videoplayer-shared/es2018";var lo=class extends yr{constructor(e){super(e),this.textTracksManager.destroy()}subscribe(){super.subscribe();let e=-1,{output:t,observableVideo:i,desiredState:r,connect:a}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),a(i.timeUpdate$,t.liveBufferTime$),a(this.player.liveSeekableDuration$,t.duration$),a(this.player.liveLatency$,t.liveLatency$);let n=new ph(1);a(i.playbackRateState$,n),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(r.isLowLatency.stateChangeEnded$.pipe(Nx(o=>o.to)).subscribe(this.player.isLowLatency$)).add(ch({liveBufferTime:t.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(Nx(({liveBufferTime:o,liveAvailabilityStartTime:u})=>o&&u?o+u:void 0)).subscribe(t.liveTime$)).add(this.player.liveStreamStatus$.pipe(Fx(o=>LV(o))).subscribe(o=>t.isLiveEnded$.next(o!=="active"&&t.position$.getValue()===0))).add(ch({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:_x(i.playbackRateState$,new ph(1))}).pipe(Fx(({liveStreamStatus:o,liveDuration:u})=>o==="active"&&!!u)).subscribe(({liveDuration:o,playbackRate:u})=>{let l=t.liveBufferTime$.getValue(),d=t.position$.getValue(),{playbackCatchupSpeedup:c}=this.params.tuning.dashCmafLive.lowLatency;d||u<1-c||this.video.paused||dh(l)||(e=o-l)})).add(ch({time:t.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:_x(i.playbackRateState$,new ph(1))}).pipe(MV((o,u)=>this.player.liveStreamStatus$.getValue()==="active"?o.liveDuration===u.liveDuration:o.time===u.time)).subscribe(({time:o,liveDuration:u,playbackRate:l})=>{let d=t.position$.getValue(),{playbackCatchupSpeedup:c}=this.params.tuning.dashCmafLive.lowLatency;if(!d&&!this.video.paused&&l>=1-c||dh(o)||dh(u))return;let h=-1*(u-o-e);t.position$.next(Math.min(h,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(o=>{if(o){let u=vx(o);this.params.output.availableTextTracks$.next([u])}}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=Math.trunc(t/1e3<=Math.abs(this.params.output.duration$.getValue())?t:0);this.player.seekLive(i).then(()=>{this.params.output.position$.next(e/1e3)})}};var Ux="X-Playback-Duration",hh=async s=>{var r;let e=await wt(s),t=await e.text(),i=(r=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t))==null?void 0:r[1];return i?parseInt(i,10):e.headers.has(Ux)?parseInt(e.headers.get(Ux),10):void 0};import{assertNever as qV,combine as jV,debounce as HV,ErrorCategory as gl,filter as zV,filterChanged as QV,isNonNullable as Hx,isNullable as Sl,map as zx,merge as GV,observableFrom as WV,Subscription as YV,ValueSubject as bh,VideoQuality as KV}from"@vkontakte/videoplayer-shared/es2018";var mh=N(qc(),1);import{videoSizeToQuality as BV,getExponentialDelay as $V}from"@vkontakte/videoplayer-shared/es2018";var DV=s=>{let e=null;if(s.QUALITY&&(e=Bi(s.QUALITY)),!e&&s.RESOLUTION){let[t,i]=s.RESOLUTION.split("x").map(r=>parseInt(r,10));e=BV({width:t,height:i})}return e!=null?e:null},CV=(s,e)=>{var a,n;let t=s.split(`
|
|
186
|
-
`),i=[],r=[];for(let o=0;o<t.length;o++){let u=t[o],l=u.match(/^#EXT-X-STREAM-INF:(.+)/),d=u.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!l&&!d)){if(l){let c=(0,mh.default)(l[1].split(",").map(v=>v.split("="))),h=(a=c.QUALITY)!=null?a:`stream-${c.BANDWIDTH}`,p=DV(c),f;c.BANDWIDTH&&(f=parseInt(c.BANDWIDTH,10)/1e3||void 0),!f&&c["AVERAGE-BANDWIDTH"]&&(f=parseInt(c["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let m=c["FRAME-RATE"]?parseFloat(c["FRAME-RATE"]):void 0,g;if(c.RESOLUTION){let[v,y]=c.RESOLUTION.split("x").map(I=>parseInt(I,10));v&&y&&(g={width:v,height:y})}let S=new URL(t[++o],e).toString();p&&i.push({id:h,quality:p,url:S,bandwidth:f,size:g,fps:m})}if(d){let c=(0,mh.default)(d[1].split(",").map(m=>{let g=m.indexOf("=");return[m.substring(0,g),m.substring(g+1)]}).map(([m,g])=>[m,g.replace(/^"|"$/g,"")])),h=(n=c.URI)==null?void 0:n.replace(/playlist$/,"subtitles.vtt"),p=c.LANGUAGE,f=c.NAME;h&&p&&r.push({type:"internal",id:p,label:f,language:p,url:h,isAuto:!1})}}}if(!i.length)throw new Error("Empty manifest");return{qualityManifests:i,textTracks:r}},VV=s=>new Promise(e=>{setTimeout(()=>{e()},s)}),fh=0,qx=async(s,e=s,t,i)=>{let a=await(await wt(s,i)).text();fh+=1;try{let{qualityManifests:n,textTracks:o}=CV(a,e);return{qualityManifests:n,textTracks:o}}catch(n){if(fh<=t.manifestRetryMaxCount)return await VV($V(fh-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),qx(s,e,t)}return{qualityManifests:[],textTracks:[]}},ml=qx;import{isNonNullable as OV,Subscription as _V,throttle as FV,ValueSubject as jx,Subject as NV,ErrorCategory as UV}from"@vkontakte/videoplayer-shared/es2018";var bl=class{constructor(e,t,i,r,a){this.subscription=new _V;this.abortControllers={destroy:new ae,nextManifest:null};this.prepareUrl=void 0;this.currentTextTrackData=null;this.availableTextTracks$=new jx(null);this.getCurrentTime$=new jx(null);this.error$=new NV;this.params={fetchManifestData:i,sourceUrl:r,downloadThreshold:a},this.subscription.add(e.pipe(FV(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 wt(r,{signal:this.abortControllers.destroy.signal})).text(),o=this.parsePlaylist(n,r);return{textTrack:i,playlist:o}}}parsePlaylist(e,t){let i={mediaSequence:0,programDateTime:"",segments:[],targetDuration:0,vkPlaybackDuration:0,segmentStartTime:0,vkStartTime:""},r=e.split(`
|
|
187
|
-
`),a=0;for(let n=0;n<r.length;++n){let o=r[n];switch(!0){case o.startsWith("#EXTINF:"):{let u=r[++n],l=new URL(u,t).toString(),d=Number(this.extractPlaylistRowValue("#EXTINF:",o))*1e3;if(i.segments.push({time:{from:a,to:a+d},url:l}),a=a+d,!i.segmentStartTime){let c=new Date(i.vkStartTime).valueOf(),h=new Date(i.programDateTime).valueOf();i.segmentStartTime=h-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(OV(e)&&this.currentTextTrackData){let{segments:t}=this.currentTextTrackData.playlist,{from:i}=t[0].time,{to:r}=t[t.length-1].time;if(e<i||e>r)return;r-e<this.params.downloadThreshold&&this.fetchNextManifestData();for(let n of t)if(n.time.from<=e&&n.time.to>=e){this.availableTextTracks$.next([{...this.currentTextTrackData.textTrack,url:n.url,isAuto:!0}]);break}}}async fetchNextManifestData(){try{if(this.abortControllers.nextManifest)return;this.abortControllers.nextManifest=new ae;let{textTracks:e}=await this.fetchManifestData(),t=await this.parseTextTracks(e,this.params.sourceUrl);this.currentTextTrackData&&t&&(this.currentTextTrackData.playlist.segments=t.playlist.segments)}catch(e){this.error("fetchNextManifestData",e)}finally{this.abortControllers.nextManifest=null}}async fetchManifestData(){var t;let e=(t=this.prepareUrl)!=null?t:this.params.sourceUrl;return await this.params.fetchManifestData(e,{signal:this.abortControllers.destroy.signal})}error(e,t){this.error$.next({id:"[LiveTextManager][HLS_LIVE_CMAF]",category:UV.WTF,thrown:t,message:e})}};var co=class{constructor(e){this.subscription=new YV;this.videoState=new G("stopped");this.textTracksManager=null;this.liveTextManager=null;this.manifests$=new bh([]);this.liveOffset=new or;this.manifestStartTime$=new bh(void 0);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),M(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(a||n||o){let d=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(d),this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((r==null?void 0:r.to)!=="paused"&&l.state==="requested"){this.videoState.startTransitionTo("ready"),this.seek(l.position&&l.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":i==="ready"?M(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),M(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&M(this.params.desiredState.playbackState,"playing");return;case"paused":if(i==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let d=this.liveOffset.getTotalOffset();d>=this.maxSeekBackTime$.getValue()&&(d=0,this.liveOffset.resetTo(d)),this.liveOffset.resume(),this.params.output.position$.next(-d/1e3),this.prepare()}else(r==null?void 0:r.to)==="paused"&&(M(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return qV(t)}};var i;this.params=e,this.video=tt(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:KV.INVARIANT,url:this.params.source.url};let t=(r,a)=>ml(r,this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},a);this.params.tuning.useHlsLiveNewTextManager?this.liveTextManager=new bl(this.params.output.liveTime$,this.video,t,this.params.source.url,this.params.tuning.hlsLiveNewTextManagerDownloadThreshold):this.textTracksManager=new xt(e.source.url),t(this.generateLiveUrl()).then(({qualityManifests:r,textTracks:a})=>{var n;r.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:gl.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),(n=this.liveTextManager)==null||n.processTextTracks(a,this.params.source.url),this.manifests$.next([this.masterManifest,...r])}).catch(r=>{this.params.output.error$.next({id:"ExtractHlsQualities",category:gl.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:r})}),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Fe(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new bh((i=e.source.maxSeekBackTime)!=null?i:1/0),this.subscribe()}selectManifest(){var u,l,d,c;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),a=(c=(d=(u=r==null?void 0:r.to)==null?void 0:u.id)!=null?d:(l=t.getState())==null?void 0:l.id)!=null?c:"master",n=this.manifests$.getValue();if(!n.length)return;let o=i?"master":a;return i&&!r&&t.startTransitionTo(this.masterManifest),n.find(h=>h.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsLiveProvider",category:gl.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},r=st(this.video);this.subscription.add(()=>r.destroy());let a=(o,u)=>this.subscription.add(o.subscribe(u,i));a(r.ended$,e.endedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.loadedMetadata$,e.loadedMetadataEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(rt(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(It(this.video,t.playbackRate,r.playbackRateState$,i)),a(Et(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"),M(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),M(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.liveTextManager&&this.subscription.add(this.liveTextManager.availableTextTracks$.subscribe(o=>{o&&this.params.output.availableTextTracks$.next(o)})),this.subscription.add(this.maxSeekBackTime$.pipe(QV(),zx(o=>-o/1e3)).subscribe(this.params.output.duration$,i)),this.subscription.add(r.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&Hx(l.to)){let c=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let h=this.manifests$.getValue().find(p=>p.id===c);h&&(this.params.output.currentVideoTrack$.next(h),this.params.output.hostname$.next(Fe(h.url)))}d&&this.params.desiredState.autoVideoTrackSwitching.setState(d.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o&&o.state==="requested"&&this.seek(o.position)},i)),this.subscription.add(r.loadedData$.subscribe(()=>{var u,l,d;let o=(d=(l=(u=this.video)==null?void 0:u.getStartDate)==null?void 0:l.call(u))==null?void 0:d.getTime();this.manifestStartTime$.next(o||void 0)},i)),this.subscription.add(jV({startTime:this.manifestStartTime$.pipe(zV(Hx)),currentTime:r.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),i)),this.subscription.add(this.manifests$.pipe(zx(o=>o.map(({id:u,quality:l,size:d,bandwidth:c,fps:h})=>({id:u,quality:l,size:d,fps:h,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,i));let n=GV(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,WV(["init"])).pipe(HV(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){var e,t;this.subscription.unsubscribe(),(e=this.textTracksManager)==null||e.destroy(),(t=this.liveTextManager)==null||t.destroy(),this.params.output.element$.next(void 0),it(this.video)}prepare(){var o,u,l;let e=this.selectManifest();if(Sl(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:d,min:c}=(u=(o=t==null?void 0:t.to)!=null?o:i)!=null?u:{};for(let[h,p]of[[d,"mq"],[c,"lq"]]){let f=String(parseFloat(h||""));p&&h&&r.searchParams.set(p,f)}}let a=this.params.format==="HLS_LIVE_CMAF"?2:0,n=Se(r.toString(),this.liveOffset.getTotalOffset(),a);(l=this.liveTextManager)==null||l.prepare(n),this.video.setAttribute("src",n),this.video.load(),hh(n).then(d=>{var c;if(!Sl(d))this.maxSeekBackTime$.next(d);else{let h=(c=this.params.source.maxSeekBackTime)!=null?c:this.maxSeekBackTime$.getValue();(Sl(h)||!isFinite(h))&&wt(n).then(p=>p.text()).then(p=>{var m;let f=(m=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(p))==null?void 0:m[1];if(f){let g=new URL(f,n).toString();hh(g).then(S=>{Sl(S)||this.maxSeekBackTime$.next(S)})}}).catch(()=>{})}})}playIfAllowed(){at(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),M(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:gl.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3),this.params.output.seekedEvent$.next()}generateLiveUrl(){let e=Se(this.params.source.url);if(this.params.tuning.useHlsLiveNewTextManager){let t=new URL(e);t.searchParams.set("enable-subtitles","yes"),e=t.toString()}return e}};import{assertNever as XV,debounce as JV,ErrorCategory as gh,fromEvent as Sh,isNonNullable as ZV,isNullable as eO,map as Qx,merge as Gx,observableFrom as Wx,Subscription as tO,ValueSubject as iO,VideoQuality as rO}from"@vkontakte/videoplayer-shared/es2018";var po=class{constructor(e){this.subscription=new tO;this.videoState=new G("stopped");this.manifests$=new iO([]);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),M(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(a||n||o){let d=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(d);let{currentTime:c}=this.video;this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:c*1e3,forcePrecise:!0});return}switch((r==null?void 0:r.to)!=="paused"&&l.state==="requested"&&this.seek(l.position),t){case"ready":i==="ready"?M(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),M(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&M(this.params.desiredState.playbackState,"playing");return;case"paused":i==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&M(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return XV(t)}};this.textTracksManager=new xt(e.source.url),this.params=e,this.video=tt(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:rO.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(Fe(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),ml(Se(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:t,textTracks:i})=>{this.manifests$.next([this.masterManifest,...t]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(i)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:gh.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){var u,l,d,c;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),a=(c=(d=(u=r==null?void 0:r.to)==null?void 0:u.id)!=null?d:(l=t.getState())==null?void 0:l.id)!=null?c:"master",n=this.manifests$.getValue();if(!n.length)return;let o=i?"master":a;return i&&(!r||!r.from)&&t.startTransitionTo(this.masterManifest),n.find(h=>h.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsProvider",category:gh.WTF,message:"HlsProvider internal logic error",thrown:o})},r=st(this.video);this.subscription.add(()=>r.destroy());let a=(o,u)=>this.subscription.add(o.subscribe(u));if(a(r.timeUpdate$,e.position$),a(r.durationChange$,e.duration$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.loadedMetadata$,e.loadedMetadataEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.seeked$,e.seekedEvent$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),a(this.videoState.stateChangeEnded$.pipe(Qx(o=>o.to)),this.params.output.playbackState$),this.subscription.add(zt(this.video,t.isLooped,i)),this.subscription.add(rt(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(It(this.video,t.playbackRate,r.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),M(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),M(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i).add(r.loadedMetadata$.subscribe(()=>{var p;let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&ZV(l.to)){let f=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let m=this.manifests$.getValue().find(g=>g.id===f);m&&(this.params.output.currentVideoTrack$.next(m),this.params.output.hostname$.next(Fe(m.url)))}let c=this.params.desiredState.playbackRate.getState(),h=(p=this.params.output.element$.getValue())==null?void 0:p.playbackRate;if(c!==h){let f=this.params.output.element$.getValue();f&&(this.params.desiredState.playbackRate.setState(c),f.playbackRate=c)}d&&this.params.desiredState.autoVideoTrackSwitching.setState(d.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o.state==="requested"&&this.seek(o.position)},i))),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(r.ended$.subscribe(()=>{this.videoState.setState("paused"),M(t.playbackState,"paused")})),this.subscription.add(this.manifests$.pipe(Qx(o=>o.map(({id:u,quality:l,size:d,bandwidth:c,fps:h})=>({id:u,quality:l,size:d,fps:h,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,i)),!j.device.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(Gx(Sh(o,"addtrack"),Sh(o,"removetrack"),Sh(o,"change"),Wx(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},i))}let n=Gx(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,Wx(["init"])).pipe(JV(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),it(this.video)}prepare(){var a,n;let e=this.selectManifest();if(eO(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:o,min:u}=(n=(a=t==null?void 0:t.to)!=null?a:i)!=null?n:{};for(let[l,d]of[[o,"mq"],[u,"lq"]]){let c=String(parseFloat(l||""));d&&l&&r.searchParams.set(d,c)}}this.video.setAttribute("src",r.toString()),this.video.load()}playIfAllowed(){at(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),M(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:gh.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var Xx=N(Ji(),1),vh=N(nr(),1),Jx=N(Ot(),1);import{assertNever as sO,assertNonNullable as Yx,debounce as aO,ErrorCategory as Kx,isHigherOrEqual as nO,isLowerOrEqual as oO,isNonNullable as uO,merge as lO,observableFrom as cO,Subscription as dO,map as pO}from"@vkontakte/videoplayer-shared/es2018";var ho=class{constructor(e){this.subscription=new dO;this.videoState=new G("stopped");this.trackUrls={};this.textTracksManager=new xt;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"),M(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let a=this.params.desiredState.autoVideoTrackLimits.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.seekState.getState();if(a&&e!=="ready"&&!n){this.handleQualityLimitTransition(a.to);return}if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(n){let{currentTime:u}=this.video;this.prepare(),o.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:u*1e3,forcePrecise:!0});return}switch((i==null?void 0:i.to)!=="paused"&&o.state==="requested"&&this.seek(o.position),e){case"ready":t==="ready"?M(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),M(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(i==null?void 0:i.to)==="playing"&&M(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&M(this.params.desiredState.playbackState,"paused");return;default:return sO(e)}};this.params=e,this.video=tt(e.container,e.tuning),this.params.output.element$.next(this.video),(0,Xx.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,vh.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:Kx.WTF,message:"MpegProvider internal logic error",thrown:o})},r=st(this.video);this.subscription.add(()=>r.destroy());let a=(o,u)=>this.subscription.add(o.subscribe(u,i));a(r.timeUpdate$,e.position$),a(r.durationChange$,e.duration$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.loadedMetadata$,e.loadedMetadataEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.seeked$,e.seekedEvent$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),a(this.videoState.stateChangeEnded$.pipe(pO(o=>o.to)),this.params.output.playbackState$),this.subscription.add(zt(this.video,t.isLooped,i)),this.subscription.add(rt(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(It(this.video,t.playbackRate,r.playbackRateState$,i)),a(Et(this.video),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),M(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),M(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var u,l;((u=this.videoState.getTransition())==null?void 0:u.to)==="ready"&&this.videoState.setState("ready");let o=this.params.desiredState.videoTrack.getTransition();if(o&&uO(o.to)){this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to.id].track);let d=this.params.desiredState.playbackRate.getState(),c=(l=this.params.output.element$.getValue())==null?void 0:l.playbackRate;if(d!==c){let h=this.params.output.element$.getValue();h&&(this.params.desiredState.playbackRate.setState(d),h.playbackRate=d)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(r.ended$.subscribe(()=>{this.videoState.setState("paused"),M(t.playbackState,"paused")})),this.textTracksManager.connect(this.video,t,e);let n=lO(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,cO(["init"])).pipe(aO(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),it(this.video)}prepare(){var i;let e=(i=this.params.desiredState.videoTrack.getState())==null?void 0:i.id;Yx(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];Yx(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=Vi(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(Fe(t))}playIfAllowed(){at(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),M(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Kx.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){var l,d;this.params.output.autoVideoTrackLimits$.next(e);let t=c=>{this.params.output.currentVideoTrack$.next(c),this.params.desiredState.videoTrack.startTransitionTo(c)},i=c=>{let h=Wt(n,{container:this.video.getBoundingClientRect(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,limits:c,abrLogger:this.params.dependencies.abrLogger});t(h)},r=(l=this.params.output.currentVideoTrack$.getValue())==null?void 0:l.quality,a=!!(e.max||e.min),n=(0,vh.default)(this.trackUrls).map(c=>c.track);if(!r||!a||qr(e,n[0].quality,(d=(0,Jx.default)(n,-1))==null?void 0:d.quality)){i();return}let o=e.max?oO(r,e.max):!0,u=e.min?nO(r,e.min):!0;o&&u||i(e)}};import{assertNever as eE,debounce as bO,merge as tE,observableFrom as gO,Subscription as SO,map as iE,ValueSubject as vO,ErrorCategory as Th,VideoQuality as yO}from"@vkontakte/videoplayer-shared/es2018";import{ErrorCategory as hO}from"@vkontakte/videoplayer-shared/es2018";var Zx=["stun:videostun.mycdn.me:80"],fO=1e3,mO=3,yh=()=>null,vl=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=yh;this.externalStopCallback=yh;this.externalErrorCallback=yh;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:Zx}]};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:hO.WTF,message:e.message})}async onPeerConnectionStream(e){let t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){let e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}async createOffer(){let e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");let t=await this.peerConnection.createOffer(e),i=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(i))throw new Error("No h264 codec support error");return t}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch(t){throw new Error("Can not parse socket message")}}closeConnections(){let e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),fO)}normalizeOptions(e={}){let t={stunServerList:Zx,maxRetryNumber:mO,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var fo=class{constructor(e){this.videoState=new G("stopped");this.maxSeekBackTime$=new vO(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"),M(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"),M(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(i==null?void 0:i.to)==="playing"&&M(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&M(this.params.desiredState.playbackState,"paused");return;default:return eE(e)}};this.subscription=new SO,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=tt(e.container,e.tuning),this.liveStreamClient=new vl(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),it(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,i=n=>{e.error$.next({id:"WebRTCLiveProvider",category:Th.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};this.subscription.add(tE(this.videoState.stateChangeStarted$.pipe(iE(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(iE(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})}));let r=st(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(Et(this.video),this.params.output.elementVisible$),this.subscription.add(r.durationChange$.subscribe(n=>{e.duration$.next(n===1/0?0:n)})).add(r.canplay$.subscribe(()=>{var n;((n=this.videoState.getTransition())==null?void 0:n.to)==="ready"&&this.videoState.setState("ready")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused")},i)).add(r.playing$.subscribe(()=>{this.videoState.setState("playing")},i)).add(r.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(rt(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 eE(n.to)}},i)).add(tE(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,gO(["init"])).pipe(bO(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(Fe(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:yO.INVARIANT}),this.video.srcObject=e,M(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:Th.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){at(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),M(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Th.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var mo=class{constructor(e){this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next()}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return!!this.current.done}};import{assertNever as go,assertNonNullable as Ni,ErrorCategory as yl,filter as uE,isNonNullable as lE,isNullable as PO,map as kO,merge as RO,once as MO,Subject as De,Subscription as cE,ValueSubject as W,flattenObject as Ih}from"@vkontakte/videoplayer-shared/es2018";import{Observable as TO,map as rE,Subscription as IO,Subject as xO}from"@vkontakte/videoplayer-shared/es2018";var sE=s=>new TO(e=>{let t=new IO,i=s.desiredPlaybackState$.stateChangeStarted$.pipe(rE(({from:l,to:d})=>`${l}-${d}`)),r=s.desiredPlaybackState$.stateChangeEnded$,a=s.providerChanged$.pipe(rE(({type:l})=>l!==void 0)),n=new xO,o=0,u="unknown";return t.add(i.subscribe(l=>{o&&window.clearTimeout(o),u=l,o=window.setTimeout(()=>n.next(l),s.maxTransitionInterval)})),t.add(r.subscribe(()=>{window.clearTimeout(o),u="unknown",o=0})),t.add(a.subscribe(l=>{o&&(window.clearTimeout(o),o=0,l&&(o=window.setTimeout(()=>n.next(u),s.maxTransitionInterval)))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});import{ErrorCategory as EO,Subscription as wO,combine as AO,filter as nE,once as oE}from"@vkontakte/videoplayer-shared/es2018";function aE(){return new(window.AudioContext||window.webkitAudioContext)}var bo=class bo{constructor(e,t,i,r){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=i;this.volumeMultiplier=r;this.destroyController=new ae;this.subscriptions=new wO;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe(nE(a=>!!a.type),oE()).subscribe(({type:a})=>this.subscribe(a)))}subscribe(e){j.browser.isSafari&&e!=="MPEG"||this.subscriptions.add(AO({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(nE(({playbackState:t,video:i,volume:{muted:r,volume:a}})=>t==="playing"&&!!i&&!r&&!!a),oE()).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=aE();this.audioContext=i;let r=i.createGain();if(this.gainNode=r,r.gain.value=t,r.connect(i.destination),i.state==="suspended"&&(await i.resume(),this.destroyController.signal.aborted))return!1;let a=i.createMediaElementSource(e);return this.mediaElementSource=a,a.connect(r),!0}cleanup(){this.mediaElementSource&&(this.mediaElementSource.disconnect(),this.mediaElementSource=null),this.gainNode&&(this.gainNode.disconnect(),this.gainNode=null),this.audioContext&&(this.audioContext.state!=="closed"&&this.audioContext.close(),this.audioContext=null)}destroy(){this.destroyController.abort(),this.subscriptions.unsubscribe(),this.cleanup()}handleError(e){var t;this.volumeMultiplierError$.next({id:bo.errorId,category:EO.VIDEO_PIPELINE,message:(t=e==null?void 0:e.message)!=null?t:`${bo.errorId} exception`,thrown:e})}};bo.errorId="VolumeMultiplierManager";var ms=bo;var LO={chunkDuration:5e3,maxParallelRequests:5},So=class{constructor(e){this.current$=new W({type:void 0});this.providerError$=new De;this.noAvailableProvidersError$=new De;this.volumeMultiplierError$=new De;this.providerOutput={position$:new W(0),duration$:new W(1/0),volume$:new W({muted:!1,volume:1}),availableVideoStreams$:new W([]),currentVideoStream$:new W(void 0),availableVideoTracks$:new W([]),currentVideoTrack$:new W(void 0),availableAudioStreams$:new W([]),currentAudioStream$:new W(void 0),availableAudioTracks$:new W([]),currentVideoSegmentLength$:new W(0),currentAudioSegmentLength$:new W(0),isAudioAvailable$:new W(!0),autoVideoTrackLimitingAvailable$:new W(!1),autoVideoTrackLimits$:new W(void 0),currentBuffer$:new W(void 0),isBuffering$:new W(!0),error$:new De,fetcherError$:new De,fetcherRecoverableError$:new De,warning$:new De,willSeekEvent$:new De,soundProhibitedEvent$:new De,seekedEvent$:new De,loopedEvent$:new De,endedEvent$:new De,firstBytesEvent$:new De,loadedMetadataEvent$:new De,firstFrameEvent$:new De,canplay$:new De,isLive$:new W(void 0),isLiveEnded$:new W(null),isLowLatency$:new W(!1),canChangePlaybackSpeed$:new W(!0),liveTime$:new W(void 0),liveBufferTime$:new W(void 0),liveLatency$:new W(void 0),severeStallOccurred$:new De,availableTextTracks$:new W([]),currentTextTrack$:new W(void 0),hostname$:new W(void 0),httpConnectionType$:new W(void 0),httpConnectionReused$:new W(void 0),inPiP$:new W(!1),inFullscreen$:new W(!1),element$:new W(void 0),elementVisible$:new W(!0),availableSources$:new W(void 0),is3DVideo$:new W(!1),playbackState$:new W(""),getCurrentTime$:new W(null)};this.subscription=new cE;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=UI([...jI(this.params.tuning),...qI(this.params.tuning)],this.params.tuning).filter(l=>lE(e.sources[l])),{forceFormat:i,formatsToAvoid:r}=this.params.tuning,a=[];i?a=[i]:r.length?a=[...t.filter(l=>!(0,xh.default)(r,l)),...t.filter(l=>(0,xh.default)(r,l))]:a=t,this.log({message:`Selected formats: ${a.join(" > ")}`}),this.tracer.log("Selected formats",Ih(a)),this.screenFormatsIterator=new mo(a);let n=[...xp(!0),...xp(!1)];this.chromecastFormatsIterator=new mo(n.filter(l=>lE(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:o=1,tuning:{useVolumeMultiplier:u}}=this.params;u&&o!==1&&ms.isSupported()&&(this.volumeMultiplierManager=new ms(this.providerOutput,this.current$,this.volumeMultiplierError$,o))}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()}))}destroy(){var e;this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe(),(e=this.volumeMultiplierManager)==null||e.destroy(),this.volumeMultiplierManager=null,this.tracer.end()}initProvider(){let e=this.chooseDestination(),t=this.chooseFormat(e);if(PO(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:yl.WTF,message:"Failed to create provider",thrown:r})}i?this.current$.next({type:t,provider:i,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.tracer.log("reinitProvider"),this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.tracer.log("switchToNextProvider",{destination:e}),this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}destroyProvider(){let e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"}),this.tracer.log("destroyProvider"),e.destroy();let t=this.providerOutput.position$.getValue()*1e3,i=this.params.desiredState.seekState.getState(),r=i.state!=="none";if(this.params.desiredState.seekState.setState({state:"requested",position:r?i.position:t,forcePrecise:r?i.forcePrecise:!1}),e.scene3D){let n=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:n.x,y:n.y})}let a=this.providerOutput.isBuffering$;a.getValue()||a.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),this.tracer.log("createProvider",{destination:e,format:t}),e){case"SCREEN":return this.createScreenProvider(t);case"CHROMECAST":return this.createChromecastProvider(t);default:return go(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 Ni(u),this.params.tuning.useNewDashProvider?new uo({...o,source:u,sourceHls:l}):new wn({...o,source:u,sourceHls:l})}case"DASH_LIVE_CMAF":{let u=this.applyFailoverHost(t[e]);return Ni(u),this.params.tuning.useNewDashProvider?new lo({...o,source:u}):new An({...o,source:u})}case"HLS":case"HLS_ONDEMAND":{let u=this.applyFailoverHost(t[e]);return Ni(u),new po({...o,source:u})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let u=this.applyFailoverHost(t[e]);return Ni(u),new co({...o,source:u,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let u=this.applyFailoverHost(t[e]);return Ni(u),new ho({...o,source:u})}case"DASH_LIVE":{let u=this.applyFailoverHost(t[e]);return Ni(u),new Uy({...o,source:u,config:{...LO,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let u=this.applyFailoverHost(t[e]);return Ni(u),new fo({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 go(e)}}createChromecastProvider(e){let{sources:t,container:i,desiredState:r,meta:a}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return Ni(o),new xa({connection:o,meta:a,container:i,source:t,format:e,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?"CHROMECAST":"SCREEN"}chooseFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case"CHROMECAST":return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return go(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return go(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 go(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,pE.default)((0,dE.default)(e).map(([r,a])=>[r,i(a)]))}initProviderErrorHandling(){let e=new cE,t=!1,i=0;return e.add(RO(this.providerOutput.error$.pipe(uE(r=>!this.params.tuning.ignoreAudioRendererError||!r.message||!/AUDIO_RENDERER_ERROR/ig.test(r.message))),sE({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(kO(r=>({id:`ProviderHangup:${r}`,category:yl.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(uE(({to:a})=>a==="playing"),MO()).subscribe(()=>t=!0);e.add(r)})),e.add(this.providerError$.subscribe(r=>{let a=this.current$.getValue().destination,n={error:r,currentDestination:a};if(a==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("SCREEN"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let o=r.category===yl.NETWORK,u=r.category===yl.FATAL,l=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),d=i<this.params.tuning.providerErrorLimit&&!u,c=l&&!u&&(o&&t||!d);n={...n,isNetworkError:o,isFatalError:u,haveFailoverHost:l,tryFailover:c,canReinitProvider:d},d?(i++,this.reinitProvider()):c?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):(i=0,this.switchToNextProvider(a!=null?a:"SCREEN"))}r.traceAsLog?this.tracer.log("providerInfo",Ih(n)):this.tracer.error("providerError",Ih(n))})),e}};import{fromEvent as Tl,once as BO,combine as $O,Subscription as hE,ValueSubject as Eh,map as DO,filter as CO,isNonNullable as Il,now as yt,safeStorage as wh}from"@vkontakte/videoplayer-shared/es2018";var VO=5e3,fE="one_video_throughput",mE="one_video_rtt",Ei=window.navigator.connection,bE=()=>{let s=Ei==null?void 0:Ei.downlink;if(Il(s)&&s!==10)return s*1e3},gE=()=>{let s=Ei==null?void 0:Ei.rtt;if(Il(s)&&s!==3e3)return s},SE=(s,e,t)=>{let i=t*8,r=i/s;return i/(r+e)},Ah=class s{constructor(e){this.subscription=new hE;this.concurrentDownloads=new Set;var r,a;this.tuningConfig=e;let t=s.load(fE)||(e.useBrowserEstimation?bE():void 0)||VO,i=(a=(r=s.load(mE))!=null?r:e.useBrowserEstimation?gE():void 0)!=null?a:0;if(this.throughput$=new Eh(t),this.rtt$=new Eh(i),this.rttAdjustedThroughput$=new Eh(SE(t,i,e.rttPenaltyRequestSize)),this.throughput=yi.getSmoothedValue(t,-1,e),this.rtt=yi.getSmoothedValue(i,1,e),e.useBrowserEstimation){let n=()=>{let u=bE();u&&this.throughput.next(u);let l=gE();Il(l)&&this.rtt.next(l)};Ei&&"onchange"in Ei&&this.subscription.add(Tl(Ei,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{wh.set(fE,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{wh.set(mE,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add($O({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(DO(({throughput:n,rtt:o})=>SE(n,o,e.rttPenaltyRequestSize)),CO(n=>{let o=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(n-o)/o>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,i=yt(),r=new hE;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add(Tl(e,"progress").pipe(BO()).subscribe(a=>{t=a.loaded,i=yt()}));break;case 1:case 0:r.add(Tl(e,"loadstart").subscribe(()=>{t=0,i=yt()}));break}r.add(Tl(e,"loadend").subscribe(a=>{if(e.status===200){let n=a.loaded,o=yt(),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=yt(),n=0,o=yt(),u=d=>{this.concurrentDownloads.delete(e),i.releaseLock(),e.cancel(`Throughput Estimator error: ${d}`).catch(()=>{})},l=async({done:d,value:c})=>{if(d)!t&&this.addRawSpeed(r,yt()-a,1),this.concurrentDownloads.delete(e);else if(c){if(t){let h=yt();if(h-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||h-a>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let f=o-a;f&&this.addRawSpeed(n,f,1,t),n=c.byteLength,a=yt()}else n+=c.byteLength;o=yt()}else r+=c.byteLength,n+=c.byteLength,n>=this.tuningConfig.streamMinSampleSize&&yt()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,yt()-o,this.concurrentDownloads.size),n=0,o=yt());await(i==null?void 0:i.read().then(l,u))}};this.concurrentDownloads.add(e),i==null||i.read().then(l,u)}addRawSpeed(e,t,i=1,r=!1){if(s.sanityCheck(e,t,r)){let a=e*8/t;this.throughput.next(a*i)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,i=!1){let r=e*8/t;return!(!r||!isFinite(r)||r>1e6||r<30||i&&e<1e4||!i&&e<10*1024||!i&&t<=20)}static load(e){var i;let t=wh.get(e);if(Il(t))return(i=parseInt(t,10))!=null?i:void 0}},vE=Ah;import{fillWithDefault as OO,VideoQuality as xl}from"@vkontakte/videoplayer-shared/es2018";var yE={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:xl.Q_4320P,activeVideoAreaThreshold:.1,highQualityLimit:xl.Q_720P,trafficSavingLimit:xl.Q_480P},stallsManager:{enabled:!1,stallDurationNoDataBeforeQualityDecrease:500,stallDurationToBeCount:100,stallCountBeforeQualityDecrease:3,resetQualityRestrictionTimeout:1e4,ignoreStallsOnSeek:!0,stallsMetricsHistoryLength:5,maxPossibleStallDuration:3e4,minTvtToBeCounted:5,maxTvtToBeCounted:10800,significantTvt:600,targetStallsDurationPerTvt:1,deviationStallsDurationPerTvt:.5,criticalStallsDurationPerTvt:6,abrAdjustingSpeed:.1,emaAlpha:.6,useTotalStallsDurationPerTvt:!0,useAverageStallsDurationPerTvt:!0,useEmaStallsDurationPerTvt:!0},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:xl.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,seekBiasInTheEnd:2e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,crashOnStallTimeout:25e3,crashOnStallTWithoutDataTimeout:5e3,enableSubSegmentBufferFeeding:!0,bufferEmptinessTolerance:100,useFetchPriorityHints:!0,enableBaseUrlSupport:!0,maxSegmentRetryCount:5,sourceOpenTimeout:1e3,vktvAbrThrottle:0,timeupdateEventTickThrottle:300},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,maxLiveDuration:7200,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:250,playbackCatchupSpeedup:.05,isActiveOnDefault:!1,bufferEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:"07A4434E",useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"dash",preferCMAF:!1,preferWebRTC:!1,preferMultiStream:!1,preferHDR:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,seekNearDurationBias:1,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useHlsJs:!1,useNativeHLSTextTracks:!1,useManagedMediaSource:!0,useNewSwitchTo:!1,useNewDashProvider:!1,useNewAutoSelectVideoTrack:!1,useSafariEndlessRequestBugfix:!0,useRefactoredSearchGap:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,audioVideoSyncRate:20,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50},useVolumeMultiplier:!1,ignoreAudioRendererError:!1,useEnableSubtitlesParam:!1,useOldMSEDetection:!1,useHlsLiveNewTextManager:!1,exposeInternalsToGlobal:!1,hlsLiveNewTextManagerDownloadThreshold:4e3,disableYandexPiP:!1,asyncResolveClientChecker:!1,autostartOnlyIfVisible:!1,changePlaybackStateToPausedWhenEnded:!1},TE=s=>{var e;return{...OO(s,yE),configName:[...(e=s.configName)!=null?e:[],...yE.configName]}};import{assertNonNullable as El,combine as wi,ErrorCategory as wl,filter as z,filterChanged as te,fromEvent as kh,isNonNullable as wE,isNullable as HO,Logger as zO,map as Z,mapTo as AE,merge as Ui,now as Al,once as Y,Subject as ie,Subscription as PE,tap as Rh,ValueSubject as D,isHigher as QO,isInvariantQuality as kE,flattenObject as qi,throttle as Mh,getTraceSubscriptionMethod as RE,TracerFactory as GO,InternalsExposure as WO}from"@vkontakte/videoplayer-shared/es2018";import{merge as _O,map as FO,filter as IE,isNonNullable as NO}from"@vkontakte/videoplayer-shared/es2018";var Ph=({seekState:s,position$:e})=>_O(s.stateChangeEnded$.pipe(FO(({to:t})=>{var i;return t.state==="none"?void 0:((i=t.position)!=null?i:NaN)/1e3}),IE(NO)),e.pipe(IE(()=>s.getState().state==="none")));import{assertNonNullable as UO}from"@vkontakte/videoplayer-shared/es2018";var xE=s=>{let e=typeof s.container=="string"?document.getElementById(s.container):s.container;return UO(e,`Wrong container or containerId {${s.container}}`),e};import{filter as qO,once as jO}from"@vkontakte/videoplayer-shared/es2018";var EE=(s,e,t,i)=>{s!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&(t==null?void 0:t.getValue().length)===0?t.pipe(qO(r=>r.length>0),jO()).subscribe(r=>{r.find(i)&&e.startTransitionTo(s)}):(s===void 0||t!=null&&t.getValue().find(i))&&e.startTransitionTo(s)};var Pl=class{constructor(e={configName:[]},t=GO.createRootTracer(!1)){this.subscription=new PE;this.logger=new zO;this.abrLogger=this.logger.createComponentLog("ABR");this.internalsExposure=null;this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new D(!1);this.hasLiveOffsetByPausedTimer=0;this.playerInitRequest=0;this.playerInited=new D(!1);this.wasSetStartedQuality=!1;this.desiredState={playbackState:new G("stopped"),seekState:new G({state:"none"}),volume:new G({volume:1,muted:!1}),videoTrack:new G(void 0),videoStream:new G(void 0),audioStream:new G(void 0),autoVideoTrackSwitching:new G(!0),autoVideoTrackLimits:new G({}),isLooped:new G(!1),isLowLatency:new G(!1),playbackRate:new G(1),externalTextTracks:new G([]),internalTextTracks:new G([]),currentTextTrack:new G(void 0),textTrackCuesSettings:new G({}),cameraOrientation:new G({x:0,y:0})};this.info={playbackState$:new D(void 0),position$:new D(0),duration$:new D(1/0),muted$:new D(!1),volume$:new D(1),availableVideoStreams$:new D([]),currentVideoStream$:new D(void 0),availableQualities$:new D([]),availableQualitiesFps$:new D({}),currentQuality$:new D(void 0),isAutoQualityEnabled$:new D(!0),autoQualityLimitingAvailable$:new D(!1),autoQualityLimits$:new D({}),predefinedQualityLimitType$:new D("unknown"),availableAudioStreams$:new D([]),currentAudioStream$:new D(void 0),availableAudioTracks$:new D([]),isAudioAvailable$:new D(!0),currentPlaybackRate$:new D(1),currentBuffer$:new D({start:0,end:0}),isBuffering$:new D(!0),isStalled$:new D(!1),isEnded$:new D(!1),isLooped$:new D(!1),isLive$:new D(void 0),isLiveEnded$:new D(null),canChangePlaybackSpeed$:new D(void 0),atLiveEdge$:new D(void 0),atLiveDurationEdge$:new D(void 0),liveTime$:new D(void 0),liveBufferTime$:new D(void 0),liveLatency$:new D(void 0),currentFormat$:new D(void 0),availableTextTracks$:new D([]),currentTextTrack$:new D(void 0),throughputEstimation$:new D(void 0),rttEstimation$:new D(void 0),videoBitrate$:new D(void 0),hostname$:new D(void 0),httpConnectionType$:new D(void 0),httpConnectionReused$:new D(void 0),surface$:new D("none"),chromecastState$:new D("NOT_AVAILABLE"),chromecastDeviceName$:new D(void 0),intrinsicVideoSize$:new D(void 0),availableSources$:new D(void 0),is3DVideo$:new D(!1),currentVideoSegmentLength$:new D(0),currentAudioSegmentLength$:new D(0)};this.events={inited$:new ie,ready$:new ie,started$:new ie,playing$:new ie,paused$:new ie,stopped$:new ie,willReady$:new ie,willStart$:new ie,willResume$:new ie,willPause$:new ie,willStop$:new ie,willDestruct$:new ie,watchCoverageRecord$:new ie,watchCoverageLive$:new ie,managedError$:new ie,fatalError$:new ie,fetcherRecoverableError$:new ie,ended$:new ie,looped$:new ie,seeked$:new ie,willSeek$:new ie,autoplaySoundProhibited$:new ie,firstBytes$:new ie,loadedMetadata$:new ie,firstFrame$:new ie,canplay$:new ie,log$:new ie,fetcherError$:new ie,severeStallOccured$:new ie};this.experimental={element$:new D(void 0),tuningConfigName$:new D([]),enableDebugTelemetry$:new D(!1),dumpTelemetry:hy,getCurrentTime$:new D(null)};if(this.initLogs(),this.tuning=TE(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new Ao({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new vE(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new WO("CORE"),this.internalsExposure.expose({player:this})),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(i,r,a)=>{let n=Reflect.get(i,r,a);return typeof n!="function"?n:(...o)=>{try{return n.apply(i,o)}catch(u){let l=o.map(h=>JSON.stringify(h,(p,f)=>{let m=typeof f;return(0,ME.default)(["number","string","boolean"],m)?f:f===null?null:`<${m}>`})),d=`Player.${String(r)}`,c=`Exception calling ${d} (${l.join(", ")})`;throw this.events.fatalError$.next({id:d,category:wl.WTF,message:c,thrown:u}),u}}}})}initVideo(e){var a;this.config=e,(a=this.internalsExposure)==null||a.expose({config:e,logger:this.logger,tuning:this.tuning}),this.setMuted(this.tuning.isAudioDisabled);let t=()=>{var u,l,d;let{container:n,...o}=e;this.tracer.log("initVideo",qi(o)),this.domContainer=xE(e),this.chromecastInitializer.contentId=(u=e.meta)==null?void 0:u.videoId,this.providerContainer=new So({sources:e.sources,meta:(l=e.meta)!=null?l:{},failoverHosts:(d=e.failoverHosts)!=null?d:[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,tracer:this.tracer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning,volumeMultiplier:e.volumeMultiplier,panelSize:e.panelSize}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.initTracerSubscription(),this.providerContainer.init(),this.setLiveLowLatency(this.tuning.dashCmafLive.lowLatency.isActiveOnDefault),this.initDebugTelemetry(),this.initWakeLock(),this.playerInited.next(!0)},i=()=>{this.tuning.autostartOnlyIfVisible&&window.requestAnimationFrame?this.playerInitRequest=window.requestAnimationFrame(()=>t()):t()},r=()=>{this.tuning.asyncResolveClientChecker?j.isInited$.pipe(z(n=>!!n),Y()).subscribe(()=>{console.log("Core SDK async start"),i()}):i()};return this.isNotActiveTabCase()?(this.tracer.log("request play from hidden tab"),kh(document,"visibilitychange").pipe(Y()).subscribe(r)):r(),this}destroy(){var e,t;this.tracer.log("destroy"),window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.playerInitRequest&&window.cancelAnimationFrame(this.playerInitRequest),this.events.willDestruct$.next(),this.stop(),(e=this.providerContainer)==null||e.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe(),this.tracer.end(),(t=this.internalsExposure)==null||t.destroy()}prepare(){return this.subscription.add(this.playerInited.pipe(z(e=>!!e),Y()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("prepare",{currentPlayBackState:e.getState()}),e.getState()==="stopped"&&e.startTransitionTo("ready")})),this}play(){return this.subscription.add(this.playerInited.pipe(z(e=>!!e),Y()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("play",{currentPlayBackState:e.getState()}),e.getState()!=="playing"&&e.startTransitionTo("playing")})),this}pause(){return this.subscription.add(this.playerInited.pipe(z(e=>!!e),Y()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("pause",{currentPlayBackState:e.getState()}),e.getState()!=="paused"&&e.startTransitionTo("paused")})),this}stop(){return this.subscription.add(this.playerInited.pipe(z(e=>!!e),Y()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("stop",{currentPlayBackState:e.getState()}),e.getState()!=="stopped"&&e.startTransitionTo("stopped")})),this}seekTime(e,t=!0){return this.subscription.add(this.playerInited.pipe(z(i=>!!i),Y()).subscribe(()=>{let i=this.info.duration$.getValue(),r=this.info.isLive$.getValue(),a=e;e>=i&&!r&&(a=i-this.tuning.seekNearDurationBias),this.tracer.log("seekTime",{duration:i,isLive:r,time:e,calculatedTime:a,forcePrecise:t}),Number.isFinite(a)&&(this.events.willSeek$.next({from:this.getExactTime(),to:a}),this.desiredState.seekState.setState({state:"requested",position:a*1e3,forcePrecise:t}))})),this}seekPercent(e){return this.subscription.add(this.playerInited.pipe(z(t=>!!t),Y()).subscribe(()=>{let t=this.info.duration$.getValue();this.tracer.log("seekPercent",{percent:e,duration:t}),isFinite(t)&&this.seekTime(Math.abs(t)*e,!1)})),this}setVolume(e,t){return this.subscription.add(this.playerInited.pipe(z(i=>!!i),Y()).subscribe(()=>{var o;let i=this.desiredState.volume,r=i.getTransition(),a=(o=r==null?void 0:r.to.muted)!=null?o:this.info.muted$.getValue(),n=t!=null?t:this.tuning.isAudioDisabled||a;this.tracer.log("setVolume",{volume:e,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:n}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setVolume(e):i.startTransitionTo({volume:e,muted:n})})),this}setMuted(e,t=!1){return this.subscription.add(this.playerInited.pipe(z(i=>!!i),Y()).subscribe(()=>{var o;let i=this.desiredState.volume,r=this.tuning.isAudioDisabled&&!t||e,a=i.getTransition(),n=(o=a==null?void 0:a.to.volume)!=null?o:this.info.volume$.getValue();this.tracer.log("setMuted",{isMuted:e,nextMuted:r,volume:n,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue()}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setMuted(r):i.startTransitionTo({volume:n,muted:r})})),this}setVideoStream(e){return this.subscription.add(this.playerInited.pipe(z(t=>!!t),Y()).subscribe(()=>{this.desiredState.videoStream.startTransitionTo(e)})),this}setAudioStream(e){return this.subscription.add(this.playerInited.pipe(z(t=>!!t),Y()).subscribe(()=>{this.desiredState.audioStream.startTransitionTo(e)})),this}setQuality(e){return this.subscription.add(this.playerInited.pipe(z(t=>!!t),Y()).subscribe(()=>{El(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(z(i=>i.length>0),Y()).subscribe(i=>{this.setVideoTrackIdByQuality(i,e)}):this.explicitInitialQuality=e:t.length>0&&this.setVideoTrackIdByQuality(t,e)})),this}setAutoQuality(e){return this.subscription.add(this.playerInited.pipe(z(t=>!!t),Y()).subscribe(()=>{this.tracer.log("setAutoQuality",{enable:e}),this.desiredState.autoVideoTrackSwitching.startTransitionTo(e)})),this}setAutoQualityLimits(e){return this.subscription.add(this.playerInited.pipe(z(t=>!!t),Y()).subscribe(()=>{this.tracer.log("setAutoQualityLimits",qi(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e)})),this}setPredefinedQualityLimits(e){return this.subscription.add(this.playerInited.pipe(z(t=>!!t),Y()).subscribe(()=>{if(this.info.predefinedQualityLimitType$.getValue()===e)return this;let{highQualityLimit:t,trafficSavingLimit:i}=this.tuning.autoTrackSelection,r;switch(e){case"high_quality":r={min:t,max:void 0};break;case"traffic_saving":r={max:i,min:void 0};break;default:r={max:void 0,min:void 0}}this.setAutoQualityLimits(r)})),this}setPlaybackRate(e){return this.subscription.add(this.playerInited.pipe(z(t=>!!t),Y()).subscribe(()=>{var i;El(this.providerContainer);let t=(i=this.providerContainer)==null?void 0:i.providerOutput.element$.getValue();this.tracer.log("setPlaybackRate",{playbackRate:e,isVideoElementAvailable:!!t}),t&&(this.desiredState.playbackRate.setState(e),t.playbackRate=e)})),this}setExternalTextTracks(e){return this.subscription.add(this.playerInited.pipe(z(t=>!!t),Y()).subscribe(()=>{e.length&&this.tracer.log("setExternalTextTracks",qi(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t})))})),this}selectTextTrack(e){return this.subscription.add(this.playerInited.pipe(z(t=>!!t),Y()).subscribe(()=>{var t;EE(e,this.desiredState.currentTextTrack,(t=this.providerContainer)==null?void 0:t.providerOutput.availableTextTracks$,i=>i.id===e),this.tracer.log("selectTextTrack",{textTrackId:e})})),this}setTextTrackCueSettings(e){return this.subscription.add(this.playerInited.pipe(z(t=>!!t),Y()).subscribe(()=>{this.tracer.log("setTextTrackCueSettings",{...e}),this.desiredState.textTrackCuesSettings.startTransitionTo(e)})),this}setLiveLowLatency(e){let t=this.info.isLive$.getValue(),i=this.desiredState.isLowLatency.getState();return!t||i===e?this:(this.tracer.log("live switch to low latency "+e),this.desiredState.isLowLatency.setState(e),this.seekTime(0))}setLooped(e){return this.subscription.add(this.playerInited.pipe(z(t=>!!t),Y()).subscribe(()=>{this.tracer.log("setLooped",{isLooped:e}),this.desiredState.isLooped.startTransitionTo(e)})),this}toggleChromecast(){this.tracer.log("toggleChromecast"),this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){return this.subscription.add(this.playerInited.pipe(z(i=>!!i),Y()).subscribe(()=>{let i=this.getScene3D();this.tracer.log("startCameraManualRotation",{isScene3DAvailable:!!i,mx:e,my:t}),i&&i.startCameraManualRotation(e,t)})),this}stopCameraManualRotation(e=!1){return this.subscription.add(this.playerInited.pipe(z(t=>!!t),Y()).subscribe(()=>{let t=this.getScene3D();this.tracer.log("stopCameraManualRotation",{isScene3DAvailable:!!t,immediate:e}),t&&t.stopCameraManualRotation(e)})),this}moveCameraFocusPX(e,t){return this.subscription.add(this.playerInited.pipe(z(i=>!!i),Y()).subscribe(()=>{let i=this.getScene3D();if(this.tracer.log("moveCameraFocusPX",{isScene3DAvailable:!!i,dxpx:e,dypx:t}),i){let r=i.getCameraRotation(),a=i.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:r.x+a.x,y:r.y+a.y})}})),this}holdCamera(){return this.subscription.add(this.playerInited.pipe(z(e=>e),Y()).subscribe(()=>{let e=this.getScene3D();e&&e.holdCamera()})),this}releaseCamera(){return this.subscription.add(this.playerInited.pipe(z(e=>!!e),Y()).subscribe(()=>{let e=this.getScene3D();e&&e.releaseCamera()})),this}getExactTime(){if(!this.providerContainer)return 0;let e=this.providerContainer.providerOutput.element$.getValue();if(HO(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),i=t.state==="none"?void 0:t.position;return wE(i)?i/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){var t,i;let e=(t=this.providerContainer)==null?void 0:t.current$.getValue();if((i=e==null?void 0:e.provider)!=null&&i.scene3D)return e.provider.scene3D}setIntrinsicVideoSize(...e){let t={width:e.reduce((i,{width:r})=>i||r||0,0),height:e.reduce((i,{height:r})=>i||r||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(Ui(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(Z(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(Z(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(Z(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(Z(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(Z(e=>e.to)).subscribe(e=>{this.info.autoQualityLimits$.next(e);let{highQualityLimit:t,trafficSavingLimit:i}=this.tuning.autoTrackSelection;this.info.predefinedQualityLimitType$.next(Nd(e,t,i))})),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(z(({from:e})=>e==="stopped"),Y()).subscribe(()=>{this.initedAt=Al(),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",qi(n)),n.state==="requested"?this.desiredState.seekState.setState({...n,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:wl.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe(Y()).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",qi(n)),n.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe(Z(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(Z(n=>n.destination),te()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(wi({availableVideoTracks:e.providerOutput.availableVideoTracks$,currentVideoStream:e.providerOutput.currentVideoStream$}).pipe(Z(({availableVideoTracks:n,currentVideoStream:o})=>n.filter(u=>o?o.id===u.streamId:!0).map(({quality:u})=>u).sort((u,l)=>kE(u)?1:kE(l)?-1:QO(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(te()).subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.pipe(z(n=>wE(n))).subscribe(n=>{this.info.currentQuality$.next(n==null?void 0:n.quality),this.info.videoBitrate$.next(n==null?void 0:n.bitrate)})).add(e.providerOutput.currentVideoSegmentLength$.pipe(te((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe(te((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(te()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(te()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(te()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.autoVideoTrackLimits$.subscribe(n=>{this.desiredState.autoVideoTrackLimits.setState(n!=null?n:{})})).add(e.providerOutput.currentBuffer$.pipe(Z(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(Rh(n=>n&&this.stop())).subscribe(this.info.isLiveEnded$)).add(e.providerOutput.canChangePlaybackSpeed$.subscribe(this.info.canChangePlaybackSpeed$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.liveBufferTime$.subscribe(this.info.liveBufferTime$)).add(e.providerOutput.liveLatency$.subscribe(this.info.liveLatency$)).add(wi({hasLiveOffsetByPaused:Ui(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(Z(n=>n.to),te(),Z(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(wi({atLiveEdge:wi({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Ph({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(Z(({isLive:n,position:o,isLowLatency:u})=>{let l=this.getActiveLiveDelay(u);return n&&Math.abs(o)<l/1e3}),te(),Rh(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(Z(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add(wi({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(Z(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),te(),Rh(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(Z(n=>n.muted),te()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(Z(n=>n.volume),te()).subscribe(this.info.volume$)).add(Ph({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(Ui(e.providerOutput.endedEvent$.pipe(AE(!0)),e.providerOutput.seekedEvent$.pipe(AE(!1))).pipe(te()).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(Z(n=>({id:n?`No${n}`:"NoProviders",category:wl.VIDEO_PIPELINE,message:n?`${n} was forced but failed or not available`:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.getCurrentTime$.subscribe(this.experimental.getCurrentTime$)).add(e.providerOutput.firstBytesEvent$.pipe(Y(),Z(n=>n!=null?n:Al()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(Y(),Z(()=>Al()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(Y(),Z(()=>Al()-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 D(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let i=new D(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(z(({to:n})=>n==="playing"),Y()).subscribe(()=>i.next(!1)));let r=0,a=Ui(e.providerOutput.isBuffering$,t,i).pipe(Z(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||i.getValue();return n&&!o}),te());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(Ui(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{let n=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n==null?void 0:n.videoWidth,height:n==null?void 0:n.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{var u,l;let o=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:(u=n==null?void 0:n.size)==null?void 0:u.width,height:(l=n==null?void 0:n.size)==null?void 0:l.height},{width:o==null?void 0:o.videoWidth,height:o==null?void 0:o.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add(Ui(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,e.providerOutput.elementVisible$,this.chromecastInitializer.castState$).subscribe(()=>{let n=e.providerOutput.inPiP$.getValue(),o=e.providerOutput.inFullscreen$.getValue(),u=e.providerOutput.element$.getValue(),l=e.providerOutput.elementVisible$.getValue(),d=this.chromecastInitializer.castState$.getValue(),c;d==="CONNECTED"?c="second_screen":u?l?n?c="pip":o?c="fullscreen":c="inline":c="invisible":c="none",this.info.surface$.getValue()!==c&&this.info.surface$.next(c)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(Z(e=>e==null?void 0:e.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new PE;this.subscription.add(t),this.subscription.add(e.current$.pipe(te((i,r)=>i.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(z(i=>i.length>0),Y()).subscribe(i=>{this.setStartingVideoTrack(i)}))}))}setStartingVideoTrack(e){var r;let t;this.wasSetStartedQuality=!0;let i=(r=this.explicitInitialQuality)!=null?r:this.info.currentQuality$.getValue();i&&(t=e.find(({quality:a})=>a===i),t||this.setAutoQuality(!0)),t||(t=Wt(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(Ui(this.desiredState.videoTrack.stateChangeStarted$.pipe(Z(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(Z(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(Z(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(Z(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(Z(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(Z(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(Z(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(Z(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(Z(e=>({component:"desiredState",message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`}))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){var t;let e=(t=this.providerContainer)==null?void 0:t.providerOutput;El(this.providerContainer),El(e),py(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(i=>dy(i)),this.providerContainer.current$.subscribe(({type:i})=>ka("provider",i)),e.duration$.subscribe(i=>ka("duration",i)),e.availableVideoTracks$.pipe(z(i=>!!i.length),Y()).subscribe(i=>ka("tracks",i)),this.events.fatalError$.subscribe(new Ke("fatalError")),this.events.managedError$.subscribe(new Ke("managedError")),e.position$.subscribe(new Ke("position")),e.currentVideoTrack$.pipe(Z(i=>i==null?void 0:i.quality)).subscribe(new Ke("quality")),this.info.currentBuffer$.subscribe(new Ke("buffer")),e.isBuffering$.subscribe(new Ke("isBuffering"))].forEach(i=>this.subscription.add(i)),ka("codecs",j.video.supportedCodecs)}initTracerSubscription(){let e=RE(this.tracer.log.bind(this.tracer)),t=RE(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(te()).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(wi({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe(z(({currentQuality:i,videoBitrate:r})=>!!i&&!!r),te((i,r)=>i.currentQuality===r.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe(z(i=>i>0),te()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe(z(i=>i>0),te()).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(wi({currentBuffer:this.info.currentBuffer$.pipe(z(i=>i.end>0),te((i,r)=>i.end===r.end&&i.start===r.start)),position:this.info.position$.pipe(te())}).pipe(Mh(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe(te()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe(te()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe(te()).subscribe(e("canChangePlaybackSpeed"))).add(wi({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(z(({liveTime:i,liveBufferTime:r})=>!!i&&!!r),Mh(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(te(),z(i=>i===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(te(),z(i=>i===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe(te()).subscribe(e("muted"))).add(this.info.volume$.pipe(te()).subscribe(e("volume"))).add(this.info.isEnded$.pipe(te(),z(i=>i===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add(wi({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(z(({throughputEstimation:i,rtt:r})=>!!i&&!!r),Mh(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(te(),z(i=>i===!0)).subscribe(e("is3DVideo"))).add(this.info.surface$.subscribe(e("surface"))).add(this.events.ended$.subscribe(e("ended"))).add(this.events.looped$.subscribe(e("looped"))).add(this.events.managedError$.subscribe(t("managedError"))).add(this.events.fatalError$.subscribe(t("fatalError"))).add(this.events.firstBytes$.subscribe(e("firstBytes"))).add(this.events.firstFrame$.subscribe(e("firstFrame"))).add(this.events.canplay$.subscribe(e("canplay")))}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e,t=()=>{e==null||e.release(),e=void 0},i=async()=>{t(),e=await window.navigator.wakeLock.request("screen").catch(r=>{r instanceof DOMException&&r.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:wl.DOM,message:String(r)})})};this.subscription.add(Ui(kh(document,"visibilitychange"),kh(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let r=document.visibilityState==="visible",a=this.desiredState.playbackState.getState()==="playing",n=!!e&&!(e!=null&&e.released);r&&a?n||i():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let i=e.find(r=>r.quality===t);this.tracer.log("setVideoTrackIdByQuality",qi({quality:t,availableTracks:qi(e),track:qi(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&&!Ca()}};import{Subscription as yee,Observable as Tee,Subject as Iee,ValueSubject as xee,VideoQuality as Eee}from"@vkontakte/videoplayer-shared/es2018";var wee=`@vkontakte/videoplayer-core@${Bh}`;export{vo as ChromecastState,Cl as HttpConnectionType,Tee as Observable,et as PlaybackState,Pl as Player,yo as PredefinedQualityLimits,wee as SDK_VERSION,Iee as Subject,yee as Subscription,Vl as Surface,Bh as VERSION,xee as ValueSubject,di as VideoFormat,Eee as VideoQuality,j as clientChecker,Pa as isMobile};
|
|
178
|
+
`;var Dr=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 Ro(this.params.fov,this.params.orientation),this.cameraRotationManager=new ko(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(uI,this.gl.VERTEX_SHADER),i=this.createShader(lI,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,i),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){let e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,i=1,r=this.frameHeight/(this.frameWidth/this.viewportWidth);return r>this.viewportHeight?t=this.viewportHeight/r:i=r/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-i,t,-i,t,i,-t,i]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){let e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,i=this.camera.fov.x/360/2,r=this.camera.fov.y/180/2,s=e-i,n=t-r,o=e+i,u=t-r,l=e+i,c=t+r,d=e-i,f=t+r;return[s,n,o,u,l,c,d,f]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){let e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}};import{isNullable as RB,now as ms,once as kB,Subscription as LB,ValueSubject as id,isNonNullable as $B,safeStorage as rd,filterChanged as MB}from"@vkontakte/videoplayer-shared/es2018";var Lo="stalls_manager_metrics",ad="stalls_manager_abr_params",cI="stalls_manager_default_tuning_abr_params",sd=class{constructor(){this.isSeeked$=new id(!1);this.isBuffering$=new id(!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 LB;this.severeStallOccurred$=new id(!1)}init(e){this.currentStallDuration$=e.currentStallDuration$,this.videoLastDataObtainedTimestamp$=e.videoLastDataObtainedTimestamp$,this.throughput$=e.throughput$,this.rtt$=e.rtt$,this.tuning=e.tuning,this.abrParams=e.abrParams,this.resetStoredAbrParamsIfNeeded(),this.subscribe(e)}get videoMaxQualityLimit(){return this.maxQualityLimit}get predictedThroughput(){return this.predictedThroughputWithoutData}get abrTuningParams(){let e=this.tuning.enabled?this.getStoredData(ad):{};return{...this.abrParams,...e}}set lastVideoTrackSelected(e){var t;((t=this.lastUniqueVideoTrackSelected)==null?void 0:t.id)!==e.id&&(this.lastUniqueVideoTrackSelected=e,this.lastUniqueVideoTrackSelectedTimestamp=ms(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe(),this.currentStallDuration$.getValue()!==0&&this.updateStallData();let e=(ms()-this.providerStartWatchingTimestamp-this.sumStallsDuration)/1e3,t=this.sumStallsDuration;this.addStallInfoToHistory(e,t),this.updateStoredAbrParams()}resetStoredAbrParamsIfNeeded(){let{bitrateFactorAtEmptyBuffer:e,bitrateFactorAtFullBuffer:t,containerSizeFactor:i}={...this.getStoredData(cI)},{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:s,containerSizeFactor:n}={...this.abrParams};this.tuning.enabled&&e===r&&t===s&&i===n||(this.removeStoredData(ad),this.setStoredData(cI,{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:s,containerSizeFactor:n}))}updateStoredAbrParams(){let e=[],t=this.getStoredData(Lo,"[]");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((o,u)=>o+u.stallsDuration,0)/i;e.push(this.calculateOptimalAbrParams(n,i))}if(this.tuning.useAverageStallsDurationPerTvt){let s=t.reduce((n,o)=>n+o.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(Lo,[]),this.setStoredData(ad,r)}calculateOptimalAbrParams(e,t){let{targetStallsDurationPerTvt:i,deviationStallsDurationPerTvt:r,criticalStallsDurationPerTvt:s,abrAdjustingSpeed:n,significantTvt:o,stallsMetricsHistoryLength:u}=this.tuning,l=n*Math.min(t/(o*u),1),c=this.abrTuningParams;return e<i-r?c={bitrateFactorAtEmptyBuffer:Math.max(c.bitrateFactorAtEmptyBuffer-l,this.abrParams.minBitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.max(c.bitrateFactorAtFullBuffer-l,this.abrParams.minBitrateFactorAtFullBuffer),containerSizeFactor:Math.min(c.containerSizeFactor+l,this.abrParams.maxContainerSizeFactor)}:e>i+r&&(c={bitrateFactorAtEmptyBuffer:Math.min(c.bitrateFactorAtEmptyBuffer+l,this.abrParams.maxBitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.min(c.bitrateFactorAtFullBuffer+l,this.abrParams.maxBitrateFactorAtFullBuffer),containerSizeFactor:Math.max(c.containerSizeFactor-l,this.abrParams.minContainerSizeFactor)}),e>s&&(c={bitrateFactorAtEmptyBuffer:Math.max(c.bitrateFactorAtEmptyBuffer,this.abrParams.bitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.max(c.bitrateFactorAtFullBuffer,this.abrParams.bitrateFactorAtFullBuffer),containerSizeFactor:Math.min(c.containerSizeFactor,this.abrParams.containerSizeFactor)}),c}getStoredData(e,t="{}"){var i;return JSON.parse((i=rd.get(e))!=null?i:t)}setStoredData(e,t){rd.set(e,JSON.stringify(t))}removeStoredData(e){rd.remove(e)}addStallInfoToHistory(e,t){if(e<this.tuning.minTvtToBeCounted||e>this.tuning.maxTvtToBeCounted||e*1e3<t)return;let i=this.getStoredData(Lo,"[]"),r=t/e,s=i.length?Dt(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(Lo,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(kB()).subscribe(t=>this.providerStartWatchingTimestamp=ms())),this.subscription.add(this.currentStallDuration$.pipe(MB()).subscribe(t=>{let{stallDurationNoDataBeforeQualityDecrease:i,stallCountBeforeQualityDecrease:r,resetQualityRestrictionTimeout:s,ignoreStallsOnSeek:n}=this.tuning;if(RB(this.lastUniqueVideoTrackSelected)||n&&this.isSeeked$.getValue())return;let o=this.rtt$.getValue(),u=this.throughput$.getValue(),l=this.videoLastDataObtainedTimestamp$.getValue(),c=ms(),d=r&&this.currentStallsCount>=r,f=i&&c-this.lastUniqueVideoTrackSelectedTimestamp>=i+o&&c-l>=i+o&&t>=i;(d||f)&&(this.severeStallOccurred$.next(!0),window.clearTimeout(this.qualityRestrictionTimer),this.maxQualityLimit=this.lastUniqueVideoTrackSelected.quality,$B(this.lastUniqueVideoTrackSelected.bitrate)&&u>this.lastUniqueVideoTrackSelected.bitrate&&(this.predictedThroughputWithoutData=this.lastUniqueVideoTrackSelected.bitrate)),!t&&ms()-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}))}},$o=sd;import{combine as DB,map as CB,observeElementSize as BB,Subscription as VB,ValueSubject as nd,noop as _B}from"@vkontakte/videoplayer-shared/es2018";var Mo=class{constructor(){this.subscription=new VB;this.pipSize$=new nd(void 0);this.videoSize$=new nd(void 0);this.elementSize$=new nd(void 0);this.pictureInPictureWindowRemoveEventListener=_B}connect({observableVideo:e,video:t}){let i=r=>{let s=r.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add(BB(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(DB({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(CB(({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 Di=class{constructor(e){this.subscription=new jB;this.videoState=new q("stopped");this.observableVideo=null;this.droppedFramesManager=new vr;this.stallsManager=new $o;this.elementSizeManager=new Mo;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Xt;this.audioTrackSwitchHistory=new Xt;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(r.state==="requested"&&(i==null?void 0:i.to)!=="paused"&&e!=="stopped"&&t!=="stopped"&&this.seek(r.position,r.forcePrecise),t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),$(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"),$(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="ready"&&$(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):t==="playing"&&this.video.paused?this.playIfAllowed():(i==null?void 0:i.to)==="playing"&&$(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&$(this.params.desiredState.playbackState,"paused");return;default:return FB(e)}}};this.init3DScene=e=>{var i,r,s;if(this.scene3D)return;this.scene3D=new Dr(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((i=e.projectionData)==null?void 0:i.pose.yaw)||0,y:((r=e.projectionData)==null?void 0:r.pose.pitch)||0,z:((s=e.projectionData)==null?void 0:s.pose.roll)||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSizeManager.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.textTracksManager=new Xe(e.source.url),this.params=e,this.video=Me(e.container,e.tuning),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Te(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.player=new Po({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params;HB(this.observableVideo)&&(this.observableVideo=Be(this.video),this.subscription.add(()=>{var n;return(n=this.observableVideo)==null?void 0:n.destroy()}));let i=this.constructor.name,r=n=>{e.error$.next({id:i,category:dI.WTF,message:`${i} internal logic error`,thrown:n})},s=(n,o)=>this.subscription.add(n.subscribe(o,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(od(l=>!!l.length),hI()).subscribe(l=>{this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:l})}));let n=this.params.desiredState.seekState.stateChangeEnded$.pipe(ud(l=>l.to.state!=="none"),Do());this.stallsManager.init({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$,videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,tuning:this.params.tuning.stallsManager,abrParams:this.params.tuning.autoTrackSelection,isBuffering$:i.isBuffering$,looped$:i.looped$,playing$:i.playing$}),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(this.player.error$,e.error$),s(this.player.fetcherRecoverableError$,e.fetcherRecoverableError$),s(this.player.fetcherError$,e.fetcherError$),s(this.player.lastConnectionType$,e.httpConnectionType$),s(this.player.lastConnectionReused$,e.httpConnectionReused$),s(this.player.isLive$,e.isLive$),s(this.player.lastRequestFirstBytes$.pipe(od(pI),hI()),e.firstBytesEvent$),s(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),s(this.videoState.stateChangeEnded$.pipe(ud(l=>l.to)),this.params.output.playbackState$),this.subscription.add(i.looped$.subscribe(()=>this.player.warmUpMediaSourceIfNeeded(),r)),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(bt(this.video,t.isLooped,r)),this.subscription.add(Ce(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Ke(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),s(Je(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),$(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),$(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:l})=>{if(l==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let c=this.player.getStreams();if(NB(c,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let f=[];for(let p of c.audio){f.push(Hc(p));let h=[];for(let m of p.representations){let b=QT(m);h.push(b),this.audioTracksMap.set(b,{stream:p,representation:m})}this.audioStreamsMap.set(p,h)}this.params.output.availableAudioStreams$.next(f)}let d=[];for(let f of c.video){d.push(jc(f));let p=[];for(let h of f.representations){let m=jT({...h,streamId:f.id});m&&(p.push(m),this.videoTracksMap.set(m,{stream:f,representation:h}))}this.videoStreamsMap.set(f,p)}this.params.output.availableVideoStreams$.next(d);for(let f of c.text)for(let p of f.representations){let h=GT(f,p);this.textTracksMap.set(h,{stream:f,representation:p})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else l==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r)),this.subscription.add(Co(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$,qB(this.video,"progress")).pipe(od(()=>this.videoTracksMap.size>0)).subscribe(async()=>{let l=this.player.state$.getState(),c=this.player.state$.getTransition();if(!(0,fI.default)(["manifest_ready","running"],l)||c)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let d=this.selectVideoAudioRepresentations();if(!d)return;let[f,p]=d,h=[...this.videoTracksMap.keys()].find(b=>{var S;return((S=this.videoTracksMap.get(b))==null?void 0:S.representation.id)===f.id});pI(h)&&(this.stallsManager.lastVideoTrackSelected=h);let m=this.params.desiredState.autoVideoTrackLimits.getTransition();if(m&&this.params.output.autoVideoTrackLimits$.next(m.to),l==="manifest_ready")await this.player.initRepresentations(f.id,p==null?void 0:p.id,this.params.sourceHls);else if(await this.player.switchRepresentation("video",f.id),p){let b=!!t.audioStream.getTransition();await this.player.switchRepresentation("audio",p.id,b)}},r)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:l})=>{this.scene3D&&l&&this.scene3D.pointCameraTo(l.x,l.y)})),this.subscription.add(this.elementSizeManager.subscribe(l=>{this.scene3D&&l&&this.scene3D.setViewportSize(l.width,l.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(Do()).subscribe(l=>{let c=[...this.videoTracksMap.entries()].find(([,{representation:m}])=>m.id===l);if(!c){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[d,{stream:f}]=c,p=this.params.desiredState.videoStream.getTransition();p&&p.to&&p.to.id===f.id&&this.params.desiredState.videoStream.setState(p.to),e.currentVideoTrack$.next(d),e.currentVideoStream$.next(jc(f));let h=this.player.calculateDurationFromSegments();h&&this.params.output.duration$.next(h/1e3)},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(Do()).subscribe(l=>{let c=[...this.audioTracksMap.entries()].find(([,{representation:h}])=>h.id===l);if(!c){e.currentAudioStream$.next(void 0);return}let[d,{stream:f}]=c,p=this.params.desiredState.audioStream.getTransition();p&&p.to&&p.to.id===f.id&&this.params.desiredState.audioStream.setState(p.to),e.currentAudioStream$.next(Hc(f))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(l=>{var c,d;if(l!=null&&l.is3dVideo&&((c=this.params.tuning.spherical)!=null&&c.enabled))try{this.init3DScene(l),e.is3DVideo$.next(!0)}catch(f){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${f}`})}else this.destroy3DScene(),(d=this.params.tuning.spherical)!=null&&d.enabled&&e.is3DVideo$.next(!1)},r)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,r)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,r)),this.textTracksManager.connect(this.video,t,e);let o=t.playbackState.stateChangeStarted$.pipe(ud(({to:l})=>l==="ready"),Do());this.subscription.add(Co(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,ld(["init"])).subscribe(()=>{let l=t.autoVideoTrackSwitching.getState(),d=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:l?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(d)})),this.subscription.add(Co(o,this.player.state$.stateChangeEnded$,ld(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let u=Co(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,ld(["init"])).pipe(UB(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){var R,V,D,_,Y,J,T,k,x,w,B,ne,Fe;if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?xa:Ea,t=this.params.tuning.useNewAutoSelectVideoTrack?eo:Zn,i=this.params.tuning.useNewAutoSelectVideoTrack?vt:Jn,{desiredState:r,output:s}=this.params,n=r.autoVideoTrackSwitching.getState(),o=(R=r.videoTrack.getState())==null?void 0:R.id,l=[...this.videoTracksMap.keys()].find(({id:ie})=>ie===o),c=s.currentVideoTrack$.getValue(),d=((_=(D=r.videoStream.getState())!=null?D:l&&((V=this.videoTracksMap.get(l))==null?void 0:V.stream))!=null?_:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!d)return;let f=[...this.videoStreamsMap.keys()].find(({id:ie})=>ie===d.id),p=f&&this.videoStreamsMap.get(f);if(!p)return;let h=me(this.video.buffered,this.video.currentTime*1e3),m;this.player.isActiveLive$.getValue()?m=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?m=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:m=n?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let b=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,S=Math.min(h/Math.min(m,b||1/0),1),y=(Y=r.audioStream.getState())!=null?Y:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,v=(J=[...this.audioStreamsMap.keys()].find(({id:ie})=>ie===(y==null?void 0:y.id)))!=null?J:this.audioStreamsMap.keys().next().value,I=0;if(v){if(l&&!n){let ie=e(l,p,(T=this.audioStreamsMap.get(v))!=null?T:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);I=Math.max(I,(k=ie==null?void 0:ie.bitrate)!=null?k:-1/0)}if(c){let ie=e(c,p,(x=this.audioStreamsMap.get(v))!=null?x:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);I=Math.max(I,(w=ie==null?void 0:ie.bitrate)!=null?w:-1/0)}}let E=i(p,{container:this.elementSizeManager.getValue(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.stallsManager.abrTuningParams,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:I,forwardBufferHealth:S,current:c,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,stallsVideoMaxQualityLimit:this.stallsManager.videoMaxQualityLimit,stallsPredictedThroughput:this.stallsManager.predictedThroughput,abrLogger:this.params.dependencies.abrLogger}),A=n?E!=null?E:l:l!=null?l:E,M=v&&t(A,p,(B=this.audioStreamsMap.get(v))!=null?B:[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.stallsManager.abrTuningParams,forwardBufferHealth:S,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),L=(ne=this.videoTracksMap.get(A))==null?void 0:ne.representation,P=M&&((Fe=this.audioTracksMap.get(M))==null?void 0:Fe.representation);if(L&&P)return[L,P];if(L&&!P&&this.audioTracksMap.size===0)return[L,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Ve(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),$(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:dI.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),De(this.video),this.tracer.end()}};var bs=class extends Di{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 cd,merge as mI,filter as bI,filterChanged as gI,isNullable as dd,map as SI,ValueSubject as pd,isNonNullable as QB}from"@vkontakte/videoplayer-shared/es2018";var gs=class extends Di{constructor(e){super(e),this.textTracksManager.destroy()}subscribe(){super.subscribe();let e=!1,t=-1,{output:i,observableVideo:r,desiredState:s,connect:n}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),n(r.timeUpdate$,i.liveBufferTime$),n(this.player.liveSeekableDuration$,i.duration$),n(this.player.liveLatency$,i.liveLatency$);let o=new pd(1);n(r.playbackRateState$,o),this.params.tuning.dashCmafLive.catchupLiveForMutedInactiveTab&&this.subscription.add(i.elementVisible$.pipe(gI()).subscribe(u=>{let l=i.position$.getValue(),c=i.volume$.getValue(),d=!c.volume||c.muted;!u&&!l&&d?e=!0:u&&e&&(this.seek(0),e=!1)})),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(s.isLowLatency.stateChangeEnded$.pipe(SI(u=>u.to)).subscribe(this.player.isLowLatency$)).add(cd({liveBufferTime:i.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(SI(({liveBufferTime:u,liveAvailabilityStartTime:l})=>u&&l?u+l:void 0)).subscribe(i.liveTime$)).add(this.player.liveStreamStatus$.pipe(bI(u=>QB(u))).subscribe(u=>i.isLiveEnded$.next(u!=="active"&&i.position$.getValue()===0))).add(cd({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:mI(r.playbackRateState$,new pd(1))}).pipe(bI(({liveStreamStatus:u,liveDuration:l})=>u==="active"&&!!l)).subscribe(({liveDuration:u,playbackRate:l})=>{let c=i.liveBufferTime$.getValue(),d=i.position$.getValue(),{playbackCatchupSpeedup:f}=this.params.tuning.dashCmafLive.lowLatency;d||l<1-f||this.video.paused||dd(c)||(t=u-c)})).add(cd({time:i.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:mI(r.playbackRateState$,new pd(1))}).pipe(gI((u,l)=>this.player.liveStreamStatus$.getValue()==="active"?u.liveDuration===l.liveDuration:u.time===l.time)).subscribe(({time:u,liveDuration:l,playbackRate:c})=>{let d=i.position$.getValue(),{playbackCatchupSpeedup:f}=this.params.tuning.dashCmafLive.lowLatency;if(!d&&!this.video.paused&&c>=1-f||dd(u)||dd(l))return;let p=-1*(l-u-t);i.position$.next(Math.min(p,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(u=>{if(u){let l=WT(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)})}};import{assertNever as g0,assertNonNullable as S0,debounce as v0,ErrorCategory as VI,filter as Rd,filterChanged as Go,fromEvent as y0,isNonNullable as _I,isNullable as T0,map as kd,merge as Wo,observableFrom as Ld,once as OI,Subscription as I0}from"@vkontakte/videoplayer-shared/es2018";var Ad=O(Ma(),1);import{abortable as Id,assertNonNullable as Vr,combine as _r,ErrorCategory as dt,filter as qo,filterChanged as Es,flattenObject as xs,fromEvent as Et,getTraceSubscriptionMethod as o0,interval as Ed,isNonNullable as ws,isNullable as CI,map as Or,merge as Oi,now as xd,Subject as Ho,Subscription as wd,tap as u0,throttle as BI,ValueSubject as se}from"@vkontakte/videoplayer-shared/es2018";var Oo=O(Ye(),1),_i=O(ot(),1),Fo=O(Ma(),1);var kI=O($n(),1);import{assertNever as GB,ErrorCategory as vI,Subject as yI}from"@vkontakte/videoplayer-shared/es2018";var WB=18,TI=!1;try{TI=N.browser.isSafari&&!!N.browser.safariVersion&&N.browser.safariVersion<=WB}catch(a){console.error(a)}var hd=class{constructor(e){this.bufferFull$=new yI;this.error$=new yI;this.queue=[];this.currentTask=null;this.destroyed=!1;this.abortRequested=!1;this.completeTask=()=>{var e;try{if(this.currentTask){let t=(e=this.currentTask.signal)==null?void 0:e.aborted;this.currentTask.callback(!t),this.currentTask=null}this.queue.length&&this.pull()}catch(t){this.error$.next({id:"BufferTaskQueueUnknown",category:vI.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(i=>{let r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(r=>{let s={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(s),this.pull()})}async abort(e){return new Promise(t=>{let i,r=s=>{this.abortRequested=!1,t(s)};TI&&e?i={operation:"safariAbort",init:e,callback:r}:i={operation:"abort",callback:r};for(let{callback:s}of this.queue)s(!1);this.abortRequested=!0,i&&(this.queue=[i]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){var r;if((this.buffer.updating||this.currentTask||this.destroyed)&&!this.abortRequested)return;let e=this.queue.shift();if(!e)return;if((r=e.signal)!=null&&r.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(s){s instanceof DOMException&&s.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):s instanceof DOMException&&s.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:vI.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:s}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){let{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:GB(t)}}},II=hd;import{abortable as ii,assertNonNullable as Oe,ErrorCategory as Bi,fromEvent as Sd,getExponentialDelay as vd,isNonNullable as Cr,isNullable as xe,now as _o,once as JB,Subject as ZB,Subscription as e0,ValueSubject as Vi}from"@vkontakte/videoplayer-shared/es2018";var fd=O(ot(),1);import{videoSizeToQuality as zB,throttleFn as YB}from"@vkontakte/videoplayer-shared/es2018";var EI=({id:a,width:e,height:t,bitrate:i,fps:r,quality:s,streamId:n})=>{var u;let o=(u=s?Kt(s):void 0)!=null?u:zB({width:e,height:t});return o&&{id:a,quality:o,bitrate:i,size:{width:e,height:t},fps:r,streamId:n}},xI=({id:a,bitrate:e})=>({id:a,bitrate:e}),wI=({language:a,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),AI=({language:a,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),md=({id:a,language:e,label:t,codecs:i,isDefault:r})=>({id:a,language:e,label:t,codec:(0,fd.default)(i.split("."),0),isDefault:r}),bd=({id:a,language:e,label:t,hdr:i,codecs:r})=>({id:a,language:e,hdr:i,label:t,codec:(0,fd.default)(r.split("."),0)}),gd=a=>"url"in a,Ge=a=>a.type==="template";var PI=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},Ci=(a,e)=>{for(let t of a)if(e(t))return t;return null},RI=a=>{let e=!1,t=YB(()=>{e=!0},a);return()=>{try{return t(),e}finally{e=!1}}};import{fromEvent as KB,Subscription as XB}from"@vkontakte/videoplayer-shared/es2018";var Bo=a=>{let e=[];for(let t=0;t<a.length;t++){let i=Math.floor(a.start(t)*1e3),r=Math.ceil(a.end(t)*1e3);e.push(i,r)}return e};var Vo=class{constructor(e,t){this.lastUpdateTs=0;this.lastCallTs=0;this.prevRanges=[];this.subscription=new XB;this.mediaSource=e,this.sourceBuffer=t,this.subscription.add(KB(this.sourceBuffer,"updateend").subscribe(()=>this.updateend()))}updateend(){if(!F(this.mediaSource,this.sourceBuffer))return;let{prevRanges:e}=this,t=Bo(this.sourceBuffer.buffered);this.prevRanges=t,this.isRangesRemoved(e,t)&&(this.lastUpdateTs=Date.now())}isRangesRemoved(e,t){if(e.length!==t.length)return!0;for(let i=0;i<e.length;i+=2){let r=e[i],s=e[i+1],n=t[i],o=t[i+1];if(n>r||o<s)return!0}return!1}wasUpdated(){let{lastCallTs:e,lastUpdateTs:t}=this;return this.lastCallTs=Date.now(),e<=t}destroy(){this.subscription.unsubscribe()}};var Ss=class{constructor(e,t,i,{fetcher:r,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new Vi(0);this.currentLowLatencySegmentLength$=new Vi(0);this.currentSegmentLength$=new Vi(0);this.onLastSegment$=new Vi(!1);this.fullyBuffered$=new Vi(!1);this.playingRepresentation$=new Vi(void 0);this.playingRepresentationInit$=new Vi(void 0);this.error$=new ZB;this.gaps=[];this.subscription=new e0;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new Z;this.switchAbortController=new Z;this.destroyAbortController=new Z;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=ii(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);Oe(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new II(this.sourceBuffer),this.sourceBufferBufferedDiff=new Vo(this.mediaSource,this.sourceBuffer),this.subscription.add(Sd(this.sourceBuffer,"updateend").subscribe(()=>{this.maintain()})),this.subscription.add(Sd(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:Bi.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o||!F(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,Ir(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=me(this.sourceBuffer.buffered,o),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,n*2,l<c).catch(d=>{this.handleAsyncError(d,"pruneBuffer")})})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);let i=this.initData.get(t.id),r=this.segments.get(t.id),s=this.parsedInitData.get(t.id);Oe(i,"No init buffer for starting representation"),Oe(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=ii(this.destroyAbortController.signal,async function*(e,t=!1){if(!F(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);Oe(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if(xe(s)||xe(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),Oe(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!F(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();Cr(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=ii(this.destroyAbortController.signal,async function*(e,t=!1){if(!F(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);Oe(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if(xe(s)||xe(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),Oe(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!F(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();Cr(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=ii(this.destroyAbortController.signal,async function*(e){var u,l;let t=(u=(0,Fo.default)(e,c=>c.representations))!=null?u:[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let c of this.representations.keys()){let d=t.find(h=>h.id===c);d&&this.representations.set(c,d);let f=this.representations.get(c);if(!f||!Ge(f.segmentReference))return;let p=this.getActualLiveStartingSegments(f.segmentReference);this.segments.set(f.id,p)}let i=(l=this.switchingToRepresentationId)!=null?l:this.downloadingRepresentationId,r=this.representations.get(i);Oe(r);let s=this.segments.get(i);Oe(s,"No segments for starting representation");let n=this.initData.get(i);if(Oe(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer))return;let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(s,r),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));var c;this.fetcher=r,this.tuning=s,this.compatibilityMode=u,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!(l!=null&&l.live),this.baseUrls=(c=l==null?void 0:l.baseUrls)!=null?c:[],this.initData=new Map(i.map(d=>[d.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(d=>[d.id,d])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchToWithPreviousAbort(e,t=!1){!F(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new Z,ii(this.switchAbortController.signal,async function*(i,r=!1){this.switchingToRepresentationId=i;let s=this.representations.get(i);Oe(s,`No such representation ${i}`);let n=this.segments.get(i),o=this.initData.get(i);if(xe(o)||xe(n)?yield this.loadInit(s,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(i),Oe(n,"No segments for starting representation"),o=this.initData.get(i),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer||!F(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();Cr(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(){!xe(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 Z,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(xe(e)||xe(this.downloadingRepresentationId)||xe(this.playingRepresentationId)||xe(this.sourceBuffer)||!F(this.mediaSource,this.sourceBuffer)||Cr(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(Oe(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;let r=i.find(c=>e>=c.time.from&&e<c.time.to);Cr(r)&&isFinite(r.time.from)&&isFinite(r.time.to)&&this.currentSegmentLength$.next((r==null?void 0:r.time.to)-r.time.from);let s=e,n=100;if(this.playingRepresentationId!==this.downloadingRepresentationId){let c=me(this.sourceBuffer.buffered,e),d=r?r.time.to+n:-1/0;r&&r.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&c>=r.time.to-e+n&&(s=d)}if(isFinite(this.bufferLimit)&&Ir(this.sourceBuffer.buffered)>=this.bufferLimit){let c=me(this.sourceBuffer.buffered,e),d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,c<d).catch(f=>{this.handleAsyncError(f,"pruneBuffer")});return}let u=null;if(!this.activeSegments.size&&(u=this.selectForwardBufferSegments(i,t.segmentReference.type,s),u!=null&&u.length)){let c="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if((0,Oo.default)(u,r))c="high";else{let d=(0,_i.default)(u,0);d&&d.time.from-r.time.to>=this.forwardBufferTarget/2&&(c="low")}this.loadSegments(u,t,c).catch(d=>{this.handleAsyncError(d,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&r&&r.status==="fed"&&!(u!=null&&u.length)&&me(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let l=(0,_i.default)(i,-1);!this.isLive&&l&&(this.fullyBuffered$.next(l.time.to-e-me(this.sourceBuffer.buffered,e)<n),this.onLastSegment$.next(e-l.time.from>0))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let i=0,r=this.isLive?this.liveInitialAdditionalOffset:0;for(let s of e)Math.trunc(s.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:s.time.from+r,persistent:!0}),i=s.time.to;Cr(t.duration)&&t.duration-i>0&&!this.isLive&&this.gaps.push({representation:t.id,from:i,to:t.duration,persistent:!0})}getActualLiveStartingSegments(e){let t=e.segments,i=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,r=[],s=0,n=t.length-1;do r.unshift(t[n]),s+=t[n].time.to-t[n].time.from,n--;while(s<i&&n>=0);return this.liveInitialAdditionalOffset=s-i,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){let t=(0,Fo.default)(e==null?void 0:e.streams[this.kind],r=>r.representations).find(r=>r.id===this.downloadingRepresentationId);if(!t)return;let i=this.segments.get(t.id);if(i!=null&&i.length)return{from:i[0].time.from,to:i[i.length-1].time.to}}updateLive(e){var i,r,s,n;let t=(i=(0,Fo.default)(e==null?void 0:e.streams[this.kind],o=>o.representations))!=null?i:[];if(![...this.segments.values()].every(o=>!o.length))for(let o of t){if(!o||!Ge(o.segmentReference))return;let u=o.segmentReference.segments.map(p=>({...p,status:"none",size:void 0})),l=100,c=(r=this.segments.get(o.id))!=null?r:[],d=(n=(s=(0,_i.default)(c,-1))==null?void 0:s.time.to)!=null?n:0,f=u==null?void 0:u.findIndex(p=>d>=p.time.from+l&&d<=p.time.to+l);if(f===-1){this.liveUpdateSegmentIndex=0;let p=this.getActualLiveStartingSegments(o.segmentReference);this.segments.set(o.id,p)}else{let p=u.slice(f+1);this.segments.set(o.id,[...c,...p])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;Oe(e);let t=this.segments.get(e);if(t!=null&&t.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}updateLowLatencyLiveIfNeeded(e){let t=0;for(let i of this.representations.values()){let r=i.segmentReference;if(!Ge(r))return;let s=this.segments.get(i.id);if(!s)continue;let n=s.find(u=>Math.floor(u.time.from)===Math.floor(e.time.from));if(n&&!isFinite(n.time.to)&&(n.time.to=e.time.to,t=n.time.to-n.time.from),!!!s.find(u=>Math.floor(u.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let u=Math.round(e.time.to*r.timescale/1e3).toString(10),l=lt(r.segmentTemplateUrl,{segmentTime:u});s.push({status:"none",time:{from:e.time.to,to:1/0},url:l})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){var s,n,o;let t=(n=(s=this.switchingToRepresentationId)!=null?s:this.downloadingRepresentationId)!=null?n:this.playingRepresentationId;if(!t)return;let i=this.segments.get(t);if(!i)return;let r=i.find(u=>u.time.from<=e&&u.time.to>=e);return(o=r==null?void 0:r.time.from)!=null?o:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e,t;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)==null||e.destroy(),(t=this.sourceBufferBufferedDiff)==null||t.destroy(),this.gapDetectionIdleCallback&&yt&&yt(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&yt&&yt(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(i){if(!(i instanceof DOMException&&i.name==="NotFoundError"))throw i}this.sourceBuffer=null,this.downloadAbortController.abort(),this.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,i){return this.checkEjectedSegments(),this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){if(this.playingRepresentationId!==this.downloadingRepresentationId){let i=e.findIndex(r=>t>=r.time.from&&t<r.time.to);this.liveUpdateSegmentIndex=i}return this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):null}selectForwardBufferSegmentsRecord(e,t,i){let r=this.getForwardBufferDuration(i),s=e.findIndex(({status:f,time:{from:p,to:h}},m)=>{let b=p<=i&&h>=i,S=p>i||b||m===0&&i===0,y=Math.min(this.forwardBufferTarget,this.bufferLimit),v=this.preloadOnly&&p<=i+y||r<y&&h-p>=y||h<=i+y;return(f==="none"||f==="partially_ejected"&&S&&v&&this.sourceBuffer&&F(this.mediaSource,this.sourceBuffer)&&!(Ie(this.sourceBuffer.buffered,p)&&Ie(this.sourceBuffer.buffered,h)))&&S&&v});if(s===-1)return null;if(t!=="byteRange")return e.slice(s,s+1);let n=e,o=0,u=0,l=[],c=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,d=this.preloadOnly?this.forwardBufferTarget:0;for(let f=s;f<n.length&&(o<=c||u<=d);f++){let p=n[f];if(o+=p.byte.to+1-p.byte.from,u+=p.time.to+1-p.time.from,p.status==="none"||p.status==="partially_ejected")l.push(p);else break}return l}async loadSegments(e,t,i="auto"){Ge(t.segmentReference)?await this.loadTemplateSegment(e[0],t,i):await this.loadByteRangeSegments(e,t,i)}async loadTemplateSegment(e,t,i="auto"){e.status="downloading";let r={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(r);let{range:s,url:n,signal:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await ii(o,async function*(){let c=vd(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,c))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let c=await this.fetcher.fetch(n,{range:s,signal:o,onProgress:u,priority:i,isLowLatency:this.isActiveLowLatency(),bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation});if(this.lastDataObtainedTimestampMs=_o(),!c)return;let d=new DataView(c),f=Tt(t.mime);if(!isFinite(r.segment.time.to)){let m=t.segmentReference.timescale;r.segment.time.to=f.getChunkEndTime(d,m)}u&&r.feedingBytes&&l?await Promise.all(l):await this.sourceBufferTaskQueue.append(d,o);let{serverDataReceivedTimestamp:p,serverDataPreparedTime:h}=f.getServerLatencyTimestamps(d);p&&h&&this.currentLiveSegmentServerLatency$.next(h-p),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(c){this.abortActiveSegments([e]),It(c)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}updateRepresentationsBaseUrlIfNeeded(){if(!this.tuning.dash.enableBaseUrlSupport||!this.baseUrls.length||this.failedDownloads<=this.tuning.dash.maxSegmentRetryCount)return;this.baseUrlsIndex=(this.baseUrlsIndex+1)%this.baseUrls.length;let e=this.baseUrls[this.baseUrlsIndex];for(let t of this.representations.values())Ge(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}async loadByteRangeSegments(e,t,i="auto"){if(!e.length)return;for(let u of e)u.status="downloading",this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:r,url:s,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(await ii(n,async function*(){let u=vd(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),Sd(window,"online").pipe(JB()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(s,{range:r,onProgress:o,signal:n,priority:i,bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation}),this.lastDataObtainedTimestampMs=_o(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),It(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(Ge(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:(0,_i.default)(e,0).byte.from,to:(0,_i.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:i,range:r,signal:s,onProgress:async(o,u)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=_o(),await this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:Bi.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!Ge(t.segmentReference))throw new Error("Representation is not template type");let i=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&i.searchParams.set("low-latency","yes");let r=i.toString(),{signal:s}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,c)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=_o();let d=this.onSomeTemplateDataLoaded({dataView:l,loaded:c,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(d)}catch(d){this.error$.next({id:"SegmentFeeding",category:Bi.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}:void 0;return{url:r,signal:s,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,Oo.default)(e,t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:s}){if(!this.activeSegments.size||!F(this.mediaSource,this.sourceBuffer))return;let n=this.representations.get(t);if(n)for(let o of this.activeSegments){let{segment:u}=o;if(o.representationId===t){if(s.aborted){r();continue}if(o.loadedBytes=i,o.loadedBytes>o.feedingBytes){let l=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),c=Tt(n.mime).parseFeedableSegmentChunk(l,this.isLive);c!=null&&c.byteLength&&(u.status="partially_fed",o.feedingBytes+=c.byteLength,await this.sourceBufferTaskQueue.append(c),o.fedBytes+=c.byteLength)}}}}async onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size||!F(this.mediaSource,this.sourceBuffer))return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){if(u.representationId!==t)continue;if(s.aborted){await n();continue}let{segment:l}=u,c=l.byte.from-i,d=l.byte.to-i,f=d-c+1,p=c<r,h=d<=r;if(p){if(l.status==="downloading"&&h){l.status="downloaded";let m=new DataView(e.buffer,e.byteOffset+c,f);await this.sourceBufferTaskQueue.append(m,s)&&!s.aborted?this.onSegmentFullyAppended(u,t):await n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(l.status==="downloading"||l.status==="partially_fed")&&(u.loadedBytes=Math.min(f,r-c),u.loadedBytes>u.feedingBytes)){let m=new DataView(e.buffer,e.byteOffset+c+u.feedingBytes,u.loadedBytes-u.feedingBytes),b=u.loadedBytes===f?m:Tt(o.mime).parseFeedableSegmentChunk(m);b!=null&&b.byteLength&&(l.status="partially_fed",u.feedingBytes+=b.byteLength,await this.sourceBufferTaskQueue.append(b,s)&&!s.aborted?(u.fedBytes+=b.byteLength,u.fedBytes===f&&this.onSegmentFullyAppended(u,t)):await n())}}}}onSegmentFullyAppended(e,t){if(!(xe(this.sourceBuffer)||!F(this.mediaSource,this.sourceBuffer))){!this.isLive&&N.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(Ie(this.sourceBuffer.buffered,e.segment.time.from,100)&&Ie(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:Bi.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",gd(e.segment)&&(e.segment.size=e.fedBytes);for(let i of this.representations.values()){if(i.id===t)continue;let r=this.segments.get(i.id);if(r)for(let s of r)s.status==="fed"&&Math.round(s.time.from)===Math.round(e.segment.time.from)&&Math.round(s.time.to)===Math.round(e.segment.time.to)&&(s.status="none")}this.isActiveLowLatency()&&this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,e.segment)}}abortSegment(e){e.status==="partially_fed"?e.status="partially_ejected":e.status!=="partially_ejected"&&(e.status="none");for(let t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[r,s]of this.initData.entries()){let n=s instanceof Promise;t||(t=n),s===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let i=this.representations.get(e);i&&(this.initLoadIdleCallback=Tr(()=>(0,kI.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?ii(this.destroyAbortController.signal,async function*(){let o=vd(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,Tt(e.mime),r)).then(o=>{if(!o)return;let{init:u,dataView:l,segments:c}=o,d=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,d);let f=c;this.isLive&&Ge(e.segmentReference)&&(f=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,f),u&&this.parsedInitData.set(e.id,u)}).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:Bi.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||!F(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||xe(e))return!1;this.checkEjectedSegments();let r=[],s=0,n=o=>{var l;if(s>=t)return;r.push({...o.time});let u=gd(o)?(l=o.size)!=null?l:0:o.byte.to-o.byte.from;s+=u};for(let o of this.segments.values())for(let u of o){let l=u.time.to<=e-this.tuning.dash.bufferPruningSafeZone,c=u.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(l||c)&&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,c=0;for(let d of this.segments.values())for(let f of d)(0,Oo.default)(["none","partially_ejected"],f.status)&&Math.round(f.time.from)<=Math.round(u)&&Math.round(f.time.to)>=Math.round(l)&&c++;if(c===this.segments.size){let d={time:{from:u,to:l},url:"",status:"none"};n(d)}}if(r.length&&i){let o=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let u of this.segments.values())for(let l of u)l.time.from>=e+o&&l.status==="fed"&&n(l)}return r.length?(r=PI(r),(await Promise.all(r.map(u=>this.sourceBufferTaskQueue.remove(u.from,u.to)))).reduce((u,l)=>u||l,!1)):!1}async abortBuffer(){if(!this.sourceBuffer||!F(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||!F(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||!F(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||!F(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||xe(e)?0:me(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!this.sourceBuffer||!F(this.mediaSource,this.sourceBuffer))return;let{buffered:i}=this.sourceBuffer;this.tuning.useRefactoredSearchGap&&(this.gaps=this.gaps.filter(s=>{if(s.persistent)return!0;let n=Math.round(s.from),o=Math.round(s.to);for(let u=0;u<i.length;u++)if(n>=Math.round(i.start(u)*1e3)&&o<=Math.round(i.end(u)*1e3))return!1;return!0}));let 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,o=i.end(s)*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(s=>r&&s.from===r.from&&s.to===r.to)&&this.gaps.push(r)}detectGapsWhenIdle(e,t){if(!(this.gapDetectionIdleCallback||!this.sourceBuffer||!F(this.mediaSource,this.sourceBuffer))){if(!this.tuning.useRefactoredSearchGap)for(let i=0;i<this.sourceBuffer.buffered.length;i++)this.gaps=this.gaps.filter(r=>r.persistent||this.sourceBuffer&&(Math.round(r.from)<Math.round(this.sourceBuffer.buffered.start(i)*1e3)||Math.round(r.to)>Math.round(this.sourceBuffer.buffered.end(i)*1e3)));this.gapDetectionIdleCallback=Tr(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:Bi.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if(xe(this.sourceBuffer)||!F(this.mediaSource,this.sourceBuffer)||xe(this.playingRepresentationId)||this.sourceBufferBufferedDiff&&!this.sourceBufferBufferedDiff.wasUpdated())return;let e=Bo(this.sourceBuffer.buffered),t=100;for(let i of this.segments.values())for(let r of i){let{status:s}=r;if(s!=="fed"&&s!=="partially_ejected")continue;let n=Math.floor(r.time.from),o=Math.ceil(r.time.to),u=!1,l=0;for(let c=0;c<e.length;c+=2){let d=e[c],f=e[c+1];u||(u=d-t<=n&&f+t>=o),(n>=d&&n<f-t||o>d+t&&o<=f)&&(l+=1)}u||(l===1?r.status="partially_ejected":this.gaps.some(c=>c.from===r.time.from||c.to===r.time.to)?r.status="partially_ejected":r.status="none")}}handleAsyncError(e,t){this.error$.next({id:t,category:Bi.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}calculateDurationFromSegments(){var t;if(!this.playingRepresentationId)return 0;let e=this.segments.get(this.playingRepresentationId);return(e?(t=(0,_i.default)(e,-1))==null?void 0:t.time.to:0)||0}};import{abortable as vs,assertNever as LI,fromEvent as $I,merge as t0,now as ys,Subject as MI,ValueSubject as yd,flattenObject as Br,ErrorCategory as Ts,SubscriptionRemovable as i0}from"@vkontakte/videoplayer-shared/es2018";var Uo=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:s=!1}){this.lastConnectionType$=new yd(void 0);this.lastConnectionReused$=new yd(void 0);this.lastRequestFirstBytes$=new yd(void 0);this.recoverableError$=new MI;this.error$=new MI;this.abortAllController=new Z;this.subscription=new i0;this.fetchManifest=vs(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=ei(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=mo(i));let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(No);return r?(t.log("success",Br({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(r.headers),r.text()):(t.error("error",Br({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=vs(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:s="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1,bufferOptimisation:l=!1}={}){var _,Y,J;let c=e,d=new Headers,f=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{d.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let T=new URL(c,location.href);T.searchParams.append("bytes",`${i.from}-${i.to}`),c=T.toString();break}default:LI(t)}this.requestQuic&&(c=ei(c));let p=this.abortAllController.signal,h;if(n){let T=new Z;if(h=t0($I(this.abortAllController.signal,"abort"),$I(n,"abort")).subscribe(()=>{try{T.abort()}catch(k){No(k)}}),this.subscription.add(h),this.abortAllController.signal.aborted||n.aborted)try{T.abort()}catch(k){No(k)}p=T.signal}let m=ys();f.log("startRequest",Br({url:c,priority:s,rangeMethod:t,range:i,isLowLatency:u,requestStartedAt:m}));let b=yield this.doFetch(c,{priority:s,headers:d,signal:p}),S=ys();if(!b)return f.error("error",{message:"No response in request"}),f.end(),this.unsubscribeAbortSubscription(h),null;if((_=this.throughputEstimator)==null||_.addRawRtt(S-m),!b.ok||!b.body){this.unsubscribeAbortSubscription(h);let T=`Fetch error ${b.status}: ${b.statusText}`;return f.error("error",{message:T}),f.end(),Promise.reject(new Error(`Fetch error ${b.status}: ${b.statusText}`))}if(this.onHeadersReceived(b.headers),!r&&!o){this.unsubscribeAbortSubscription(h);let T=ys(),k={requestStartedAt:m,requestEndedAt:T,duration:T-m};return f.log("endRequest",Br(k)),f.end(),b.arrayBuffer()}let y=b.body;if(o){let T;[y,T]=b.body.tee(),(Y=this.throughputEstimator)==null||Y.trackStream(T,u)}let v=y.getReader(),I,E=parseInt((J=b.headers.get("content-length"))!=null?J:"",10);Number.isFinite(E)&&(I=E),!I&&i&&(I=i.to-i.from+1);let A=0,M=I?new Uint8Array(I):new Uint8Array(0),L=!1,P=T=>{this.unsubscribeAbortSubscription(h),L=!0,No(T)},R=vs(p,async function*({done:T,value:k}){if(A===0&&this.lastRequestFirstBytes$.next(ys()-m),p.aborted){this.unsubscribeAbortSubscription(h);return}if(!T&&k){if(l&&I)M.set(k,A),A+=k.byteLength;else{let x=new Uint8Array(M.length+k.length);x.set(M),x.set(k,M.length),M=x,A+=k.byteLength}r==null||r(new DataView(M.buffer),A),yield v==null?void 0:v.read().then(R,P)}}.bind(this));yield v==null?void 0:v.read().then(R,P),this.unsubscribeAbortSubscription(h);let V=ys(),D={failed:L,requestStartedAt:m,requestEndedAt:V,duration:V-m};return L?(f.error("endRequest",Br(D)),f.end(),null):(f.log("endRequest",Br(D)),f.end(),M.buffer)}.bind(this));this.fetchByteRangeRepresentation=vs(this.abortAllController.signal,async function*(e,t,i){var S;if(e.type!=="byteRange")return null;let{from:r,to:s}=e.initRange,n=r,o=s,u=!1,l,c;e.indexRange&&(l=e.indexRange.from,c=e.indexRange.to,u=s+1===l,u&&(n=Math.min(l,r),o=Math.max(c,s))),n=Math.min(n,0);let d=yield this.fetch(e.url,{range:{from:n,to:o},priority:i,measureThroughput:!1});if(!d)return null;let f=new DataView(d,r-n,s-n+1);if(!t.validateData(f))throw new Error("Invalid media file");let p=t.parseInit(f),h=(S=e.indexRange)!=null?S:t.getIndexRange(p);if(!h)throw new ReferenceError("No way to load representation index");let m;if(u)m=new DataView(d,h.from-n,h.to-h.from+1);else{let y=yield this.fetch(e.url,{range:h,priority:i,measureThroughput:!1});if(!y)return null;m=new DataView(y)}let b=t.parseSegments(m,p,h);return{init:p,dataView:new DataView(d),segments:b}}.bind(this));this.fetchTemplateRepresentation=vs(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}=fo(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,t,i="auto"){var s,n;let{type:r}=e;switch(r){case"byteRange":return(s=await this.fetchByteRangeRepresentation(e,t,i))!=null?s:null;case"template":return(n=await this.fetchTemplateRepresentation(e,i))!=null?n:null;default:LI(r)}}destroy(){this.abortAllController.abort(),this.tracer.end(),this.subscription.unsubscribe()}async doFetch(e,t){let i=await Ze(e,t);if(i.ok)return i;let r=await i.text(),s=parseInt(r);if(!isNaN(s))switch(s){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:Ts.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:Ts.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:Ts.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:Ts.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${s})`,category:Ts.FATAL})}}unsubscribeAbortSubscription(e){e&&(e.unsubscribe(),this.subscription.remove(e))}},No=a=>{if(!It(a))throw a};import{isNullable as r0,ValueSubject as a0}from"@vkontakte/videoplayer-shared/es2018";var Is=class a{constructor(e,t){this.currentRepresentation$=new a0(null);this.maxRepresentations=4;this.representationsCursor=0;this.representations=[];this.currentSegment=null;this.getCurrentPosition=t.getCurrentPosition,this.processStreams(e)}updateLive(e){this.processStreams(e==null?void 0:e.streams.text)}seekLive(e){this.processStreams(e)}maintain(e=this.getCurrentPosition()){var t;if(!r0(e))for(let i of this.representations)for(let r of i){let s=r.segmentReference,n=s.segments.length,o=s.segments[0].time.from,u=s.segments[n-1].time.to;if(e<o||e>u)continue;let l=s.segments.find(c=>c.time.from<=e&&c.time.to>=e);!l||((t=this.currentSegment)==null?void 0:t.time.from)===l.time.from&&this.currentSegment.time.to===l.time.to||(this.currentSegment=l,this.currentRepresentation$.next({...r,label:"Live Text",language:"ru",isAuto:!0,url:new URL(l.url,s.baseUrl).toString()}))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e!=null?e:[]){let i=a.filterRepresentations(t.representations);if(i){this.representations[this.representationsCursor]=i,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!(e!=null&&e.some(t=>a.filterRepresentations(t.representations)))}static filterRepresentations(e){return e==null?void 0:e.filter(t=>t.kind==="text"&&"segmentReference"in t&&Ge(t.segmentReference))}};var l0=["progress","play","seeked","stalled","waiting"],c0=["timeupdate","progress","loadeddata","playing","seeked"];var jo=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new wd;this.representationSubscription=new wd;this.state$=new q("none");this.currentVideoRepresentation$=new se(void 0);this.currentVideoRepresentationInit$=new se(void 0);this.currentAudioRepresentation$=new se(void 0);this.currentVideoSegmentLength$=new se(0);this.currentAudioSegmentLength$=new se(0);this.error$=new Ho;this.lastConnectionType$=new se(void 0);this.lastConnectionReused$=new se(void 0);this.lastRequestFirstBytes$=new se(void 0);this.currentLiveTextRepresentation$=new se(null);this.isLive$=new se(!1);this.isActiveLive$=new se(!1);this.isLowLatency$=new se(!1);this.liveDuration$=new se(0);this.liveSeekableDuration$=new se(0);this.liveAvailabilityStartTime$=new se(0);this.liveStreamStatus$=new se(void 0);this.bufferLength$=new se(0);this.liveLatency$=new se(void 0);this.liveLoadBufferLength$=new se(0);this.livePositionFromPlayer$=new se(0);this.currentStallDuration$=new se(0);this.videoLastDataObtainedTimestamp$=new se(0);this.fetcherRecoverableError$=new Ho;this.fetcherError$=new Ho;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new Ho;this.gapWatchdogActive=!1;this.destroyController=new Z;this.initManifest=Id(this.destroyController.signal,async function*(e,t,i){var r;this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=le(t,i,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),(r=this.manifest)!=null&&r.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:dt.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=Id(this.destroyController.signal,async function*(){var n,o;this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(u=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:dt.NETWORK,message:"Failed to load manifest",thrown:u})});if(!e)return null;let t=null;try{t=lo(e!=null?e:"",this.manifestUrlString)}catch(u){let l=(n=oo(e))!=null?n:{id:"ManifestParsing",category:dt.PARSER,message:"Failed to parse MPD manifest",thrown:u};this.error$.next(l)}if(!t)return null;let i=(u,l,c)=>{var d,f,p,h;return!!((f=(d=this.element)==null?void 0:d.canPlayType)!=null&&f.call(d,l)&&((h=(p=je())==null?void 0:p.isTypeSupported)!=null&&h.call(p,`${l}; codecs="${c}"`))||u==="text")};if(t.live){this.isLive$.next(!!t.live);let{availabilityStartTime:u,latestSegmentPublishTime:l,streamIsUnpublished:c,streamIsAlive:d}=t.live,f=((o=t.duration)!=null?o:0)/1e3;this.liveSeekableDuration$.next(-1*f),this.liveDuration$.next((l-u)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let p="active";d||(p=c?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(p)}let r={text:t.streams.text,video:[],audio:[]};for(let u of["video","audio"]){let c=t.streams[u].filter(({mime:p,codecs:h})=>i(u,p,h)),d=new Set(c.map(({codecs:p})=>p)),f=xo(d);if(f&&(r[u]=c.filter(({codecs:p})=>p.startsWith(f))),u==="video"){let p=this.tuning.preferHDR,h=r.video.some(b=>b.hdr),m=r.video.some(b=>!b.hdr);N.display.isHDR&&p&&h?r.video=r.video.filter(b=>b.hdr):m&&(r.video=r.video.filter(b=>!b.hdr))}}let s={...t,streams:r};return this.tracer.log("updateManifestEnd",xs(s)),s}.bind(this));this.initRepresentations=Id(this.destroyController.signal,async function*(e,t,i){var f;this.tracer.log("initRepresentationsStart",xs({initialVideo:e,initialAudio:t,sourceHls:i})),Vr(this.manifest),Vr(this.element),this.representationSubscription.unsubscribe(),this.representationSubscription=new wd,this.state$.startTransitionTo("representations_ready");let r=p=>{this.representationSubscription.add(Et(p,"error").pipe(qo(h=>{var m;return!!((m=this.element)!=null&&m.played.length)})).subscribe(h=>{this.error$.next({id:"VideoSource",category:dt.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=this.tuning.useManagedMediaSource?_n():new MediaSource;let s=document.createElement("source");if(r(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&hr())if(i){let p=document.createElement("source");r(p),p.type="application/x-mpegurl",p.src=i.url,this.element.appendChild(p)}else this.element.disableRemotePlayback=!0;this.isActiveLive$.next(this.isLive$.getValue());let n={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),manifest:this.manifest},o=this.manifest.streams.video.reduce((p,h)=>[...p,...h.representations],[]);if(this.videoBufferManager=new Ss("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],ws(t)){let p=this.manifest.streams.audio.reduce((h,m)=>[...h,...m.representations],[]);this.audioBufferManager=new Ss("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}Is.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new Is(this.manifest.streams.text,n)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$));let u=()=>{var p;(p=this.stallWatchdogSubscription)==null||p.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add(Oi(...c0.map(p=>Et(this.element,p))).pipe(Or(p=>this.element?me(this.element.buffered,this.element.currentTime*1e3):0),Es(),u0(p=>{p>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add(Oi(Et(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe(Es()).subscribe(h=>this.liveStreamEndTimestamp=xd())),this.subscription.add(Et(this.element,"pause").subscribe(()=>{this.livePauseWatchdogSubscription=Ed(1e3).subscribe(h=>{let m=zt(this.manifestUrlString,2);this.manifestUrlString=le(this.manifestUrlString,m+1e3,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add(Et(this.element,"play").subscribe(h=>{var m;return(m=this.livePauseWatchdogSubscription)==null?void 0:m.unsubscribe()})),this.representationSubscription.add(_r({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(Or(({isActiveLive:h,isLowLatency:m})=>h&&m),Es()).subscribe(h=>{this.isManualDecreasePlaybackInLive()||kr(this.element,1)})),this.representationSubscription.add(_r({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(qo(({bufferLength:h,isActiveLive:m,isLowLatency:b})=>m&&b&&!!h)).subscribe(({bufferLength:h})=>this.liveBuffer.next(h))),this.representationSubscription.add(this.videoBufferManager.currentLowLatencySegmentLength$.subscribe(h=>{if(!this.isActiveLive$.getValue()&&!this.isLowLatency$.getValue()&&!h)return;let m=this.liveSeekableDuration$.getValue()-h/1e3;this.liveSeekableDuration$.next(Math.max(m,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+h/1e3)})),this.representationSubscription.add(_r({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(qo(({isLive:h})=>h),Es((h,m)=>m.bufferLength<h.bufferLength),Or(({rtt:h,bufferLength:m,segmentServerLatency:b})=>{let S=zt(this.manifestUrlString,2);return(h/2+m+b+S)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(_r({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:h,isActiveLive:m,isLowLatency:b})=>{if(!b||!m)return;let S=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,y=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,v=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,I=h-S;if(this.isManualDecreasePlaybackInLive())return;let E=1;Math.abs(I)>y&&(E=1+Math.sign(I)*v),kr(this.element,E)})),this.representationSubscription.add(this.bufferLength$.subscribe(h=>{var b,S;let m=0;if(h){let y=((S=(b=this.element)==null?void 0:b.currentTime)!=null?S:0)*1e3;m=Math.min(...this.bufferManagers.map(I=>{var E,A;return(A=(E=I.getLiveSegmentsToLoadState(this.manifest))==null?void 0:E.to)!=null?A:y}))-y}this.liveLoadBufferLength$.getValue()!==m&&this.liveLoadBufferLength$.next(m)}));let p=0;this.representationSubscription.add(_r({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(BI(1e3)).subscribe(async({liveLoadBufferLength:h,bufferLength:m})=>{if(!this.element||this.isUpdatingLive)return;let b=this.element.playbackRate,S=zt(this.manifestUrlString,2),y=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,v=Math.min(y,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*b),I=this.tuning.dashCmafLive.normalizedActualBufferOffset*b,E=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*b,A=isFinite(h)?h:m,M=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),L=y<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(L);let P="none";if(M?P="active_low_latency":this.isLowLatency$.getValue()&&L?(this.bufferManagers.forEach(R=>R.proceedLowLatencyLive()),P="active_low_latency"):S!==0&&A<v?P="live_forward_buffering":A<v+E&&(P="live_with_target_offset"),isFinite(h)&&(p=h>p?h:p),P==="live_forward_buffering"||P==="live_with_target_offset"){let R=p-(v+I),V=this.normolizeLiveOffset(Math.trunc(S+R/b)),D=Math.abs(V-S),_=0;!h||D<=this.tuning.dashCmafLive.offsetCalculationError?_=S:V>0&&D>this.tuning.dashCmafLive.offsetCalculationError&&(_=V),this.manifestUrlString=le(this.manifestUrlString,_,2)}(P==="live_with_target_offset"||P==="live_forward_buffering")&&(p=0,await this.updateLive())},h=>{this.error$.next({id:"updateLive",category:dt.VIDEO_PIPELINE,thrown:h,message:"Failed to update live with subscription"})}))}let l=Oi(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe(Or(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),c=Oi(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe(Or(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue()))),d=_r({allBuffersFull:l,someBufferEnded:c}).pipe(Es(),Or(({allBuffersFull:p,someBufferEnded:h})=>p&&h),qo(p=>p));if(this.representationSubscription.add(Oi(this.forceEnded$,d).subscribe(()=>{var p;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(h=>!h.updating))try{(p=this.source)==null||p.endOfStream()}catch(h){this.error$.next({id:"EndOfStream",category:dt.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:h})}})),this.representationSubscription.add(Oi(...this.bufferManagers.map(p=>p.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.representationSubscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.representationSubscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.liveTextManager&&this.representationSubscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$)),this.source.readyState!=="open"){let p=this.tuning.dash.sourceOpenTimeout>=0;yield new Promise(h=>{var m;p&&(this.timeoutSourceOpenId=setTimeout(()=>{var b;if(((b=this.source)==null?void 0:b.readyState)==="open"){h();return}this.error$.next({id:"OpenOfStream",category:dt.VIDEO_PIPELINE,message:"Failed to open MediaSource",thrown:new Error("Timeout reject when wait sourceopen event"),traceAsLog:!0})},this.tuning.dash.sourceOpenTimeout)),(m=this.source)==null||m.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),h()},{once:!0})})}if(!this.isLive$.getValue()){let p=[(f=this.manifest.duration)!=null?f:0,...(0,Ad.default)((0,Ad.default)([...this.manifest.streams.audio,...this.manifest.streams.video],h=>h.representations),h=>{let m=[];return h.duration&&m.push(h.duration),Ge(h.segmentReference)&&h.segmentReference.totalSegmentsDurationMs&&m.push(h.segmentReference.totalSegmentsDurationMs),m})];this.source.duration=Math.max(...p)/1e3}this.audioBufferManager&&ws(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")}.bind(this));this.tick=()=>{var t,i,r,s;if(!this.element||!this.videoBufferManager||((t=this.source)==null?void 0:t.readyState)!=="open")return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),(i=this.audioBufferManager)==null||i.maintain(e),(r=this.liveTextManager)==null||r.maintain(e),(this.videoBufferManager.gaps.length||(s=this.audioBufferManager)!=null&&s.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=Ed(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),n=>{this.error$.next({id:"GapWatchdog",category:dt.WTF,message:"Error handling gaps",thrown:n})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.fetcher=new Uo({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.subscription.add(this.fetcher.recoverableError$.subscribe(this.fetcherRecoverableError$)),this.subscription.add(this.fetcher.error$.subscribe(this.fetcherError$)),this.liveBuffer=Ct.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator}),this.initTracerSubscription()}async seekLive(e){var r,s,n;Vr(this.element);let t=this.liveStreamStatus$.getValue()!=="active"?xd()-this.liveStreamEndTimestamp:0,i=this.normolizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=le(this.manifestUrlString,i,2),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await((r=this.videoBufferManager)==null?void 0:r.seekLive(this.manifest.streams.video)),await((s=this.audioBufferManager)==null?void 0:s.seekLive(this.manifest.streams.audio)),(n=this.liveTextManager)==null||n.seekLive(this.manifest.streams.text))}initBuffer(){Vr(this.element),this.state$.setState("running");let e=Et(this.element,"timeupdate");this.tuning.dash.timeupdateEventTickThrottle&&(e=e.pipe(BI(this.tuning.dash.timeupdateEventTickThrottle))),this.subscription.add(Oi(...l0.map(t=>Et(this.element,t)),Et(window,"online"),e).subscribe(()=>this.tick(),t=>{this.error$.next({id:"DashVKPlayer",category:dt.WTF,message:"Internal logic error",thrown:t})})),this.subscription.add(Et(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(Et(this.element,"waiting").subscribe(()=>{var i;this.element&&this.element.readyState===HTMLMediaElement.HAVE_CURRENT_DATA&&!this.element.seeking&&Ie(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let t=()=>{var h,m,b,S,y,v,I,E,A,M,L;if(!this.element||((h=this.source)==null?void 0:h.readyState)!=="open")return;let r=this.currentStallDuration$.getValue();r+=50,this.currentStallDuration$.next(r);let s={timeInWaiting:r},n=xd(),o=100,u=(b=(m=this.videoBufferManager)==null?void 0:m.lastDataObtainedTimestamp)!=null?b:0;this.videoLastDataObtainedTimestamp$.next(u);let l=(y=(S=this.audioBufferManager)==null?void 0:S.lastDataObtainedTimestamp)!=null?y:0,c=(I=(v=this.videoBufferManager)==null?void 0:v.getForwardBufferDuration())!=null?I:0,d=(A=(E=this.audioBufferManager)==null?void 0:E.getForwardBufferDuration())!=null?A:0,f=c<o&&n-u>this.tuning.dash.crashOnStallTWithoutDataTimeout,p=this.audioBufferManager&&d<o&&n-l>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((f||p)&&r>this.tuning.dash.crashOnStallTWithoutDataTimeout||r>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${r} ms`);if(this.isLive$.getValue()&&r%2e3===0){let P=this.normolizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(P).catch(R=>{this.error$.next({id:"stallIntervalCallback",category:dt.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:R})}),s.liveLastOffset=P}else{let P=this.element.currentTime*1e3;(M=this.videoBufferManager)==null||M.maintain(P),(L=this.audioBufferManager)==null||L.maintain(P),s.position=P}this.tracer.log("stallIntervalCallback",xs(s))};(i=this.stallWatchdogSubscription)==null||i.unsubscribe(),this.stallWatchdogSubscription=Ed(50).subscribe(t,r=>{this.error$.next({id:"StallWatchdogCallback",category:dt.NETWORK,message:"Can't restore DASH after stall.",thrown:r})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,i=!1){let r={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return this.tuning.useNewSwitchTo?this.currentStallDuration$.getValue()>0?r==null?void 0:r.switchToWithPreviousAbort(t,i):r==null?void 0:r.switchTo(t,i):r==null?void 0:r.switchToOld(t,i)}async seek(e,t){var r,s,n,o,u;Vr(this.element),Vr(this.videoBufferManager);let i;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?i=e:i=Math.max((r=this.videoBufferManager.findSegmentStartTime(e))!=null?r:e,(n=(s=this.audioBufferManager)==null?void 0:s.findSegmentStartTime(e))!=null?n:e),this.warmUpMediaSourceIfNeeded(i),Ie(this.element.buffered,i)||await Promise.all([this.videoBufferManager.abort(),(o=this.audioBufferManager)==null?void 0:o.abort()]),!(CI(this.element)||CI(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),(u=this.audioBufferManager)==null||u.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",xs({requestedPosition:e,forcePrecise:t,position:i})))}warmUpMediaSourceIfNeeded(e=(t=>(t=this.element)==null?void 0:t.currentTime)()){var i;ws(this.element)&&ws(this.source)&&ws(e)&&((i=this.source)==null?void 0:i.readyState)==="ended"&&this.element.duration*1e3-e>this.tuning.dash.seekBiasInTheEnd&&this.bufferManagers.forEach(r=>r.warmUpMediaSource())}get isStreamEnded(){var e;return((e=this.source)==null?void 0:e.readyState)==="ended"}stop(){var e,t,i;this.tracer.log("stop"),(e=this.element)==null||e.querySelectorAll("source").forEach(r=>{URL.revokeObjectURL(r.src),r.remove()}),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(t=this.videoBufferManager)==null||t.destroy(),this.videoBufferManager=null,(i=this.audioBufferManager)==null||i.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){var e;return(e=this.manifest)==null?void 0:e.streams}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){var e;this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),((e=this.source)==null?void 0:e.readyState)==="open"&&Array.from(this.source.sourceBuffers).every(t=>!t.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=o0(this.tracer.error.bind(this.tracer));this.subscription.add(this.error$.subscribe(e("error")))}isManualDecreasePlaybackInLive(){return!this.element||!this.isLive$.getValue()?!1:1-this.element.playbackRate>this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){var e,t;this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&((e=this.bufferManagers)==null||e.forEach(i=>i.updateLive(this.manifest)),(t=this.liveTextManager)==null||t.updateLive(this.manifest)),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getBufferedTo();if(e===null)return;let t=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),i=this.isJumpGapAfterSeekLive,r=this.element.currentTime;this.isJumpGapAfterSeekLive&&!t&&this.element.currentTime>e&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let s=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<=s&&l.to+o>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 u=n+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,u===1/0?this.forceEnded$.next():(this.element.currentTime=u/1e3,this.tracer.log("jumpGap",xs({isJumpGapAfterSeekLive:i,isActiveLowLatency:t,initialCurrentTime:r,jumpTo:u,resultCurrentTime:this.element.currentTime})))}}calculateDurationFromSegments(){var e,t;return Math.max(((e=this.videoBufferManager)==null?void 0:e.calculateDurationFromSegments())||0,((t=this.audioBufferManager)==null?void 0:t.calculateDurationFromSegments())||0)}};import{combine as d0,map as p0,observeElementSize as h0,Subscription as f0,ValueSubject as Pd,noop as m0}from"@vkontakte/videoplayer-shared/es2018";var Qo=class{constructor(){this.subscription=new f0;this.pipSize$=new Pd(void 0);this.videoSize$=new Pd(void 0);this.elementSize$=new Pd(void 0);this.pictureInPictureWindowRemoveEventListener=m0}connect({observableVideo:e,video:t}){let i=r=>{let s=r.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add(h0(t).subscribe(this.videoSize$)).add(e.enterPip$.subscribe(({pictureInPictureWindow:r})=>{this.pipSize$.next({width:r.width,height:r.height}),r.addEventListener("resize",i),this.pictureInPictureWindowRemoveEventListener=()=>{r.removeEventListener("resize",i)}})).add(e.leavePip$.subscribe(()=>{this.pictureInPictureWindowRemoveEventListener()})).add(d0({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(p0(({videoSize:r,inPip: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 I0;this.videoState=new q("stopped");this.observableVideo=null;this.droppedFramesManager=new vr;this.stallsManager=new $o;this.elementSizeManager=new Qo;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Xt;this.audioTrackSwitchHistory=new Xt;this.selectedRepresentations={audio:null,video:null};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(r.state==="requested"&&(i==null?void 0:i.to)!=="paused"&&e!=="stopped"&&t!=="stopped"&&this.seek(r.position,r.forcePrecise),t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),$(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"),$(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="ready"&&$(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):t==="playing"&&this.video.paused?this.playIfAllowed():(i==null?void 0:i.to)==="playing"&&$(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&$(this.params.desiredState.playbackState,"paused");return;default:return g0(e)}}};this.init3DScene=e=>{var i,r,s;if(this.scene3D)return;this.scene3D=new Dr(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((i=e.projectionData)==null?void 0:i.pose.yaw)||0,y:((r=e.projectionData)==null?void 0:r.pose.pitch)||0,z:((s=e.projectionData)==null?void 0:s.pose.roll)||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSizeManager.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.textTracksManager=new Xe(e.source.url),this.params=e,this.video=Me(e.container,e.tuning),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Te(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.player=new jo({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params;T0(this.observableVideo)&&(this.observableVideo=Be(this.video),this.subscription.add(()=>{var n;return(n=this.observableVideo)==null?void 0:n.destroy()}));let i=this.constructor.name,r=n=>{e.error$.next({id:i,category:VI.WTF,message:`${i} internal logic error`,thrown:n})},s=(n,o)=>this.subscription.add(n.subscribe(o,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(Rd(d=>!!d.length),OI()).subscribe(d=>{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:d})}));let n=this.params.desiredState.seekState.stateChangeEnded$.pipe(kd(d=>d.to.state!=="none"),Go());this.stallsManager.init({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$,videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,tuning:this.params.tuning.stallsManager,abrParams:this.params.tuning.autoTrackSelection,isBuffering$:i.isBuffering$,looped$:i.looped$,playing$:i.playing$}),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(this.player.error$,e.error$),s(this.player.fetcherRecoverableError$,e.fetcherRecoverableError$),s(this.player.fetcherError$,e.fetcherError$),s(this.player.lastConnectionType$,e.httpConnectionType$),s(this.player.lastConnectionReused$,e.httpConnectionReused$),s(this.player.isLive$,e.isLive$),s(this.player.lastRequestFirstBytes$.pipe(Rd(_I),OI()),e.firstBytesEvent$),s(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),s(this.videoState.stateChangeEnded$.pipe(kd(d=>d.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(Ce(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Ke(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),s(Je(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),$(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),$(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:d})=>{if(d==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let f=this.player.getStreams();if(S0(f,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let h=[];for(let m of f.audio){h.push(md(m));let b=[];for(let S of m.representations){let y=xI(S);b.push(y),this.audioTracksMap.set(y,{stream:m,representation:S})}this.audioStreamsMap.set(m,b)}this.params.output.availableAudioStreams$.next(h)}let p=[];for(let h of f.video){p.push(bd(h));let m=[];for(let b of h.representations){let S=EI({...b,streamId:h.id});S&&(m.push(S),this.videoTracksMap.set(S,{stream:h,representation:b}))}this.videoStreamsMap.set(h,m)}this.params.output.availableVideoStreams$.next(p);for(let h of f.text)for(let m of h.representations){let b=wI(h,m);this.textTracksMap.set(b,{stream:h,representation:m})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else d==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r));let{vktvAbrThrottle:o}=this.params.tuning.dash,u=o&&RI(o)||null;this.subscription.add(Wo(this.player.currentStallDuration$,this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,this.elementSizeManager.getObservable(),this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,y0(this.video,"progress")).pipe(Rd(()=>this.videoTracksMap.size>0)).subscribe(async()=>{let d=this.player.state$.getState(),f=this.player.state$.getTransition();if(d!=="manifest_ready"&&d!=="running"||f||d==="running"&&u&&!u())return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState()),this.selectVideoAudioRepresentations();let{video:p,audio:h}=this.selectedRepresentations;if(!p)return;let m=Ci(this.videoTracksMap.keys(),S=>{var y;return((y=this.videoTracksMap.get(S))==null?void 0:y.representation.id)===p.id});_I(m)&&(this.stallsManager.lastVideoTrackSelected=m);let b=this.params.desiredState.autoVideoTrackLimits.getTransition();if(b&&this.params.output.autoVideoTrackLimits$.next(b.to),d==="manifest_ready")await this.player.initRepresentations(p.id,h==null?void 0:h.id,this.params.sourceHls);else if(await this.player.switchRepresentation("video",p.id),h){let S=!!t.audioStream.getTransition();await this.player.switchRepresentation("audio",h.id,S)}},r)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:d})=>{this.scene3D&&d&&this.scene3D.pointCameraTo(d.x,d.y)})),this.subscription.add(this.elementSizeManager.subscribe(d=>{this.scene3D&&d&&this.scene3D.setViewportSize(d.width,d.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(Go()).subscribe(d=>{let f=Ci(this.videoTracksMap.entries(),([,{representation:S}])=>S.id===d);if(!f){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[p,{stream:h}]=f,m=this.params.desiredState.videoStream.getTransition();m&&m.to&&m.to.id===h.id&&this.params.desiredState.videoStream.setState(m.to),e.currentVideoTrack$.next(p),e.currentVideoStream$.next(bd(h));let b=this.player.calculateDurationFromSegments();b&&this.params.output.duration$.next(b/1e3)},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(Go()).subscribe(d=>{let f=Ci(this.audioTracksMap.entries(),([,{representation:b}])=>b.id===d);if(!f){e.currentAudioStream$.next(void 0);return}let[p,{stream:h}]=f,m=this.params.desiredState.audioStream.getTransition();m&&m.to&&m.to.id===h.id&&this.params.desiredState.audioStream.setState(m.to),e.currentAudioStream$.next(md(h))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(d=>{var f,p;if(d!=null&&d.is3dVideo&&((f=this.params.tuning.spherical)!=null&&f.enabled))try{this.init3DScene(d),e.is3DVideo$.next(!0)}catch(h){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${h}`})}else this.destroy3DScene(),(p=this.params.tuning.spherical)!=null&&p.enabled&&e.is3DVideo$.next(!1)},r)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,r)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,r)),this.textTracksManager.connect(this.video,t,e);let l=t.playbackState.stateChangeStarted$.pipe(kd(({to:d})=>d==="ready"),Go());this.subscription.add(Wo(l,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,Ld(["init"])).subscribe(()=>{let d=t.autoVideoTrackSwitching.getState(),p=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:d?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(p)})),this.subscription.add(Wo(l,this.player.state$.stateChangeEnded$,Ld(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let c=Wo(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Ld(["init"])).pipe(v0(0));this.subscription.add(c.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){var L,P,R,V,D,_,Y,J,T,k,x,w;if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?xa:Ea,t=this.params.tuning.useNewAutoSelectVideoTrack?eo:Zn,i=this.params.tuning.useNewAutoSelectVideoTrack?vt:Jn,{desiredState:r,output:s}=this.params,n=r.autoVideoTrackSwitching.getState(),o=(L=r.videoTrack.getState())==null?void 0:L.id,u=Ci(this.videoTracksMap.keys(),B=>B.id===o),l=s.currentVideoTrack$.getValue(),c=((V=(R=r.videoStream.getState())!=null?R:u&&((P=this.videoTracksMap.get(u))==null?void 0:P.stream))!=null?V:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!c)return;let d=Ci(this.videoStreamsMap.keys(),B=>B.id===c.id),f=d&&this.videoStreamsMap.get(d);if(!f)return;let p=me(this.video.buffered,this.video.currentTime*1e3),h;this.player.isActiveLive$.getValue()?h=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?h=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:h=n?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let m=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,b=Math.min(p/Math.min(h,m||1/0),1),S=(D=r.audioStream.getState())!=null?D:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,y=(S==null?void 0:S.id)&&Ci(this.audioStreamsMap.keys(),B=>B.id===S.id)||this.audioStreamsMap.keys().next().value,v=0;if(y){if(u&&!n){let B=e(u,f,(_=this.audioStreamsMap.get(y))!=null?_:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);v=Math.max(v,(Y=B==null?void 0:B.bitrate)!=null?Y:-1/0)}if(l){let B=e(l,f,(J=this.audioStreamsMap.get(y))!=null?J:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);v=Math.max(v,(T=B==null?void 0:B.bitrate)!=null?T:-1/0)}}let I=u;(n||!I)&&(I=i(f,{container:this.elementSizeManager.getValue(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.stallsManager.abrTuningParams,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:v,forwardBufferHealth:b,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 E=y&&t(I,f,(k=this.audioStreamsMap.get(y))!=null?k:[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.stallsManager.abrTuningParams,forwardBufferHealth:b,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),A=(x=this.videoTracksMap.get(I))==null?void 0:x.representation,M=E&&((w=this.audioTracksMap.get(E))==null?void 0:w.representation);A&&M?(this.selectedRepresentations.video=A,this.selectedRepresentations.audio=M):A&&!M&&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(){Ve(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),$(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:VI.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),De(this.video),this.tracer.end()}};var As=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 $d,merge as FI,filter as NI,filterChanged as UI,isNullable as Md,map as qI,ValueSubject as Dd,isNonNullable as E0}from"@vkontakte/videoplayer-shared/es2018";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),n(r.timeUpdate$,i.liveBufferTime$),n(this.player.liveSeekableDuration$,i.duration$),n(this.player.liveLatency$,i.liveLatency$);let o=new Dd(1);n(r.playbackRateState$,o),this.params.tuning.dashCmafLive.catchupLiveForMutedInactiveTab&&this.subscription.add(i.elementVisible$.pipe(UI()).subscribe(u=>{let l=i.position$.getValue(),c=i.volume$.getValue(),d=!c.volume||c.muted;!u&&!l&&d?e=!0:u&&e&&(this.seek(0),e=!1)})),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(s.isLowLatency.stateChangeEnded$.pipe(qI(u=>u.to)).subscribe(this.player.isLowLatency$)).add($d({liveBufferTime:i.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(qI(({liveBufferTime:u,liveAvailabilityStartTime:l})=>u&&l?u+l:void 0)).subscribe(i.liveTime$)).add(this.player.liveStreamStatus$.pipe(NI(u=>E0(u))).subscribe(u=>i.isLiveEnded$.next(u!=="active"&&i.position$.getValue()===0))).add($d({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:FI(r.playbackRateState$,new Dd(1))}).pipe(NI(({liveStreamStatus:u,liveDuration:l})=>u==="active"&&!!l)).subscribe(({liveDuration:u,playbackRate:l})=>{let c=i.liveBufferTime$.getValue(),d=i.position$.getValue(),{playbackCatchupSpeedup:f}=this.params.tuning.dashCmafLive.lowLatency;d||l<1-f||this.video.paused||Md(c)||(t=u-c)})).add($d({time:i.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:FI(r.playbackRateState$,new Dd(1))}).pipe(UI((u,l)=>this.player.liveStreamStatus$.getValue()==="active"?u.liveDuration===l.liveDuration:u.time===l.time)).subscribe(({time:u,liveDuration:l,playbackRate:c})=>{let d=i.position$.getValue(),{playbackCatchupSpeedup:f}=this.params.tuning.dashCmafLive.lowLatency;if(!d&&!this.video.paused&&c>=1-f||Md(u)||Md(l))return;let p=-1*(l-u-t);i.position$.next(Math.min(p,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(u=>{if(u){let l=AI(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 HI="X-Playback-Duration",Cd=async a=>{var r;let e=await Ze(a),t=await e.text(),i=(r=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t))==null?void 0:r[1];return i?parseInt(i,10):e.headers.has(HI)?parseInt(e.headers.get(HI),10):void 0};import{assertNever as C0,combine as B0,debounce as V0,ErrorCategory as Ko,filter as _0,filterChanged as O0,isNonNullable as GI,isNullable as Xo,map as WI,merge as F0,observableFrom as N0,Subscription as U0,ValueSubject as _d,VideoQuality as q0}from"@vkontakte/videoplayer-shared/es2018";var Vd=O(vl(),1);import{videoSizeToQuality as x0,getExponentialDelay as w0}from"@vkontakte/videoplayer-shared/es2018";var A0=a=>{let e=null;if(a.QUALITY&&(e=Kt(a.QUALITY)),!e&&a.RESOLUTION){let[t,i]=a.RESOLUTION.split("x").map(r=>parseInt(r,10));e=x0({width:t,height:i})}return e!=null?e:null},P0=(a,e)=>{var s,n;let t=a.split(`
|
|
179
|
+
`),i=[],r=[];for(let o=0;o<t.length;o++){let u=t[o],l=u.match(/^#EXT-X-STREAM-INF:(.+)/),c=u.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!l&&!c)){if(l){let d=(0,Vd.default)(l[1].split(",").map(y=>y.split("="))),f=(s=d.QUALITY)!=null?s:`stream-${d.BANDWIDTH}`,p=A0(d),h;d.BANDWIDTH&&(h=parseInt(d.BANDWIDTH,10)/1e3||void 0),!h&&d["AVERAGE-BANDWIDTH"]&&(h=parseInt(d["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let m=d["FRAME-RATE"]?parseFloat(d["FRAME-RATE"]):void 0,b;if(d.RESOLUTION){let[y,v]=d.RESOLUTION.split("x").map(I=>parseInt(I,10));y&&v&&(b={width:y,height:v})}let S=new URL(t[++o],e).toString();p&&i.push({id:f,quality:p,url:S,bandwidth:h,size:b,fps:m})}if(c){let d=(0,Vd.default)(c[1].split(",").map(m=>{let b=m.indexOf("=");return[m.substring(0,b),m.substring(b+1)]}).map(([m,b])=>[m,b.replace(/^"|"$/g,"")])),f=(n=d.URI)==null?void 0:n.replace(/playlist$/,"subtitles.vtt"),p=d.LANGUAGE,h=d.NAME;f&&p&&r.push({type:"internal",id:p,label:h,language:p,url:f,isAuto:!1})}}}if(!i.length)throw new Error("Empty manifest");return{qualityManifests:i,textTracks:r}},R0=a=>new Promise(e=>{setTimeout(()=>{e()},a)}),Bd=0,jI=async(a,e=a,t,i)=>{let s=await(await Ze(a,i)).text();Bd+=1;try{let{qualityManifests:n,textTracks:o}=P0(s,e);return{qualityManifests:n,textTracks:o}}catch(n){if(Bd<=t.manifestRetryMaxCount)return await R0(w0(Bd-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),jI(a,e,t)}return{qualityManifests:[],textTracks:[]}},zo=jI;import{isNonNullable as k0,Subscription as L0,throttle as $0,ValueSubject as QI,Subject as M0,ErrorCategory as D0}from"@vkontakte/videoplayer-shared/es2018";var Yo=class{constructor(e,t,i,r,s){this.subscription=new L0;this.abortControllers={destroy:new Z,nextManifest:null};this.prepareUrl=void 0;this.currentTextTrackData=null;this.availableTextTracks$=new QI(null);this.getCurrentTime$=new QI(null);this.error$=new M0;this.params={fetchManifestData:i,sourceUrl:r,downloadThreshold:s},this.subscription.add(e.pipe($0(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 Ze(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
|
+
`),s=0;for(let n=0;n<r.length;++n){let o=r[n];switch(!0){case o.startsWith("#EXTINF:"):{let u=r[++n],l=new URL(u,t).toString(),c=Number(this.extractPlaylistRowValue("#EXTINF:",o))*1e3;if(i.segments.push({time:{from:s,to:s+c},url:l}),s=s+c,!i.segmentStartTime){let d=new Date(i.vkStartTime).valueOf(),f=new Date(i.programDateTime).valueOf();i.segmentStartTime=f-d}break}case o.startsWith("#EXT-X-TARGETDURATION:"):i.targetDuration=Number(this.extractPlaylistRowValue("#EXT-X-TARGETDURATION:",o));break;case o.startsWith("#EXT-X-MEDIA-SEQUENCE:"):i.mediaSequence=Number(this.extractPlaylistRowValue("#EXT-X-MEDIA-SEQUENCE:",o));break;case o.startsWith("#EXT-X-VK-PLAYBACK-DURATION:"):i.vkPlaybackDuration=Number(this.extractPlaylistRowValue("#EXT-X-VK-PLAYBACK-DURATION:",o));break;case o.startsWith("#EXT-X-PROGRAM-DATE-TIME:"):{let u=this.extractPlaylistRowValue("#EXT-X-PROGRAM-DATE-TIME:",o);i.programDateTime=u;let l=new Date(u);l.setMilliseconds(0),s=l.valueOf();break}case o.startsWith("#EXT-X-VK-START-TIME:"):i.vkStartTime=this.extractPlaylistRowValue("#EXT-X-VK-START-TIME:",o);break}}return i}extractPlaylistRowValue(e,t){switch(e){case"#EXTINF:":return t.substring(e.length,t.length-1);default:return t.substring(e.length)}}processLiveTime(e){if(k0(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 Z;let{textTracks:e}=await this.fetchManifestData(),t=await this.parseTextTracks(e,this.params.sourceUrl);this.currentTextTrackData&&t&&(this.currentTextTrackData.playlist.segments=t.playlist.segments)}catch(e){this.error("fetchNextManifestData",e)}finally{this.abortControllers.nextManifest=null}}async fetchManifestData(){var t;let e=(t=this.prepareUrl)!=null?t:this.params.sourceUrl;return await this.params.fetchManifestData(e,{signal:this.abortControllers.destroy.signal})}error(e,t){this.error$.next({id:"[LiveTextManager][HLS_LIVE_CMAF]",category:D0.WTF,thrown:t,message:e})}};var Rs=class{constructor(e){this.subscription=new U0;this.videoState=new q("stopped");this.textTracksManager=null;this.liveTextManager=null;this.manifests$=new _d([]);this.liveOffset=new wi;this.manifestStartTime$=new _d(void 0);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),$(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let c=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(c),this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((r==null?void 0:r.to)!=="paused"&&l.state==="requested"){this.videoState.startTransitionTo("ready"),this.seek(l.position&&l.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":i==="ready"?$(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),$(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&$(this.params.desiredState.playbackState,"playing");return;case"paused":if(i==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let c=this.liveOffset.getTotalOffset();c>=this.maxSeekBackTime$.getValue()&&(c=0,this.liveOffset.resetTo(c)),this.liveOffset.resume(),this.params.output.position$.next(-c/1e3),this.prepare()}else(r==null?void 0:r.to)==="paused"&&($(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return C0(t)}};var i;this.params=e,this.video=Me(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:q0.INVARIANT,url:this.params.source.url};let t=(r,s)=>zo(r,this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},s);this.params.tuning.useHlsLiveNewTextManager?this.liveTextManager=new Yo(this.params.output.liveTime$,this.video,t,this.params.source.url,this.params.tuning.hlsLiveNewTextManagerDownloadThreshold):this.textTracksManager=new Xe(e.source.url),t(this.generateLiveUrl()).then(({qualityManifests:r,textTracks:s})=>{var n;r.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:Ko.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),(n=this.liveTextManager)==null||n.processTextTracks(s,this.params.source.url),this.manifests$.next([this.masterManifest,...r])}).catch(r=>{this.params.output.error$.next({id:"ExtractHlsQualities",category:Ko.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:r})}),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Te(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new _d((i=e.source.maxSeekBackTime)!=null?i:1/0),this.subscribe()}selectManifest(){var u,l,c,d;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),s=(d=(c=(u=r==null?void 0:r.to)==null?void 0:u.id)!=null?c:(l=t.getState())==null?void 0:l.id)!=null?d:"master",n=this.manifests$.getValue();if(!n.length)return;let o=i?"master":s;return i&&!r&&t.startTransitionTo(this.masterManifest),n.find(f=>f.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsLiveProvider",category:Ko.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},r=Be(this.video);this.subscription.add(()=>r.destroy());let s=(o,u)=>this.subscription.add(o.subscribe(u,i));s(r.ended$,e.endedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.loadedMetadata$,e.firstBytesEvent$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(Ce(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Ke(this.video,t.playbackRate,r.playbackRateState$,i)),s(Je(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"),$(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),$(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.liveTextManager&&this.subscription.add(this.liveTextManager.availableTextTracks$.subscribe(o=>{o&&this.params.output.availableTextTracks$.next(o)})),this.subscription.add(this.maxSeekBackTime$.pipe(O0(),WI(o=>-o/1e3)).subscribe(this.params.output.duration$,i)),this.subscription.add(r.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&GI(l.to)){let d=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let f=this.manifests$.getValue().find(p=>p.id===d);f&&(this.params.output.currentVideoTrack$.next(f),this.params.output.hostname$.next(Te(f.url)))}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o&&o.state==="requested"&&this.seek(o.position)},i)),this.subscription.add(r.loadedData$.subscribe(()=>{var u,l,c;let o=(c=(l=(u=this.video)==null?void 0:u.getStartDate)==null?void 0:l.call(u))==null?void 0:c.getTime();this.manifestStartTime$.next(o||void 0)},i)),this.subscription.add(B0({startTime:this.manifestStartTime$.pipe(_0(GI)),currentTime:r.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),i)),this.subscription.add(this.manifests$.pipe(WI(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:f})=>({id:u,quality:l,size:c,fps:f,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,i));let n=F0(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,N0(["init"])).pipe(V0(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){var e,t;this.subscription.unsubscribe(),(e=this.textTracksManager)==null||e.destroy(),(t=this.liveTextManager)==null||t.destroy(),this.params.output.element$.next(void 0),De(this.video)}prepare(){var o,u,l;let e=this.selectManifest();if(Xo(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:c,min:d}=(u=(o=t==null?void 0:t.to)!=null?o:i)!=null?u:{};for(let[f,p]of[[c,"mq"],[d,"lq"]]){let h=String(parseFloat(f||""));p&&f&&r.searchParams.set(p,h)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,n=le(r.toString(),this.liveOffset.getTotalOffset(),s);(l=this.liveTextManager)==null||l.prepare(n),this.video.setAttribute("src",n),this.video.load(),Cd(n).then(c=>{var d;if(!Xo(c))this.maxSeekBackTime$.next(c);else{let f=(d=this.params.source.maxSeekBackTime)!=null?d:this.maxSeekBackTime$.getValue();(Xo(f)||!isFinite(f))&&Ze(n).then(p=>p.text()).then(p=>{var m;let h=(m=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(p))==null?void 0:m[1];if(h){let b=new URL(h,n).toString();Cd(b).then(S=>{Xo(S)||this.maxSeekBackTime$.next(S)})}}).catch(()=>{})}})}playIfAllowed(){Ve(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),$(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Ko.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=le(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 H0,debounce as j0,ErrorCategory as Od,fromEvent as Fd,isNonNullable as Q0,isNullable as G0,map as zI,merge as YI,observableFrom as KI,Subscription as W0,ValueSubject as z0,VideoQuality as Y0}from"@vkontakte/videoplayer-shared/es2018";var ks=class{constructor(e){this.subscription=new W0;this.videoState=new q("stopped");this.manifests$=new z0([]);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),$(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let c=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(c);let{currentTime:d}=this.video;this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:d*1e3,forcePrecise:!0});return}switch((r==null?void 0:r.to)!=="paused"&&l.state==="requested"&&this.seek(l.position),t){case"ready":i==="ready"?$(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),$(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&$(this.params.desiredState.playbackState,"playing");return;case"paused":i==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&$(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return H0(t)}};this.textTracksManager=new Xe(e.source.url),this.params=e,this.video=Me(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:Y0.INVARIANT,url:this.params.source.url},this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Te(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),zo(le(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:t,textTracks:i})=>{this.manifests$.next([this.masterManifest,...t]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(i)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:Od.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){var u,l,c,d;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),s=(d=(c=(u=r==null?void 0:r.to)==null?void 0:u.id)!=null?c:(l=t.getState())==null?void 0:l.id)!=null?d:"master",n=this.manifests$.getValue();if(!n.length)return;let o=i?"master":s;return i&&(!r||!r.from)&&t.startTransitionTo(this.masterManifest),n.find(f=>f.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsProvider",category:Od.WTF,message:"HlsProvider internal logic error",thrown:o})},r=Be(this.video);this.subscription.add(()=>r.destroy());let s=(o,u)=>this.subscription.add(o.subscribe(u));if(s(r.timeUpdate$,e.position$),s(r.durationChange$,e.duration$),s(r.ended$,e.endedEvent$),s(r.looped$,e.loopedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.loadedMetadata$,e.firstBytesEvent$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.seeked$,e.seekedEvent$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe(zI(o=>o.to)),this.params.output.playbackState$),this.subscription.add(bt(this.video,t.isLooped,i)),this.subscription.add(Ce(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Ke(this.video,t.playbackRate,r.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),$(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),$(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i).add(r.loadedMetadata$.subscribe(()=>{var p;let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&Q0(l.to)){let h=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let m=this.manifests$.getValue().find(b=>b.id===h);m&&(this.params.output.currentVideoTrack$.next(m),this.params.output.hostname$.next(Te(m.url)))}let d=this.params.desiredState.playbackRate.getState(),f=(p=this.params.output.element$.getValue())==null?void 0:p.playbackRate;if(d!==f){let h=this.params.output.element$.getValue();h&&(this.params.desiredState.playbackRate.setState(d),h.playbackRate=d)}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o.state==="requested"&&this.seek(o.position)},i))),this.subscription.add(this.manifests$.pipe(zI(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:f})=>({id:u,quality:l,size:c,fps:f,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,i)),!N.device.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(YI(Fd(o,"addtrack"),Fd(o,"removetrack"),Fd(o,"change"),KI(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},i))}let n=YI(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,KI(["init"])).pipe(j0(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),De(this.video)}prepare(){var s,n;let e=this.selectManifest();if(G0(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:o,min:u}=(n=(s=t==null?void 0:t.to)!=null?s:i)!=null?n:{};for(let[l,c]of[[o,"mq"],[u,"lq"]]){let d=String(parseFloat(l||""));c&&l&&r.searchParams.set(c,d)}}this.video.setAttribute("src",r.toString()),this.video.load()}playIfAllowed(){Ve(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),$(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Od.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var ZI=O(er(),1),Nd=O(dr(),1),eE=O(ot(),1);import{assertNever as K0,assertNonNullable as XI,debounce as X0,ErrorCategory as JI,isHigherOrEqual as J0,isLowerOrEqual as Z0,isNonNullable as eV,merge as tV,observableFrom as iV,Subscription as rV,map as aV}from"@vkontakte/videoplayer-shared/es2018";var Ls=class{constructor(e){this.subscription=new rV;this.videoState=new q("stopped");this.trackUrls={};this.textTracksManager=new Xe;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"),$(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.autoVideoTrackLimits.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.seekState.getState();if(s&&e!=="ready"&&!n){this.handleQualityLimitTransition(s.to);return}if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(n){let{currentTime:u}=this.video;this.prepare(),o.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:u*1e3,forcePrecise:!0});return}switch((i==null?void 0:i.to)!=="paused"&&o.state==="requested"&&this.seek(o.position),e){case"ready":t==="ready"?$(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),$(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(i==null?void 0:i.to)==="playing"&&$(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&$(this.params.desiredState.playbackState,"paused");return;default:return K0(e)}};this.params=e,this.video=Me(e.container,e.tuning),this.params.output.element$.next(this.video),(0,ZI.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,Nd.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:JI.WTF,message:"MpegProvider internal logic error",thrown:o})},r=Be(this.video);this.subscription.add(()=>r.destroy());let s=(o,u)=>this.subscription.add(o.subscribe(u,i));s(r.timeUpdate$,e.position$),s(r.durationChange$,e.duration$),s(r.ended$,e.endedEvent$),s(r.looped$,e.loopedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.loadedMetadata$,e.firstBytesEvent$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.seeked$,e.seekedEvent$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe(aV(o=>o.to)),this.params.output.playbackState$),this.subscription.add(bt(this.video,t.isLooped,i)),this.subscription.add(Ce(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Ke(this.video,t.playbackRate,r.playbackRateState$,i)),s(Je(this.video),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),$(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),$(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var u,l;((u=this.videoState.getTransition())==null?void 0:u.to)==="ready"&&this.videoState.setState("ready");let o=this.params.desiredState.videoTrack.getTransition();if(o&&eV(o.to)){this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to.id].track);let c=this.params.desiredState.playbackRate.getState(),d=(l=this.params.output.element$.getValue())==null?void 0:l.playbackRate;if(c!==d){let f=this.params.output.element$.getValue();f&&(this.params.desiredState.playbackRate.setState(c),f.playbackRate=c)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.textTracksManager.connect(this.video,t,e);let n=tV(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,iV(["init"])).pipe(X0(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),De(this.video)}prepare(){var i;let e=(i=this.params.desiredState.videoTrack.getState())==null?void 0:i.id;XI(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];XI(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=ei(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(Te(t))}playIfAllowed(){Ve(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),$(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:JI.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){var l,c;this.params.output.autoVideoTrackLimits$.next(e);let t=d=>{this.params.output.currentVideoTrack$.next(d),this.params.desiredState.videoTrack.startTransitionTo(d)},i=d=>{let f=vt(n,{container:this.video.getBoundingClientRect(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,limits:d,abrLogger:this.params.dependencies.abrLogger});t(f)},r=(l=this.params.output.currentVideoTrack$.getValue())==null?void 0:l.quality,s=!!(e.max||e.min),n=(0,Nd.default)(this.trackUrls).map(d=>d.track);if(!r||!s||fr(e,n[0].quality,(c=(0,eE.default)(n,-1))==null?void 0:c.quality)){i();return}let o=e.max?Z0(r,e.max):!0,u=e.min?J0(r,e.min):!0;o&&u||i(e)}};import{assertNever as iE,debounce as uV,merge as rE,observableFrom as lV,Subscription as cV,map as aE,ValueSubject as dV,ErrorCategory as qd,VideoQuality as pV}from"@vkontakte/videoplayer-shared/es2018";import{ErrorCategory as sV}from"@vkontakte/videoplayer-shared/es2018";var tE=["stun:videostun.mycdn.me:80"],nV=1e3,oV=3,Ud=()=>null,Jo=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=Ud;this.externalStopCallback=Ud;this.externalErrorCallback=Ud;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:tE}]};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:sV.WTF,message:e.message})}async onPeerConnectionStream(e){let t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){let e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}async createOffer(){let e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");let t=await this.peerConnection.createOffer(e),i=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(i))throw new Error("No h264 codec support error");return t}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch(t){throw new Error("Can not parse socket message")}}closeConnections(){let e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),nV)}normalizeOptions(e={}){let t={stunServerList:tE,maxRetryNumber:oV,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var $s=class{constructor(e){this.videoState=new q("stopped");this.maxSeekBackTime$=new dV(0);this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.pause(),this.video.srcObject=null,this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),$(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"),$(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(i==null?void 0:i.to)==="playing"&&$(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&$(this.params.desiredState.playbackState,"paused");return;default:return iE(e)}};this.subscription=new cV,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=Me(e.container,e.tuning),this.liveStreamClient=new Jo(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),De(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,i=n=>{e.error$.next({id:"WebRTCLiveProvider",category:qd.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};this.subscription.add(rE(this.videoState.stateChangeStarted$.pipe(aE(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(aE(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})}));let r=Be(this.video);this.subscription.add(()=>r.destroy());let s=(n,o)=>this.subscription.add(n.subscribe(o,i));s(r.timeUpdate$,e.liveTime$),s(r.ended$,e.endedEvent$),s(r.looped$,e.loopedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(Je(this.video),this.params.output.elementVisible$),this.subscription.add(r.durationChange$.subscribe(n=>{e.duration$.next(n===1/0?0:n)})).add(r.canplay$.subscribe(()=>{var n;((n=this.videoState.getTransition())==null?void 0:n.to)==="ready"&&this.videoState.setState("ready")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused")},i)).add(r.playing$.subscribe(()=>{this.videoState.setState("playing")},i)).add(r.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(Ce(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 iE(n.to)}},i)).add(rE(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,lV(["init"])).pipe(uV(0)).subscribe(this.syncPlayback.bind(this),i)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),i))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(Te(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.currentVideoTrack$.next({id:"webrtc",quality:pV.INVARIANT}),this.video.srcObject=e,$(this.params.desiredState.playbackState,"playing")}onLiveStreamStop(){this.videoState.startTransitionTo("stopped"),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.params.output.endedEvent$.next()}onLiveStreamError(e){this.onLiveStreamStop(),this.params.output.error$.next({id:"WebRTC stream runtime error",category:qd.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){Ve(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),$(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:qd.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var Ms=class{constructor(e){this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next()}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return!!this.current.done}};import{assertNever as Cs,assertNonNullable as ri,ErrorCategory as Zo,filter as cE,isNonNullable as dE,isNullable as vV,map as yV,merge as TV,once as IV,Subject as be,Subscription as pE,ValueSubject as H,flattenObject as Hd}from"@vkontakte/videoplayer-shared/es2018";import{Observable as hV,map as sE,Subscription as fV,Subject as mV}from"@vkontakte/videoplayer-shared/es2018";var nE=a=>new hV(e=>{let t=new fV,i=a.desiredPlaybackState$.stateChangeStarted$.pipe(sE(({from:l,to:c})=>`${l}-${c}`)),r=a.desiredPlaybackState$.stateChangeEnded$,s=a.providerChanged$.pipe(sE(({type:l})=>l!==void 0)),n=new mV,o=0,u="unknown";return t.add(i.subscribe(l=>{o&&window.clearTimeout(o),u=l,o=window.setTimeout(()=>n.next(l),a.maxTransitionInterval)})),t.add(r.subscribe(()=>{window.clearTimeout(o),u="unknown",o=0})),t.add(s.subscribe(l=>{o&&(window.clearTimeout(o),o=0,l&&(o=window.setTimeout(()=>n.next(u),a.maxTransitionInterval)))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});import{ErrorCategory as bV,Subscription as gV,combine as SV,filter as uE,once as lE}from"@vkontakte/videoplayer-shared/es2018";function oE(){return new(window.AudioContext||window.webkitAudioContext)}var Ds=class Ds{constructor(e,t,i,r){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=i;this.volumeMultiplier=r;this.destroyController=new Z;this.subscriptions=new gV;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe(uE(s=>!!s.type),lE()).subscribe(({type:s})=>this.subscribe(s)))}subscribe(e){N.browser.isSafari&&e!=="MPEG"||this.subscriptions.add(SV({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(uE(({playbackState:t,video:i,volume:{muted:r,volume:s}})=>t==="playing"&&!!i&&!r&&!!s),lE()).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=oE();this.audioContext=i;let r=i.createGain();if(this.gainNode=r,r.gain.value=t,r.connect(i.destination),i.state==="suspended"&&(await i.resume(),this.destroyController.signal.aborted))return!1;let s=i.createMediaElementSource(e);return this.mediaElementSource=s,s.connect(r),!0}cleanup(){this.mediaElementSource&&(this.mediaElementSource.disconnect(),this.mediaElementSource=null),this.gainNode&&(this.gainNode.disconnect(),this.gainNode=null),this.audioContext&&(this.audioContext.state!=="closed"&&this.audioContext.close(),this.audioContext=null)}destroy(){this.destroyController.abort(),this.subscriptions.unsubscribe(),this.cleanup()}handleError(e){var t;this.volumeMultiplierError$.next({id:Ds.errorId,category:bV.VIDEO_PIPELINE,message:(t=e==null?void 0:e.message)!=null?t:`${Ds.errorId} exception`,thrown:e})}};Ds.errorId="VolumeMultiplierManager";var Fr=Ds;var EV={chunkDuration:5e3,maxParallelRequests:5},Bs=class{constructor(e){this.current$=new H({type:void 0});this.providerError$=new be;this.noAvailableProvidersError$=new be;this.volumeMultiplierError$=new be;this.providerOutput={position$:new H(0),duration$:new H(1/0),volume$:new H({muted:!1,volume:1}),availableVideoStreams$:new H([]),currentVideoStream$:new H(void 0),availableVideoTracks$:new H([]),currentVideoTrack$:new H(void 0),availableAudioStreams$:new H([]),currentAudioStream$:new H(void 0),availableAudioTracks$:new H([]),currentVideoSegmentLength$:new H(0),currentAudioSegmentLength$:new H(0),isAudioAvailable$:new H(!0),autoVideoTrackLimitingAvailable$:new H(!1),autoVideoTrackLimits$:new H(void 0),currentBuffer$:new H(void 0),isBuffering$:new H(!0),error$:new be,fetcherError$:new be,fetcherRecoverableError$:new be,warning$:new be,willSeekEvent$:new be,soundProhibitedEvent$:new be,seekedEvent$:new be,loopedEvent$:new be,endedEvent$:new be,firstBytesEvent$:new be,loadedMetadataEvent$:new be,firstFrameEvent$:new be,canplay$:new be,isLive$:new H(void 0),isLiveEnded$:new H(null),isLowLatency$:new H(!1),canChangePlaybackSpeed$:new H(!0),liveTime$:new H(void 0),liveBufferTime$:new H(void 0),liveLatency$:new H(void 0),severeStallOccurred$:new be,availableTextTracks$:new H([]),currentTextTrack$:new H(void 0),hostname$:new H(void 0),httpConnectionType$:new H(void 0),httpConnectionReused$:new H(void 0),inPiP$:new H(!1),inFullscreen$:new H(!1),element$:new H(void 0),elementVisible$:new H(!0),availableSources$:new H(void 0),is3DVideo$:new H(!1),playbackState$:new H(""),getCurrentTime$:new H(null)};this.subscription=new pE;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=tI([...rI(this.params.tuning),...iI(this.params.tuning)],this.params.tuning).filter(l=>dE(e.sources[l])),{forceFormat:i,formatsToAvoid:r}=this.params.tuning,s=[];i?s=[i]:r.length?s=[...t.filter(l=>!(0,jd.default)(r,l)),...t.filter(l=>(0,jd.default)(r,l))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",Hd(s)),this.screenFormatsIterator=new Ms(s);let n=[...Kc(!0),...Kc(!1)];this.chromecastFormatsIterator=new Ms(n.filter(l=>dE(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:o=1,tuning:{useVolumeMultiplier:u}}=this.params;u&&o!==1&&Fr.isSupported()&&(this.volumeMultiplierManager=new Fr(this.providerOutput,this.current$,this.volumeMultiplierError$,o))}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()}))}destroy(){var e;this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe(),(e=this.volumeMultiplierManager)==null||e.destroy(),this.volumeMultiplierManager=null,this.tracer.end()}initProvider(){let e=this.chooseDestination(),t=this.chooseFormat(e);if(vV(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:Zo.WTF,message:"Failed to create provider",thrown:r})}i?this.current$.next({type:t,provider:i,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.tracer.log("reinitProvider"),this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.tracer.log("switchToNextProvider",{destination:e}),this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}destroyProvider(){let e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"}),this.tracer.log("destroyProvider"),e.destroy();let t=this.providerOutput.position$.getValue()*1e3,i=this.params.desiredState.seekState.getState(),r=i.state!=="none";if(this.params.desiredState.seekState.setState({state:"requested",position:r?i.position:t,forcePrecise:r?i.forcePrecise:!1}),e.scene3D){let n=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:n.x,y:n.y})}let s=this.providerOutput.isBuffering$;s.getValue()||s.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),this.tracer.log("createProvider",{destination:e,format:t}),e){case"SCREEN":return this.createScreenProvider(t);case"CHROMECAST":return this.createChromecastProvider(t);default:return Cs(e)}}createScreenProvider(e){let{sources:t,container:i,desiredState:r,panelSize:s}=this.params,n=this.providerOutput,o={container:i,source:null,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning,panelSize:s};switch(e){case"DASH_SEP":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_ONDEMAND":case"DASH_STREAMS":{let u=this.applyFailoverHost(t[e]),l=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return ri(u),this.params.tuning.useNewDashProvider?new As({...o,source:u,sourceHls:l}):new bs({...o,source:u,sourceHls:l})}case"DASH_LIVE_CMAF":{let u=this.applyFailoverHost(t[e]);return ri(u),this.params.tuning.useNewDashProvider?new Ps({...o,source:u}):new gs({...o,source:u})}case"HLS":case"HLS_ONDEMAND":{let u=this.applyFailoverHost(t[e]);return ri(u),new ks({...o,source:u})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let u=this.applyFailoverHost(t[e]);return ri(u),new Rs({...o,source:u,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let u=this.applyFailoverHost(t[e]);return ri(u),new Ls({...o,source:u})}case"DASH_LIVE":{let u=this.applyFailoverHost(t[e]);return ri(u),new Wv({...o,source:u,config:{...EV,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let u=this.applyFailoverHost(t[e]);return ri(u),new $s({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 Cs(e)}}createChromecastProvider(e){let{sources:t,container:i,desiredState:r,meta:s}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return ri(o),new ga({connection:o,meta:s,container:i,source:t,format:e,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?"CHROMECAST":"SCREEN"}chooseFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case"CHROMECAST":return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return Cs(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return Cs(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 Cs(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,fE.default)((0,hE.default)(e).map(([r,s])=>[r,i(s)]))}initProviderErrorHandling(){let e=new pE,t=!1,i=0;return e.add(TV(this.providerOutput.error$.pipe(cE(r=>!this.params.tuning.ignoreAudioRendererError||!r.message||!/AUDIO_RENDERER_ERROR/ig.test(r.message))),nE({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(yV(r=>({id:`ProviderHangup:${r}`,category:Zo.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(cE(({to:s})=>s==="playing"),IV()).subscribe(()=>t=!0);e.add(r)})),e.add(this.providerError$.subscribe(r=>{let s=this.current$.getValue().destination,n={error:r,currentDestination:s};if(s==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("SCREEN"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let o=r.category===Zo.NETWORK,u=r.category===Zo.FATAL,l=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),c=i<this.params.tuning.providerErrorLimit&&!u,d=l&&!u&&(o&&t||!c);n={...n,isNetworkError:o,isFatalError:u,haveFailoverHost:l,tryFailover:d,canReinitProvider:c},c?(i++,this.reinitProvider()):d?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):(i=0,this.switchToNextProvider(s!=null?s:"SCREEN"))}r.traceAsLog?this.tracer.log("providerInfo",Hd(n)):this.tracer.error("providerError",Hd(n))})),e}};import{fromEvent as eu,once as xV,combine as wV,Subscription as mE,ValueSubject as Qd,map as AV,filter as PV,isNonNullable as tu,now as We,safeStorage as Gd}from"@vkontakte/videoplayer-shared/es2018";var RV=5e3,bE="one_video_throughput",gE="one_video_rtt",Vt=window.navigator.connection,SE=()=>{let a=Vt==null?void 0:Vt.downlink;if(tu(a)&&a!==10)return a*1e3},vE=()=>{let a=Vt==null?void 0:Vt.rtt;if(tu(a)&&a!==3e3)return a},yE=(a,e,t)=>{let i=t*8,r=i/a;return i/(r+e)},Wd=class a{constructor(e){this.subscription=new mE;this.concurrentDownloads=new Set;var r,s;this.tuningConfig=e;let t=a.load(bE)||(e.useBrowserEstimation?SE():void 0)||RV,i=(s=(r=a.load(gE))!=null?r:e.useBrowserEstimation?vE():void 0)!=null?s:0;if(this.throughput$=new Qd(t),this.rtt$=new Qd(i),this.rttAdjustedThroughput$=new Qd(yE(t,i,e.rttPenaltyRequestSize)),this.throughput=Ct.getSmoothedValue(t,-1,e),this.rtt=Ct.getSmoothedValue(i,1,e),e.useBrowserEstimation){let n=()=>{let u=SE();u&&this.throughput.next(u);let l=vE();tu(l)&&this.rtt.next(l)};Vt&&"onchange"in Vt&&this.subscription.add(eu(Vt,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{Gd.set(bE,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{Gd.set(gE,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(wV({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(AV(({throughput:n,rtt:o})=>yE(n,o,e.rttPenaltyRequestSize)),PV(n=>{let o=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(n-o)/o>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,i=We(),r=new mE;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add(eu(e,"progress").pipe(xV()).subscribe(s=>{t=s.loaded,i=We()}));break;case 1:case 0:r.add(eu(e,"loadstart").subscribe(()=>{t=0,i=We()}));break}r.add(eu(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=We(),u=n-t,l=o-i;this.addRawSpeed(u,l,1)}this.concurrentDownloads.delete(e),r.unsubscribe()}))}trackStream(e,t=!1){let i=e.getReader();if(!i){e.cancel("Could not get reader");return}let r=0,s=We(),n=0,o=We(),u=c=>{this.concurrentDownloads.delete(e),i.releaseLock(),e.cancel(`Throughput Estimator error: ${c}`).catch(()=>{})},l=async({done:c,value:d})=>{if(c)!t&&this.addRawSpeed(r,We()-s,1),this.concurrentDownloads.delete(e);else if(d){if(t){let f=We();if(f-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||f-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let h=o-s;h&&this.addRawSpeed(n,h,1,t),n=d.byteLength,s=We()}else n+=d.byteLength;o=We()}else r+=d.byteLength,n+=d.byteLength,n>=this.tuningConfig.streamMinSampleSize&&We()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,We()-o,this.concurrentDownloads.size),n=0,o=We());await(i==null?void 0:i.read().then(l,u))}};this.concurrentDownloads.add(e),i==null||i.read().then(l,u)}addRawSpeed(e,t,i=1,r=!1){if(a.sanityCheck(e,t,r)){let s=e*8/t;this.throughput.next(s*i)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,i=!1){let r=e*8/t;return!(!r||!isFinite(r)||r>1e6||r<30||i&&e<1e4||!i&&e<10*1024||!i&&t<=20)}static load(e){var i;let t=Gd.get(e);if(tu(t))return(i=parseInt(t,10))!=null?i:void 0}},TE=Wd;import{fillWithDefault as kV,VideoQuality as iu}from"@vkontakte/videoplayer-shared/es2018";var IE={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:iu.Q_4320P,activeVideoAreaThreshold:.1,highQualityLimit:iu.Q_720P,trafficSavingLimit:iu.Q_480P},stallsManager:{enabled:!1,stallDurationNoDataBeforeQualityDecrease:500,stallDurationToBeCount:100,stallCountBeforeQualityDecrease:3,resetQualityRestrictionTimeout:1e4,ignoreStallsOnSeek:!0,stallsMetricsHistoryLength:5,maxPossibleStallDuration:3e4,minTvtToBeCounted:5,maxTvtToBeCounted:10800,significantTvt:600,targetStallsDurationPerTvt:1,deviationStallsDurationPerTvt:.5,criticalStallsDurationPerTvt:6,abrAdjustingSpeed:.1,emaAlpha:.6,useTotalStallsDurationPerTvt:!0,useAverageStallsDurationPerTvt:!0,useEmaStallsDurationPerTvt:!0},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:iu.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,seekBiasInTheEnd:2e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,crashOnStallTimeout:25e3,crashOnStallTWithoutDataTimeout:5e3,enableSubSegmentBufferFeeding:!0,bufferEmptinessTolerance:100,useFetchPriorityHints:!0,enableBaseUrlSupport:!0,maxSegmentRetryCount:5,sourceOpenTimeout:1e3,vktvAbrThrottle:0,timeupdateEventTickThrottle:300,fetcherBufferOptimisation:!0},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,maxLiveDuration:7200,catchupLiveForMutedInactiveTab:!0,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:250,playbackCatchupSpeedup:.05,isActiveOnDefault:!1,bufferEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:"07A4434E",useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"dash",preferCMAF:!1,preferWebRTC:!1,preferMultiStream:!1,preferHDR:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,seekNearDurationBias:1,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useHlsJs:!1,useNativeHLSTextTracks:!1,useManagedMediaSource:!0,useNewSwitchTo:!1,useNewDashProvider:!1,useNewAutoSelectVideoTrack:!1,useSafariEndlessRequestBugfix:!0,useRefactoredSearchGap:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,audioVideoSyncRate:20,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50},useVolumeMultiplier:!1,ignoreAudioRendererError:!1,useEnableSubtitlesParam:!1,useOldMSEDetection:!1,useHlsLiveNewTextManager:!1,exposeInternalsToGlobal:!1,hlsLiveNewTextManagerDownloadThreshold:4e3,disableYandexPiP:!1,asyncResolveClientChecker:!1,autostartOnlyIfVisible:!1},EE=a=>{var e;return{...kV(a,IE),configName:[...(e=a.configName)!=null?e:[],...IE.configName]}};import{assertNonNullable as ru,combine as _t,ErrorCategory as au,filter as U,filterChanged as z,fromEvent as Yd,isNonNullable as PE,isNullable as VV,Logger as _V,map as G,mapTo as RE,merge as ai,now as su,once as j,Subject as K,Subscription as kE,tap as Kd,ValueSubject as C,isHigher as OV,isInvariantQuality as LE,flattenObject as si,throttle as Xd,getTraceSubscriptionMethod as $E,TracerFactory as FV,InternalsExposure as NV}from"@vkontakte/videoplayer-shared/es2018";import{merge as LV,map as $V,filter as xE,isNonNullable as MV}from"@vkontakte/videoplayer-shared/es2018";var zd=({seekState:a,position$:e})=>LV(a.stateChangeEnded$.pipe($V(({to:t})=>{var i;return t.state==="none"?void 0:((i=t.position)!=null?i:NaN)/1e3}),xE(MV)),e.pipe(xE(()=>a.getState().state==="none")));import{assertNonNullable as DV}from"@vkontakte/videoplayer-shared/es2018";var wE=a=>{let e=typeof a.container=="string"?document.getElementById(a.container):a.container;return DV(e,`Wrong container or containerId {${a.container}}`),e};import{filter as CV,once as BV}from"@vkontakte/videoplayer-shared/es2018";var AE=(a,e,t,i)=>{a!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&(t==null?void 0:t.getValue().length)===0?t.pipe(CV(r=>r.length>0),BV()).subscribe(r=>{r.find(i)&&e.startTransitionTo(a)}):(a===void 0||t!=null&&t.getValue().find(i))&&e.startTransitionTo(a)};var nu=class{constructor(e={configName:[]},t=FV.createRootTracer(!1)){this.subscription=new kE;this.logger=new _V;this.abrLogger=this.logger.createComponentLog("ABR");this.internalsExposure=null;this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new C(!1);this.hasLiveOffsetByPausedTimer=0;this.playerInitRequest=0;this.playerInited=new C(!1);this.wasSetStartedQuality=!1;this.desiredState={playbackState:new q("stopped"),seekState:new q({state:"none"}),volume:new q({volume:1,muted:!1}),videoTrack:new q(void 0),videoStream:new q(void 0),audioStream:new q(void 0),autoVideoTrackSwitching:new q(!0),autoVideoTrackLimits:new q({}),isLooped:new q(!1),isLowLatency:new q(!1),playbackRate:new q(1),externalTextTracks:new q([]),internalTextTracks:new q([]),currentTextTrack:new q(void 0),textTrackCuesSettings:new q({}),cameraOrientation:new q({x:0,y:0})};this.info={playbackState$:new C(void 0),position$:new C(0),duration$:new C(1/0),muted$:new C(!1),volume$:new C(1),availableVideoStreams$:new C([]),currentVideoStream$:new C(void 0),availableQualities$:new C([]),availableQualitiesFps$:new C({}),currentQuality$:new C(void 0),isAutoQualityEnabled$:new C(!0),autoQualityLimitingAvailable$:new C(!1),autoQualityLimits$:new C({}),predefinedQualityLimitType$:new C("unknown"),availableAudioStreams$:new C([]),currentAudioStream$:new C(void 0),availableAudioTracks$:new C([]),isAudioAvailable$:new C(!0),currentPlaybackRate$:new C(1),currentBuffer$:new C({start:0,end:0}),isBuffering$:new C(!0),isStalled$:new C(!1),isEnded$:new C(!1),isLooped$:new C(!1),isLive$:new C(void 0),isLiveEnded$:new C(null),canChangePlaybackSpeed$:new C(void 0),atLiveEdge$:new C(void 0),atLiveDurationEdge$:new C(void 0),liveTime$:new C(void 0),liveBufferTime$:new C(void 0),liveLatency$:new C(void 0),currentFormat$:new C(void 0),availableTextTracks$:new C([]),currentTextTrack$:new C(void 0),throughputEstimation$:new C(void 0),rttEstimation$:new C(void 0),videoBitrate$:new C(void 0),hostname$:new C(void 0),httpConnectionType$:new C(void 0),httpConnectionReused$:new C(void 0),surface$:new C("none"),chromecastState$:new C("NOT_AVAILABLE"),chromecastDeviceName$:new C(void 0),intrinsicVideoSize$:new C(void 0),availableSources$:new C(void 0),is3DVideo$:new C(!1),currentVideoSegmentLength$:new C(0),currentAudioSegmentLength$:new C(0)};this.events={inited$:new K,ready$:new K,started$:new K,playing$:new K,paused$:new K,stopped$:new K,willReady$:new K,willStart$:new K,willResume$:new K,willPause$:new K,willStop$:new K,willDestruct$:new K,watchCoverageRecord$:new K,watchCoverageLive$:new K,managedError$:new K,fatalError$:new K,fetcherRecoverableError$:new K,ended$:new K,looped$:new K,seeked$:new K,willSeek$:new K,autoplaySoundProhibited$:new K,firstBytes$:new K,loadedMetadata$:new K,firstFrame$:new K,canplay$:new K,log$:new K,fetcherError$:new K,severeStallOccured$:new K};this.experimental={element$:new C(void 0),tuningConfigName$:new C([]),enableDebugTelemetry$:new C(!1),dumpTelemetry:vv,getCurrentTime$:new C(null)};if(this.initLogs(),this.tuning=EE(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new rn({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new TE(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new NV("CORE"),this.internalsExposure.expose({player:this})),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(i,r,s)=>{let n=Reflect.get(i,r,s);return typeof n!="function"?n:(...o)=>{try{return n.apply(i,o)}catch(u){let l=o.map(f=>JSON.stringify(f,(p,h)=>{let m=typeof h;return(0,ME.default)(["number","string","boolean"],m)?h:h===null?null:`<${m}>`})),c=`Player.${String(r)}`,d=`Exception calling ${c} (${l.join(", ")})`;throw this.events.fatalError$.next({id:c,category:au.WTF,message:d,thrown:u}),u}}}})}initVideo(e){var s;this.config=e,(s=this.internalsExposure)==null||s.expose({config:e,logger:this.logger,tuning:this.tuning}),this.setMuted(this.tuning.isAudioDisabled);let t=()=>{var u,l,c;let{container:n,...o}=e;this.tracer.log("initVideo",si(o)),this.domContainer=wE(e),this.chromecastInitializer.contentId=(u=e.meta)==null?void 0:u.videoId,this.providerContainer=new Bs({sources:e.sources,meta:(l=e.meta)!=null?l:{},failoverHosts:(c=e.failoverHosts)!=null?c:[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,tracer:this.tracer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning,volumeMultiplier:e.volumeMultiplier,panelSize:e.panelSize}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.initTracerSubscription(),this.providerContainer.init(),this.setLiveLowLatency(this.tuning.dashCmafLive.lowLatency.isActiveOnDefault),this.initDebugTelemetry(),this.initWakeLock(),this.playerInited.next(!0)},i=()=>{this.tuning.autostartOnlyIfVisible&&window.requestAnimationFrame?this.playerInitRequest=window.requestAnimationFrame(()=>t()):t()},r=()=>{this.tuning.asyncResolveClientChecker?N.isInited$.pipe(U(n=>!!n),j()).subscribe(()=>{console.log("Core SDK async start"),i()}):i()};return this.isNotActiveTabCase()?(this.tracer.log("request play from hidden tab"),Yd(document,"visibilitychange").pipe(j()).subscribe(r)):r(),this}destroy(){var e,t;this.tracer.log("destroy"),window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.playerInitRequest&&window.cancelAnimationFrame(this.playerInitRequest),this.events.willDestruct$.next(),this.stop(),(e=this.providerContainer)==null||e.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe(),this.tracer.end(),(t=this.internalsExposure)==null||t.destroy()}prepare(){return this.subscription.add(this.playerInited.pipe(U(e=>!!e),j()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("prepare",{currentPlayBackState:e.getState()}),e.getState()==="stopped"&&e.startTransitionTo("ready")})),this}play(){return this.subscription.add(this.playerInited.pipe(U(e=>!!e),j()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("play",{currentPlayBackState:e.getState()}),e.getState()!=="playing"&&e.startTransitionTo("playing")})),this}pause(){return this.subscription.add(this.playerInited.pipe(U(e=>!!e),j()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("pause",{currentPlayBackState:e.getState()}),e.getState()!=="paused"&&e.startTransitionTo("paused")})),this}stop(){return this.subscription.add(this.playerInited.pipe(U(e=>!!e),j()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("stop",{currentPlayBackState:e.getState()}),e.getState()!=="stopped"&&e.startTransitionTo("stopped")})),this}seekTime(e,t=!0){return this.subscription.add(this.playerInited.pipe(U(i=>!!i),j()).subscribe(()=>{let i=this.info.duration$.getValue(),r=this.info.isLive$.getValue(),s=e;e>=i&&!r&&(s=i-this.tuning.seekNearDurationBias),this.tracer.log("seekTime",{duration:i,isLive:r,time:e,calculatedTime:s,forcePrecise:t}),Number.isFinite(s)&&(this.events.willSeek$.next({from:this.getExactTime(),to:s}),this.desiredState.seekState.setState({state:"requested",position:s*1e3,forcePrecise:t}))})),this}seekPercent(e){return this.subscription.add(this.playerInited.pipe(U(t=>!!t),j()).subscribe(()=>{let t=this.info.duration$.getValue();this.tracer.log("seekPercent",{percent:e,duration:t}),isFinite(t)&&this.seekTime(Math.abs(t)*e,!1)})),this}setVolume(e,t){return this.subscription.add(this.playerInited.pipe(U(i=>!!i),j()).subscribe(()=>{var o;let i=this.desiredState.volume,r=i.getTransition(),s=(o=r==null?void 0:r.to.muted)!=null?o:this.info.muted$.getValue(),n=t!=null?t:this.tuning.isAudioDisabled||s;this.tracer.log("setVolume",{volume:e,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:n}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setVolume(e):i.startTransitionTo({volume:e,muted:n})})),this}setMuted(e,t=!1){return this.subscription.add(this.playerInited.pipe(U(i=>!!i),j()).subscribe(()=>{var o;let i=this.desiredState.volume,r=this.tuning.isAudioDisabled&&!t||e,s=i.getTransition(),n=(o=s==null?void 0:s.to.volume)!=null?o:this.info.volume$.getValue();this.tracer.log("setMuted",{isMuted:e,nextMuted:r,volume:n,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue()}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setMuted(r):i.startTransitionTo({volume:n,muted:r})})),this}setVideoStream(e){return this.subscription.add(this.playerInited.pipe(U(t=>!!t),j()).subscribe(()=>{this.desiredState.videoStream.startTransitionTo(e)})),this}setAudioStream(e){return this.subscription.add(this.playerInited.pipe(U(t=>!!t),j()).subscribe(()=>{this.desiredState.audioStream.startTransitionTo(e)})),this}setQuality(e){return this.subscription.add(this.playerInited.pipe(U(t=>!!t),j()).subscribe(()=>{ru(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(U(i=>i.length>0),j()).subscribe(i=>{this.setVideoTrackIdByQuality(i,e)}):this.explicitInitialQuality=e:t.length>0&&this.setVideoTrackIdByQuality(t,e)})),this}setAutoQuality(e){return this.subscription.add(this.playerInited.pipe(U(t=>!!t),j()).subscribe(()=>{this.tracer.log("setAutoQuality",{enable:e}),this.desiredState.autoVideoTrackSwitching.startTransitionTo(e)})),this}setAutoQualityLimits(e){return this.subscription.add(this.playerInited.pipe(U(t=>!!t),j()).subscribe(()=>{this.tracer.log("setAutoQualityLimits",si(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e)})),this}setPredefinedQualityLimits(e){return this.subscription.add(this.playerInited.pipe(U(t=>!!t),j()).subscribe(()=>{if(this.info.predefinedQualityLimitType$.getValue()===e)return this;let{highQualityLimit:t,trafficSavingLimit:i}=this.tuning.autoTrackSelection,r;switch(e){case"high_quality":r={min:t,max:void 0};break;case"traffic_saving":r={max:i,min:void 0};break;default:r={max:void 0,min:void 0}}this.setAutoQualityLimits(r)})),this}setPlaybackRate(e){return this.subscription.add(this.playerInited.pipe(U(t=>!!t),j()).subscribe(()=>{var i;ru(this.providerContainer);let t=(i=this.providerContainer)==null?void 0:i.providerOutput.element$.getValue();this.tracer.log("setPlaybackRate",{playbackRate:e,isVideoElementAvailable:!!t}),t&&(this.desiredState.playbackRate.setState(e),t.playbackRate=e)})),this}setExternalTextTracks(e){return this.subscription.add(this.playerInited.pipe(U(t=>!!t),j()).subscribe(()=>{e.length&&this.tracer.log("setExternalTextTracks",si(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t})))})),this}selectTextTrack(e){return this.subscription.add(this.playerInited.pipe(U(t=>!!t),j()).subscribe(()=>{var t;AE(e,this.desiredState.currentTextTrack,(t=this.providerContainer)==null?void 0:t.providerOutput.availableTextTracks$,i=>i.id===e),this.tracer.log("selectTextTrack",{textTrackId:e})})),this}setTextTrackCueSettings(e){return this.subscription.add(this.playerInited.pipe(U(t=>!!t),j()).subscribe(()=>{this.tracer.log("setTextTrackCueSettings",{...e}),this.desiredState.textTrackCuesSettings.startTransitionTo(e)})),this}setLiveLowLatency(e){let t=this.info.isLive$.getValue(),i=this.desiredState.isLowLatency.getState();return!t||i===e?this:(this.tracer.log("live switch to low latency "+e),this.desiredState.isLowLatency.setState(e),this.seekTime(0))}setLooped(e){return this.subscription.add(this.playerInited.pipe(U(t=>!!t),j()).subscribe(()=>{this.tracer.log("setLooped",{isLooped:e}),this.desiredState.isLooped.startTransitionTo(e)})),this}toggleChromecast(){this.tracer.log("toggleChromecast"),this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){return this.subscription.add(this.playerInited.pipe(U(i=>!!i),j()).subscribe(()=>{let i=this.getScene3D();this.tracer.log("startCameraManualRotation",{isScene3DAvailable:!!i,mx:e,my:t}),i&&i.startCameraManualRotation(e,t)})),this}stopCameraManualRotation(e=!1){return this.subscription.add(this.playerInited.pipe(U(t=>!!t),j()).subscribe(()=>{let t=this.getScene3D();this.tracer.log("stopCameraManualRotation",{isScene3DAvailable:!!t,immediate:e}),t&&t.stopCameraManualRotation(e)})),this}moveCameraFocusPX(e,t){return this.subscription.add(this.playerInited.pipe(U(i=>!!i),j()).subscribe(()=>{let i=this.getScene3D();if(this.tracer.log("moveCameraFocusPX",{isScene3DAvailable:!!i,dxpx:e,dypx:t}),i){let r=i.getCameraRotation(),s=i.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:r.x+s.x,y:r.y+s.y})}})),this}holdCamera(){return this.subscription.add(this.playerInited.pipe(U(e=>e),j()).subscribe(()=>{let e=this.getScene3D();e&&e.holdCamera()})),this}releaseCamera(){return this.subscription.add(this.playerInited.pipe(U(e=>!!e),j()).subscribe(()=>{let e=this.getScene3D();e&&e.releaseCamera()})),this}getExactTime(){if(!this.providerContainer)return 0;let e=this.providerContainer.providerOutput.element$.getValue();if(VV(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),i=t.state==="none"?void 0:t.position;return PE(i)?i/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){var t,i;let e=(t=this.providerContainer)==null?void 0:t.current$.getValue();if((i=e==null?void 0:e.provider)!=null&&i.scene3D)return e.provider.scene3D}setIntrinsicVideoSize(...e){let t={width:e.reduce((i,{width:r})=>i||r||0,0),height:e.reduce((i,{height:r})=>i||r||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(ai(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(gc(e,t,i))})),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(U(({from:e})=>e==="stopped"),j()).subscribe(()=>{this.initedAt=su(),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",si(n)),n.state==="requested"?this.desiredState.seekState.setState({...n,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:au.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe(j()).subscribe(this.events.autoplaySoundProhibited$)).add(e.providerOutput.severeStallOccurred$.subscribe(this.events.severeStallOccured$)).add(e.providerOutput.seekedEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("seekedEvent",si(n)),n.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe(G(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(G(n=>n.destination),z()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(_t({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)=>LE(u)?1:LE(l)?-1:OV(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(z()).subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.pipe(U(n=>PE(n))).subscribe(n=>{this.info.currentQuality$.next(n==null?void 0:n.quality),this.info.videoBitrate$.next(n==null?void 0:n.bitrate)})).add(e.providerOutput.currentVideoSegmentLength$.pipe(z((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe(z((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(z()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(z()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(z()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.autoVideoTrackLimits$.subscribe(n=>{this.desiredState.autoVideoTrackLimits.setState(n!=null?n:{})})).add(e.providerOutput.currentBuffer$.pipe(G(n=>n?{start:n.from,end:n.to}:{start:0,end:0})).subscribe(this.info.currentBuffer$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.isLiveEnded$.pipe(Kd(n=>n&&this.stop())).subscribe(this.info.isLiveEnded$)).add(e.providerOutput.canChangePlaybackSpeed$.subscribe(this.info.canChangePlaybackSpeed$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.liveBufferTime$.subscribe(this.info.liveBufferTime$)).add(e.providerOutput.liveLatency$.subscribe(this.info.liveLatency$)).add(_t({hasLiveOffsetByPaused:ai(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(G(n=>n.to),z(),G(n=>n==="paused")),isLowLatency:e.providerOutput.isLowLatency$}).subscribe(({hasLiveOffsetByPaused:n,isLowLatency:o})=>{if(window.clearTimeout(this.hasLiveOffsetByPausedTimer),n){this.hasLiveOffsetByPausedTimer=window.setTimeout(()=>{this.hasLiveOffsetByPaused.next(!0)},this.getActiveLiveDelay(o));return}this.hasLiveOffsetByPaused.next(!1)})).add(_t({atLiveEdge:_t({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:zd({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}),z(),Kd(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(G(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add(_t({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),z(),Kd(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(G(n=>n.muted),z()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(G(n=>n.volume),z()).subscribe(this.info.volume$)).add(zd({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(ai(e.providerOutput.endedEvent$.pipe(RE(!0)),e.providerOutput.seekedEvent$.pipe(RE(!1))).pipe(z()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.providerOutput.fetcherRecoverableError$.subscribe(this.events.fetcherRecoverableError$)).add(e.providerOutput.fetcherError$.subscribe(this.events.fatalError$)).add(e.volumeMultiplierError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe(G(n=>({id:n?`No${n}`:"NoProviders",category:au.VIDEO_PIPELINE,message:n?`${n} was forced but failed or not available`:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.getCurrentTime$.subscribe(this.experimental.getCurrentTime$)).add(e.providerOutput.firstBytesEvent$.pipe(j(),G(n=>n!=null?n:su()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(j(),G(()=>su()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(j(),G(()=>su()-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 C(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let i=new C(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(U(({to:n})=>n==="playing"),j()).subscribe(()=>i.next(!1)));let r=0,s=ai(e.providerOutput.isBuffering$,t,i).pipe(G(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||i.getValue();return n&&!o}),z());this.subscription.add(s.subscribe(n=>{n?r=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(r),this.info.isStalled$.next(!1))})),this.subscription.add(ai(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{let n=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n==null?void 0:n.videoWidth,height:n==null?void 0:n.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{var u,l;let o=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:(u=n==null?void 0:n.size)==null?void 0:u.width,height:(l=n==null?void 0:n.size)==null?void 0:l.height},{width:o==null?void 0:o.videoWidth,height:o==null?void 0:o.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add(ai(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,e.providerOutput.elementVisible$,this.chromecastInitializer.castState$).subscribe(()=>{let n=e.providerOutput.inPiP$.getValue(),o=e.providerOutput.inFullscreen$.getValue(),u=e.providerOutput.element$.getValue(),l=e.providerOutput.elementVisible$.getValue(),c=this.chromecastInitializer.castState$.getValue(),d;c==="CONNECTED"?d="second_screen":u?l?n?d="pip":o?d="fullscreen":d="inline":d="invisible":d="none",this.info.surface$.getValue()!==d&&this.info.surface$.next(d)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(G(e=>e==null?void 0:e.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new kE;this.subscription.add(t),this.subscription.add(e.current$.pipe(z((i,r)=>i.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(U(i=>i.length>0),j()).subscribe(i=>{this.setStartingVideoTrack(i)}))}))}setStartingVideoTrack(e){var r;let t;this.wasSetStartedQuality=!0;let i=(r=this.explicitInitialQuality)!=null?r:this.info.currentQuality$.getValue();i&&(t=e.find(({quality:s})=>s===i),t||this.setAutoQuality(!0)),t||(t=vt(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(ai(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(){var t;let e=(t=this.providerContainer)==null?void 0:t.providerOutput;ru(this.providerContainer),ru(e),Sv(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(i=>gv(i)),this.providerContainer.current$.subscribe(({type:i})=>Ia("provider",i)),e.duration$.subscribe(i=>Ia("duration",i)),e.availableVideoTracks$.pipe(U(i=>!!i.length),j()).subscribe(i=>Ia("tracks",i)),this.events.fatalError$.subscribe(new Re("fatalError")),this.events.managedError$.subscribe(new Re("managedError")),e.position$.subscribe(new Re("position")),e.currentVideoTrack$.pipe(G(i=>i==null?void 0:i.quality)).subscribe(new Re("quality")),this.info.currentBuffer$.subscribe(new Re("buffer")),e.isBuffering$.subscribe(new Re("isBuffering"))].forEach(i=>this.subscription.add(i)),Ia("codecs",N.video.supportedCodecs)}initTracerSubscription(){let e=$E(this.tracer.log.bind(this.tracer)),t=$E(this.tracer.error.bind(this.tracer));this.subscription.add(this.info.playbackState$.subscribe(e("playbackState"))).add(this.info.isLooped$.subscribe(e("isLooped"))).add(this.info.currentPlaybackRate$.pipe(z()).subscribe(e("currentPlaybackRate"))).add(this.info.isAutoQualityEnabled$.subscribe(e("isAutoQualityEnabled"))).add(this.info.autoQualityLimits$.subscribe(e("autoQualityLimits"))).add(this.info.currentFormat$.subscribe(e("currentFormat"))).add(this.info.availableQualities$.subscribe(e("availableQualities"))).add(this.info.availableQualitiesFps$.subscribe(e("availableQualitiesFps"))).add(this.info.availableAudioTracks$.subscribe(e("availableAudioTracks"))).add(this.info.isAudioAvailable$.subscribe(e("isAudioAvailable"))).add(_t({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe(U(({currentQuality:i,videoBitrate:r})=>!!i&&!!r),z((i,r)=>i.currentQuality===r.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe(U(i=>i>0),z()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe(U(i=>i>0),z()).subscribe(e("currentAudioSegmentLength"))).add(this.info.hostname$.subscribe(e("hostname"))).add(this.info.currentTextTrack$.subscribe(e("currentTextTrack"))).add(this.info.availableTextTracks$.subscribe(e("availableTextTracks"))).add(this.info.autoQualityLimitingAvailable$.subscribe(e("autoQualityLimitingAvailable"))).add(_t({currentBuffer:this.info.currentBuffer$.pipe(U(i=>i.end>0),z((i,r)=>i.end===r.end&&i.start===r.start)),position:this.info.position$.pipe(z())}).pipe(Xd(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe(z()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe(z()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe(z()).subscribe(e("canChangePlaybackSpeed"))).add(_t({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(U(({liveTime:i,liveBufferTime:r})=>!!i&&!!r),Xd(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(z(),U(i=>i===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(z(),U(i=>i===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe(z()).subscribe(e("muted"))).add(this.info.volume$.pipe(z()).subscribe(e("volume"))).add(this.info.isEnded$.pipe(z(),U(i=>i===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add(_t({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(U(({throughputEstimation:i,rtt:r})=>!!i&&!!r),Xd(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(z(),U(i=>i===!0)).subscribe(e("is3DVideo"))).add(this.info.surface$.subscribe(e("surface"))).add(this.events.ended$.subscribe(e("ended"))).add(this.events.looped$.subscribe(e("looped"))).add(this.events.managedError$.subscribe(t("managedError"))).add(this.events.fatalError$.subscribe(t("fatalError"))).add(this.events.firstBytes$.subscribe(e("firstBytes"))).add(this.events.firstFrame$.subscribe(e("firstFrame"))).add(this.events.canplay$.subscribe(e("canplay")))}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e,t=()=>{e==null||e.release(),e=void 0},i=async()=>{t(),e=await window.navigator.wakeLock.request("screen").catch(r=>{r instanceof DOMException&&r.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:au.DOM,message:String(r)})})};this.subscription.add(ai(Yd(document,"visibilitychange"),Yd(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let r=document.visibilityState==="visible",s=this.desiredState.playbackState.getState()==="playing",n=!!e&&!(e!=null&&e.released);r&&s?n||i():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let i=e.find(r=>r.quality===t);this.tracer.log("setVideoTrackIdByQuality",si({quality:t,availableTracks:si(e),track:si(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&&!ka()}};import{Subscription as K7,Observable as X7,Subject as J7,ValueSubject as Z7,VideoQuality as eJ}from"@vkontakte/videoplayer-shared/es2018";var tJ=`@vkontakte/videoplayer-core@${_p}`;export{Ys as ChromecastState,pu as HttpConnectionType,X7 as Observable,Le as PlaybackState,nu as Player,Ks as PredefinedQualityLimits,tJ as SDK_VERSION,J7 as Subject,K7 as Subscription,hu as Surface,_p as VERSION,Z7 as ValueSubject,At as VideoFormat,eJ as VideoQuality,N as clientChecker,Ta as isMobile};
|