@vkontakte/videoplayer-core 2.0.131-dev.6210de2e.0 → 2.0.131-dev.85f5d8d6.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 +32 -93
- package/es2015.esm.js +28 -89
- package/es2018.cjs.js +33 -94
- package/es2018.esm.js +29 -90
- package/es2024.cjs.js +34 -95
- package/es2024.esm.js +31 -92
- package/esnext.cjs.js +34 -95
- package/esnext.esm.js +31 -92
- package/evergreen.esm.js +28 -89
- package/package.json +2 -2
- package/types/player/Player.d.ts +1 -5
- package/types/providers/utils/StallsManager.d.ts +4 -18
- package/types/utils/autoSelectTrack.d.ts +3 -6
- package/types/utils/qualityLimits.d.ts +18 -3
- package/types/utils/tuningConfig.d.ts +7 -28
- package/types/providers/DashProviderNew/baseDashProvider.d.ts +0 -57
- package/types/providers/DashProviderNew/consts.d.ts +0 -3
- package/types/providers/DashProviderNew/index.d.ts +0 -2
- package/types/providers/DashProviderNew/lib/ElementSizeManager.d.ts +0 -19
- package/types/providers/DashProviderNew/lib/LiveTextManager.d.ts +0 -23
- package/types/providers/DashProviderNew/lib/buffer.d.ts +0 -117
- package/types/providers/DashProviderNew/lib/fetcher.d.ts +0 -59
- 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/mpd.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/DashProviderNew/lib/player.d.ts +0 -92
- package/types/providers/DashProviderNew/lib/sourceBufferTaskQueue.d.ts +0 -19
- package/types/providers/DashProviderNew/lib/types.d.ts +0 -186
- package/types/providers/DashProviderNew/lib/utils.d.ts +0 -21
- package/types/providers/DashProviderNew/newDashCmafLiveProvider.d.ts +0 -8
- package/types/providers/DashProviderNew/newDashProvider.d.ts +0 -6
package/es2018.esm.js
CHANGED
|
@@ -1,127 +1,73 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @vkontakte/videoplayer-core v2.0.131-dev.
|
|
3
|
-
* Mon, 12 May 2025
|
|
2
|
+
* @vkontakte/videoplayer-core v2.0.131-dev.85f5d8d6.0
|
|
3
|
+
* Mon, 12 May 2025 13:34:07 GMT
|
|
4
4
|
* https://st.mycdn.me/static/vkontakte-videoplayer/2-0-131/doc/
|
|
5
5
|
*/
|
|
6
|
-
var VE=Object.create;var Ul=Object.defineProperty;var Bh=Object.getOwnPropertyDescriptor;var OE=Object.getOwnPropertyNames;var _E=Object.getPrototypeOf,FE=Object.prototype.hasOwnProperty;var b=(s,e)=>()=>(e||s((e={exports:{}}).exports,e),e.exports);var NE=(s,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of OE(e))!FE.call(s,r)&&r!==t&&Ul(s,r,{get:()=>e[r],enumerable:!(i=Bh(e,r))||i.enumerable});return s};var U=(s,e,t)=>(t=s!=null?VE(_E(s)):{},NE(e||!s||!s.__esModule?Ul(t,"default",{value:s,enumerable:!0}):t,s));var ne=(s,e,t,i)=>{for(var r=i>1?void 0:i?Bh(e,t):e,a=s.length-1,n;a>=0;a--)(n=s[a])&&(r=(i?n(e,t,r):n(r))||r);return i&&r&&Ul(e,t,r),r};var ve=b((Hl,Vh)=>{"use strict";var aa=function(s){return s&&s.Math===Math&&s};Vh.exports=aa(typeof globalThis=="object"&&globalThis)||aa(typeof window=="object"&&window)||aa(typeof self=="object"&&self)||aa(typeof global=="object"&&global)||aa(typeof Hl=="object"&&Hl)||function(){return this}()||Function("return this")()});var Fe=b((o_,Oh)=>{"use strict";Oh.exports=function(s){try{return!!s()}catch(e){return!0}}});var na=b((u_,_h)=>{"use strict";var UE=Fe();_h.exports=!UE(function(){var s=function(){}.bind();return typeof s!="function"||s.hasOwnProperty("prototype")})});var Wl=b((l_,qh)=>{"use strict";var qE=na(),Uh=Function.prototype,Fh=Uh.apply,Nh=Uh.call;qh.exports=typeof Reflect=="object"&&Reflect.apply||(qE?Nh.bind(Fh):function(){return Nh.apply(Fh,arguments)})});var De=b((c_,Wh)=>{"use strict";var jh=na(),Hh=Function.prototype,zl=Hh.call,jE=jh&&Hh.bind.bind(zl,zl);Wh.exports=jh?jE:function(s){return function(){return zl.apply(s,arguments)}}});var Zi=b((d_,Gh)=>{"use strict";var zh=De(),HE=zh({}.toString),WE=zh("".slice);Gh.exports=function(s){return WE(HE(s),8,-1)}});var Gl=b((p_,Qh)=>{"use strict";var zE=Zi(),GE=De();Qh.exports=function(s){if(zE(s)==="Function")return GE(s)}});var ge=b((h_,Yh)=>{"use strict";var Ql=typeof document=="object"&&document.all;Yh.exports=typeof Ql=="undefined"&&Ql!==void 0?function(s){return typeof s=="function"||s===Ql}:function(s){return typeof s=="function"}});var St=b((f_,Kh)=>{"use strict";var QE=Fe();Kh.exports=!QE(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var vt=b((m_,Xh)=>{"use strict";var YE=na(),Ro=Function.prototype.call;Xh.exports=YE?Ro.bind(Ro):function(){return Ro.apply(Ro,arguments)}});var Yl=b(ef=>{"use strict";var Jh={}.propertyIsEnumerable,Zh=Object.getOwnPropertyDescriptor,KE=Zh&&!Jh.call({1:2},1);ef.f=KE?function(e){var t=Zh(this,e);return!!t&&t.enumerable}:Jh});var oa=b((g_,tf)=>{"use strict";tf.exports=function(s,e){return{enumerable:!(s&1),configurable:!(s&2),writable:!(s&4),value:e}}});var sf=b((S_,rf)=>{"use strict";var XE=De(),JE=Fe(),ZE=Zi(),Kl=Object,ew=XE("".split);rf.exports=JE(function(){return!Kl("z").propertyIsEnumerable(0)})?function(s){return ZE(s)==="String"?ew(s,""):Kl(s)}:Kl});var wr=b((v_,af)=>{"use strict";af.exports=function(s){return s==null}});var Mi=b((y_,nf)=>{"use strict";var tw=wr(),iw=TypeError;nf.exports=function(s){if(tw(s))throw new iw("Can't call method on "+s);return s}});var er=b((T_,of)=>{"use strict";var rw=sf(),sw=Mi();of.exports=function(s){return rw(sw(s))}});var yt=b((I_,uf)=>{"use strict";var aw=ge();uf.exports=function(s){return typeof s=="object"?s!==null:aw(s)}});var Pr=b((x_,lf)=>{"use strict";lf.exports={}});var mi=b((E_,df)=>{"use strict";var Xl=Pr(),Jl=ve(),nw=ge(),cf=function(s){return nw(s)?s:void 0};df.exports=function(s,e){return arguments.length<2?cf(Xl[s])||cf(Jl[s]):Xl[s]&&Xl[s][e]||Jl[s]&&Jl[s][e]}});var ua=b((w_,pf)=>{"use strict";var ow=De();pf.exports=ow({}.isPrototypeOf)});var tr=b((P_,mf)=>{"use strict";var uw=ve(),hf=uw.navigator,ff=hf&&hf.userAgent;mf.exports=ff?String(ff):""});var ec=b((A_,Tf)=>{"use strict";var yf=ve(),Zl=tr(),bf=yf.process,gf=yf.Deno,Sf=bf&&bf.versions||gf&&gf.version,vf=Sf&&Sf.v8,Vt,Lo;vf&&(Vt=vf.split("."),Lo=Vt[0]>0&&Vt[0]<4?1:+(Vt[0]+Vt[1]));!Lo&&Zl&&(Vt=Zl.match(/Edge\/(\d+)/),(!Vt||Vt[1]>=74)&&(Vt=Zl.match(/Chrome\/(\d+)/),Vt&&(Lo=+Vt[1])));Tf.exports=Lo});var tc=b((k_,xf)=>{"use strict";var If=ec(),lw=Fe(),cw=ve(),dw=cw.String;xf.exports=!!Object.getOwnPropertySymbols&&!lw(function(){var s=Symbol("symbol detection");return!dw(s)||!(Object(s)instanceof Symbol)||!Symbol.sham&&If&&If<41})});var ic=b((R_,Ef)=>{"use strict";var pw=tc();Ef.exports=pw&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var rc=b((L_,wf)=>{"use strict";var hw=mi(),fw=ge(),mw=ua(),bw=ic(),gw=Object;wf.exports=bw?function(s){return typeof s=="symbol"}:function(s){var e=hw("Symbol");return fw(e)&&mw(e.prototype,gw(s))}});var la=b((M_,Pf)=>{"use strict";var Sw=String;Pf.exports=function(s){try{return Sw(s)}catch(e){return"Object"}}});var Wt=b(($_,Af)=>{"use strict";var vw=ge(),yw=la(),Tw=TypeError;Af.exports=function(s){if(vw(s))return s;throw new Tw(yw(s)+" is not a function")}});var ca=b((D_,kf)=>{"use strict";var Iw=Wt(),xw=wr();kf.exports=function(s,e){var t=s[e];return xw(t)?void 0:Iw(t)}});var Lf=b((B_,Rf)=>{"use strict";var sc=vt(),ac=ge(),nc=yt(),Ew=TypeError;Rf.exports=function(s,e){var t,i;if(e==="string"&&ac(t=s.toString)&&!nc(i=sc(t,s))||ac(t=s.valueOf)&&!nc(i=sc(t,s))||e!=="string"&&ac(t=s.toString)&&!nc(i=sc(t,s)))return i;throw new Ew("Can't convert object to primitive value")}});var Ot=b((C_,Mf)=>{"use strict";Mf.exports=!0});var Bf=b((V_,Df)=>{"use strict";var $f=ve(),ww=Object.defineProperty;Df.exports=function(s,e){try{ww($f,s,{value:e,configurable:!0,writable:!0})}catch(t){$f[s]=e}return e}});var da=b((O_,Of)=>{"use strict";var Pw=Ot(),Aw=ve(),kw=Bf(),Cf="__core-js_shared__",Vf=Of.exports=Aw[Cf]||kw(Cf,{});(Vf.versions||(Vf.versions=[])).push({version:"3.38.0",mode:Pw?"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 oc=b((__,Ff)=>{"use strict";var _f=da();Ff.exports=function(s,e){return _f[s]||(_f[s]=e||{})}});var Ar=b((F_,Nf)=>{"use strict";var Rw=Mi(),Lw=Object;Nf.exports=function(s){return Lw(Rw(s))}});var _t=b((N_,Uf)=>{"use strict";var Mw=De(),$w=Ar(),Dw=Mw({}.hasOwnProperty);Uf.exports=Object.hasOwn||function(e,t){return Dw($w(e),t)}});var uc=b((U_,qf)=>{"use strict";var Bw=De(),Cw=0,Vw=Math.random(),Ow=Bw(1 .toString);qf.exports=function(s){return"Symbol("+(s===void 0?"":s)+")_"+Ow(++Cw+Vw,36)}});var Ne=b((q_,Hf)=>{"use strict";var _w=ve(),Fw=oc(),jf=_t(),Nw=uc(),Uw=tc(),qw=ic(),kr=_w.Symbol,lc=Fw("wks"),jw=qw?kr.for||kr:kr&&kr.withoutSetter||Nw;Hf.exports=function(s){return jf(lc,s)||(lc[s]=Uw&&jf(kr,s)?kr[s]:jw("Symbol."+s)),lc[s]}});var Qf=b((j_,Gf)=>{"use strict";var Hw=vt(),Wf=yt(),zf=rc(),Ww=ca(),zw=Lf(),Gw=Ne(),Qw=TypeError,Yw=Gw("toPrimitive");Gf.exports=function(s,e){if(!Wf(s)||zf(s))return s;var t=Ww(s,Yw),i;if(t){if(e===void 0&&(e="default"),i=Hw(t,s,e),!Wf(i)||zf(i))return i;throw new Qw("Can't convert object to primitive value")}return e===void 0&&(e="number"),zw(s,e)}});var cc=b((H_,Yf)=>{"use strict";var Kw=Qf(),Xw=rc();Yf.exports=function(s){var e=Kw(s,"string");return Xw(e)?e:e+""}});var Mo=b((W_,Xf)=>{"use strict";var Jw=ve(),Kf=yt(),dc=Jw.document,Zw=Kf(dc)&&Kf(dc.createElement);Xf.exports=function(s){return Zw?dc.createElement(s):{}}});var pc=b((z_,Jf)=>{"use strict";var eP=St(),tP=Fe(),iP=Mo();Jf.exports=!eP&&!tP(function(){return Object.defineProperty(iP("div"),"a",{get:function(){return 7}}).a!==7})});var tm=b(em=>{"use strict";var rP=St(),sP=vt(),aP=Yl(),nP=oa(),oP=er(),uP=cc(),lP=_t(),cP=pc(),Zf=Object.getOwnPropertyDescriptor;em.f=rP?Zf:function(e,t){if(e=oP(e),t=uP(t),cP)try{return Zf(e,t)}catch(i){}if(lP(e,t))return nP(!sP(aP.f,e,t),e[t])}});var hc=b((Q_,im)=>{"use strict";var dP=Fe(),pP=ge(),hP=/#|\.prototype\./,pa=function(s,e){var t=mP[fP(s)];return t===gP?!0:t===bP?!1:pP(e)?dP(e):!!e},fP=pa.normalize=function(s){return String(s).replace(hP,".").toLowerCase()},mP=pa.data={},bP=pa.NATIVE="N",gP=pa.POLYFILL="P";im.exports=pa});var Rr=b((Y_,sm)=>{"use strict";var rm=Gl(),SP=Wt(),vP=na(),yP=rm(rm.bind);sm.exports=function(s,e){return SP(s),e===void 0?s:vP?yP(s,e):function(){return s.apply(e,arguments)}}});var fc=b((K_,am)=>{"use strict";var TP=St(),IP=Fe();am.exports=TP&&IP(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var zt=b((X_,nm)=>{"use strict";var xP=yt(),EP=String,wP=TypeError;nm.exports=function(s){if(xP(s))return s;throw new wP(EP(s)+" is not an object")}});var ir=b(um=>{"use strict";var PP=St(),AP=pc(),kP=fc(),$o=zt(),om=cc(),RP=TypeError,mc=Object.defineProperty,LP=Object.getOwnPropertyDescriptor,bc="enumerable",gc="configurable",Sc="writable";um.f=PP?kP?function(e,t,i){if($o(e),t=om(t),$o(i),typeof e=="function"&&t==="prototype"&&"value"in i&&Sc in i&&!i[Sc]){var r=LP(e,t);r&&r[Sc]&&(e[t]=i.value,i={configurable:gc in i?i[gc]:r[gc],enumerable:bc in i?i[bc]:r[bc],writable:!1})}return mc(e,t,i)}:mc:function(e,t,i){if($o(e),t=om(t),$o(i),AP)try{return mc(e,t,i)}catch(r){}if("get"in i||"set"in i)throw new RP("Accessors not supported");return"value"in i&&(e[t]=i.value),e}});var Lr=b((Z_,lm)=>{"use strict";var MP=St(),$P=ir(),DP=oa();lm.exports=MP?function(s,e,t){return $P.f(s,e,DP(1,t))}:function(s,e,t){return s[e]=t,s}});var Ee=b((eF,dm)=>{"use strict";var ha=ve(),BP=Wl(),CP=Gl(),VP=ge(),OP=tm().f,_P=hc(),Mr=Pr(),FP=Rr(),$r=Lr(),cm=_t();da();var NP=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 BP(s,this,arguments)};return e.prototype=s.prototype,e};dm.exports=function(s,e){var t=s.target,i=s.global,r=s.stat,a=s.proto,n=i?ha:r?ha[t]:ha[t]&&ha[t].prototype,o=i?Mr:Mr[t]||$r(Mr,t,{})[t],u=o.prototype,l,d,c,h,p,f,m,g,S;for(h in e)l=_P(i?h:t+(r?".":"#")+h,s.forced),d=!l&&n&&cm(n,h),f=o[h],d&&(s.dontCallGetSet?(S=OP(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=FP(p,ha):s.wrap&&d?g=NP(p):a&&VP(p)?g=CP(p):g=p,(s.sham||p&&p.sham||f&&f.sham)&&$r(g,"sham",!0),$r(o,h,g),a&&(c=t+"Prototype",cm(Mr,c)||$r(Mr,c,{}),$r(Mr[c],h,p),s.real&&u&&(l||!u[h])&&$r(u,h,p)))}});var hm=b((tF,pm)=>{"use strict";var UP=Math.ceil,qP=Math.floor;pm.exports=Math.trunc||function(e){var t=+e;return(t>0?qP:UP)(t)}});var fa=b((iF,fm)=>{"use strict";var jP=hm();fm.exports=function(s){var e=+s;return e!==e||e===0?0:jP(e)}});var bm=b((rF,mm)=>{"use strict";var HP=fa(),WP=Math.max,zP=Math.min;mm.exports=function(s,e){var t=HP(s);return t<0?WP(t+e,0):zP(t,e)}});var vc=b((sF,gm)=>{"use strict";var GP=fa(),QP=Math.min;gm.exports=function(s){var e=GP(s);return e>0?QP(e,9007199254740991):0}});var Dr=b((aF,Sm)=>{"use strict";var YP=vc();Sm.exports=function(s){return YP(s.length)}});var yc=b((nF,ym)=>{"use strict";var KP=er(),XP=bm(),JP=Dr(),vm=function(s){return function(e,t,i){var r=KP(e),a=JP(r);if(a===0)return!s&&-1;var n=XP(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}};ym.exports={includes:vm(!0),indexOf:vm(!1)}});var ma=b((oF,Tm)=>{"use strict";Tm.exports=function(){}});var Im=b(()=>{"use strict";var ZP=Ee(),eA=yc().includes,tA=Fe(),iA=ma(),rA=tA(function(){return!Array(1).includes()});ZP({target:"Array",proto:!0,forced:rA},{includes:function(e){return eA(this,e,arguments.length>1?arguments[1]:void 0)}});iA("includes")});var $i=b((cF,xm)=>{"use strict";var sA=mi();xm.exports=sA});var wm=b((dF,Em)=>{"use strict";Im();var aA=$i();Em.exports=aA("Array","includes")});var Am=b((pF,Pm)=>{"use strict";var nA=wm();Pm.exports=nA});var Tt=b((hF,km)=>{"use strict";var oA=Am();km.exports=oA});var Co=b((wF,Vm)=>{"use strict";var mA=oc(),bA=uc(),Cm=mA("keys");Vm.exports=function(s){return Cm[s]||(Cm[s]=bA(s))}});var _m=b((PF,Om)=>{"use strict";var gA=Fe();Om.exports=!gA(function(){function s(){}return s.prototype.constructor=null,Object.getPrototypeOf(new s)!==s.prototype})});var Vo=b((AF,Nm)=>{"use strict";var SA=_t(),vA=ge(),yA=Ar(),TA=Co(),IA=_m(),Fm=TA("IE_PROTO"),xc=Object,xA=xc.prototype;Nm.exports=IA?xc.getPrototypeOf:function(s){var e=yA(s);if(SA(e,Fm))return e[Fm];var t=e.constructor;return vA(t)&&e instanceof t?t.prototype:e instanceof xc?xA:null}});var Oo=b((kF,Um)=>{"use strict";Um.exports={}});var Hm=b((RF,jm)=>{"use strict";var EA=De(),Ec=_t(),wA=er(),PA=yc().indexOf,AA=Oo(),qm=EA([].push);jm.exports=function(s,e){var t=wA(s),i=0,r=[],a;for(a in t)!Ec(AA,a)&&Ec(t,a)&&qm(r,a);for(;e.length>i;)Ec(t,a=e[i++])&&(~PA(r,a)||qm(r,a));return r}});var wc=b((LF,Wm)=>{"use strict";Wm.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var Pc=b((MF,zm)=>{"use strict";var kA=Hm(),RA=wc();zm.exports=Object.keys||function(e){return kA(e,RA)}});var Ac=b(($F,Xm)=>{"use strict";var Qm=St(),LA=Fe(),Ym=De(),MA=Vo(),$A=Pc(),DA=er(),BA=Yl().f,Km=Ym(BA),CA=Ym([].push),VA=Qm&&LA(function(){var s=Object.create(null);return s[2]=2,!Km(s,2)}),Gm=function(s){return function(e){for(var t=DA(e),i=$A(t),r=VA&&MA(t)===null,a=i.length,n=0,o=[],u;a>n;)u=i[n++],(!Qm||(r?u in t:Km(t,u)))&&CA(o,s?[u,t[u]]:t[u]);return o}};Xm.exports={entries:Gm(!0),values:Gm(!1)}});var Jm=b(()=>{"use strict";var OA=Ee(),_A=Ac().entries;OA({target:"Object",stat:!0},{entries:function(e){return _A(e)}})});var eb=b((CF,Zm)=>{"use strict";Jm();var FA=Pr();Zm.exports=FA.Object.entries});var ib=b((VF,tb)=>{"use strict";var NA=eb();tb.exports=NA});var rr=b((OF,rb)=>{"use strict";var UA=ib();rb.exports=UA});var sr=b((_F,sb)=>{"use strict";sb.exports={}});var ob=b((FF,nb)=>{"use strict";var qA=ve(),jA=ge(),ab=qA.WeakMap;nb.exports=jA(ab)&&/native code/.test(String(ab))});var Mc=b((NF,cb)=>{"use strict";var HA=ob(),lb=ve(),WA=yt(),zA=Lr(),kc=_t(),Rc=da(),GA=Co(),QA=Oo(),ub="Object already initialized",Lc=lb.TypeError,YA=lb.WeakMap,_o,ba,Fo,KA=function(s){return Fo(s)?ba(s):_o(s,{})},XA=function(s){return function(e){var t;if(!WA(e)||(t=ba(e)).type!==s)throw new Lc("Incompatible receiver, "+s+" required");return t}};HA||Rc.state?(Ft=Rc.state||(Rc.state=new YA),Ft.get=Ft.get,Ft.has=Ft.has,Ft.set=Ft.set,_o=function(s,e){if(Ft.has(s))throw new Lc(ub);return e.facade=s,Ft.set(s,e),e},ba=function(s){return Ft.get(s)||{}},Fo=function(s){return Ft.has(s)}):(ar=GA("state"),QA[ar]=!0,_o=function(s,e){if(kc(s,ar))throw new Lc(ub);return e.facade=s,zA(s,ar,e),e},ba=function(s){return kc(s,ar)?s[ar]:{}},Fo=function(s){return kc(s,ar)});var Ft,ar;cb.exports={set:_o,get:ba,has:Fo,enforce:KA,getterFor:XA}});var Bc=b((UF,pb)=>{"use strict";var $c=St(),JA=_t(),db=Function.prototype,ZA=$c&&Object.getOwnPropertyDescriptor,Dc=JA(db,"name"),ek=Dc&&function(){}.name==="something",tk=Dc&&(!$c||$c&&ZA(db,"name").configurable);pb.exports={EXISTS:Dc,PROPER:ek,CONFIGURABLE:tk}});var fb=b(hb=>{"use strict";var ik=St(),rk=fc(),sk=ir(),ak=zt(),nk=er(),ok=Pc();hb.f=ik&&!rk?Object.defineProperties:function(e,t){ak(e);for(var i=nk(t),r=ok(t),a=r.length,n=0,o;a>n;)sk.f(e,o=r[n++],i[o]);return e}});var Cc=b((jF,mb)=>{"use strict";var uk=mi();mb.exports=uk("document","documentElement")});var Fc=b((HF,Ib)=>{"use strict";var lk=zt(),ck=fb(),bb=wc(),dk=Oo(),pk=Cc(),hk=Mo(),fk=Co(),gb=">",Sb="<",Oc="prototype",_c="script",yb=fk("IE_PROTO"),Vc=function(){},Tb=function(s){return Sb+_c+gb+s+Sb+"/"+_c+gb},vb=function(s){s.write(Tb("")),s.close();var e=s.parentWindow.Object;return s=null,e},mk=function(){var s=hk("iframe"),e="java"+_c+":",t;return s.style.display="none",pk.appendChild(s),s.src=String(e),t=s.contentWindow.document,t.open(),t.write(Tb("document.F=Object")),t.close(),t.F},No,Uo=function(){try{No=new ActiveXObject("htmlfile")}catch(e){}Uo=typeof document!="undefined"?document.domain&&No?vb(No):mk():vb(No);for(var s=bb.length;s--;)delete Uo[Oc][bb[s]];return Uo()};dk[yb]=!0;Ib.exports=Object.create||function(e,t){var i;return e!==null?(Vc[Oc]=lk(e),i=new Vc,Vc[Oc]=null,i[yb]=e):i=Uo(),t===void 0?i:ck.f(i,t)}});var Br=b((WF,xb)=>{"use strict";var bk=Lr();xb.exports=function(s,e,t,i){return i&&i.enumerable?s[e]=t:bk(s,e,t),s}});var jc=b((zF,Pb)=>{"use strict";var gk=Fe(),Sk=ge(),vk=yt(),yk=Fc(),Eb=Vo(),Tk=Br(),Ik=Ne(),xk=Ot(),qc=Ik("iterator"),wb=!1,bi,Nc,Uc;[].keys&&(Uc=[].keys(),"next"in Uc?(Nc=Eb(Eb(Uc)),Nc!==Object.prototype&&(bi=Nc)):wb=!0);var Ek=!vk(bi)||gk(function(){var s={};return bi[qc].call(s)!==s});Ek?bi={}:xk&&(bi=yk(bi));Sk(bi[qc])||Tk(bi,qc,function(){return this});Pb.exports={IteratorPrototype:bi,BUGGY_SAFARI_ITERATORS:wb}});var qo=b((GF,kb)=>{"use strict";var wk=Ne(),Pk=wk("toStringTag"),Ab={};Ab[Pk]="z";kb.exports=String(Ab)==="[object z]"});var ga=b((QF,Rb)=>{"use strict";var Ak=qo(),kk=ge(),jo=Zi(),Rk=Ne(),Lk=Rk("toStringTag"),Mk=Object,$k=jo(function(){return arguments}())==="Arguments",Dk=function(s,e){try{return s[e]}catch(t){}};Rb.exports=Ak?jo:function(s){var e,t,i;return s===void 0?"Undefined":s===null?"Null":typeof(t=Dk(e=Mk(s),Lk))=="string"?t:$k?jo(e):(i=jo(e))==="Object"&&kk(e.callee)?"Arguments":i}});var Mb=b((YF,Lb)=>{"use strict";var Bk=qo(),Ck=ga();Lb.exports=Bk?{}.toString:function(){return"[object "+Ck(this)+"]"}});var Sa=b((KF,Db)=>{"use strict";var Vk=qo(),Ok=ir().f,_k=Lr(),Fk=_t(),Nk=Mb(),Uk=Ne(),$b=Uk("toStringTag");Db.exports=function(s,e,t,i){var r=t?s:s&&s.prototype;r&&(Fk(r,$b)||Ok(r,$b,{configurable:!0,value:e}),i&&!Vk&&_k(r,"toString",Nk))}});var Cb=b((XF,Bb)=>{"use strict";var qk=jc().IteratorPrototype,jk=Fc(),Hk=oa(),Wk=Sa(),zk=sr(),Gk=function(){return this};Bb.exports=function(s,e,t,i){var r=e+" Iterator";return s.prototype=jk(qk,{next:Hk(+!i,t)}),Wk(s,r,!1,!0),zk[r]=Gk,s}});var Ob=b((JF,Vb)=>{"use strict";var Qk=De(),Yk=Wt();Vb.exports=function(s,e,t){try{return Qk(Yk(Object.getOwnPropertyDescriptor(s,e)[t]))}catch(i){}}});var Fb=b((ZF,_b)=>{"use strict";var Kk=yt();_b.exports=function(s){return Kk(s)||s===null}});var Ub=b((eN,Nb)=>{"use strict";var Xk=Fb(),Jk=String,Zk=TypeError;Nb.exports=function(s){if(Xk(s))return s;throw new Zk("Can't set "+Jk(s)+" as a prototype")}});var Hc=b((tN,qb)=>{"use strict";var eR=Ob(),tR=yt(),iR=Mi(),rR=Ub();qb.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var s=!1,e={},t;try{t=eR(Object.prototype,"__proto__","set"),t(e,[]),s=e instanceof Array}catch(i){}return function(r,a){return iR(r),rR(a),tR(r)&&(s?t(r,a):r.__proto__=a),r}}():void 0)});var Zb=b((iN,Jb)=>{"use strict";var sR=Ee(),aR=vt(),Ho=Ot(),Kb=Bc(),nR=ge(),oR=Cb(),jb=Vo(),Hb=Hc(),uR=Sa(),lR=Lr(),Wc=Br(),cR=Ne(),Wb=sr(),Xb=jc(),dR=Kb.PROPER,pR=Kb.CONFIGURABLE,zb=Xb.IteratorPrototype,Wo=Xb.BUGGY_SAFARI_ITERATORS,va=cR("iterator"),Gb="keys",ya="values",Qb="entries",Yb=function(){return this};Jb.exports=function(s,e,t,i,r,a,n){oR(t,e,i);var o=function(S){if(S===r&&h)return h;if(!Wo&&S&&S in d)return d[S];switch(S){case Gb:return function(){return new t(this,S)};case ya:return function(){return new t(this,S)};case Qb:return function(){return new t(this,S)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,d=s.prototype,c=d[va]||d["@@iterator"]||r&&d[r],h=!Wo&&c||o(r),p=e==="Array"&&d.entries||c,f,m,g;if(p&&(f=jb(p.call(new s)),f!==Object.prototype&&f.next&&(!Ho&&jb(f)!==zb&&(Hb?Hb(f,zb):nR(f[va])||Wc(f,va,Yb)),uR(f,u,!0,!0),Ho&&(Wb[u]=Yb))),dR&&r===ya&&c&&c.name!==ya&&(!Ho&&pR?lR(d,"name",ya):(l=!0,h=function(){return aR(c,this)})),r)if(m={values:o(ya),keys:a?h:o(Gb),entries:o(Qb)},n)for(g in m)(Wo||l||!(g in d))&&Wc(d,g,m[g]);else sR({target:e,proto:!0,forced:Wo||l},m);return(!Ho||n)&&d[va]!==h&&Wc(d,va,h,{name:r}),Wb[e]=h,m}});var tg=b((rN,eg)=>{"use strict";eg.exports=function(s,e){return{value:s,done:e}}});var Gc=b((sN,ng)=>{"use strict";var hR=er(),zc=ma(),ig=sr(),sg=Mc(),fR=ir().f,mR=Zb(),zo=tg(),bR=Ot(),gR=St(),ag="Array Iterator",SR=sg.set,vR=sg.getterFor(ag);ng.exports=mR(Array,"Array",function(s,e){SR(this,{type:ag,target:hR(s),index:0,kind:e})},function(){var s=vR(this),e=s.target,t=s.index++;if(!e||t>=e.length)return s.target=void 0,zo(void 0,!0);switch(s.kind){case"keys":return zo(t,!1);case"values":return zo(e[t],!1)}return zo([t,e[t]],!1)},"values");var rg=ig.Arguments=ig.Array;zc("keys");zc("values");zc("entries");if(!bR&&gR&&rg.name!=="values")try{fR(rg,"name",{value:"values"})}catch(s){}});var ug=b((aN,og)=>{"use strict";var yR=Ne(),TR=sr(),IR=yR("iterator"),xR=Array.prototype;og.exports=function(s){return s!==void 0&&(TR.Array===s||xR[IR]===s)}});var Qc=b((nN,cg)=>{"use strict";var ER=ga(),lg=ca(),wR=wr(),PR=sr(),AR=Ne(),kR=AR("iterator");cg.exports=function(s){if(!wR(s))return lg(s,kR)||lg(s,"@@iterator")||PR[ER(s)]}});var pg=b((oN,dg)=>{"use strict";var RR=vt(),LR=Wt(),MR=zt(),$R=la(),DR=Qc(),BR=TypeError;dg.exports=function(s,e){var t=arguments.length<2?DR(s):e;if(LR(t))return MR(RR(t,s));throw new BR($R(s)+" is not iterable")}});var mg=b((uN,fg)=>{"use strict";var CR=vt(),hg=zt(),VR=ca();fg.exports=function(s,e,t){var i,r;hg(s);try{if(i=VR(s,"return"),!i){if(e==="throw")throw t;return t}i=CR(i,s)}catch(a){r=!0,i=a}if(e==="throw")throw t;if(r)throw i;return hg(i),t}});var Qo=b((lN,vg)=>{"use strict";var OR=Rr(),_R=vt(),FR=zt(),NR=la(),UR=ug(),qR=Dr(),bg=ua(),jR=pg(),HR=Qc(),gg=mg(),WR=TypeError,Go=function(s,e){this.stopped=s,this.result=e},Sg=Go.prototype;vg.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=OR(e,i),l,d,c,h,p,f,m,g=function(y){return l&&gg(l,"normal",y),new Go(!0,y)},S=function(y){return r?(FR(y),o?u(y[0],y[1],g):u(y[0],y[1])):o?u(y,g):u(y)};if(a)l=s.iterator;else if(n)l=s;else{if(d=HR(s),!d)throw new WR(NR(s)+" is not iterable");if(UR(d)){for(c=0,h=qR(s);h>c;c++)if(p=S(s[c]),p&&bg(Sg,p))return p;return new Go(!1)}l=jR(s,d)}for(f=a?s.next:l.next;!(m=_R(f,l)).done;){try{p=S(m.value)}catch(y){gg(l,"throw",y)}if(typeof p=="object"&&p&&bg(Sg,p))return p}return new Go(!1)}});var Tg=b((cN,yg)=>{"use strict";var zR=St(),GR=ir(),QR=oa();yg.exports=function(s,e,t){zR?GR.f(s,e,QR(0,t)):s[e]=t}});var Ig=b(()=>{"use strict";var YR=Ee(),KR=Qo(),XR=Tg();YR({target:"Object",stat:!0},{fromEntries:function(e){var t={};return KR(e,function(i,r){XR(t,i,r)},{AS_ENTRIES:!0}),t}})});var Eg=b((hN,xg)=>{"use strict";Gc();Ig();var JR=Pr();xg.exports=JR.Object.fromEntries});var Pg=b((fN,wg)=>{"use strict";wg.exports={CSSRuleList:0,CSSStyleDeclaration:0,CSSValueList:0,ClientRectList:0,DOMRectList:0,DOMStringList:0,DOMTokenList:1,DataTransferItemList:0,FileList:0,HTMLAllCollection:0,HTMLCollection:0,HTMLFormElement:0,HTMLSelectElement:0,MediaList:0,MimeTypeArray:0,NamedNodeMap:0,NodeList:1,PaintRequestList:0,Plugin:0,PluginArray:0,SVGLengthList:0,SVGNumberList:0,SVGPathSegList:0,SVGPointList:0,SVGStringList:0,SVGTransformList:0,SourceBufferList:0,StyleSheetList:0,TextTrackCueList:0,TextTrackList:0,TouchList:0}});var kg=b(()=>{"use strict";Gc();var ZR=Pg(),eL=ve(),tL=Sa(),Ag=sr();for(Yo in ZR)tL(eL[Yo],Yo),Ag[Yo]=Ag.Array;var Yo});var Lg=b((gN,Rg)=>{"use strict";var iL=Eg();kg();Rg.exports=iL});var Yc=b((SN,Mg)=>{"use strict";var rL=Lg();Mg.exports=rL});var $g=b(()=>{"use strict"});var Kc=b((TN,Dg)=>{"use strict";var Ta=ve(),sL=tr(),aL=Zi(),Ko=function(s){return sL.slice(0,s.length)===s};Dg.exports=function(){return Ko("Bun/")?"BUN":Ko("Cloudflare-Workers")?"CLOUDFLARE":Ko("Deno/")?"DENO":Ko("Node.js/")?"NODE":Ta.Bun&&typeof Bun.version=="string"?"BUN":Ta.Deno&&typeof Deno.version=="object"?"DENO":aL(Ta.process)==="process"?"NODE":Ta.window&&Ta.document?"BROWSER":"REST"}()});var Xo=b((IN,Bg)=>{"use strict";var nL=Kc();Bg.exports=nL==="NODE"});var Vg=b((xN,Cg)=>{"use strict";var oL=ir();Cg.exports=function(s,e,t){return oL.f(s,e,t)}});var Fg=b((EN,_g)=>{"use strict";var uL=mi(),lL=Vg(),cL=Ne(),dL=St(),Og=cL("species");_g.exports=function(s){var e=uL(s);dL&&e&&!e[Og]&&lL(e,Og,{configurable:!0,get:function(){return this}})}});var Ug=b((wN,Ng)=>{"use strict";var pL=ua(),hL=TypeError;Ng.exports=function(s,e){if(pL(e,s))return s;throw new hL("Incorrect invocation")}});var Jc=b((PN,qg)=>{"use strict";var fL=De(),mL=ge(),Xc=da(),bL=fL(Function.toString);mL(Xc.inspectSource)||(Xc.inspectSource=function(s){return bL(s)});qg.exports=Xc.inspectSource});var ed=b((AN,Gg)=>{"use strict";var gL=De(),SL=Fe(),jg=ge(),vL=ga(),yL=mi(),TL=Jc(),Hg=function(){},Wg=yL("Reflect","construct"),Zc=/^\s*(?:class|function)\b/,IL=gL(Zc.exec),xL=!Zc.test(Hg),Ia=function(e){if(!jg(e))return!1;try{return Wg(Hg,[],e),!0}catch(t){return!1}},zg=function(e){if(!jg(e))return!1;switch(vL(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return xL||!!IL(Zc,TL(e))}catch(t){return!0}};zg.sham=!0;Gg.exports=!Wg||SL(function(){var s;return Ia(Ia.call)||!Ia(Object)||!Ia(function(){s=!0})||s})?zg:Ia});var Yg=b((kN,Qg)=>{"use strict";var EL=ed(),wL=la(),PL=TypeError;Qg.exports=function(s){if(EL(s))return s;throw new PL(wL(s)+" is not a constructor")}});var td=b((RN,Xg)=>{"use strict";var Kg=zt(),AL=Yg(),kL=wr(),RL=Ne(),LL=RL("species");Xg.exports=function(s,e){var t=Kg(s).constructor,i;return t===void 0||kL(i=Kg(t)[LL])?e:AL(i)}});var Zg=b((LN,Jg)=>{"use strict";var ML=De();Jg.exports=ML([].slice)});var tS=b((MN,eS)=>{"use strict";var $L=TypeError;eS.exports=function(s,e){if(s<e)throw new $L("Not enough arguments");return s}});var id=b(($N,iS)=>{"use strict";var DL=tr();iS.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(DL)});var dd=b((DN,dS)=>{"use strict";var It=ve(),BL=Wl(),CL=Rr(),rS=ge(),VL=_t(),cS=Fe(),sS=Cc(),OL=Zg(),aS=Mo(),_L=tS(),FL=id(),NL=Xo(),ud=It.setImmediate,ld=It.clearImmediate,UL=It.process,rd=It.Dispatch,qL=It.Function,nS=It.MessageChannel,jL=It.String,sd=0,xa={},oS="onreadystatechange",Ea,nr,ad,nd;cS(function(){Ea=It.location});var cd=function(s){if(VL(xa,s)){var e=xa[s];delete xa[s],e()}},od=function(s){return function(){cd(s)}},uS=function(s){cd(s.data)},lS=function(s){It.postMessage(jL(s),Ea.protocol+"//"+Ea.host)};(!ud||!ld)&&(ud=function(e){_L(arguments.length,1);var t=rS(e)?e:qL(e),i=OL(arguments,1);return xa[++sd]=function(){BL(t,void 0,i)},nr(sd),sd},ld=function(e){delete xa[e]},NL?nr=function(s){UL.nextTick(od(s))}:rd&&rd.now?nr=function(s){rd.now(od(s))}:nS&&!FL?(ad=new nS,nd=ad.port2,ad.port1.onmessage=uS,nr=CL(nd.postMessage,nd)):It.addEventListener&&rS(It.postMessage)&&!It.importScripts&&Ea&&Ea.protocol!=="file:"&&!cS(lS)?(nr=lS,It.addEventListener("message",uS,!1)):oS in aS("script")?nr=function(s){sS.appendChild(aS("script"))[oS]=function(){sS.removeChild(this),cd(s)}}:nr=function(s){setTimeout(od(s),0)});dS.exports={set:ud,clear:ld}});var fS=b((BN,hS)=>{"use strict";var pS=ve(),HL=St(),WL=Object.getOwnPropertyDescriptor;hS.exports=function(s){if(!HL)return pS[s];var e=WL(pS,s);return e&&e.value}});var pd=b((CN,bS)=>{"use strict";var mS=function(){this.head=null,this.tail=null};mS.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}}};bS.exports=mS});var SS=b((VN,gS)=>{"use strict";var zL=tr();gS.exports=/ipad|iphone|ipod/i.test(zL)&&typeof Pebble!="undefined"});var yS=b((ON,vS)=>{"use strict";var GL=tr();vS.exports=/web0s(?!.*chrome)/i.test(GL)});var AS=b((_N,PS)=>{"use strict";var Vr=ve(),QL=fS(),TS=Rr(),hd=dd().set,YL=pd(),KL=id(),XL=SS(),JL=yS(),fd=Xo(),IS=Vr.MutationObserver||Vr.WebKitMutationObserver,xS=Vr.document,ES=Vr.process,Jo=Vr.Promise,gd=QL("queueMicrotask"),Cr,md,bd,Zo,wS;gd||(wa=new YL,Pa=function(){var s,e;for(fd&&(s=ES.domain)&&s.exit();e=wa.get();)try{e()}catch(t){throw wa.head&&Cr(),t}s&&s.enter()},!KL&&!fd&&!JL&&IS&&xS?(md=!0,bd=xS.createTextNode(""),new IS(Pa).observe(bd,{characterData:!0}),Cr=function(){bd.data=md=!md}):!XL&&Jo&&Jo.resolve?(Zo=Jo.resolve(void 0),Zo.constructor=Jo,wS=TS(Zo.then,Zo),Cr=function(){wS(Pa)}):fd?Cr=function(){ES.nextTick(Pa)}:(hd=TS(hd,Vr),Cr=function(){hd(Pa)}),gd=function(s){wa.head||Cr(),wa.add(s)});var wa,Pa;PS.exports=gd});var RS=b((FN,kS)=>{"use strict";kS.exports=function(s,e){try{arguments.length===1?console.error(s):console.error(s,e)}catch(t){}}});var eu=b((NN,LS)=>{"use strict";LS.exports=function(s){try{return{error:!1,value:s()}}catch(e){return{error:!0,value:e}}}});var or=b((UN,MS)=>{"use strict";var ZL=ve();MS.exports=ZL.Promise});var Or=b((qN,CS)=>{"use strict";var eM=ve(),Aa=or(),tM=ge(),iM=hc(),rM=Jc(),sM=Ne(),$S=Kc(),aM=Ot(),Sd=ec(),DS=Aa&&Aa.prototype,nM=sM("species"),vd=!1,BS=tM(eM.PromiseRejectionEvent),oM=iM("Promise",function(){var s=rM(Aa),e=s!==String(Aa);if(!e&&Sd===66||aM&&!(DS.catch&&DS.finally))return!0;if(!Sd||Sd<51||!/native code/.test(s)){var t=new Aa(function(a){a(1)}),i=function(a){a(function(){},function(){})},r=t.constructor={};if(r[nM]=i,vd=t.then(function(){})instanceof i,!vd)return!0}return!e&&($S==="BROWSER"||$S==="DENO")&&!BS});CS.exports={CONSTRUCTOR:oM,REJECTION_EVENT:BS,SUBCLASSING:vd}});var _r=b((jN,OS)=>{"use strict";var VS=Wt(),uM=TypeError,lM=function(s){var e,t;this.promise=new s(function(i,r){if(e!==void 0||t!==void 0)throw new uM("Bad Promise constructor");e=i,t=r}),this.resolve=VS(e),this.reject=VS(t)};OS.exports.f=function(s){return new lM(s)}});var iv=b(()=>{"use strict";var cM=Ee(),dM=Ot(),su=Xo(),Di=ve(),qr=vt(),_S=Br(),FS=Hc(),pM=Sa(),hM=Fg(),fM=Wt(),ru=ge(),mM=yt(),bM=Ug(),gM=td(),HS=dd().set,Ed=AS(),SM=RS(),vM=eu(),yM=pd(),WS=Mc(),au=or(),wd=Or(),zS=_r(),nu="Promise",GS=wd.CONSTRUCTOR,TM=wd.REJECTION_EVENT,IM=wd.SUBCLASSING,yd=WS.getterFor(nu),xM=WS.set,Fr=au&&au.prototype,ur=au,tu=Fr,QS=Di.TypeError,Td=Di.document,Pd=Di.process,Id=zS.f,EM=Id,wM=!!(Td&&Td.createEvent&&Di.dispatchEvent),YS="unhandledrejection",PM="rejectionhandled",NS=0,KS=1,AM=2,Ad=1,XS=2,iu,US,kM,qS,JS=function(s){var e;return mM(s)&&ru(e=s.then)?e:!1},ZS=function(s,e){var t=e.value,i=e.state===KS,r=i?s.ok:s.fail,a=s.resolve,n=s.reject,o=s.domain,u,l,d;try{r?(i||(e.rejection===XS&&LM(e),e.rejection=Ad),r===!0?u=t:(o&&o.enter(),u=r(t),o&&(o.exit(),d=!0)),u===s.promise?n(new QS("Promise-chain cycle")):(l=JS(u))?qr(l,u,a,n):a(u)):n(t)}catch(c){o&&!d&&o.exit(),n(c)}},ev=function(s,e){s.notified||(s.notified=!0,Ed(function(){for(var t=s.reactions,i;i=t.get();)ZS(i,s);s.notified=!1,e&&!s.rejection&&RM(s)}))},tv=function(s,e,t){var i,r;wM?(i=Td.createEvent("Event"),i.promise=e,i.reason=t,i.initEvent(s,!1,!0),Di.dispatchEvent(i)):i={promise:e,reason:t},!TM&&(r=Di["on"+s])?r(i):s===YS&&SM("Unhandled promise rejection",t)},RM=function(s){qr(HS,Di,function(){var e=s.facade,t=s.value,i=jS(s),r;if(i&&(r=vM(function(){su?Pd.emit("unhandledRejection",t,e):tv(YS,e,t)}),s.rejection=su||jS(s)?XS:Ad,r.error))throw r.value})},jS=function(s){return s.rejection!==Ad&&!s.parent},LM=function(s){qr(HS,Di,function(){var e=s.facade;su?Pd.emit("rejectionHandled",e):tv(PM,e,s.value)})},Nr=function(s,e,t){return function(i){s(e,i,t)}},Ur=function(s,e,t){s.done||(s.done=!0,t&&(s=t),s.value=e,s.state=AM,ev(s,!0))},xd=function(s,e,t){if(!s.done){s.done=!0,t&&(s=t);try{if(s.facade===e)throw new QS("Promise can't be resolved itself");var i=JS(e);i?Ed(function(){var r={done:!1};try{qr(i,e,Nr(xd,r,s),Nr(Ur,r,s))}catch(a){Ur(r,a,s)}}):(s.value=e,s.state=KS,ev(s,!1))}catch(r){Ur({done:!1},r,s)}}};if(GS&&(ur=function(e){bM(this,tu),fM(e),qr(iu,this);var t=yd(this);try{e(Nr(xd,t),Nr(Ur,t))}catch(i){Ur(t,i)}},tu=ur.prototype,iu=function(e){xM(this,{type:nu,done:!1,notified:!1,parent:!1,reactions:new yM,rejection:!1,state:NS,value:void 0})},iu.prototype=_S(tu,"then",function(e,t){var i=yd(this),r=Id(gM(this,ur));return i.parent=!0,r.ok=ru(e)?e:!0,r.fail=ru(t)&&t,r.domain=su?Pd.domain:void 0,i.state===NS?i.reactions.add(r):Ed(function(){ZS(r,i)}),r.promise}),US=function(){var s=new iu,e=yd(s);this.promise=s,this.resolve=Nr(xd,e),this.reject=Nr(Ur,e)},zS.f=Id=function(s){return s===ur||s===kM?new US(s):EM(s)},!dM&&ru(au)&&Fr!==Object.prototype)){qS=Fr.then,IM||_S(Fr,"then",function(e,t){var i=this;return new ur(function(r,a){qr(qS,i,r,a)}).then(e,t)},{unsafe:!0});try{delete Fr.constructor}catch(s){}FS&&FS(Fr,tu)}cM({global:!0,constructor:!0,wrap:!0,forced:GS},{Promise:ur});pM(ur,nu,!1,!0);hM(nu)});var ov=b((zN,nv)=>{"use strict";var MM=Ne(),sv=MM("iterator"),av=!1;try{rv=0,kd={next:function(){return{done:!!rv++}},return:function(){av=!0}},kd[sv]=function(){return this},Array.from(kd,function(){throw 2})}catch(s){}var rv,kd;nv.exports=function(s,e){try{if(!e&&!av)return!1}catch(r){return!1}var t=!1;try{var i={};i[sv]=function(){return{next:function(){return{done:t=!0}}}},s(i)}catch(r){}return t}});var Rd=b((GN,uv)=>{"use strict";var $M=or(),DM=ov(),BM=Or().CONSTRUCTOR;uv.exports=BM||!DM(function(s){$M.all(s).then(void 0,function(){})})});var lv=b(()=>{"use strict";var CM=Ee(),VM=vt(),OM=Wt(),_M=_r(),FM=eu(),NM=Qo(),UM=Rd();CM({target:"Promise",stat:!0,forced:UM},{all:function(e){var t=this,i=_M.f(t),r=i.resolve,a=i.reject,n=FM(function(){var o=OM(t.resolve),u=[],l=0,d=1;NM(e,function(c){var h=l++,p=!1;d++,VM(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 dv=b(()=>{"use strict";var qM=Ee(),jM=Ot(),HM=Or().CONSTRUCTOR,Md=or(),WM=mi(),zM=ge(),GM=Br(),cv=Md&&Md.prototype;qM({target:"Promise",proto:!0,forced:HM,real:!0},{catch:function(s){return this.then(void 0,s)}});!jM&&zM(Md)&&(Ld=WM("Promise").prototype.catch,cv.catch!==Ld&&GM(cv,"catch",Ld,{unsafe:!0}));var Ld});var pv=b(()=>{"use strict";var QM=Ee(),YM=vt(),KM=Wt(),XM=_r(),JM=eu(),ZM=Qo(),e$=Rd();QM({target:"Promise",stat:!0,forced:e$},{race:function(e){var t=this,i=XM.f(t),r=i.reject,a=JM(function(){var n=KM(t.resolve);ZM(e,function(o){YM(n,t,o).then(i.resolve,r)})});return a.error&&r(a.value),i.promise}})});var hv=b(()=>{"use strict";var t$=Ee(),i$=_r(),r$=Or().CONSTRUCTOR;t$({target:"Promise",stat:!0,forced:r$},{reject:function(e){var t=i$.f(this),i=t.reject;return i(e),t.promise}})});var $d=b((iU,fv)=>{"use strict";var s$=zt(),a$=yt(),n$=_r();fv.exports=function(s,e){if(s$(s),a$(e)&&e.constructor===s)return e;var t=n$.f(s),i=t.resolve;return i(e),t.promise}});var gv=b(()=>{"use strict";var o$=Ee(),u$=mi(),mv=Ot(),l$=or(),bv=Or().CONSTRUCTOR,c$=$d(),d$=u$("Promise"),p$=mv&&!bv;o$({target:"Promise",stat:!0,forced:mv||bv},{resolve:function(e){return c$(p$&&this===d$?l$:this,e)}})});var Sv=b(()=>{"use strict";iv();lv();dv();pv();hv();gv()});var Iv=b(()=>{"use strict";var h$=Ee(),f$=Ot(),ou=or(),m$=Fe(),yv=mi(),Tv=ge(),b$=td(),vv=$d(),g$=Br(),Bd=ou&&ou.prototype,S$=!!ou&&m$(function(){Bd.finally.call({then:function(){}},function(){})});h$({target:"Promise",proto:!0,real:!0,forced:S$},{finally:function(s){var e=b$(this,yv("Promise")),t=Tv(s);return this.then(t?function(i){return vv(e,s()).then(function(){return i})}:s,t?function(i){return vv(e,s()).then(function(){throw i})}:s)}});!f$&&Tv(ou)&&(Dd=yv("Promise").prototype.finally,Bd.finally!==Dd&&g$(Bd,"finally",Dd,{unsafe:!0}));var Dd});var Ev=b((lU,xv)=>{"use strict";$g();Sv();Iv();var v$=$i();xv.exports=v$("Promise","finally")});var Pv=b((cU,wv)=>{"use strict";var y$=Ev();wv.exports=y$});var ka=b((dU,Av)=>{"use strict";var T$=Pv();Av.exports=T$});var Nv=b(()=>{"use strict";var C$=Ee(),V$=Ac().values;C$({target:"Object",stat:!0},{values:function(e){return V$(e)}})});var qv=b((YU,Uv)=>{"use strict";Nv();var O$=Pr();Uv.exports=O$.Object.values});var Hv=b((KU,jv)=>{"use strict";var _$=qv();jv.exports=_$});var dr=b((XU,Wv)=>{"use strict";var F$=Hv();Wv.exports=F$});var oy=b(()=>{"use strict";var lD=Ee(),cD=Ar(),dD=Dr(),pD=fa(),hD=ma();lD({target:"Array",proto:!0},{at:function(e){var t=cD(this),i=dD(t),r=pD(e),a=r>=0?r:i+r;return a<0||a>=i?void 0:t[a]}});hD("at")});var ly=b((nq,uy)=>{"use strict";oy();var fD=$i();uy.exports=fD("Array","at")});var dy=b((oq,cy)=>{"use strict";var mD=ly();cy.exports=mD});var Nt=b((uq,py)=>{"use strict";var bD=dy();py.exports=bD});var rp=b((Gj,Wy)=>{"use strict";var YD=Zi();Wy.exports=Array.isArray||function(e){return YD(e)==="Array"}});var Gy=b((Qj,zy)=>{"use strict";var KD=TypeError,XD=9007199254740991;zy.exports=function(s){if(s>XD)throw KD("Maximum allowed index exceeded");return s}});var Ky=b((Yj,Yy)=>{"use strict";var JD=rp(),ZD=Dr(),eB=Gy(),tB=Rr(),Qy=function(s,e,t,i,r,a,n,o){for(var u=r,l=0,d=n?tB(n,o):!1,c,h;l<i;)l in t&&(c=d?d(t[l],l,e):t[l],a>0&&JD(c)?(h=ZD(c),u=Qy(s,e,c,h,u,a-1)-1):(eB(u+1),s[u]=c),u++),l++;return u};Yy.exports=Qy});var eT=b((Kj,Zy)=>{"use strict";var Xy=rp(),iB=ed(),rB=yt(),sB=Ne(),aB=sB("species"),Jy=Array;Zy.exports=function(s){var e;return Xy(s)&&(e=s.constructor,iB(e)&&(e===Jy||Xy(e.prototype))?e=void 0:rB(e)&&(e=e[aB],e===null&&(e=void 0))),e===void 0?Jy:e}});var iT=b((Xj,tT)=>{"use strict";var nB=eT();tT.exports=function(s,e){return new(nB(s))(e===0?0:e)}});var rT=b(()=>{"use strict";var oB=Ee(),uB=Ky(),lB=Wt(),cB=Ar(),dB=Dr(),pB=iT();oB({target:"Array",proto:!0},{flatMap:function(e){var t=cB(this),i=dB(t),r;return lB(e),r=pB(t,0),r.length=uB(r,t,t,i,0,1,e,arguments.length>1?arguments[1]:void 0),r}})});var sT=b(()=>{"use strict";var hB=ma();hB("flatMap")});var nT=b((iH,aT)=>{"use strict";rT();sT();var fB=$i();aT.exports=fB("Array","flatMap")});var uT=b((rH,oT)=>{"use strict";var mB=nT();oT.exports=mB});var Wa=b((sH,lT)=>{"use strict";var bB=uT();lT.exports=bB});var za=b((aH,cT)=>{"use strict";var gB=ga(),SB=String;cT.exports=function(s){if(gB(s)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return SB(s)}});var sp=b((nH,dT)=>{"use strict";dT.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 fT=b((oH,hT)=>{"use strict";var vB=De(),yB=Mi(),TB=za(),np=sp(),pT=vB("".replace),IB=RegExp("^["+np+"]+"),xB=RegExp("(^|[^"+np+"])["+np+"]+$"),ap=function(s){return function(e){var t=TB(yB(e));return s&1&&(t=pT(t,IB,"")),s&2&&(t=pT(t,xB,"$1")),t}};hT.exports={start:ap(1),end:ap(2),trim:ap(3)}});var ST=b((uH,gT)=>{"use strict";var EB=Bc().PROPER,wB=Fe(),mT=sp(),bT="\u200B\x85\u180E";gT.exports=function(s){return wB(function(){return!!mT[s]()||bT[s]()!==bT||EB&&mT[s].name!==s})}});var op=b((lH,vT)=>{"use strict";var PB=fT().start,AB=ST();vT.exports=AB("trimStart")?function(){return PB(this)}:"".trimStart});var TT=b(()=>{"use strict";var kB=Ee(),yT=op();kB({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==yT},{trimLeft:yT})});var xT=b(()=>{"use strict";TT();var RB=Ee(),IT=op();RB({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==IT},{trimStart:IT})});var wT=b((fH,ET)=>{"use strict";xT();var LB=$i();ET.exports=LB("String","trimLeft")});var AT=b((mH,PT)=>{"use strict";var MB=wT();PT.exports=MB});var RT=b((bH,kT)=>{"use strict";var $B=AT();kT.exports=$B});var HT=b(()=>{"use strict"});var WT=b(()=>{"use strict"});var GT=b((K3,zT)=>{"use strict";var t0=yt(),i0=Zi(),r0=Ne(),s0=r0("match");zT.exports=function(s){var e;return t0(s)&&((e=s[s0])!==void 0?!!e:i0(s)==="RegExp")}});var YT=b((X3,QT)=>{"use strict";var a0=zt();QT.exports=function(){var s=a0(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 JT=b((J3,XT)=>{"use strict";var n0=vt(),o0=_t(),u0=ua(),l0=YT(),KT=RegExp.prototype;XT.exports=function(s){var e=s.flags;return e===void 0&&!("flags"in KT)&&!o0(s,"flags")&&u0(KT,s)?n0(l0,s):e}});var eI=b((Z3,ZT)=>{"use strict";var hp=De(),c0=Ar(),d0=Math.floor,dp=hp("".charAt),p0=hp("".replace),pp=hp("".slice),h0=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,f0=/\$([$&'`]|\d{1,2})/g;ZT.exports=function(s,e,t,i,r,a){var n=t+s.length,o=i.length,u=f0;return r!==void 0&&(r=c0(r),u=h0),p0(a,u,function(l,d){var c;switch(dp(d,0)){case"$":return"$";case"&":return s;case"`":return pp(e,0,t);case"'":return pp(e,n);case"<":c=r[pp(d,1,-1)];break;default:var h=+d;if(h===0)return l;if(h>o){var p=d0(h/10);return p===0?l:p<=o?i[p-1]===void 0?dp(d,1):i[p-1]+dp(d,1):l}c=i[h-1]}return c===void 0?"":c})}});var rI=b(()=>{"use strict";var m0=Ee(),b0=vt(),mp=De(),tI=Mi(),g0=ge(),S0=wr(),v0=GT(),is=za(),y0=ca(),T0=JT(),I0=eI(),x0=Ne(),E0=Ot(),w0=x0("replace"),P0=TypeError,fp=mp("".indexOf),A0=mp("".replace),iI=mp("".slice),k0=Math.max;m0({target:"String",proto:!0},{replaceAll:function(e,t){var i=tI(this),r,a,n,o,u,l,d,c,h,p,f=0,m="";if(!S0(e)){if(r=v0(e),r&&(a=is(tI(T0(e))),!~fp(a,"g")))throw new P0("`.replaceAll` does not allow non-global regexes");if(n=y0(e,w0),n)return b0(n,e,i,t);if(E0&&r)return A0(is(i),e,t)}for(o=is(i),u=is(e),l=g0(t),l||(t=is(t)),d=u.length,c=k0(1,d),h=fp(o,u);h!==-1;)p=l?is(t(u,h,o)):I0(u,o,h,[],void 0,t),m+=iI(o,f,h)+p,f=h+d,h=h+c>o.length?-1:fp(o,u,h+c);return f<o.length&&(m+=iI(o,f)),m}})});var aI=b((iW,sI)=>{"use strict";HT();WT();rI();var R0=$i();sI.exports=R0("String","replaceAll")});var oI=b((rW,nI)=>{"use strict";var L0=aI();nI.exports=L0});var bp=b((sW,uI)=>{"use strict";var M0=oI();uI.exports=M0});var cI=b((aW,lI)=>{"use strict";var $0=fa(),D0=za(),B0=Mi(),C0=RangeError;lI.exports=function(e){var t=D0(B0(this)),i="",r=$0(e);if(r<0||r===1/0)throw new C0("Wrong number of repetitions");for(;r>0;(r>>>=1)&&(t+=t))r&1&&(i+=t);return i}});var mI=b((nW,fI)=>{"use strict";var hI=De(),V0=vc(),dI=za(),O0=cI(),_0=Mi(),F0=hI(O0),N0=hI("".slice),U0=Math.ceil,pI=function(s){return function(e,t,i){var r=dI(_0(e)),a=V0(t),n=r.length,o=i===void 0?" ":dI(i),u,l;return a<=n||o===""?r:(u=a-n,l=F0(o,U0(u/o.length)),l.length>u&&(l=N0(l,0,u)),s?r+l:l+r)}};fI.exports={start:pI(!1),end:pI(!0)}});var gI=b((oW,bI)=>{"use strict";var q0=tr();bI.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(q0)});var SI=b(()=>{"use strict";var j0=Ee(),H0=mI().start,W0=gI();j0({target:"String",proto:!0,forced:W0},{padStart:function(e){return H0(this,e,arguments.length>1?arguments[1]:void 0)}})});var yI=b((cW,vI)=>{"use strict";SI();var z0=$i();vI.exports=z0("String","padStart")});var II=b((dW,TI)=>{"use strict";var G0=yI();TI.exports=G0});var gp=b((pW,xI)=>{"use strict";var Q0=II();xI.exports=Q0});var Ch="2.0.131-dev.6210de2e.0";var at=(r=>(r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused",r))(at||{}),fi=(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))(fi||{});var Ao=(r=>(r.NOT_AVAILABLE="NOT_AVAILABLE",r.AVAILABLE="AVAILABLE",r.CONNECTING="CONNECTING",r.CONNECTED="CONNECTED",r))(Ao||{}),ql=(i=>(i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic",i))(ql||{});var jl=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(jl||{}),ko=(i=>(i.TRAFFIC_SAVING="traffic_saving",i.HIGH_QUALITY="high_quality",i.UNKNOWN="unknown",i))(ko||{});var CE=U(Tt(),1);import{assertNever as Bm,assertNonNullable as uA,isNonNullable as Do,ValueSubject as Tc,Subject as lA,Subscription as cA,merge as dA,observableFrom as pA,fromEvent as Lm,map as Mm,tap as $m,filterChanged as hA,isNullable as Ic,ErrorCategory as Dm}from"@vkontakte/videoplayer-shared/es2018";var Rm=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 Bo=class{constructor(e){this.connection$=new Tc(void 0);this.castState$=new Tc("NOT_AVAILABLE");this.errorEvent$=new lA;this.realCastState$=new Tc("NOT_AVAILABLE");this.subscription=new cA;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=Do((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||Rm("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:Dm.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(){Do(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();Ic(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();Ic(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(Lm(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 Bm(r.sessionState)}})).add(dA(Lm(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe($m(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),Mm(r=>r.castState)),pA([i.getCastState()])).pipe(hA(),Mm(fA),$m(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{var o,u;let a=r==="CONNECTED",n=Do(this.connection$.getValue());if(a&&!n){let l=i.getCurrentSession();uA(l);let d=l.getCastDevice(),c=(u=(o=l.getMediaSession())==null?void 0:o.media)==null?void 0:u.contentId;(Ic(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"?Do(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:Dm.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:a})}}},fA=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 Bm(s)}};var Ph=U(Tt(),1),bE=U(rr(),1),gE=U(Yc(),1);var Ov=U(ka(),1);import{assertNever as kv}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:kv(t)}return s},Bi=(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:kv(e)}};var R=(s,e,t=!1)=>{let i=s.getTransition();(t||!i||i.to===e)&&s.setState(e)};import{isNonNullable as I$,Subject as uu,merge as Rv}from"@vkontakte/videoplayer-shared/es2018";var H=class{constructor(e){this.transitionStarted$=new uu;this.transitionEnded$=new uu;this.transitionUpdated$=new uu;this.forceChanged$=new uu;this.stateChangeStarted$=Rv(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=Rv(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||I$(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 x$}from"@vkontakte/videoplayer-shared/es2018";var Lv=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 x$(s)}};import{assertNever as jr,assertNonNullable as lr,debounce as Mv,ErrorCategory as $v,fromEvent as cr,isNonNullable as Dv,map as Bv,merge as Cv,observableFrom as E$,Subject as w$,Subscription as Cd,timeout as P$,getHighestQuality as A$}from"@vkontakte/videoplayer-shared/es2018";var k$=5,R$=5,L$=500,Vv=7e3,Ra=class{constructor(e){this.subscription=new Cd;this.loadMediaTimeoutSubscription=new Cd;this.videoState=new H("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:jr(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:jr(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:jr(e)}break}default:jr(i)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(Lv(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 Cd;this.subscription.add(e),this.subscription.add(Cv(this.videoState.stateChangeStarted$.pipe(Bv(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe(Bv(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 w$;e.add(r.pipe(Mv(L$)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let a=NaN;e.add(cr(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)>k$)&&r.next(o),a=o})),e.add(cr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(cr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(cr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t(cr(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<R$&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),R(this.params.desiredState.playbackState,"stopped");break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:jr(n)}}),t(cr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t(cr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});let i=Cv(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,E$(["init"])).pipe(Mv(0));t(i,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});let{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState("paused"),R(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),R(this.params.desiredState.playbackState,"playing"));let i=this.params.output.isLive$.getValue();this.params.output.duration$.next(i?0:t.duration),this.params.output.position$.next(i?0:t.currentTime),this.params.desiredState.seekState.setState({state:"none"})}}prepare(){let e=this.params.format;this.log({message:`[prepare] format: ${e}`});let t=this.createMediaInfo(e),i=this.createLoadRequest(t);this.loadMedia(i)}handleRemotePause(){let e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="paused"||e==="playing")&&(this.videoState.setState("paused"),R(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"),R(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"&&R(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];lr(d);let c=A$(Object.keys(d));lr(c);let h=d[c];lr(h),i=h,r="video/mp4",a=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let d=t[e];lr(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];lr(d),i=d.url,r="application/dash+xml",a=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let d=t[e];lr(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];lr(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:$v.VIDEO_PIPELINE,message:d,thrown:c}),c}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return jr(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 Dv(o)&&(n.metadata.title=o),Dv(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(P$(Vv).subscribe(()=>a(`timeout(${Vv})`)))});(0,Ov.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:$v.VIDEO_PIPELINE,message:a,thrown:r})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var tp=U(Tt(),1);import{clearVideoElement as Fv}from"@vkontakte/videoplayer-shared/es2018";import{clearVideoElement as M$}from"@vkontakte/videoplayer-shared/es2018";var _v=s=>{try{s.pause(),s.playbackRate=0,M$(s),s.remove()}catch(e){console.error(e)}};import{fromEvent as $$,Subscription as D$}from"@vkontakte/videoplayer-shared/es2018";var Vd=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)}},Od=window.WeakMap?new WeakMap:new Vd,_d=window.WeakMap?new WeakMap:new Map,B$=(s,e=20)=>{let t=0;return $$(s,"ratechange").subscribe(i=>{t++,t>=e&&(s.currentTime=s.currentTime,t=0)})},Ue=(s,{audioVideoSyncRate:e,disableYandexPiP:t})=>{let i=s.querySelector("video"),r=!!i;i?Fv(i):(i=document.createElement("video"),s.appendChild(i)),Od.set(i,r);let a=new D$;return a.add(B$(i,e)),_d.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},qe=s=>{let e=_d.get(s);e==null||e.unsubscribe(),_d.delete(s);let t=Od.get(s);Od.delete(s),t?Fv(s):_v(s)};var Nd=U(dr(),1);import{assertNonNullable as La,isNonNullable as Qt,isNullable as q$,fromEvent as Hr,merge as zv,observableFrom as Gv,filterChanged as Qv,map as Ma,Subject as Yv,Subscription as j$,ValueSubject as H$,ErrorCategory as W$}from"@vkontakte/videoplayer-shared/es2018";import{isNonNullable as Fd,isNullable as N$,Subscription as U$}from"@vkontakte/videoplayer-shared/es2018";var lu=(s,e,t,{equal:i=(n,o)=>n===o,changed$:r,onError:a}={})=>{let n=s.getState(),o=e(),u=N$(r),l=new U$;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},Pt=(s,e,t)=>lu(e,()=>s.loop,i=>{Fd(i)&&(s.loop=i)},{onError:t}),je=(s,e,t,i)=>lu(e,()=>({muted:s.muted,volume:s.volume}),r=>{Fd(r)&&(s.muted=r.muted,s.volume=r.volume)},{equal:(r,a)=>r===a||(r==null?void 0:r.muted)===(a==null?void 0:a.muted)&&(r==null?void 0:r.volume)===(a==null?void 0:a.volume),changed$:t,onError:i}),nt=(s,e,t,i)=>lu(e,()=>s.playbackRate,r=>{Fd(r)&&(s.playbackRate=r)},{changed$:t,onError:i}),Ci=lu;var z$=s=>["__",s.language,s.label].join("|"),G$=(s,e)=>{if(s.id===e)return!0;let[t,i,r]=e.split("|");return s.language===i&&s.label===r},Ud=class s{constructor(e){this.available$=new Yv;this.current$=new H$(void 0);this.error$=new Yv;this.subscription=new j$;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:W$.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(Ci(t.internalTextTracks,()=>(0,Nd.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(Ma(a=>a.filter(({type:n})=>n==="internal"))),onError:r})),this.subscription.add(Ci(t.externalTextTracks,()=>(0,Nd.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(Ma(a=>a.filter(({type:n})=>n==="external"))),onError:r})),this.subscription.add(Ci(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(Ci(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let a of this.htmlTextTracksAsArray())this.applyCueSettings(a.cues),this.applyCueSettings(a.activeCues)}))}subscribe(){La(this.video);let{textTracks:e}=this.video;this.subscription.add(Hr(e,"addtrack").subscribe(()=>{let i=this.current$.getValue();i&&this.select(i)})),this.subscription.add(zv(Hr(e,"addtrack"),Hr(e,"removetrack"),Gv(["init"])).pipe(Ma(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),Qv((i,r)=>i.length===r.length&&i.every(({id:a},n)=>a===r[n].id))).subscribe(this.available$)),this.subscription.add(zv(Hr(e,"change"),Gv(["init"])).pipe(Ma(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),Ma(i=>i&&this.htmlTextTrackToITextTrack(i).id),Qv()).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(Hr(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(Hr(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){La(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:z$(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){La(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(q$(e)||!G$(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){La(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){La(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)}},ot=Ud;var pr=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 Kv=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},qd=s=>{let e=Kv(s);return!!(e&&e.fullscreenElement&&e.fullscreenElement===s)},Xv=s=>{let e=Kv(s);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===s)};import{fromEvent as ut,map as Vi,merge as Hd,filterChanged as iD,isNonNullable as ay,Subject as rD,filter as Da,mapTo as Wd,combine as sD,once as aD,throttle as nD,ErrorCategory as oD,ValueSubject as ny,Subscription as uD}from"@vkontakte/videoplayer-shared/es2018";var Q$=3,Jv=(s,e,t=Q$)=>{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 cu=class{get current(){return this._current}get isYandex(){return this.current==="Yandex"}get isSafari(){return this.current==="Safari"}get isSamsungBrowser(){return this.current==="SamsungBrowser"}get safariVersion(){return this._safariVersion}detect(){let{userAgent:e}=navigator;try{let t=/yabrowser/i.test(e)?"Yandex":void 0,i=/samsungbrowser/i.test(e)?"SamsungBrowser":void 0,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._current=t||i||n||u||l||r||a||o||"Rest"}catch(t){console.error(t)}this.isSafari&&this.detectSafariVersion()}detectSafariVersion(){try{let{userAgent:e}=window.navigator,t=e.match(/Version\/(\d+)/);if(!t)return;let i=t[1],r=parseInt(i,10);if(isNaN(r))return;this._safariVersion=r}catch(e){console.error(e)}}};var Zv=U(Tt(),1);var $a=()=>{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 du=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,Zv.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=$a()}catch(t){console.error(t)}this.detectDevice(e),this.detectHighEntropyValues(),this.isIOS&&this.detectIOSVersion()}async detectHighEntropyValues(){let{userAgentData:e}=navigator;if(e){let t=await e.getHighEntropyValues(["architecture","bitness","brands","mobile","platform","formFactor","model","platformVersion","wow64"]);this._highEntropyValues=t}}detectDevice(e){try{let t=/android/i.test(e)?"Android":void 0,i=/iphone/i.test(e)?"iPhone":void 0,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 pu=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 xt=()=>window.ManagedMediaSource||window.MediaSource,Wr=()=>{var s,e;return!!(window.ManagedMediaSource&&((e=(s=window.ManagedSourceBuffer)==null?void 0:s.prototype)!=null&&e.appendBuffer))},ey=()=>{var s,e;return!!(window.MediaSource&&((e=(s=window.SourceBuffer)==null?void 0:s.prototype)!=null&&e.appendBuffer))},hu=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var Y$=document.createElement("video"),K$='video/mp4; codecs="avc1.42000a,mp4a.40.2"',X$='video/mp4; codecs="hev1.1.6.L93.B0"',ty='video/webm; codecs="vp09.00.10.08"',iy='video/webm; codecs="av01.0.00M.08"',J$='audio/mp4; codecs="mp4a.40.2"',Z$='audio/webm; codecs="opus"',ry,eD=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:iy}}),window.navigator.mediaCapabilities.decodingInfo({...s,video:{...s.video,contentType:ty}})]);ry={DASH_WEBM_AV1:e,DASH_WEBM:t}};eD().catch(s=>{console.log(Y$),console.error(s)});var fu=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 ry}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,y,v,I;this._video=document.createElement("video");try{this._protocols={mms:Wr(),mse:ey(),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=xt())==null?void 0:l.isTypeSupported)!=null&&d.call(l,K$)),E=!!((h=(c=xt())==null?void 0:c.isTypeSupported)!=null&&h.call(c,X$)),V=!!((f=(p=xt())==null?void 0:p.isTypeSupported)!=null&&f.call(p,J$));this._codecs={h264:T,h265:E,vp9:!!((g=(m=xt())==null?void 0:m.isTypeSupported)!=null&&g.call(m,ty)),av1:!!((y=(S=xt())==null?void 0:S.isTypeSupported)!=null&&y.call(S,iy)),aac:V,opus:!!((I=(v=xt())==null?void 0:v.isTypeSupported)!=null&&I.call(v,Z$)),mpeg:(T||E)&&V},this._nativeHlsSupported=this._protocols.hls&&this._containers.mp4}catch(T){console.error(T)}this.destroyVideoElement()}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 sy="audio/mpeg",mu=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,sy))},this._codecs={mp3:!!((r=(i=xt())==null?void 0:i.isTypeSupported)!=null&&r.call(i,sy))}}catch(a){console.error(a)}this.destroyAudioElement()}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 tD}from"@vkontakte/videoplayer-shared/es2018";var jd=class{constructor(){this.isInited$=new tD(!1);this._displayChecker=new pu,this._deviceChecker=new du(this._displayChecker),this._browserChecker=new cu,this._videoChecker=new fu(this._deviceChecker,this._browserChecker),this._audioChecker=new mu,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 jd;var He=s=>{let e=P=>ut(s,P).pipe(Wd(void 0)),t=new uD,i=()=>t.unsubscribe(),a=Hd(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(P=>ut(s,P))).pipe(Vi(P=>P.type==="ended"?s.readyState<2:s.readyState<3),iD()),n=Hd(ut(s,"progress"),ut(s,"timeupdate")).pipe(Vi(()=>Jv(s.buffered,s.currentTime))),o=j.browser.isSafari?sD({play:e("play").pipe(aD()),playing:e("playing")}).pipe(Wd(void 0)):e("playing"),u=ut(s,"volumechange").pipe(Vi(()=>({muted:s.muted,volume:s.volume}))),l=ut(s,"ratechange").pipe(Vi(()=>s.playbackRate)),d=ut(s,"error").pipe(Da(()=>!!(s.error||s.played.length)),Vi(()=>{var O;let P=s.error;return{id:P?`MediaError#${P.code}`:"HtmlVideoError",category:oD.VIDEO_PIPELINE,message:P?P.message:"Error event from HTML video element",thrown:(O=s.error)!=null?O:void 0}})),c=ut(s,"timeupdate").pipe(Vi(()=>s.currentTime)),h=new rD,p=.3,f;t.add(c.subscribe(P=>{s.loop&&ay(f)&&ay(P)&&f>=s.duration-p&&P<=p&&h.next(f),f=P}));let m=e("pause").pipe(Da(()=>!s.error&&f!==s.duration)),g=ut(s,"enterpictureinpicture"),S=ut(s,"leavepictureinpicture"),y=new ny(Xv(s));t.add(g.subscribe(()=>y.next(!0))),t.add(S.subscribe(()=>y.next(!1)));let v=new ny(qd(s)),I=ut(s,"fullscreenchange");t.add(I.pipe(Vi(()=>qd(s))).subscribe(v));let T=.1,E=1e3,V=ut(s,"timeupdate").pipe(Da(P=>s.duration-s.currentTime<T)),L=Hd(V.pipe(Da(P=>!s.loop)),ut(s,"ended")).pipe(nD(E),Wd(void 0)),k=V.pipe(Da(P=>s.loop));return{playing$:o,pause$:m,canplay$:e("canplay"),ended$:L,looped$:h,loopExpected$:k,error$:d,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:c,durationChange$:ut(s,"durationchange").pipe(Vi(()=>s.duration)),isBuffering$:a,currentBuffer$:n,volumeState$:u,playbackRateState$:l,inPiP$:y,inFullscreen$:v,enterPip$:g,leavePip$:S,destroy:i}};import{VideoQuality as Oi}from"@vkontakte/videoplayer-shared/es2018";var Yt=s=>{switch(s){case"mobile":return Oi.Q_144P;case"lowest":return Oi.Q_240P;case"low":return Oi.Q_360P;case"sd":case"medium":return Oi.Q_480P;case"hd":case"high":return Oi.Q_720P;case"fullhd":case"full":return Oi.Q_1080P;case"quadhd":case"quad":return Oi.Q_1440P;case"ultrahd":case"ultra":return Oi.Q_2160P}};var it=U(Nt(),1),Qd=U(Tt(),1),hr=U(rr(),1);import{isNonNullable as te,isNullable as yu,now as Iy,isHigher as Tu,isHigherOrEqual as Gr,isInvariantQuality as Iu,isLowerOrEqual as Qr,videoSizeToQuality as xy,assertNotEmptyArray as xu,assertNonNullable as Ey}from"@vkontakte/videoplayer-shared/es2018";var zd=!1,gi={},hy=s=>{zd=s},fy=()=>{gi={}},my=s=>{s(gi)},Ba=(s,e)=>{var t;zd&&(gi.meta=(t=gi.meta)!=null?t:{},gi.meta[s]=e)},tt=class{constructor(e){this.name=e}next(e){var i,r;if(!zd)return;gi.series=(i=gi.series)!=null?i:{};let t=(r=gi.series[this.name])!=null?r:[];t.push([Date.now(),e]),gi.series[this.name]=t}};import{isHigher as gD,isHigherOrEqual as fq,isLower as by,isLowerOrEqual as mq,isNonNullable as bu,isNullable as SD,videoHeightToQuality as gu}from"@vkontakte/videoplayer-shared/es2018";function Gd(s,e,t){return!s.max&&s.min===e?"high_quality":!s.min&&s.max===t?"traffic_saving":"unknown"}function Su(s,e,t){return!!s&&Gd(s,e,t)==="high_quality"}function zr(s,e,t){return SD(s)||bu(s.min)&&bu(s.max)&&by(s.max,s.min)||bu(s.min)&&e&&gD(s.min,e)||bu(s.max)&&t&&by(s.max,t)}function gy({limits:s,highestAvailableHeight:e,lowestAvailableHeight:t}){return zr({max:s!=null&&s.max?gu(s.max):void 0,min:s!=null&&s.min?gu(s.min):void 0},e?gu(e):void 0,t?gu(t):void 0)}var wy=new tt("best_bitrate"),Eu=(s,e,t)=>(e-t)*Math.pow(2,-10*s)+t;var Yr=s=>(e,t)=>s*(Number(e.bitrate)-Number(t.bitrate)),_i=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=Iy()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},wu='Assertion "ABR Tracks is empty array" failed',vu=new WeakMap,Sy=new WeakMap,vy=new WeakMap,Ca=(s,e,t,i)=>{var u;let r=[...e].sort(Yr(1)),a=[...t].sort(Yr(1)),n=a.filter(l=>te(l.bitrate)&&te(s.bitrate)?s.bitrate/l.bitrate>i:!0),o=(u=(0,it.default)(a,Math.round(a.length*r.indexOf(s)/(r.length+1))))!=null?u:(0,it.default)(a,-1);return o&&(0,Qd.default)(n,o)?o:n.length?(0,it.default)(n,-1):(0,it.default)(a,0)},Va=(s,e,t,i)=>{var u;let r=vu.get(e);r||(r=[...e].sort(Yr(1)),vu.set(e,r));let a=vu.get(t);a||(a=[...t].sort(Yr(1)),vu.set(t,a));let n=vy.get(s);n||(n=a.filter(l=>te(l.bitrate)&&te(s.bitrate)?s.bitrate/l.bitrate>i:!0),vy.set(s,n));let o=(u=(0,it.default)(a,Math.round(a.length*r.indexOf(s)/(r.length+1))))!=null?u:(0,it.default)(a,-1);return o&&(0,Qd.default)(n,o)?o:n.length?(0,it.default)(n,-1):(0,it.default)(a,0)},yy=s=>"quality"in s,Pu=(s,e,t,i)=>{var n;let r=te((n=i==null?void 0:i.last)==null?void 0:n.bitrate)&&te(t==null?void 0:t.bitrate)&&i.last.bitrate<t.bitrate?s.trackCooldownIncreaseQuality:s.trackCooldownDecreaseQuality,a=t&&i&&i.history[t.id]&&Iy()-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=yy(o)?"video":"audio",l=yy(o)?o.quality:o.bitrate;return e({message:`
|
|
6
|
+
var QT=Object.create;var od=Object.defineProperty;var GT=Object.getOwnPropertyDescriptor;var WT=Object.getOwnPropertyNames;var YT=Object.getPrototypeOf,zT=Object.prototype.hasOwnProperty;var f=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports);var KT=(a,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of WT(e))!zT.call(a,r)&&r!==t&&od(a,r,{get:()=>e[r],enumerable:!(i=GT(e,r))||i.enumerable});return a};var C=(a,e,t)=>(t=a!=null?QT(YT(a)):{},KT(e||!a||!a.__esModule?od(t,"default",{value:a,enumerable:!0}):t,a));var ie=f((Jn,ld)=>{"use strict";var pr=function(a){return a&&a.Math===Math&&a};ld.exports=pr(typeof globalThis=="object"&&globalThis)||pr(typeof window=="object"&&window)||pr(typeof self=="object"&&self)||pr(typeof global=="object"&&global)||pr(typeof Jn=="object"&&Jn)||function(){return this}()||Function("return this")()});var de=f((P0,cd)=>{"use strict";cd.exports=function(a){try{return!!a()}catch(e){return!0}}});var hr=f((w0,dd)=>{"use strict";var XT=de();dd.exports=!XT(function(){var a=function(){}.bind();return typeof a!="function"||a.hasOwnProperty("prototype")})});var Zn=f((A0,fd)=>{"use strict";var JT=hr(),md=Function.prototype,pd=md.apply,hd=md.call;fd.exports=typeof Reflect=="object"&&Reflect.apply||(JT?hd.bind(pd):function(){return hd.apply(pd,arguments)})});var ne=f((k0,vd)=>{"use strict";var bd=hr(),gd=Function.prototype,eo=gd.call,ZT=bd&&gd.bind.bind(eo,eo);vd.exports=bd?ZT:function(a){return function(){return eo.apply(a,arguments)}}});var Xt=f((R0,yd)=>{"use strict";var Sd=ne(),eI=Sd({}.toString),tI=Sd("".slice);yd.exports=function(a){return tI(eI(a),8,-1)}});var to=f(($0,Td)=>{"use strict";var iI=Xt(),rI=ne();Td.exports=function(a){if(iI(a)==="Function")return rI(a)}});var ee=f((L0,Id)=>{"use strict";var io=typeof document=="object"&&document.all;Id.exports=typeof io=="undefined"&&io!==void 0?function(a){return typeof a=="function"||a===io}:function(a){return typeof a=="function"}});var Le=f((M0,Ed)=>{"use strict";var aI=de();Ed.exports=!aI(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var Me=f((C0,xd)=>{"use strict";var sI=hr(),cs=Function.prototype.call;xd.exports=sI?cs.bind(cs):function(){return cs.apply(cs,arguments)}});var ro=f(Ad=>{"use strict";var Pd={}.propertyIsEnumerable,wd=Object.getOwnPropertyDescriptor,nI=wd&&!Pd.call({1:2},1);Ad.f=nI?function(e){var t=wd(this,e);return!!t&&t.enumerable}:Pd});var mr=f((V0,kd)=>{"use strict";kd.exports=function(a,e){return{enumerable:!(a&1),configurable:!(a&2),writable:!(a&4),value:e}}});var $d=f((O0,Rd)=>{"use strict";var oI=ne(),uI=de(),lI=Xt(),ao=Object,cI=oI("".split);Rd.exports=uI(function(){return!ao("z").propertyIsEnumerable(0)})?function(a){return lI(a)==="String"?cI(a,""):ao(a)}:ao});var xi=f((B0,Ld)=>{"use strict";Ld.exports=function(a){return a==null}});var At=f((_0,Md)=>{"use strict";var dI=xi(),pI=TypeError;Md.exports=function(a){if(dI(a))throw new pI("Can't call method on "+a);return a}});var Jt=f((N0,Cd)=>{"use strict";var hI=$d(),mI=At();Cd.exports=function(a){return hI(mI(a))}});var Ce=f((F0,Dd)=>{"use strict";var fI=ee();Dd.exports=function(a){return typeof a=="object"?a!==null:fI(a)}});var Pi=f((q0,Vd)=>{"use strict";Vd.exports={}});var ct=f((U0,Bd)=>{"use strict";var so=Pi(),no=ie(),bI=ee(),Od=function(a){return bI(a)?a:void 0};Bd.exports=function(a,e){return arguments.length<2?Od(so[a])||Od(no[a]):so[a]&&so[a][e]||no[a]&&no[a][e]}});var fr=f((H0,_d)=>{"use strict";var gI=ne();_d.exports=gI({}.isPrototypeOf)});var Zt=f((j0,qd)=>{"use strict";var vI=ie(),Nd=vI.navigator,Fd=Nd&&Nd.userAgent;qd.exports=Fd?String(Fd):""});var uo=f((Q0,Wd)=>{"use strict";var Gd=ie(),oo=Zt(),Ud=Gd.process,Hd=Gd.Deno,jd=Ud&&Ud.versions||Hd&&Hd.version,Qd=jd&&jd.v8,je,ds;Qd&&(je=Qd.split("."),ds=je[0]>0&&je[0]<4?1:+(je[0]+je[1]));!ds&&oo&&(je=oo.match(/Edge\/(\d+)/),(!je||je[1]>=74)&&(je=oo.match(/Chrome\/(\d+)/),je&&(ds=+je[1])));Wd.exports=ds});var lo=f((G0,zd)=>{"use strict";var Yd=uo(),SI=de(),yI=ie(),TI=yI.String;zd.exports=!!Object.getOwnPropertySymbols&&!SI(function(){var a=Symbol("symbol detection");return!TI(a)||!(Object(a)instanceof Symbol)||!Symbol.sham&&Yd&&Yd<41})});var co=f((W0,Kd)=>{"use strict";var II=lo();Kd.exports=II&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var po=f((Y0,Xd)=>{"use strict";var EI=ct(),xI=ee(),PI=fr(),wI=co(),AI=Object;Xd.exports=wI?function(a){return typeof a=="symbol"}:function(a){var e=EI("Symbol");return xI(e)&&PI(e.prototype,AI(a))}});var br=f((z0,Jd)=>{"use strict";var kI=String;Jd.exports=function(a){try{return kI(a)}catch(e){return"Object"}}});var et=f((K0,Zd)=>{"use strict";var RI=ee(),$I=br(),LI=TypeError;Zd.exports=function(a){if(RI(a))return a;throw new LI($I(a)+" is not a function")}});var gr=f((X0,ep)=>{"use strict";var MI=et(),CI=xi();ep.exports=function(a,e){var t=a[e];return CI(t)?void 0:MI(t)}});var ip=f((J0,tp)=>{"use strict";var ho=Me(),mo=ee(),fo=Ce(),DI=TypeError;tp.exports=function(a,e){var t,i;if(e==="string"&&mo(t=a.toString)&&!fo(i=ho(t,a))||mo(t=a.valueOf)&&!fo(i=ho(t,a))||e!=="string"&&mo(t=a.toString)&&!fo(i=ho(t,a)))return i;throw new DI("Can't convert object to primitive value")}});var Qe=f((Z0,rp)=>{"use strict";rp.exports=!0});var np=f((eV,sp)=>{"use strict";var ap=ie(),VI=Object.defineProperty;sp.exports=function(a,e){try{VI(ap,a,{value:e,configurable:!0,writable:!0})}catch(t){ap[a]=e}return e}});var vr=f((tV,lp)=>{"use strict";var OI=Qe(),BI=ie(),_I=np(),op="__core-js_shared__",up=lp.exports=BI[op]||_I(op,{});(up.versions||(up.versions=[])).push({version:"3.38.0",mode:OI?"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 bo=f((iV,dp)=>{"use strict";var cp=vr();dp.exports=function(a,e){return cp[a]||(cp[a]=e||{})}});var wi=f((rV,pp)=>{"use strict";var NI=At(),FI=Object;pp.exports=function(a){return FI(NI(a))}});var Ge=f((aV,hp)=>{"use strict";var qI=ne(),UI=wi(),HI=qI({}.hasOwnProperty);hp.exports=Object.hasOwn||function(e,t){return HI(UI(e),t)}});var go=f((sV,mp)=>{"use strict";var jI=ne(),QI=0,GI=Math.random(),WI=jI(1 .toString);mp.exports=function(a){return"Symbol("+(a===void 0?"":a)+")_"+WI(++QI+GI,36)}});var pe=f((nV,bp)=>{"use strict";var YI=ie(),zI=bo(),fp=Ge(),KI=go(),XI=lo(),JI=co(),Ai=YI.Symbol,vo=zI("wks"),ZI=JI?Ai.for||Ai:Ai&&Ai.withoutSetter||KI;bp.exports=function(a){return fp(vo,a)||(vo[a]=XI&&fp(Ai,a)?Ai[a]:ZI("Symbol."+a)),vo[a]}});var yp=f((oV,Sp)=>{"use strict";var eE=Me(),gp=Ce(),vp=po(),tE=gr(),iE=ip(),rE=pe(),aE=TypeError,sE=rE("toPrimitive");Sp.exports=function(a,e){if(!gp(a)||vp(a))return a;var t=tE(a,sE),i;if(t){if(e===void 0&&(e="default"),i=eE(t,a,e),!gp(i)||vp(i))return i;throw new aE("Can't convert object to primitive value")}return e===void 0&&(e="number"),iE(a,e)}});var So=f((uV,Tp)=>{"use strict";var nE=yp(),oE=po();Tp.exports=function(a){var e=nE(a,"string");return oE(e)?e:e+""}});var ps=f((lV,Ep)=>{"use strict";var uE=ie(),Ip=Ce(),yo=uE.document,lE=Ip(yo)&&Ip(yo.createElement);Ep.exports=function(a){return lE?yo.createElement(a):{}}});var To=f((cV,xp)=>{"use strict";var cE=Le(),dE=de(),pE=ps();xp.exports=!cE&&!dE(function(){return Object.defineProperty(pE("div"),"a",{get:function(){return 7}}).a!==7})});var Ap=f(wp=>{"use strict";var hE=Le(),mE=Me(),fE=ro(),bE=mr(),gE=Jt(),vE=So(),SE=Ge(),yE=To(),Pp=Object.getOwnPropertyDescriptor;wp.f=hE?Pp:function(e,t){if(e=gE(e),t=vE(t),yE)try{return Pp(e,t)}catch(i){}if(SE(e,t))return bE(!mE(fE.f,e,t),e[t])}});var Io=f((pV,kp)=>{"use strict";var TE=de(),IE=ee(),EE=/#|\.prototype\./,Sr=function(a,e){var t=PE[xE(a)];return t===AE?!0:t===wE?!1:IE(e)?TE(e):!!e},xE=Sr.normalize=function(a){return String(a).replace(EE,".").toLowerCase()},PE=Sr.data={},wE=Sr.NATIVE="N",AE=Sr.POLYFILL="P";kp.exports=Sr});var ki=f((hV,$p)=>{"use strict";var Rp=to(),kE=et(),RE=hr(),$E=Rp(Rp.bind);$p.exports=function(a,e){return kE(a),e===void 0?a:RE?$E(a,e):function(){return a.apply(e,arguments)}}});var Eo=f((mV,Lp)=>{"use strict";var LE=Le(),ME=de();Lp.exports=LE&&ME(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var tt=f((fV,Mp)=>{"use strict";var CE=Ce(),DE=String,VE=TypeError;Mp.exports=function(a){if(CE(a))return a;throw new VE(DE(a)+" is not an object")}});var ei=f(Dp=>{"use strict";var OE=Le(),BE=To(),_E=Eo(),hs=tt(),Cp=So(),NE=TypeError,xo=Object.defineProperty,FE=Object.getOwnPropertyDescriptor,Po="enumerable",wo="configurable",Ao="writable";Dp.f=OE?_E?function(e,t,i){if(hs(e),t=Cp(t),hs(i),typeof e=="function"&&t==="prototype"&&"value"in i&&Ao in i&&!i[Ao]){var r=FE(e,t);r&&r[Ao]&&(e[t]=i.value,i={configurable:wo in i?i[wo]:r[wo],enumerable:Po in i?i[Po]:r[Po],writable:!1})}return xo(e,t,i)}:xo:function(e,t,i){if(hs(e),t=Cp(t),hs(i),BE)try{return xo(e,t,i)}catch(r){}if("get"in i||"set"in i)throw new NE("Accessors not supported");return"value"in i&&(e[t]=i.value),e}});var Ri=f((gV,Vp)=>{"use strict";var qE=Le(),UE=ei(),HE=mr();Vp.exports=qE?function(a,e,t){return UE.f(a,e,HE(1,t))}:function(a,e,t){return a[e]=t,a}});var se=f((vV,Bp)=>{"use strict";var yr=ie(),jE=Zn(),QE=to(),GE=ee(),WE=Ap().f,YE=Io(),$i=Pi(),zE=ki(),Li=Ri(),Op=Ge();vr();var KE=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 jE(a,this,arguments)};return e.prototype=a.prototype,e};Bp.exports=function(a,e){var t=a.target,i=a.global,r=a.stat,s=a.proto,n=i?yr:r?yr[t]:yr[t]&&yr[t].prototype,o=i?$i:$i[t]||Li($i,t,{})[t],u=o.prototype,l,c,d,h,p,m,b,g,v;for(h in e)l=YE(i?h:t+(r?".":"#")+h,a.forced),c=!l&&n&&Op(n,h),m=o[h],c&&(a.dontCallGetSet?(v=WE(n,h),b=v&&v.value):b=n[h]),p=c&&b?b:e[h],!(!l&&!s&&typeof m==typeof p)&&(a.bind&&c?g=zE(p,yr):a.wrap&&c?g=KE(p):s&&GE(p)?g=QE(p):g=p,(a.sham||p&&p.sham||m&&m.sham)&&Li(g,"sham",!0),Li(o,h,g),s&&(d=t+"Prototype",Op($i,d)||Li($i,d,{}),Li($i[d],h,p),a.real&&u&&(l||!u[h])&&Li(u,h,p)))}});var Np=f((SV,_p)=>{"use strict";var XE=Math.ceil,JE=Math.floor;_p.exports=Math.trunc||function(e){var t=+e;return(t>0?JE:XE)(t)}});var Tr=f((yV,Fp)=>{"use strict";var ZE=Np();Fp.exports=function(a){var e=+a;return e!==e||e===0?0:ZE(e)}});var Up=f((TV,qp)=>{"use strict";var ex=Tr(),tx=Math.max,ix=Math.min;qp.exports=function(a,e){var t=ex(a);return t<0?tx(t+e,0):ix(t,e)}});var ko=f((IV,Hp)=>{"use strict";var rx=Tr(),ax=Math.min;Hp.exports=function(a){var e=rx(a);return e>0?ax(e,9007199254740991):0}});var Mi=f((EV,jp)=>{"use strict";var sx=ko();jp.exports=function(a){return sx(a.length)}});var Ro=f((xV,Gp)=>{"use strict";var nx=Jt(),ox=Up(),ux=Mi(),Qp=function(a){return function(e,t,i){var r=nx(e),s=ux(r);if(s===0)return!a&&-1;var n=ox(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}};Gp.exports={includes:Qp(!0),indexOf:Qp(!1)}});var Ir=f((PV,Wp)=>{"use strict";Wp.exports=function(){}});var Yp=f(()=>{"use strict";var lx=se(),cx=Ro().includes,dx=de(),px=Ir(),hx=dx(function(){return!Array(1).includes()});lx({target:"Array",proto:!0,forced:hx},{includes:function(e){return cx(this,e,arguments.length>1?arguments[1]:void 0)}});px("includes")});var kt=f((kV,zp)=>{"use strict";var mx=ct();zp.exports=mx});var Xp=f((RV,Kp)=>{"use strict";Yp();var fx=kt();Kp.exports=fx("Array","includes")});var Zp=f(($V,Jp)=>{"use strict";var bx=Xp();Jp.exports=bx});var Be=f((LV,eh)=>{"use strict";var gx=Zp();eh.exports=gx});var bs=f((HV,uh)=>{"use strict";var Px=bo(),wx=go(),oh=Px("keys");uh.exports=function(a){return oh[a]||(oh[a]=wx(a))}});var ch=f((jV,lh)=>{"use strict";var Ax=de();lh.exports=!Ax(function(){function a(){}return a.prototype.constructor=null,Object.getPrototypeOf(new a)!==a.prototype})});var gs=f((QV,ph)=>{"use strict";var kx=Ge(),Rx=ee(),$x=wi(),Lx=bs(),Mx=ch(),dh=Lx("IE_PROTO"),Mo=Object,Cx=Mo.prototype;ph.exports=Mx?Mo.getPrototypeOf:function(a){var e=$x(a);if(kx(e,dh))return e[dh];var t=e.constructor;return Rx(t)&&e instanceof t?t.prototype:e instanceof Mo?Cx:null}});var vs=f((GV,hh)=>{"use strict";hh.exports={}});var bh=f((WV,fh)=>{"use strict";var Dx=ne(),Co=Ge(),Vx=Jt(),Ox=Ro().indexOf,Bx=vs(),mh=Dx([].push);fh.exports=function(a,e){var t=Vx(a),i=0,r=[],s;for(s in t)!Co(Bx,s)&&Co(t,s)&&mh(r,s);for(;e.length>i;)Co(t,s=e[i++])&&(~Ox(r,s)||mh(r,s));return r}});var Do=f((YV,gh)=>{"use strict";gh.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var Vo=f((zV,vh)=>{"use strict";var _x=bh(),Nx=Do();vh.exports=Object.keys||function(e){return _x(e,Nx)}});var Oo=f((KV,Eh)=>{"use strict";var yh=Le(),Fx=de(),Th=ne(),qx=gs(),Ux=Vo(),Hx=Jt(),jx=ro().f,Ih=Th(jx),Qx=Th([].push),Gx=yh&&Fx(function(){var a=Object.create(null);return a[2]=2,!Ih(a,2)}),Sh=function(a){return function(e){for(var t=Hx(e),i=Ux(t),r=Gx&&qx(t)===null,s=i.length,n=0,o=[],u;s>n;)u=i[n++],(!yh||(r?u in t:Ih(t,u)))&&Qx(o,a?[u,t[u]]:t[u]);return o}};Eh.exports={entries:Sh(!0),values:Sh(!1)}});var xh=f(()=>{"use strict";var Wx=se(),Yx=Oo().entries;Wx({target:"Object",stat:!0},{entries:function(e){return Yx(e)}})});var wh=f((ZV,Ph)=>{"use strict";xh();var zx=Pi();Ph.exports=zx.Object.entries});var kh=f((eO,Ah)=>{"use strict";var Kx=wh();Ah.exports=Kx});var Ci=f((tO,Rh)=>{"use strict";var Xx=kh();Rh.exports=Xx});var ti=f((iO,$h)=>{"use strict";$h.exports={}});var Ch=f((rO,Mh)=>{"use strict";var Jx=ie(),Zx=ee(),Lh=Jx.WeakMap;Mh.exports=Zx(Lh)&&/native code/.test(String(Lh))});var Fo=f((aO,Oh)=>{"use strict";var eP=Ch(),Vh=ie(),tP=Ce(),iP=Ri(),Bo=Ge(),_o=vr(),rP=bs(),aP=vs(),Dh="Object already initialized",No=Vh.TypeError,sP=Vh.WeakMap,Ss,Er,ys,nP=function(a){return ys(a)?Er(a):Ss(a,{})},oP=function(a){return function(e){var t;if(!tP(e)||(t=Er(e)).type!==a)throw new No("Incompatible receiver, "+a+" required");return t}};eP||_o.state?(We=_o.state||(_o.state=new sP),We.get=We.get,We.has=We.has,We.set=We.set,Ss=function(a,e){if(We.has(a))throw new No(Dh);return e.facade=a,We.set(a,e),e},Er=function(a){return We.get(a)||{}},ys=function(a){return We.has(a)}):(ii=rP("state"),aP[ii]=!0,Ss=function(a,e){if(Bo(a,ii))throw new No(Dh);return e.facade=a,iP(a,ii,e),e},Er=function(a){return Bo(a,ii)?a[ii]:{}},ys=function(a){return Bo(a,ii)});var We,ii;Oh.exports={set:Ss,get:Er,has:ys,enforce:nP,getterFor:oP}});var Ho=f((sO,_h)=>{"use strict";var qo=Le(),uP=Ge(),Bh=Function.prototype,lP=qo&&Object.getOwnPropertyDescriptor,Uo=uP(Bh,"name"),cP=Uo&&function(){}.name==="something",dP=Uo&&(!qo||qo&&lP(Bh,"name").configurable);_h.exports={EXISTS:Uo,PROPER:cP,CONFIGURABLE:dP}});var Fh=f(Nh=>{"use strict";var pP=Le(),hP=Eo(),mP=ei(),fP=tt(),bP=Jt(),gP=Vo();Nh.f=pP&&!hP?Object.defineProperties:function(e,t){fP(e);for(var i=bP(t),r=gP(t),s=r.length,n=0,o;s>n;)mP.f(e,o=r[n++],i[o]);return e}});var jo=f((oO,qh)=>{"use strict";var vP=ct();qh.exports=vP("document","documentElement")});var Yo=f((uO,Yh)=>{"use strict";var SP=tt(),yP=Fh(),Uh=Do(),TP=vs(),IP=jo(),EP=ps(),xP=bs(),Hh=">",jh="<",Go="prototype",Wo="script",Gh=xP("IE_PROTO"),Qo=function(){},Wh=function(a){return jh+Wo+Hh+a+jh+"/"+Wo+Hh},Qh=function(a){a.write(Wh("")),a.close();var e=a.parentWindow.Object;return a=null,e},PP=function(){var a=EP("iframe"),e="java"+Wo+":",t;return a.style.display="none",IP.appendChild(a),a.src=String(e),t=a.contentWindow.document,t.open(),t.write(Wh("document.F=Object")),t.close(),t.F},Ts,Is=function(){try{Ts=new ActiveXObject("htmlfile")}catch(e){}Is=typeof document!="undefined"?document.domain&&Ts?Qh(Ts):PP():Qh(Ts);for(var a=Uh.length;a--;)delete Is[Go][Uh[a]];return Is()};TP[Gh]=!0;Yh.exports=Object.create||function(e,t){var i;return e!==null?(Qo[Go]=SP(e),i=new Qo,Qo[Go]=null,i[Gh]=e):i=Is(),t===void 0?i:yP.f(i,t)}});var Di=f((lO,zh)=>{"use strict";var wP=Ri();zh.exports=function(a,e,t,i){return i&&i.enumerable?a[e]=t:wP(a,e,t),a}});var Jo=f((cO,Jh)=>{"use strict";var AP=de(),kP=ee(),RP=Ce(),$P=Yo(),Kh=gs(),LP=Di(),MP=pe(),CP=Qe(),Xo=MP("iterator"),Xh=!1,dt,zo,Ko;[].keys&&(Ko=[].keys(),"next"in Ko?(zo=Kh(Kh(Ko)),zo!==Object.prototype&&(dt=zo)):Xh=!0);var DP=!RP(dt)||AP(function(){var a={};return dt[Xo].call(a)!==a});DP?dt={}:CP&&(dt=$P(dt));kP(dt[Xo])||LP(dt,Xo,function(){return this});Jh.exports={IteratorPrototype:dt,BUGGY_SAFARI_ITERATORS:Xh}});var Es=f((dO,em)=>{"use strict";var VP=pe(),OP=VP("toStringTag"),Zh={};Zh[OP]="z";em.exports=String(Zh)==="[object z]"});var xr=f((pO,tm)=>{"use strict";var BP=Es(),_P=ee(),xs=Xt(),NP=pe(),FP=NP("toStringTag"),qP=Object,UP=xs(function(){return arguments}())==="Arguments",HP=function(a,e){try{return a[e]}catch(t){}};tm.exports=BP?xs:function(a){var e,t,i;return a===void 0?"Undefined":a===null?"Null":typeof(t=HP(e=qP(a),FP))=="string"?t:UP?xs(e):(i=xs(e))==="Object"&&_P(e.callee)?"Arguments":i}});var rm=f((hO,im)=>{"use strict";var jP=Es(),QP=xr();im.exports=jP?{}.toString:function(){return"[object "+QP(this)+"]"}});var Pr=f((mO,sm)=>{"use strict";var GP=Es(),WP=ei().f,YP=Ri(),zP=Ge(),KP=rm(),XP=pe(),am=XP("toStringTag");sm.exports=function(a,e,t,i){var r=t?a:a&&a.prototype;r&&(zP(r,am)||WP(r,am,{configurable:!0,value:e}),i&&!GP&&YP(r,"toString",KP))}});var om=f((fO,nm)=>{"use strict";var JP=Jo().IteratorPrototype,ZP=Yo(),ew=mr(),tw=Pr(),iw=ti(),rw=function(){return this};nm.exports=function(a,e,t,i){var r=e+" Iterator";return a.prototype=ZP(JP,{next:ew(+!i,t)}),tw(a,r,!1,!0),iw[r]=rw,a}});var lm=f((bO,um)=>{"use strict";var aw=ne(),sw=et();um.exports=function(a,e,t){try{return aw(sw(Object.getOwnPropertyDescriptor(a,e)[t]))}catch(i){}}});var dm=f((gO,cm)=>{"use strict";var nw=Ce();cm.exports=function(a){return nw(a)||a===null}});var hm=f((vO,pm)=>{"use strict";var ow=dm(),uw=String,lw=TypeError;pm.exports=function(a){if(ow(a))return a;throw new lw("Can't set "+uw(a)+" as a prototype")}});var Zo=f((SO,mm)=>{"use strict";var cw=lm(),dw=Ce(),pw=At(),hw=hm();mm.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var a=!1,e={},t;try{t=cw(Object.prototype,"__proto__","set"),t(e,[]),a=e instanceof Array}catch(i){}return function(r,s){return pw(r),hw(s),dw(r)&&(a?t(r,s):r.__proto__=s),r}}():void 0)});var Pm=f((yO,xm)=>{"use strict";var mw=se(),fw=Me(),Ps=Qe(),Im=Ho(),bw=ee(),gw=om(),fm=gs(),bm=Zo(),vw=Pr(),Sw=Ri(),eu=Di(),yw=pe(),gm=ti(),Em=Jo(),Tw=Im.PROPER,Iw=Im.CONFIGURABLE,vm=Em.IteratorPrototype,ws=Em.BUGGY_SAFARI_ITERATORS,wr=yw("iterator"),Sm="keys",Ar="values",ym="entries",Tm=function(){return this};xm.exports=function(a,e,t,i,r,s,n){gw(t,e,i);var o=function(v){if(v===r&&h)return h;if(!ws&&v&&v in c)return c[v];switch(v){case Sm:return function(){return new t(this,v)};case Ar:return function(){return new t(this,v)};case ym:return function(){return new t(this,v)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,c=a.prototype,d=c[wr]||c["@@iterator"]||r&&c[r],h=!ws&&d||o(r),p=e==="Array"&&c.entries||d,m,b,g;if(p&&(m=fm(p.call(new a)),m!==Object.prototype&&m.next&&(!Ps&&fm(m)!==vm&&(bm?bm(m,vm):bw(m[wr])||eu(m,wr,Tm)),vw(m,u,!0,!0),Ps&&(gm[u]=Tm))),Tw&&r===Ar&&d&&d.name!==Ar&&(!Ps&&Iw?Sw(c,"name",Ar):(l=!0,h=function(){return fw(d,this)})),r)if(b={values:o(Ar),keys:s?h:o(Sm),entries:o(ym)},n)for(g in b)(ws||l||!(g in c))&&eu(c,g,b[g]);else mw({target:e,proto:!0,forced:ws||l},b);return(!Ps||n)&&c[wr]!==h&&eu(c,wr,h,{name:r}),gm[e]=h,b}});var Am=f((TO,wm)=>{"use strict";wm.exports=function(a,e){return{value:a,done:e}}});var iu=f((IO,Mm)=>{"use strict";var Ew=Jt(),tu=Ir(),km=ti(),$m=Fo(),xw=ei().f,Pw=Pm(),As=Am(),ww=Qe(),Aw=Le(),Lm="Array Iterator",kw=$m.set,Rw=$m.getterFor(Lm);Mm.exports=Pw(Array,"Array",function(a,e){kw(this,{type:Lm,target:Ew(a),index:0,kind:e})},function(){var a=Rw(this),e=a.target,t=a.index++;if(!e||t>=e.length)return a.target=void 0,As(void 0,!0);switch(a.kind){case"keys":return As(t,!1);case"values":return As(e[t],!1)}return As([t,e[t]],!1)},"values");var Rm=km.Arguments=km.Array;tu("keys");tu("values");tu("entries");if(!ww&&Aw&&Rm.name!=="values")try{xw(Rm,"name",{value:"values"})}catch(a){}});var Dm=f((EO,Cm)=>{"use strict";var $w=pe(),Lw=ti(),Mw=$w("iterator"),Cw=Array.prototype;Cm.exports=function(a){return a!==void 0&&(Lw.Array===a||Cw[Mw]===a)}});var ru=f((xO,Om)=>{"use strict";var Dw=xr(),Vm=gr(),Vw=xi(),Ow=ti(),Bw=pe(),_w=Bw("iterator");Om.exports=function(a){if(!Vw(a))return Vm(a,_w)||Vm(a,"@@iterator")||Ow[Dw(a)]}});var _m=f((PO,Bm)=>{"use strict";var Nw=Me(),Fw=et(),qw=tt(),Uw=br(),Hw=ru(),jw=TypeError;Bm.exports=function(a,e){var t=arguments.length<2?Hw(a):e;if(Fw(t))return qw(Nw(t,a));throw new jw(Uw(a)+" is not iterable")}});var qm=f((wO,Fm)=>{"use strict";var Qw=Me(),Nm=tt(),Gw=gr();Fm.exports=function(a,e,t){var i,r;Nm(a);try{if(i=Gw(a,"return"),!i){if(e==="throw")throw t;return t}i=Qw(i,a)}catch(s){r=!0,i=s}if(e==="throw")throw t;if(r)throw i;return Nm(i),t}});var Rs=f((AO,Qm)=>{"use strict";var Ww=ki(),Yw=Me(),zw=tt(),Kw=br(),Xw=Dm(),Jw=Mi(),Um=fr(),Zw=_m(),eA=ru(),Hm=qm(),tA=TypeError,ks=function(a,e){this.stopped=a,this.result=e},jm=ks.prototype;Qm.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=Ww(e,i),l,c,d,h,p,m,b,g=function(S){return l&&Hm(l,"normal",S),new ks(!0,S)},v=function(S){return r?(zw(S),o?u(S[0],S[1],g):u(S[0],S[1])):o?u(S,g):u(S)};if(s)l=a.iterator;else if(n)l=a;else{if(c=eA(a),!c)throw new tA(Kw(a)+" is not iterable");if(Xw(c)){for(d=0,h=Jw(a);h>d;d++)if(p=v(a[d]),p&&Um(jm,p))return p;return new ks(!1)}l=Zw(a,c)}for(m=s?a.next:l.next;!(b=Yw(m,l)).done;){try{p=v(b.value)}catch(S){Hm(l,"throw",S)}if(typeof p=="object"&&p&&Um(jm,p))return p}return new ks(!1)}});var Wm=f((kO,Gm)=>{"use strict";var iA=Le(),rA=ei(),aA=mr();Gm.exports=function(a,e,t){iA?rA.f(a,e,aA(0,t)):a[e]=t}});var Ym=f(()=>{"use strict";var sA=se(),nA=Rs(),oA=Wm();sA({target:"Object",stat:!0},{fromEntries:function(e){var t={};return nA(e,function(i,r){oA(t,i,r)},{AS_ENTRIES:!0}),t}})});var Km=f((LO,zm)=>{"use strict";iu();Ym();var uA=Pi();zm.exports=uA.Object.fromEntries});var Jm=f((MO,Xm)=>{"use strict";Xm.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 ef=f(()=>{"use strict";iu();var lA=Jm(),cA=ie(),dA=Pr(),Zm=ti();for($s in lA)dA(cA[$s],$s),Zm[$s]=Zm.Array;var $s});var rf=f((VO,tf)=>{"use strict";var pA=Km();ef();tf.exports=pA});var au=f((OO,af)=>{"use strict";var hA=rf();af.exports=hA});var sf=f(()=>{"use strict"});var su=f((NO,nf)=>{"use strict";var kr=ie(),mA=Zt(),fA=Xt(),Ls=function(a){return mA.slice(0,a.length)===a};nf.exports=function(){return Ls("Bun/")?"BUN":Ls("Cloudflare-Workers")?"CLOUDFLARE":Ls("Deno/")?"DENO":Ls("Node.js/")?"NODE":kr.Bun&&typeof Bun.version=="string"?"BUN":kr.Deno&&typeof Deno.version=="object"?"DENO":fA(kr.process)==="process"?"NODE":kr.window&&kr.document?"BROWSER":"REST"}()});var Ms=f((FO,of)=>{"use strict";var bA=su();of.exports=bA==="NODE"});var lf=f((qO,uf)=>{"use strict";var gA=ei();uf.exports=function(a,e,t){return gA.f(a,e,t)}});var pf=f((UO,df)=>{"use strict";var vA=ct(),SA=lf(),yA=pe(),TA=Le(),cf=yA("species");df.exports=function(a){var e=vA(a);TA&&e&&!e[cf]&&SA(e,cf,{configurable:!0,get:function(){return this}})}});var mf=f((HO,hf)=>{"use strict";var IA=fr(),EA=TypeError;hf.exports=function(a,e){if(IA(e,a))return a;throw new EA("Incorrect invocation")}});var ou=f((jO,ff)=>{"use strict";var xA=ne(),PA=ee(),nu=vr(),wA=xA(Function.toString);PA(nu.inspectSource)||(nu.inspectSource=function(a){return wA(a)});ff.exports=nu.inspectSource});var lu=f((QO,yf)=>{"use strict";var AA=ne(),kA=de(),bf=ee(),RA=xr(),$A=ct(),LA=ou(),gf=function(){},vf=$A("Reflect","construct"),uu=/^\s*(?:class|function)\b/,MA=AA(uu.exec),CA=!uu.test(gf),Rr=function(e){if(!bf(e))return!1;try{return vf(gf,[],e),!0}catch(t){return!1}},Sf=function(e){if(!bf(e))return!1;switch(RA(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return CA||!!MA(uu,LA(e))}catch(t){return!0}};Sf.sham=!0;yf.exports=!vf||kA(function(){var a;return Rr(Rr.call)||!Rr(Object)||!Rr(function(){a=!0})||a})?Sf:Rr});var If=f((GO,Tf)=>{"use strict";var DA=lu(),VA=br(),OA=TypeError;Tf.exports=function(a){if(DA(a))return a;throw new OA(VA(a)+" is not a constructor")}});var cu=f((WO,xf)=>{"use strict";var Ef=tt(),BA=If(),_A=xi(),NA=pe(),FA=NA("species");xf.exports=function(a,e){var t=Ef(a).constructor,i;return t===void 0||_A(i=Ef(t)[FA])?e:BA(i)}});var wf=f((YO,Pf)=>{"use strict";var qA=ne();Pf.exports=qA([].slice)});var kf=f((zO,Af)=>{"use strict";var UA=TypeError;Af.exports=function(a,e){if(a<e)throw new UA("Not enough arguments");return a}});var du=f((KO,Rf)=>{"use strict";var HA=Zt();Rf.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(HA)});var yu=f((XO,_f)=>{"use strict";var De=ie(),jA=Zn(),QA=ki(),$f=ee(),GA=Ge(),Bf=de(),Lf=jo(),WA=wf(),Mf=ps(),YA=kf(),zA=du(),KA=Ms(),gu=De.setImmediate,vu=De.clearImmediate,XA=De.process,pu=De.Dispatch,JA=De.Function,Cf=De.MessageChannel,ZA=De.String,hu=0,$r={},Df="onreadystatechange",Lr,ri,mu,fu;Bf(function(){Lr=De.location});var Su=function(a){if(GA($r,a)){var e=$r[a];delete $r[a],e()}},bu=function(a){return function(){Su(a)}},Vf=function(a){Su(a.data)},Of=function(a){De.postMessage(ZA(a),Lr.protocol+"//"+Lr.host)};(!gu||!vu)&&(gu=function(e){YA(arguments.length,1);var t=$f(e)?e:JA(e),i=WA(arguments,1);return $r[++hu]=function(){jA(t,void 0,i)},ri(hu),hu},vu=function(e){delete $r[e]},KA?ri=function(a){XA.nextTick(bu(a))}:pu&&pu.now?ri=function(a){pu.now(bu(a))}:Cf&&!zA?(mu=new Cf,fu=mu.port2,mu.port1.onmessage=Vf,ri=QA(fu.postMessage,fu)):De.addEventListener&&$f(De.postMessage)&&!De.importScripts&&Lr&&Lr.protocol!=="file:"&&!Bf(Of)?(ri=Of,De.addEventListener("message",Vf,!1)):Df in Mf("script")?ri=function(a){Lf.appendChild(Mf("script"))[Df]=function(){Lf.removeChild(this),Su(a)}}:ri=function(a){setTimeout(bu(a),0)});_f.exports={set:gu,clear:vu}});var qf=f((JO,Ff)=>{"use strict";var Nf=ie(),ek=Le(),tk=Object.getOwnPropertyDescriptor;Ff.exports=function(a){if(!ek)return Nf[a];var e=tk(Nf,a);return e&&e.value}});var Tu=f((ZO,Hf)=>{"use strict";var Uf=function(){this.head=null,this.tail=null};Uf.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}}};Hf.exports=Uf});var Qf=f((eB,jf)=>{"use strict";var ik=Zt();jf.exports=/ipad|iphone|ipod/i.test(ik)&&typeof Pebble!="undefined"});var Wf=f((tB,Gf)=>{"use strict";var rk=Zt();Gf.exports=/web0s(?!.*chrome)/i.test(rk)});var eb=f((iB,Zf)=>{"use strict";var Oi=ie(),ak=qf(),Yf=ki(),Iu=yu().set,sk=Tu(),nk=du(),ok=Qf(),uk=Wf(),Eu=Ms(),zf=Oi.MutationObserver||Oi.WebKitMutationObserver,Kf=Oi.document,Xf=Oi.process,Cs=Oi.Promise,wu=ak("queueMicrotask"),Vi,xu,Pu,Ds,Jf;wu||(Mr=new sk,Cr=function(){var a,e;for(Eu&&(a=Xf.domain)&&a.exit();e=Mr.get();)try{e()}catch(t){throw Mr.head&&Vi(),t}a&&a.enter()},!nk&&!Eu&&!uk&&zf&&Kf?(xu=!0,Pu=Kf.createTextNode(""),new zf(Cr).observe(Pu,{characterData:!0}),Vi=function(){Pu.data=xu=!xu}):!ok&&Cs&&Cs.resolve?(Ds=Cs.resolve(void 0),Ds.constructor=Cs,Jf=Yf(Ds.then,Ds),Vi=function(){Jf(Cr)}):Eu?Vi=function(){Xf.nextTick(Cr)}:(Iu=Yf(Iu,Oi),Vi=function(){Iu(Cr)}),wu=function(a){Mr.head||Vi(),Mr.add(a)});var Mr,Cr;Zf.exports=wu});var ib=f((rB,tb)=>{"use strict";tb.exports=function(a,e){try{arguments.length===1?console.error(a):console.error(a,e)}catch(t){}}});var Vs=f((aB,rb)=>{"use strict";rb.exports=function(a){try{return{error:!1,value:a()}}catch(e){return{error:!0,value:e}}}});var ai=f((sB,ab)=>{"use strict";var lk=ie();ab.exports=lk.Promise});var Bi=f((nB,ub)=>{"use strict";var ck=ie(),Dr=ai(),dk=ee(),pk=Io(),hk=ou(),mk=pe(),sb=su(),fk=Qe(),Au=uo(),nb=Dr&&Dr.prototype,bk=mk("species"),ku=!1,ob=dk(ck.PromiseRejectionEvent),gk=pk("Promise",function(){var a=hk(Dr),e=a!==String(Dr);if(!e&&Au===66||fk&&!(nb.catch&&nb.finally))return!0;if(!Au||Au<51||!/native code/.test(a)){var t=new Dr(function(s){s(1)}),i=function(s){s(function(){},function(){})},r=t.constructor={};if(r[bk]=i,ku=t.then(function(){})instanceof i,!ku)return!0}return!e&&(sb==="BROWSER"||sb==="DENO")&&!ob});ub.exports={CONSTRUCTOR:gk,REJECTION_EVENT:ob,SUBCLASSING:ku}});var _i=f((oB,cb)=>{"use strict";var lb=et(),vk=TypeError,Sk=function(a){var e,t;this.promise=new a(function(i,r){if(e!==void 0||t!==void 0)throw new vk("Bad Promise constructor");e=i,t=r}),this.resolve=lb(e),this.reject=lb(t)};cb.exports.f=function(a){return new Sk(a)}});var Rb=f(()=>{"use strict";var yk=se(),Tk=Qe(),Ns=Ms(),Rt=ie(),Ui=Me(),db=Di(),pb=Zo(),Ik=Pr(),Ek=pf(),xk=et(),_s=ee(),Pk=Ce(),wk=mf(),Ak=cu(),gb=yu().set,Cu=eb(),kk=ib(),Rk=Vs(),$k=Tu(),vb=Fo(),Fs=ai(),Du=Bi(),Sb=_i(),qs="Promise",yb=Du.CONSTRUCTOR,Lk=Du.REJECTION_EVENT,Mk=Du.SUBCLASSING,Ru=vb.getterFor(qs),Ck=vb.set,Ni=Fs&&Fs.prototype,si=Fs,Os=Ni,Tb=Rt.TypeError,$u=Rt.document,Vu=Rt.process,Lu=Sb.f,Dk=Lu,Vk=!!($u&&$u.createEvent&&Rt.dispatchEvent),Ib="unhandledrejection",Ok="rejectionhandled",hb=0,Eb=1,Bk=2,Ou=1,xb=2,Bs,mb,_k,fb,Pb=function(a){var e;return Pk(a)&&_s(e=a.then)?e:!1},wb=function(a,e){var t=e.value,i=e.state===Eb,r=i?a.ok:a.fail,s=a.resolve,n=a.reject,o=a.domain,u,l,c;try{r?(i||(e.rejection===xb&&Fk(e),e.rejection=Ou),r===!0?u=t:(o&&o.enter(),u=r(t),o&&(o.exit(),c=!0)),u===a.promise?n(new Tb("Promise-chain cycle")):(l=Pb(u))?Ui(l,u,s,n):s(u)):n(t)}catch(d){o&&!c&&o.exit(),n(d)}},Ab=function(a,e){a.notified||(a.notified=!0,Cu(function(){for(var t=a.reactions,i;i=t.get();)wb(i,a);a.notified=!1,e&&!a.rejection&&Nk(a)}))},kb=function(a,e,t){var i,r;Vk?(i=$u.createEvent("Event"),i.promise=e,i.reason=t,i.initEvent(a,!1,!0),Rt.dispatchEvent(i)):i={promise:e,reason:t},!Lk&&(r=Rt["on"+a])?r(i):a===Ib&&kk("Unhandled promise rejection",t)},Nk=function(a){Ui(gb,Rt,function(){var e=a.facade,t=a.value,i=bb(a),r;if(i&&(r=Rk(function(){Ns?Vu.emit("unhandledRejection",t,e):kb(Ib,e,t)}),a.rejection=Ns||bb(a)?xb:Ou,r.error))throw r.value})},bb=function(a){return a.rejection!==Ou&&!a.parent},Fk=function(a){Ui(gb,Rt,function(){var e=a.facade;Ns?Vu.emit("rejectionHandled",e):kb(Ok,e,a.value)})},Fi=function(a,e,t){return function(i){a(e,i,t)}},qi=function(a,e,t){a.done||(a.done=!0,t&&(a=t),a.value=e,a.state=Bk,Ab(a,!0))},Mu=function(a,e,t){if(!a.done){a.done=!0,t&&(a=t);try{if(a.facade===e)throw new Tb("Promise can't be resolved itself");var i=Pb(e);i?Cu(function(){var r={done:!1};try{Ui(i,e,Fi(Mu,r,a),Fi(qi,r,a))}catch(s){qi(r,s,a)}}):(a.value=e,a.state=Eb,Ab(a,!1))}catch(r){qi({done:!1},r,a)}}};if(yb&&(si=function(e){wk(this,Os),xk(e),Ui(Bs,this);var t=Ru(this);try{e(Fi(Mu,t),Fi(qi,t))}catch(i){qi(t,i)}},Os=si.prototype,Bs=function(e){Ck(this,{type:qs,done:!1,notified:!1,parent:!1,reactions:new $k,rejection:!1,state:hb,value:void 0})},Bs.prototype=db(Os,"then",function(e,t){var i=Ru(this),r=Lu(Ak(this,si));return i.parent=!0,r.ok=_s(e)?e:!0,r.fail=_s(t)&&t,r.domain=Ns?Vu.domain:void 0,i.state===hb?i.reactions.add(r):Cu(function(){wb(r,i)}),r.promise}),mb=function(){var a=new Bs,e=Ru(a);this.promise=a,this.resolve=Fi(Mu,e),this.reject=Fi(qi,e)},Sb.f=Lu=function(a){return a===si||a===_k?new mb(a):Dk(a)},!Tk&&_s(Fs)&&Ni!==Object.prototype)){fb=Ni.then,Mk||db(Ni,"then",function(e,t){var i=this;return new si(function(r,s){Ui(fb,i,r,s)}).then(e,t)},{unsafe:!0});try{delete Ni.constructor}catch(a){}pb&&pb(Ni,Os)}yk({global:!0,constructor:!0,wrap:!0,forced:yb},{Promise:si});Ik(si,qs,!1,!0);Ek(qs)});var Db=f((cB,Cb)=>{"use strict";var qk=pe(),Lb=qk("iterator"),Mb=!1;try{$b=0,Bu={next:function(){return{done:!!$b++}},return:function(){Mb=!0}},Bu[Lb]=function(){return this},Array.from(Bu,function(){throw 2})}catch(a){}var $b,Bu;Cb.exports=function(a,e){try{if(!e&&!Mb)return!1}catch(r){return!1}var t=!1;try{var i={};i[Lb]=function(){return{next:function(){return{done:t=!0}}}},a(i)}catch(r){}return t}});var _u=f((dB,Vb)=>{"use strict";var Uk=ai(),Hk=Db(),jk=Bi().CONSTRUCTOR;Vb.exports=jk||!Hk(function(a){Uk.all(a).then(void 0,function(){})})});var Ob=f(()=>{"use strict";var Qk=se(),Gk=Me(),Wk=et(),Yk=_i(),zk=Vs(),Kk=Rs(),Xk=_u();Qk({target:"Promise",stat:!0,forced:Xk},{all:function(e){var t=this,i=Yk.f(t),r=i.resolve,s=i.reject,n=zk(function(){var o=Wk(t.resolve),u=[],l=0,c=1;Kk(e,function(d){var h=l++,p=!1;c++,Gk(o,t,d).then(function(m){p||(p=!0,u[h]=m,--c||r(u))},s)}),--c||r(u)});return n.error&&s(n.value),i.promise}})});var _b=f(()=>{"use strict";var Jk=se(),Zk=Qe(),eR=Bi().CONSTRUCTOR,Fu=ai(),tR=ct(),iR=ee(),rR=Di(),Bb=Fu&&Fu.prototype;Jk({target:"Promise",proto:!0,forced:eR,real:!0},{catch:function(a){return this.then(void 0,a)}});!Zk&&iR(Fu)&&(Nu=tR("Promise").prototype.catch,Bb.catch!==Nu&&rR(Bb,"catch",Nu,{unsafe:!0}));var Nu});var Nb=f(()=>{"use strict";var aR=se(),sR=Me(),nR=et(),oR=_i(),uR=Vs(),lR=Rs(),cR=_u();aR({target:"Promise",stat:!0,forced:cR},{race:function(e){var t=this,i=oR.f(t),r=i.reject,s=uR(function(){var n=nR(t.resolve);lR(e,function(o){sR(n,t,o).then(i.resolve,r)})});return s.error&&r(s.value),i.promise}})});var Fb=f(()=>{"use strict";var dR=se(),pR=_i(),hR=Bi().CONSTRUCTOR;dR({target:"Promise",stat:!0,forced:hR},{reject:function(e){var t=pR.f(this),i=t.reject;return i(e),t.promise}})});var qu=f((yB,qb)=>{"use strict";var mR=tt(),fR=Ce(),bR=_i();qb.exports=function(a,e){if(mR(a),fR(e)&&e.constructor===a)return e;var t=bR.f(a),i=t.resolve;return i(e),t.promise}});var jb=f(()=>{"use strict";var gR=se(),vR=ct(),Ub=Qe(),SR=ai(),Hb=Bi().CONSTRUCTOR,yR=qu(),TR=vR("Promise"),IR=Ub&&!Hb;gR({target:"Promise",stat:!0,forced:Ub||Hb},{resolve:function(e){return yR(IR&&this===TR?SR:this,e)}})});var Qb=f(()=>{"use strict";Rb();Ob();_b();Nb();Fb();jb()});var zb=f(()=>{"use strict";var ER=se(),xR=Qe(),Us=ai(),PR=de(),Wb=ct(),Yb=ee(),wR=cu(),Gb=qu(),AR=Di(),Hu=Us&&Us.prototype,kR=!!Us&&PR(function(){Hu.finally.call({then:function(){}},function(){})});ER({target:"Promise",proto:!0,real:!0,forced:kR},{finally:function(a){var e=wR(this,Wb("Promise")),t=Yb(a);return this.then(t?function(i){return Gb(e,a()).then(function(){return i})}:a,t?function(i){return Gb(e,a()).then(function(){throw i})}:a)}});!xR&&Yb(Us)&&(Uu=Wb("Promise").prototype.finally,Hu.finally!==Uu&&AR(Hu,"finally",Uu,{unsafe:!0}));var Uu});var Xb=f((AB,Kb)=>{"use strict";sf();Qb();zb();var RR=kt();Kb.exports=RR("Promise","finally")});var Zb=f((kB,Jb)=>{"use strict";var $R=Xb();Jb.exports=$R});var Hs=f((RB,eg)=>{"use strict";var LR=Zb();eg.exports=LR});var hg=f(()=>{"use strict";var QR=se(),GR=Oo().values;QR({target:"Object",stat:!0},{values:function(e){return GR(e)}})});var fg=f((h_,mg)=>{"use strict";hg();var WR=Pi();mg.exports=WR.Object.values});var gg=f((m_,bg)=>{"use strict";var YR=fg();bg.exports=YR});var ji=f((f_,vg)=>{"use strict";var zR=gg();vg.exports=zR});var Vg=f(()=>{"use strict";var S$=se(),y$=wi(),T$=Mi(),I$=Tr(),E$=Ir();S$({target:"Array",proto:!0},{at:function(e){var t=y$(this),i=T$(t),r=I$(e),s=r>=0?r:i+r;return s<0||s>=i?void 0:t[s]}});E$("at")});var Bg=f((xN,Og)=>{"use strict";Vg();var x$=kt();Og.exports=x$("Array","at")});var Ng=f((PN,_g)=>{"use strict";var P$=Bg();_g.exports=P$});var Dt=f((wN,Fg)=>{"use strict";var w$=Ng();Fg.exports=w$});var fl=f((dq,Tv)=>{"use strict";var lL=Xt();Tv.exports=Array.isArray||function(e){return lL(e)==="Array"}});var Ev=f((pq,Iv)=>{"use strict";var cL=TypeError,dL=9007199254740991;Iv.exports=function(a){if(a>dL)throw cL("Maximum allowed index exceeded");return a}});var wv=f((hq,Pv)=>{"use strict";var pL=fl(),hL=Mi(),mL=Ev(),fL=ki(),xv=function(a,e,t,i,r,s,n,o){for(var u=r,l=0,c=n?fL(n,o):!1,d,h;l<i;)l in t&&(d=c?c(t[l],l,e):t[l],s>0&&pL(d)?(h=hL(d),u=xv(a,e,d,h,u,s-1)-1):(mL(u+1),a[u]=d),u++),l++;return u};Pv.exports=xv});var $v=f((mq,Rv)=>{"use strict";var Av=fl(),bL=lu(),gL=Ce(),vL=pe(),SL=vL("species"),kv=Array;Rv.exports=function(a){var e;return Av(a)&&(e=a.constructor,bL(e)&&(e===kv||Av(e.prototype))?e=void 0:gL(e)&&(e=e[SL],e===null&&(e=void 0))),e===void 0?kv:e}});var Mv=f((fq,Lv)=>{"use strict";var yL=$v();Lv.exports=function(a,e){return new(yL(a))(e===0?0:e)}});var Cv=f(()=>{"use strict";var TL=se(),IL=wv(),EL=et(),xL=wi(),PL=Mi(),wL=Mv();TL({target:"Array",proto:!0},{flatMap:function(e){var t=xL(this),i=PL(t),r;return EL(e),r=wL(t,0),r.length=IL(r,t,t,i,0,1,e,arguments.length>1?arguments[1]:void 0),r}})});var Dv=f(()=>{"use strict";var AL=Ir();AL("flatMap")});var Ov=f((yq,Vv)=>{"use strict";Cv();Dv();var kL=kt();Vv.exports=kL("Array","flatMap")});var _v=f((Tq,Bv)=>{"use strict";var RL=Ov();Bv.exports=RL});var bl=f((Iq,Nv)=>{"use strict";var $L=_v();Nv.exports=$L});var Xr=f((Eq,Fv)=>{"use strict";var LL=xr(),ML=String;Fv.exports=function(a){if(LL(a)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return ML(a)}});var gl=f((xq,qv)=>{"use strict";qv.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 jv=f((Pq,Hv)=>{"use strict";var CL=ne(),DL=At(),VL=Xr(),Sl=gl(),Uv=CL("".replace),OL=RegExp("^["+Sl+"]+"),BL=RegExp("(^|[^"+Sl+"])["+Sl+"]+$"),vl=function(a){return function(e){var t=VL(DL(e));return a&1&&(t=Uv(t,OL,"")),a&2&&(t=Uv(t,BL,"$1")),t}};Hv.exports={start:vl(1),end:vl(2),trim:vl(3)}});var Yv=f((wq,Wv)=>{"use strict";var _L=Ho().PROPER,NL=de(),Qv=gl(),Gv="\u200B\x85\u180E";Wv.exports=function(a){return NL(function(){return!!Qv[a]()||Gv[a]()!==Gv||_L&&Qv[a].name!==a})}});var yl=f((Aq,zv)=>{"use strict";var FL=jv().start,qL=Yv();zv.exports=qL("trimStart")?function(){return FL(this)}:"".trimStart});var Xv=f(()=>{"use strict";var UL=se(),Kv=yl();UL({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==Kv},{trimLeft:Kv})});var Zv=f(()=>{"use strict";Xv();var HL=se(),Jv=yl();HL({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==Jv},{trimStart:Jv})});var tS=f((Mq,eS)=>{"use strict";Zv();var jL=kt();eS.exports=jL("String","trimLeft")});var rS=f((Cq,iS)=>{"use strict";var QL=tS();iS.exports=QL});var sS=f((Dq,aS)=>{"use strict";var GL=rS();aS.exports=GL});var TS=f(()=>{"use strict"});var IS=f(()=>{"use strict"});var xS=f((mH,ES)=>{"use strict";var fM=Ce(),bM=Xt(),gM=pe(),vM=gM("match");ES.exports=function(a){var e;return fM(a)&&((e=a[vM])!==void 0?!!e:bM(a)==="RegExp")}});var wS=f((fH,PS)=>{"use strict";var SM=tt();PS.exports=function(){var a=SM(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 RS=f((bH,kS)=>{"use strict";var yM=Me(),TM=Ge(),IM=fr(),EM=wS(),AS=RegExp.prototype;kS.exports=function(a){var e=a.flags;return e===void 0&&!("flags"in AS)&&!TM(a,"flags")&&IM(AS,a)?yM(EM,a):e}});var LS=f((gH,$S)=>{"use strict";var kl=ne(),xM=wi(),PM=Math.floor,wl=kl("".charAt),wM=kl("".replace),Al=kl("".slice),AM=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,kM=/\$([$&'`]|\d{1,2})/g;$S.exports=function(a,e,t,i,r,s){var n=t+a.length,o=i.length,u=kM;return r!==void 0&&(r=xM(r),u=AM),wM(s,u,function(l,c){var d;switch(wl(c,0)){case"$":return"$";case"&":return a;case"`":return Al(e,0,t);case"'":return Al(e,n);case"<":d=r[Al(c,1,-1)];break;default:var h=+c;if(h===0)return l;if(h>o){var p=PM(h/10);return p===0?l:p<=o?i[p-1]===void 0?wl(c,1):i[p-1]+wl(c,1):l}d=i[h-1]}return d===void 0?"":d})}});var DS=f(()=>{"use strict";var RM=se(),$M=Me(),$l=ne(),MS=At(),LM=ee(),MM=xi(),CM=xS(),Ki=Xr(),DM=gr(),VM=RS(),OM=LS(),BM=pe(),_M=Qe(),NM=BM("replace"),FM=TypeError,Rl=$l("".indexOf),qM=$l("".replace),CS=$l("".slice),UM=Math.max;RM({target:"String",proto:!0},{replaceAll:function(e,t){var i=MS(this),r,s,n,o,u,l,c,d,h,p,m=0,b="";if(!MM(e)){if(r=CM(e),r&&(s=Ki(MS(VM(e))),!~Rl(s,"g")))throw new FM("`.replaceAll` does not allow non-global regexes");if(n=DM(e,NM),n)return $M(n,e,i,t);if(_M&&r)return qM(Ki(i),e,t)}for(o=Ki(i),u=Ki(e),l=LM(t),l||(t=Ki(t)),c=u.length,d=UM(1,c),h=Rl(o,u);h!==-1;)p=l?Ki(t(u,h,o)):OM(u,o,h,[],void 0,t),b+=CS(o,m,h)+p,m=h+c,h=h+d>o.length?-1:Rl(o,u,h+d);return m<o.length&&(b+=CS(o,m)),b}})});var OS=f((yH,VS)=>{"use strict";TS();IS();DS();var HM=kt();VS.exports=HM("String","replaceAll")});var _S=f((TH,BS)=>{"use strict";var jM=OS();BS.exports=jM});var FS=f((IH,NS)=>{"use strict";var QM=_S();NS.exports=QM});var US=f((EH,qS)=>{"use strict";var GM=Tr(),WM=Xr(),YM=At(),zM=RangeError;qS.exports=function(e){var t=WM(YM(this)),i="",r=GM(e);if(r<0||r===1/0)throw new zM("Wrong number of repetitions");for(;r>0;(r>>>=1)&&(t+=t))r&1&&(i+=t);return i}});var WS=f((xH,GS)=>{"use strict";var QS=ne(),KM=ko(),HS=Xr(),XM=US(),JM=At(),ZM=QS(XM),eC=QS("".slice),tC=Math.ceil,jS=function(a){return function(e,t,i){var r=HS(JM(e)),s=KM(t),n=r.length,o=i===void 0?" ":HS(i),u,l;return s<=n||o===""?r:(u=s-n,l=ZM(o,tC(u/o.length)),l.length>u&&(l=eC(l,0,u)),a?r+l:l+r)}};GS.exports={start:jS(!1),end:jS(!0)}});var zS=f((PH,YS)=>{"use strict";var iC=Zt();YS.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(iC)});var KS=f(()=>{"use strict";var rC=se(),aC=WS().start,sC=zS();rC({target:"String",proto:!0,forced:sC},{padStart:function(e){return aC(this,e,arguments.length>1?arguments[1]:void 0)}})});var JS=f((kH,XS)=>{"use strict";KS();var nC=kt();XS.exports=nC("String","padStart")});var ey=f((RH,ZS)=>{"use strict";var oC=JS();ZS.exports=oC});var iy=f(($H,ty)=>{"use strict";var uC=ey();ty.exports=uC});var ud="2.0.131-dev.85f5d8d6.0";var $e=(r=>(r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused",r))($e||{}),lt=(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))(lt||{});var us=(r=>(r.NOT_AVAILABLE="NOT_AVAILABLE",r.AVAILABLE="AVAILABLE",r.CONNECTING="CONNECTING",r.CONNECTED="CONNECTED",r))(us||{}),Kn=(i=>(i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic",i))(Kn||{});var Xn=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(Xn||{}),ls=(i=>(i.TRAFFIC_SAVING="traffic_saving",i.HIGH_QUALITY="high_quality",i.UNKNOWN="unknown",i))(ls||{});var BT=C(Be(),1);import{assertNever as nh,assertNonNullable as vx,isNonNullable as ms,ValueSubject as $o,Subject as Sx,Subscription as yx,merge as Tx,observableFrom as Ix,fromEvent as ih,map as rh,tap as ah,filterChanged as Ex,isNullable as Lo,ErrorCategory as sh}from"@vkontakte/videoplayer-shared/es2018";var th=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 fs=class{constructor(e){this.connection$=new $o(void 0);this.castState$=new $o("NOT_AVAILABLE");this.errorEvent$=new Sx;this.realCastState$=new $o("NOT_AVAILABLE");this.subscription=new yx;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=ms((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||th("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:sh.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(){ms(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();Lo(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();Lo(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.isDestroyed=!0,this.subscription.unsubscribe()}initListeners(){let e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),i=cast.framework.CastContext.getInstance();this.subscription.add(ih(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 nh(r.sessionState)}})).add(Tx(ih(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(ah(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),rh(r=>r.castState)),Ix([i.getCastState()])).pipe(Ex(),rh(xx),ah(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{var o,u;let s=r==="CONNECTED",n=ms(this.connection$.getValue());if(s&&!n){let l=i.getCurrentSession();vx(l);let c=l.getCastDevice(),d=(u=(o=l.getMediaSession())==null?void 0:o.media)==null?void 0:u.contentId;(Lo(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"?ms(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:sh.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:s})}}},xx=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 nh(a)}};var fc=C(Be(),1),vT=C(Ci(),1),ST=C(au(),1);var cg=C(Hs(),1);import{assertNever as tg}from"@vkontakte/videoplayer-shared/es2018";var he=(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:tg(t)}return a},js=(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:tg(e)}};var P=(a,e,t=!1)=>{let i=a.getTransition();(t||!i||i.to===e)&&a.setState(e)};import{isNonNullable as MR,Subject as Qs,merge as ig}from"@vkontakte/videoplayer-shared/es2018";var D=class{constructor(e){this.transitionStarted$=new Qs;this.transitionEnded$=new Qs;this.transitionUpdated$=new Qs;this.forceChanged$=new Qs;this.stateChangeStarted$=ig(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=ig(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||MR(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 CR}from"@vkontakte/videoplayer-shared/es2018";var rg=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 CR(a)}};import{assertNever as Hi,assertNonNullable as ni,debounce as ag,ErrorCategory as sg,fromEvent as oi,isNonNullable as ng,map as og,merge as ug,observableFrom as DR,Subject as VR,Subscription as ju,timeout as OR,getHighestQuality as BR}from"@vkontakte/videoplayer-shared/es2018";var _R=5,NR=5,FR=500,lg=7e3,Vr=class{constructor(e){this.subscription=new ju;this.loadMediaTimeoutSubscription=new ju;this.videoState=new D("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:Hi(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:Hi(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:Hi(e)}break}default:Hi(i)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(rg(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 ju;this.subscription.add(e),this.subscription.add(ug(this.videoState.stateChangeStarted$.pipe(og(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe(og(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 VR;e.add(r.pipe(ag(FR)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add(oi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(n=>{this.logRemoteEvent(n);let o=n.value;this.params.output.position$.next(o),(this.params.desiredState.seekState.getState().state==="applying"||Math.abs(o-s)>_R)&&r.next(o),s=o})),e.add(oi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(oi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(oi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t(oi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),r=>{this.logRemoteEvent(r);let{remotePlayer: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<NR&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),P(this.params.desiredState.playbackState,"stopped");break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:Hi(n)}}),t(oi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t(oi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});let i=ug(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,DR(["init"])).pipe(ag(0));t(i,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});let{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),P(this.params.desiredState.playbackState,"playing"));let i=this.params.output.isLive$.getValue();this.params.output.duration$.next(i?0:t.duration),this.params.output.position$.next(i?0:t.currentTime),this.params.desiredState.seekState.setState({state:"none"})}}prepare(){let e=this.params.format;this.log({message:`[prepare] format: ${e}`});let t=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"),P(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"),P(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"&&P(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];ni(c);let d=BR(Object.keys(c));ni(d);let h=c[d];ni(h),i=h,r="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let c=t[e];ni(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];ni(c),i=c.url,r="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let c=t[e];ni(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];ni(c),i=he(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:sg.VIDEO_PIPELINE,message:c,thrown:d}),d}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return Hi(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 ng(o)&&(n.metadata.title=o),ng(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(OR(lg).subscribe(()=>s(`timeout(${lg})`)))});(0,cg.default)(Promise.race([t,i]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},r=>{let s=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${r}`;this.log({message:s}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:sg.VIDEO_PIPELINE,message:s,thrown:r})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var hl=C(Be(),1);import{clearVideoElement as pg}from"@vkontakte/videoplayer-shared/es2018";import{clearVideoElement as qR}from"@vkontakte/videoplayer-shared/es2018";var dg=a=>{try{a.pause(),a.playbackRate=0,qR(a),a.remove()}catch(e){console.error(e)}};import{fromEvent as UR,Subscription as HR}from"@vkontakte/videoplayer-shared/es2018";var Qu=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)}},Gu=window.WeakMap?new WeakMap:new Qu,Wu=window.WeakMap?new WeakMap:new Map,jR=(a,e=20)=>{let t=0;return UR(a,"ratechange").subscribe(i=>{t++,t>=e&&(a.currentTime=a.currentTime,t=0)})},Ee=(a,{audioVideoSyncRate:e,disableYandexPiP:t})=>{let i=a.querySelector("video"),r=!!i;i?pg(i):(i=document.createElement("video"),a.appendChild(i)),Gu.set(i,r);let s=new HR;return s.add(jR(i,e)),Wu.set(i,s),i.setAttribute("crossorigin","anonymous"),i.setAttribute("playsinline","playsinline"),t&&i.setAttribute("x-yandex-pip","false"),i.controls=!1,i.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),i},xe=a=>{let e=Wu.get(a);e==null||e.unsubscribe(),Wu.delete(a);let t=Gu.get(a);Gu.delete(a),t?pg(a):dg(a)};var zu=C(ji(),1);import{assertNonNullable as Or,isNonNullable as rt,isNullable as JR,fromEvent as Qi,merge as Sg,observableFrom as yg,filterChanged as Tg,map as Br,Subject as Ig,Subscription as ZR,ValueSubject as e$,ErrorCategory as t$}from"@vkontakte/videoplayer-shared/es2018";import{isNonNullable as Yu,isNullable as KR,Subscription as XR}from"@vkontakte/videoplayer-shared/es2018";var Gs=(a,e,t,{equal:i=(n,o)=>n===o,changed$:r,onError:s}={})=>{let n=a.getState(),o=e(),u=KR(r),l=new XR;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},it=(a,e,t)=>Gs(e,()=>a.loop,i=>{Yu(i)&&(a.loop=i)},{onError:t}),Pe=(a,e,t,i)=>Gs(e,()=>({muted:a.muted,volume:a.volume}),r=>{Yu(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}),_e=(a,e,t,i)=>Gs(e,()=>a.playbackRate,r=>{Yu(r)&&(a.playbackRate=r)},{changed$:t,onError:i}),$t=Gs;var i$=a=>["__",a.language,a.label].join("|"),r$=(a,e)=>{if(a.id===e)return!0;let[t,i,r]=e.split("|");return a.language===i&&a.label===r},Ku=class a{constructor(e){this.available$=new Ig;this.current$=new e$(void 0);this.error$=new Ig;this.subscription=new ZR;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:t$.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($t(t.internalTextTracks,()=>(0,zu.default)(this.internalTracks),s=>{rt(s)&&this.setInternal(s)},{equal:(s,n)=>rt(s)&&rt(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(Br(s=>s.filter(({type:n})=>n==="internal"))),onError:r})),this.subscription.add($t(t.externalTextTracks,()=>(0,zu.default)(this.externalTracks),s=>{rt(s)&&this.setExternal(s)},{equal:(s,n)=>rt(s)&&rt(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(Br(s=>s.filter(({type:n})=>n==="external"))),onError:r})),this.subscription.add($t(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($t(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){Or(this.video);let{textTracks:e}=this.video;this.subscription.add(Qi(e,"addtrack").subscribe(()=>{let i=this.current$.getValue();i&&this.select(i)})),this.subscription.add(Sg(Qi(e,"addtrack"),Qi(e,"removetrack"),yg(["init"])).pipe(Br(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),Tg((i,r)=>i.length===r.length&&i.every(({id:s},n)=>s===r[n].id))).subscribe(this.available$)),this.subscription.add(Sg(Qi(e,"change"),yg(["init"])).pipe(Br(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),Br(i=>i&&this.htmlTextTrackToITextTrack(i).id),Tg()).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(Qi(e,"addtrack").subscribe(i=>{var s,n;(s=i.track)==null||s.addEventListener("cuechange",t);let r=o=>{var l,c,d,h,p;let u=(c=(l=o.target)==null?void 0:l.cues)!=null?c:null;u&&u.length&&(this.applyCueSettings((h=(d=o.target)==null?void 0:d.cues)!=null?h:null),(p=o.target)==null||p.removeEventListener("cuechange",r))};(n=i.track)==null||n.addEventListener("cuechange",r)})),this.subscription.add(Qi(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;rt(t.align)&&(r.align=t.align),rt(t.position)&&(r.position=t.position),rt(t.size)&&(r.size=t.size),rt(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){Or(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:i$(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){Or(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(JR(e)||!r$(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){Or(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){Or(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)}},Ne=Ku;var ui=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 Eg=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},Xu=a=>{let e=Eg(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},xg=a=>{let e=Eg(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)};import{fromEvent as we,map as Lt,merge as Zu,filterChanged as p$,isNonNullable as Cg,Subject as h$,filter as Nr,mapTo as el,combine as m$,once as f$,throttle as b$,ErrorCategory as g$,ValueSubject as Dg,Subscription as v$}from"@vkontakte/videoplayer-shared/es2018";var a$=3,Pg=(a,e,t=a$)=>{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 Ws=class{get current(){return this._current}get isYandex(){return this.current==="Yandex"}get isSafari(){return this.current==="Safari"}get isSamsungBrowser(){return this.current==="SamsungBrowser"}get safariVersion(){return this._safariVersion}detect(){let{userAgent:e}=navigator;try{let t=/yabrowser/i.test(e)?"Yandex":void 0,i=/samsungbrowser/i.test(e)?"SamsungBrowser":void 0,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._current=t||i||n||u||l||r||s||o||"Rest"}catch(t){console.error(t)}this.isSafari&&this.detectSafariVersion()}detectSafariVersion(){try{let{userAgent:e}=window.navigator,t=e.match(/Version\/(\d+)/);if(!t)return;let i=t[1],r=parseInt(i,10);if(isNaN(r))return;this._safariVersion=r}catch(e){console.error(e)}}};var wg=C(Be(),1);var _r=()=>{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 Ys=class{constructor(e){this._highEntropyValues={};this._displayChecker=e}get current(){return this._current}get isIOS(){let e=["iPhone","iPad","iPod"];return this._highEntropyValues.platform==="iOS"||(0,wg.default)(e,this.current)}get isMac(){return this._highEntropyValues.platform==="macOS"||this.current==="Mac"}get isApple(){return this.isIOS||this.isMac}get isIphoneOrOldIpad(){if(!this.isApple||!this._displayChecker.isTouch)return!1;let e=this.current==="iPad"||this._displayChecker.width>700,t=this._iosVersion;return!e||e&&!!t&&t<16}get isAndroid(){return this._highEntropyValues.platform==="Android"||this.current==="Android"}get isMobile(){return this._highEntropyValues.mobile||this._isMobile}get iOSVersion(){return this._iosVersion}detect(){let{userAgent:e}=navigator;try{this._isMobile=_r()}catch(t){console.error(t)}this.detectDevice(e),this.detectHighEntropyValues(),this.isIOS&&this.detectIOSVersion()}async detectHighEntropyValues(){let{userAgentData:e}=navigator;if(e){let t=await e.getHighEntropyValues(["architecture","bitness","brands","mobile","platform","formFactor","model","platformVersion","wow64"]);this._highEntropyValues=t}}detectDevice(e){try{let t=/android/i.test(e)?"Android":void 0,i=/iphone/i.test(e)?"iPhone":void 0,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 zs=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 Ye=()=>window.ManagedMediaSource||window.MediaSource,Ks=()=>{var a,e;return!!(window.ManagedMediaSource&&((e=(a=window.ManagedSourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},Ag=()=>{var a,e;return!!(window.MediaSource&&((e=(a=window.SourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},kg=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var s$=document.createElement("video"),n$='video/mp4; codecs="avc1.42000a,mp4a.40.2"',o$='video/mp4; codecs="hev1.1.6.L93.B0"',Rg='video/webm; codecs="vp09.00.10.08"',$g='video/webm; codecs="av01.0.00M.08"',u$='audio/mp4; codecs="mp4a.40.2"',l$='audio/webm; codecs="opus"',Lg,c$=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:$g}}),window.navigator.mediaCapabilities.decodingInfo({...a,video:{...a.video,contentType:Rg}})]);Lg={DASH_WEBM_AV1:e,DASH_WEBM:t}};c$().catch(a=>{console.log(s$),console.error(a)});var Xs=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 Lg}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,h,p,m,b,g,v,S,y,I;this._video=document.createElement("video");try{this._protocols={mms:Ks(),mse:Ag(),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 T=!!((c=(l=Ye())==null?void 0:l.isTypeSupported)!=null&&c.call(l,n$)),R=!!((h=(d=Ye())==null?void 0:d.isTypeSupported)!=null&&h.call(d,o$)),q=!!((m=(p=Ye())==null?void 0:p.isTypeSupported)!=null&&m.call(p,u$));this._codecs={h264:T,h265:R,vp9:!!((g=(b=Ye())==null?void 0:b.isTypeSupported)!=null&&g.call(b,Rg)),av1:!!((S=(v=Ye())==null?void 0:v.isTypeSupported)!=null&&S.call(v,$g)),aac:q,opus:!!((I=(y=Ye())==null?void 0:y.isTypeSupported)!=null&&I.call(y,l$)),mpeg:(T||R)&&q},this._nativeHlsSupported=this._protocols.hls&&this._containers.mp4}catch(T){console.error(T)}this.destroyVideoElement()}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 Mg="audio/mpeg",Js=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,Mg))},this._codecs={mp3:!!((r=(i=Ye())==null?void 0:i.isTypeSupported)!=null&&r.call(i,Mg))}}catch(s){console.error(s)}this.destroyAudioElement()}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 d$}from"@vkontakte/videoplayer-shared/es2018";var Ju=class{constructor(){this.isInited$=new d$(!1);this._displayChecker=new zs,this._deviceChecker=new Ys(this._displayChecker),this._browserChecker=new Ws,this._videoChecker=new Xs(this._deviceChecker,this._browserChecker),this._audioChecker=new Js,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 Ju;var Ae=a=>{let e=w=>we(a,w).pipe(el(void 0)),t=new v$,i=()=>t.unsubscribe(),s=Zu(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(w=>we(a,w))).pipe(Lt(w=>w.type==="ended"?a.readyState<2:a.readyState<3),p$()),n=Zu(we(a,"progress"),we(a,"timeupdate")).pipe(Lt(()=>Pg(a.buffered,a.currentTime))),o=N.browser.isSafari?m$({play:e("play").pipe(f$()),playing:e("playing")}).pipe(el(void 0)):e("playing"),u=we(a,"volumechange").pipe(Lt(()=>({muted:a.muted,volume:a.volume}))),l=we(a,"ratechange").pipe(Lt(()=>a.playbackRate)),c=we(a,"error").pipe(Nr(()=>!!(a.error||a.played.length)),Lt(()=>{var U;let w=a.error;return{id:w?`MediaError#${w.code}`:"HtmlVideoError",category:g$.VIDEO_PIPELINE,message:w?w.message:"Error event from HTML video element",thrown:(U=a.error)!=null?U:void 0}})),d=we(a,"timeupdate").pipe(Lt(()=>a.currentTime)),h=new h$,p=.3,m;t.add(d.subscribe(w=>{a.loop&&Cg(m)&&Cg(w)&&m>=a.duration-p&&w<=p&&h.next(m),m=w}));let b=e("pause").pipe(Nr(()=>!a.error&&m!==a.duration)),g=we(a,"enterpictureinpicture"),v=we(a,"leavepictureinpicture"),S=new Dg(xg(a));t.add(g.subscribe(()=>S.next(!0))),t.add(v.subscribe(()=>S.next(!1)));let y=new Dg(Xu(a)),I=we(a,"fullscreenchange");t.add(I.pipe(Lt(()=>Xu(a))).subscribe(y));let T=.1,R=1e3,q=we(a,"timeupdate").pipe(Nr(w=>a.duration-a.currentTime<T)),O=Zu(q.pipe(Nr(w=>!a.loop)),we(a,"ended")).pipe(b$(R),el(void 0)),_=q.pipe(Nr(w=>a.loop));return{playing$:o,pause$:b,canplay$:e("canplay"),ended$:O,looped$:h,loopExpected$:_,error$:c,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:d,durationChange$:we(a,"durationchange").pipe(Lt(()=>a.duration)),isBuffering$:s,currentBuffer$:n,volumeState$:u,playbackRateState$:l,inPiP$:S,inFullscreen$:y,enterPip$:g,leavePip$:v,destroy:i}};import{VideoQuality as Mt}from"@vkontakte/videoplayer-shared/es2018";var Ct=a=>{switch(a){case"mobile":return Mt.Q_144P;case"lowest":return Mt.Q_240P;case"low":return Mt.Q_360P;case"sd":case"medium":return Mt.Q_480P;case"hd":case"high":return Mt.Q_720P;case"fullhd":case"full":return Mt.Q_1080P;case"quadhd":case"quad":return Mt.Q_1440P;case"ultrahd":case"ultra":return Mt.Q_2160P}};var Vt=C(Dt(),1),Kg=C(Be(),1),tn=C(Ci(),1);import{isNonNullable as Se,isNullable as Gg,now as Xg,isHigher as Wg,isHigherOrEqual as al,isInvariantQuality as Yg,isLowerOrEqual as sl,videoSizeToQuality as R$,assertNotEmptyArray as Jg,assertNonNullable as $$}from"@vkontakte/videoplayer-shared/es2018";var tl=!1,ht={},qg=a=>{tl=a},Ug=()=>{ht={}},Hg=a=>{a(ht)},Fr=(a,e)=>{var t;tl&&(ht.meta=(t=ht.meta)!=null?t:{},ht.meta[a]=e)},ve=class{constructor(e){this.name=e}next(e){var i,r;if(!tl)return;ht.series=(i=ht.series)!=null?i:{};let t=(r=ht.series[this.name])!=null?r:[];t.push([Date.now(),e]),ht.series[this.name]=t}};import{isHigher as A$,isHigherOrEqual as MN,isLower as jg,isLowerOrEqual as CN,isNonNullable as Zs,isNullable as k$,videoHeightToQuality as en}from"@vkontakte/videoplayer-shared/es2018";function il({limits:a,highQualityLimit:e,trafficSavingLimit:t}){return!a.max&&a.min===e?"high_quality":!a.min&&a.max===t?"traffic_saving":"unknown"}function rl({limits:a,highQualityLimit:e,trafficSavingLimit:t}){return!!a&&il({limits:a,highQualityLimit:e,trafficSavingLimit:t})==="high_quality"}function qr({limits:a,highestAvailableQuality:e,lowestAvailableQuality:t}){return k$(a)||Zs(a.min)&&Zs(a.max)&&jg(a.max,a.min)||Zs(a.min)&&e&&A$(a.min,e)||Zs(a.max)&&t&&jg(a.max,t)}function Qg({limits:a,highestAvailableHeight:e,lowestAvailableHeight:t}){return qr({limits:{max:a!=null&&a.max?en(a.max):void 0,min:a!=null&&a.min?en(a.min):void 0},highestAvailableQuality:e?en(e):void 0,lowestAvailableQuality:t?en(t):void 0})}var L$=new ve("best_bitrate"),Zg=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t;var nl=a=>(e,t)=>a*(Number(e.bitrate)-Number(t.bitrate)),Ur=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=Xg()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},ev='Assertion "ABR Tracks is empty array" failed',rn=(a,e,t,i)=>{var u;let r=[...e].sort(nl(1)),s=[...t].sort(nl(1)),n=s.filter(l=>Se(l.bitrate)&&Se(a.bitrate)?a.bitrate/l.bitrate>i:!0),o=(u=(0,Vt.default)(s,Math.round(s.length*r.indexOf(a)/(r.length+1))))!=null?u:(0,Vt.default)(s,-1);return o&&(0,Kg.default)(n,o)?o:n.length?(0,Vt.default)(n,-1):(0,Vt.default)(s,0)},zg=a=>"quality"in a,tv=(a,e,t,i)=>{var n;let r=Se((n=i==null?void 0:i.last)==null?void 0:n.bitrate)&&Se(t==null?void 0:t.bitrate)&&i.last.bitrate<t.bitrate?a.trackCooldownIncreaseQuality:a.trackCooldownDecreaseQuality,s=t&&i&&i.history[t.id]&&Xg()-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=zg(o)?"video":"audio",l=zg(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},M$=(a,e)=>Math.log(e)/Math.log(a),C$=({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=M$(n,o*s+u)+l;Number.isFinite(c)&&(r*=c)}}return rl({highQualityLimit:a.highQualityLimit,trafficSavingLimit:a.trafficSavingLimit,limits:t})&&(r*=2),{containerSizeLimit:a.limitByContainer&&e&&e.width>0&&e.height>0?{width:e.width*r,height:e.height*r}:void 0,containerSizeFactor:r}},Ot=(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:h,stallsPredictedThroughput:p,abrLogger:m,panelSize:b})=>{var W,ae,A,B,Y;Jg(a,ev);let{containerSizeFactor:g,containerSizeLimit:v}=C$({container:e,tuning:i,limits:r,panelSize:b}),S=i.considerPlaybackRate&&Se(o)?o:1,y=a.filter(E=>!Yg(E.quality)).sort((E,$)=>Wg(E.quality,$.quality)?-1:1),I=(W=(0,Vt.default)(y,-1))==null?void 0:W.quality,T=(ae=(0,Vt.default)(y,0))==null?void 0:ae.quality,R=qr({limits:r,lowestAvailableQuality:I,highestAvailableQuality:T}),q=S*Zg(n!=null?n:.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),O={},w=y.filter(E=>{let $=!0;if(v)if(E.size)$=E.size.width<=v.width&&E.size.height<=v.height;else{let ot=v&&R$(v);$=ot?sl(E.quality,ot):!0}if(!$)return O[E.quality]="FitsContainer",!1;let ce=p||t,bi=Se(ce)&&isFinite(ce)&&Se(E.bitrate)?ce-s>=E.bitrate*q:!0,nt=rl({highQualityLimit:i.highQualityLimit,trafficSavingLimit:i.trafficSavingLimit,limits:r})&&(r==null?void 0:r.min)===E.quality;if(!bi&&!nt)return O[E.quality]="FitsThroughput",!1;if(i.lazyQualitySwitch&&Se(i.minBufferToSwitchUp)&&u&&!Yg(u.quality)&&(n!=null?n:0)<i.minBufferToSwitchUp&&Wg(E.quality,u.quality))return O[E.quality]="Buffer",!1;if(!!d&&al(E.quality,d)&&!nt)return O[E.quality]="DroppedFramesLimit",!1;if(!!h&&al(E.quality,h)&&!nt)return O[E.quality]="StallsLimit",!1;let Ie=R||(Gg(r==null?void 0:r.max)||sl(E.quality,r.max))&&(Gg(r==null?void 0:r.min)||al(E.quality,r.min)),Xe=Se(c)&&!c?sl(E.quality,i.backgroundVideoQualityLimit):!0;return!Ie||!Xe?(O[E.quality]="FitsQualityLimits",!1):!0})[0];w&&w.bitrate&&L$.next(w.bitrate);let U=(A=w!=null?w:(0,Vt.default)(y,-1))!=null?A:a[0],L=l==null?void 0:l.last,k=tv(i,m,U,l);return Se(l)&&k.quality!==(L==null?void 0:L.quality)&&m({message:`
|
|
10
10
|
[VIDEO TRACKS ABR]
|
|
11
11
|
[available video tracks]
|
|
12
|
-
${
|
|
12
|
+
${a.map(E=>{var $,ce;return`{ id: ${E.id}, quality: ${E.quality}, bitrate: ${E.bitrate}, size: ${($=E.size)==null?void 0:$.width}:${(ce=E.size)==null?void 0:ce.height} }`}).join(`
|
|
13
13
|
`)}
|
|
14
14
|
|
|
15
15
|
[tuning]
|
|
16
|
-
${(0,
|
|
16
|
+
${(0,tn.default)(i!=null?i:{}).map(([E,$])=>`${E}: ${$}`).join(`
|
|
17
17
|
`)}
|
|
18
18
|
|
|
19
19
|
[limit params]
|
|
20
20
|
containerSizeFactor: ${g},
|
|
21
|
-
containerSizeLimit: ${(
|
|
21
|
+
containerSizeLimit: ${(B=v==null?void 0:v.width)!=null?B:0} x ${(Y=v==null?void 0:v.height)!=null?Y:0},
|
|
22
22
|
estimatedThroughput: ${t},
|
|
23
23
|
stallsPredictedThroughput: ${p},
|
|
24
|
-
reserve: ${
|
|
24
|
+
reserve: ${s},
|
|
25
25
|
playbackRate: ${o},
|
|
26
|
-
playbackRateFactor: ${
|
|
26
|
+
playbackRateFactor: ${S},
|
|
27
27
|
forwardBufferHealth: ${n},
|
|
28
|
-
bitrateFactor: ${
|
|
28
|
+
bitrateFactor: ${q},
|
|
29
29
|
minBufferToSwitchUp: ${i.minBufferToSwitchUp},
|
|
30
|
-
droppedVideoMaxQualityLimit: ${
|
|
30
|
+
droppedVideoMaxQualityLimit: ${d},
|
|
31
31
|
stallsVideoMaxQualityLimit: ${h},
|
|
32
|
-
limitsAreInvalid: ${
|
|
32
|
+
limitsAreInvalid: ${R},
|
|
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,tn.default)(O).map(([E,$])=>`${E}: ${$}`).join(`
|
|
38
38
|
`)||"All tracks are available"}
|
|
39
39
|
|
|
40
|
-
[best video track] ${
|
|
41
|
-
[selected video track] ${
|
|
42
|
-
`})
|
|
43
|
-
[VIDEO TRACKS ABR]
|
|
44
|
-
[available video tracks]
|
|
45
|
-
${s.map(x=>{var D,oe;return`{ id: ${x.id}, quality: ${x.quality}, bitrate: ${x.bitrate}, size: ${(D=x.size)==null?void 0:D.width}:${(oe=x.size)==null?void 0:oe.height} }`}).join(`
|
|
46
|
-
`)}
|
|
47
|
-
|
|
48
|
-
[tuning]
|
|
49
|
-
${(0,hr.default)(i!=null?i:{}).map(([x,D])=>`${x}: ${D}`).join(`
|
|
50
|
-
`)}
|
|
51
|
-
|
|
52
|
-
[limit params]
|
|
53
|
-
containerSizeFactor: ${g},
|
|
54
|
-
containerSizeLimit: ${(N=S==null?void 0:S.width)!=null?N:0} x ${(A=S==null?void 0:S.height)!=null?A:0},
|
|
55
|
-
estimatedThroughput: ${t},
|
|
56
|
-
stallsPredictedThroughput: ${p},
|
|
57
|
-
reserve: ${a},
|
|
58
|
-
playbackRate: ${o},
|
|
59
|
-
playbackRateFactor: ${y},
|
|
60
|
-
forwardBufferHealth: ${n},
|
|
61
|
-
bitrateFactor: ${V},
|
|
62
|
-
minBufferToSwitchUp: ${i.minBufferToSwitchUp},
|
|
63
|
-
droppedVideoMaxQualityLimit: ${c},
|
|
64
|
-
stallsVideoMaxQualityLimit: ${h},
|
|
65
|
-
limitsAreInvalid: ${E},
|
|
66
|
-
maxQualityLimit: ${r==null?void 0:r.max},
|
|
67
|
-
minQualityLimit: ${r==null?void 0:r.min},
|
|
68
|
-
|
|
69
|
-
[limited video tracks]
|
|
70
|
-
${(0,hr.default)(L).map(([x,D])=>`${x}: ${D}`).join(`
|
|
71
|
-
`)||"All tracks are available"}
|
|
72
|
-
|
|
73
|
-
[best video track] ${P==null?void 0:P.quality}
|
|
74
|
-
[selected video track] ${M==null?void 0:M.quality}
|
|
75
|
-
`}),M},ku=(s,e,t,{estimatedThroughput:i,tuning:r,playbackRate:a,forwardBufferHealth:n,history:o,abrLogger:u,stallsPredictedThroughput:l})=>{xu(t,wu);let d=r.considerPlaybackRate&&te(a)?a:1,c=[...t].sort(Yr(-1)),h=s.bitrate;Ey(h);let p=d*Eu(n!=null?n:.5,r.bitrateAudioFactorAtEmptyBuffer,r.bitrateAudioFactorAtFullBuffer),f,m=Ca(s,e,t,r.minVideoAudioRatio),g=l||i;te(g)&&isFinite(g)&&(f=c.find(v=>te(v.bitrate)&&te(m==null?void 0:m.bitrate)?g-h>=v.bitrate*p&&v.bitrate>=m.bitrate:!1)),f||(f=m);let S=o==null?void 0:o.last,y=f&&Pu(r,u,f,o);return te(o)&&(y==null?void 0:y.bitrate)!==(S==null?void 0:S.bitrate)&&u({message:`
|
|
40
|
+
[best video track] ${w==null?void 0:w.quality}
|
|
41
|
+
[selected video track] ${k==null?void 0:k.quality}
|
|
42
|
+
`}),k},iv=(a,e,t,{estimatedThroughput:i,tuning:r,playbackRate:s,forwardBufferHealth:n,history:o,abrLogger:u,stallsPredictedThroughput:l})=>{Jg(t,ev);let c=r.considerPlaybackRate&&Se(s)?s:1,d=[...t].sort(nl(-1)),h=a.bitrate;$$(h);let p=c*Zg(n!=null?n:.5,r.bitrateAudioFactorAtEmptyBuffer,r.bitrateAudioFactorAtFullBuffer),m,b=rn(a,e,t,r.minVideoAudioRatio),g=l||i;Se(g)&&isFinite(g)&&(m=d.find(y=>Se(y.bitrate)&&Se(b==null?void 0:b.bitrate)?g-h>=y.bitrate*p&&y.bitrate>=b.bitrate:!1)),m||(m=b);let v=o==null?void 0:o.last,S=m&&tv(r,u,m,o);return Se(o)&&(S==null?void 0:S.bitrate)!==(v==null?void 0:v.bitrate)&&u({message:`
|
|
76
43
|
[AUDIO TRACKS ABR]
|
|
77
44
|
[available audio tracks]
|
|
78
|
-
${t.map(
|
|
45
|
+
${t.map(y=>`{ id: ${y.id}, bitrate: ${y.bitrate} }`).join(`
|
|
79
46
|
`)}
|
|
80
47
|
|
|
81
48
|
[tuning]
|
|
82
|
-
${(0,
|
|
49
|
+
${(0,tn.default)(r!=null?r:{}).map(([y,I])=>`${y}: ${I}`).join(`
|
|
83
50
|
`)}
|
|
84
51
|
|
|
85
52
|
[limit params]
|
|
86
53
|
estimatedThroughput: ${i},
|
|
87
54
|
stallsPredictedThroughput: ${l},
|
|
88
55
|
reserve: ${h},
|
|
89
|
-
playbackRate: ${
|
|
90
|
-
playbackRateFactor: ${
|
|
56
|
+
playbackRate: ${s},
|
|
57
|
+
playbackRateFactor: ${c},
|
|
91
58
|
forwardBufferHealth: ${n},
|
|
92
59
|
bitrateFactor: ${p},
|
|
93
60
|
minBufferToSwitchUp: ${r.minBufferToSwitchUp},
|
|
94
61
|
|
|
95
|
-
[selected audio track] ${
|
|
96
|
-
`}),y},Ru=(s,e,t,{estimatedThroughput:i,tuning:r,playbackRate:a,forwardBufferHealth:n,history:o,abrLogger:u,stallsPredictedThroughput:l})=>{xu(t,wu);let d=r.considerPlaybackRate&&te(a)?a:1,c=Sy.get(t);c||(c=[...t].sort(Yr(-1)),Sy.set(t,c));let h=s.bitrate;Ey(h);let p=d*Eu(n!=null?n:.5,r.bitrateAudioFactorAtEmptyBuffer,r.bitrateAudioFactorAtFullBuffer),f,m=Va(s,e,t,r.minVideoAudioRatio),g=l||i;te(g)&&isFinite(g)&&(f=c.find(v=>te(v.bitrate)&&te(m==null?void 0:m.bitrate)?g-h>=v.bitrate*p&&v.bitrate>=m.bitrate:!1)),f||(f=m);let S=o==null?void 0:o.last,y=f&&Pu(r,u,f,o);return te(o)&&(y==null?void 0:y.bitrate)!==(S==null?void 0:S.bitrate)&&u({message:`
|
|
97
|
-
[
|
|
98
|
-
[available audio tracks]
|
|
99
|
-
${t.map(v=>`{ id: ${v.id}, bitrate: ${v.bitrate} }`).join(`
|
|
100
|
-
`)}
|
|
101
|
-
|
|
102
|
-
[tuning]
|
|
103
|
-
${(0,hr.default)(r!=null?r:{}).map(([v,I])=>`${v}: ${I}`).join(`
|
|
104
|
-
`)}
|
|
105
|
-
|
|
106
|
-
[limit params]
|
|
107
|
-
estimatedThroughput: ${i},
|
|
108
|
-
stallsPredictedThroughput: ${l},
|
|
109
|
-
reserve: ${h},
|
|
110
|
-
playbackRate: ${a},
|
|
111
|
-
playbackRateFactor: ${d},
|
|
112
|
-
forwardBufferHealth: ${n},
|
|
113
|
-
bitrateFactor: ${p},
|
|
114
|
-
minBufferToSwitchUp: ${r.minBufferToSwitchUp},
|
|
115
|
-
|
|
116
|
-
[selected audio track] ${y==null?void 0:y.id}
|
|
117
|
-
`}),y};var we=s=>new URL(s).hostname;import{assertNever as Oy,assertNonNullable as _y,combine as ND,debounce as UD,ErrorCategory as Fy,filter as Ny,filterChanged as qD,isNonNullable as Zd,map as Du,merge as Uy,observableFrom as jD,once as HD,Subscription as WD,ValueSubject as ep,videoQualityToHeight as qy,videoSizeToQuality as zD}from"@vkontakte/videoplayer-shared/es2018";var Dy=U(Nt(),1);var ky=U(Tt(),1),Ay=s=>{if(s instanceof DOMException&&(0,ky.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"))},We=async(s,e)=>{let t=s.muted;try{await s.play()}catch(i){if(!Ay(i))return!1;if(e&&e(),t)return console.warn(i),!1;s.muted=!0;try{await s.play()}catch(r){return Ay(r)&&(s.muted=!1,console.warn(r)),!1}}return!0};import{isNonNullable as Mu,isNullable as ID,assertNonNullable as Fa}from"@vkontakte/videoplayer-shared/es2018";var Ly=U(dr(),1);import{isNonNullable as Ry,assertNonNullable as Lu,now as yD}from"@vkontakte/videoplayer-shared/es2018";function Be(){return yD()}function Yd(s){return Be()-s}function Kd(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 My(s,e,t){let i=(...r)=>{t.apply(null,r),s.removeEventListener(e,i)};s.addEventListener(e,i)}function Kr(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;Lu(d);let $=Yd(d),M;if($<m){M=m-$,setTimeout(g,M);return}m*=2,m>f&&(m=f),n&&n.abort(),n=new r,E()},S=$=>(a=$,O),y=$=>(c=$,O),v=()=>(p="json",O),I=()=>{if(!u){if(--l>=0){g(),i&&i();return}u=!0,c&&c(),t&&t()}},T=$=>(h=$,O),E=()=>{d=Be(),n=new r,n.open("get",s);let $=0,M,G=0,q=()=>(Lu(d),Math.max(d,Math.max(M||0,G||0)));if(a&&n.addEventListener("progress",w=>{let N=Be();a.updateChunk&&w.loaded>$&&(a.updateChunk(q(),w.loaded-$),$=w.loaded,M=N)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>I())),n.addEventListener("load",()=>{if(u)return;Lu(n);let w=n.status;if(w>=200&&w<300){let{response:N,responseType:A}=n,x=N==null?void 0:N.byteLength;if(typeof x=="number"&&a){let D=x-$;D&&a.updateChunk&&a.updateChunk(q(),D)}A==="json"&&(!N||!(0,Ly.default)(N).length)?I():(c&&c(),e(N))}else I()}),n.addEventListener("error",()=>{I()}),h){let w=()=>{Lu(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(G=Be(),n.removeEventListener("readystatechange",w))};n.addEventListener("readystatechange",w)}return n.responseType=p,n.send(),O},O={withBitrateReporting:S,withParallel:T,withJSONResponse:v,withRetryCount:$=>(l=$,O),withRetryInterval:($,M)=>(Ry($)&&(m=$),Ry(M)&&(f=M),O),withTimeout:$=>(o=$,O),withFinally:y,send:E,abort:()=>{n&&(n.abort(),n=void 0),u=!0,c&&c()}};return O}var Oa=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 $y=U(dr(),1);var _a=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=Kr(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,$y.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 xD}from"@vkontakte/videoplayer-shared/es2018";var $u=1e4,Xd=3;var ED=6e4,wD=10,PD=1,AD=500,Na=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 xD,this.chunkRateEstimator=new Oa(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=Kd(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setAutoQualityLimits(e){this.autoQualityLimits=e}switchByName(e){let t;for(let i=0;i<this.manifest.length;++i)if(t=this.manifest[i],t.name===e){this._switchToQuality(t);return}}catchUp(){this.rep&&this.rep.stop(),this.currentManifestEntry&&(this.paused=!1,this._initPlayerWith(this.currentManifestEntry),this._notifyBuffering(!0))}stop(){this.params.videoElement.pause(),this.rep&&(this.rep.stop(),this.rep=null)}pause(){this.paused=!0,this.params.videoElement.pause(),this.videoPlayStarted=!1,this._notifyBuffering(!1)}play(){this.paused=!1;let e=this.lowLatency&&this._getBufferSizeSec()>this.sourceJitter+5;this.rep&&!e?(this.bufferStates=[],this.videoPlayStarted=!1,this.shouldPlay()?this._playVideoElement():this._notifyBuffering(!0)):this.catchUp()}startPlay(e,t){this.autoQuality=t,this._initPlayerWith(e)}destroy(){this.destroyed=!0,this.rep&&(this.rep.stop(),this.rep=null),this.manifestRequest&&this.manifestRequest.abort(),this.manifestRefetchTimer&&(clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=void 0)}reinit(e){this.manifestUrl=e,this.urlResolver=Kd(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;!!e.error&&!this.destroyed&&(t(`Video element error: ${(r=e.error)==null?void 0:r.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{let i=this._getBufferSizeSec();!this.paused&&i<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(i+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){let{logger:e,videoElement:t}=this.params,i=t.buffered.length,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||{};!gy({limits:this.autoQualityLimits,highestAvailableHeight:this.manifest[0].video.height,lowestAvailableHeight:(0,Dy.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||Mu(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=()=>{My(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 _a(Xd,$u,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=Kr(this.urlResolver.resolve(I,!1),T,E,()=>this._retryCallback()).withTimeout($u).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Xd).withFinally(()=>{u=null}).send()},p=(I,T,E)=>{Fa(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,V=0;for(let k=0;k<this.bufferStates.length;k++){let P=this.bufferStates[k];I=Math.min(I,P.buf),P.ts<E&&V++}this.bufferStates.splice(0,V),t(`update playback rate; minBuffer=${I} drop=${V} jitter=${this.sourceJitter}`);let L=I-PD;this.sourceJitter>=0?L-=this.sourceJitter/2:this.sourceJitter-=1,L>3?f(1.15):L>1?f(1.1):L>.3?f(1.05):f(1)}},S=I=>{let T,E=()=>T&&T.start?T.start.length:0,V=w=>T.start[w]/1e3,L=w=>T.dur[w]/1e3,k=w=>T.fragIndex+w,P=(w,N)=>({chunkIdx:k(w),startTS:V(w),dur:L(w),discontinuity:N}),O=()=>{let w=0;if(T&&T.dur){let N=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,A=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,x=N;this.sourceJitter>1&&(x+=this.sourceJitter-1);let D=T.dur.length-1;for(;D>=0&&(x-=T.dur[D],!(x<=0));--D);w=Math.min(D,T.dur.length-1-A),w=Math.max(w,0)}return P(w,!0)},$=w=>{let N=E();if(!(N<=0)){if(Mu(w)){for(let A=0;A<N;A++)if(V(A)>w)return P(A)}return O()}},M=w=>{let N=E(),A=w?w.chunkIdx+1:0,x=A-T.fragIndex;if(!(N<=0)){if(!w||x<0||x-N>wD)return t(`Resync: offset=${x} bChunks=${N} chunk=`+JSON.stringify(w)),O();if(!(x>=N))return P(A-T.fragIndex,!1)}},G=(w,N,A)=>{l&&l.abort(),l=Kr(this.urlResolver.resolve(w,!0,this.lowLatency),N,A,()=>this._retryCallback()).withTimeout($u).withRetryCount(Xd).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(w,N)=>{G(I,A=>{if(!c())return;T=A;let x=!!T.lowLatency;x!==this.lowLatency&&m(x);let D=0;for(let oe=0;oe<T.dur.length;++oe)D+=T.dur[oe];D>0&&(Fa(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(D/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,w($(N))},()=>this._handleNetworkError())},nextChunk:M}},y=()=>{a=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),Fa(this.filesFetcher),this.filesFetcher.abortAll()};return d={start:I=>{let{videoElement:T,logger:E}=this.params,V=S(e.jidxUrl),L,k,P,O,$=0,M,G,q,w=()=>{M&&(clearTimeout(M),M=void 0);let Y=Math.max(AD,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),ye=$+Y,Te=Be(),Ie=Math.min(1e4,ye-Te);$=Te;let _e=()=>{l||c()&&V.seek(()=>{c()&&($=Be(),N(),w())})};Ie>0?M=window.setTimeout(()=>{this.paused?w():_e()},Ie):_e()},N=()=>{let Y;for(;Y=V.nextChunk(O);)O=Y,Oe(Y);let ye=V.nextChunk(P);if(ye){if(P&&ye.discontinuity){E("Detected discontinuity; restarting playback"),this.paused?w():(y(),this._initPlayerWith(e));return}oe(ye)}else w()},A=(Y,ye)=>{if(!c()||!this.sourceBuffer)return;let Te,Ie,_e,wt=Rt=>{window.setTimeout(()=>{c()&&A(Y,ye)},Rt)};if(this.sourceBuffer.updating)E("Source buffer is updating; delaying appendBuffer"),wt(100);else{let Rt=Be(),Ht=T.currentTime;!this.paused&&T.buffered.length>1&&G===Ht&&Rt-q>500&&(E("Stall suspected; trying to fix"),this._fixupStall()),G!==Ht&&(G=Ht,q=Rt);let ei=this._getBufferSizeSec();if(ei>30)E(`Buffered ${ei} seconds; delaying appendBuffer`),wt(2e3);else try{this.sourceBuffer.appendBuffer(Y),this.videoPlayStarted?(this.bufferStates.push({ts:Rt,buf:ei}),g(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),ye&&ye()}catch(Li){if(Li.name==="QuotaExceededError")E("QuotaExceededError; delaying appendBuffer"),_e=this.sourceBuffer.buffered.length,_e!==0&&(Te=this.sourceBuffer.buffered.start(0),Ie=Ht,Ie-Te>4&&this.sourceBuffer.remove(Te,Ie-3)),wt(1e3);else throw Li}}},x=()=>{k&&L&&(E([`Appending chunk, sz=${k.byteLength}:`,JSON.stringify(P)]),A(k,function(){k=null,N()}))},D=Y=>e.fragUrlTemplate.replace("%%id%%",Y.chunkIdx),oe=Y=>{c()&&p(D(Y),(ye,Te)=>{if(c()){if(Te/=1e3,k=ye,P=Y,n=Y.startTS,Te){let Ie=Math.min(10,Y.dur/Te);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*Ie:Ie}x()}},()=>this._handleNetworkError())},Oe=Y=>{c()&&(Fa(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(D(Y),!1)))},re=Y=>{c()&&(e.cachedHeader=Y,A(Y,()=>{L=!0,x()}))};a=!0,V.seek(Y=>{if(c()){if($=Be(),!Y){w();return}O=Y,!ID(I)||Y.startTS>I?oe(Y):(P=Y,N())}},I),e.cachedHeader?re(e.cachedHeader):h(e.headerUrl,re,()=>this._handleNetworkError())},stop:y,getTimestampSec:()=>n},d}_switchToQuality(e){let{logger:t,playerCallback:i}=this.params,r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),Mu(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,Fa(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return Mu(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&&Yd(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=Kr(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout($u).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;We(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))},ED))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var Vy=U(rr(),1);import{debounce as kD,filter as By,fromEvent as RD,interval as LD,isHigher as MD,isInvariantQuality as $D,isLower as DD,merge as BD,Subject as Cy,Subscription as CD}from"@vkontakte/videoplayer-shared/es2018";var Jd=class{constructor(){this.onDroopedVideoFramesLimit$=new Cy;this.subscription=new CD;this.playing=!1;this.tracks=[];this.forceChecker$=new Cy;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&&!$D(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&&MD(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(RD(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=LD(this.droppedFramesChecker.checkTime).pipe(By(()=>this.playing),By(()=>{let r=!!this.isForceCheckCounter;return r&&(this.isForceCheckCounter-=1),!r})),t=this.forceChecker$.pipe(kD(this.droppedFramesChecker.checkTime)),i=BD(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,Vy.default)(this.limitCounts).filter(([,a])=>a>=this.droppedFramesChecker.countLimit).sort(([a],[n])=>DD(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}},Xr=Jd;import{map as VD,Observable as OD}from"@vkontakte/videoplayer-shared/es2018";import{fromEvent as _D}from"@vkontakte/videoplayer-shared/es2018";var Ua=()=>{var s;return!!((s=window.documentPictureInPicture)!=null&&s.window)||!!document.pictureInPictureElement};var FD=(s,e)=>new OD(t=>{if(!window.IntersectionObserver)return;let i={root:null},r=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||Ua()))},{...i,...e});r.observe(s);let a=_D(document,"visibilitychange").pipe(VD(n=>!document.hidden||Ua())).subscribe(n=>t.next(n));return()=>{r.unobserve(s),a.unsubscribe()}}),lt=FD;var GD=["paused","playing","ready"],QD=["paused","playing","ready"],qa=class{constructor(e){this.subscription=new WD;this.videoState=new H("stopped");this.representations$=new ep([]);this.droppedFramesManager=new Xr;this.maxSeekBackTime$=new ep(1/0);this.zeroTime$=new ep(void 0);this.liveOffset=new pr;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:Fy.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=Yt(u.name))!=null?i:zD(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),Zd(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,tp.default)(QD,e)&&(n||o)){this.prepare();return}if((r==null?void 0:r.to)!=="paused"&&a.state==="requested"&&(0,tp.default)(GD,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 Oy(e)}};this.textTracksManager=new ot(e.source.url),this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=r=>{e.output.error$.next({id:"DashLiveProvider",category:Fy.WTF,message:"DashLiveProvider internal logic error",thrown:r})};this.subscription.add(Uy(this.videoState.stateChangeStarted$.pipe(Du(r=>({transition:r,type:"start"}))),this.videoState.stateChangeEnded$.pipe(Du(r=>({transition:r,type:"end"})))).subscribe(({transition:r,type:a})=>{this.log({message:`[videoState change] ${a}: ${JSON.stringify(r)}`})})),this.video=Ue(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(we(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=He(this.video);this.subscription.add(()=>i.destroy()),this.subscription.add(this.representations$.pipe(Du(r=>r.map(({track:a})=>a)),Ny(r=>!!r.length),HD()).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(qD(),Du(r=>-r/1e3)).subscribe(this.params.output.duration$)).add(ND({zeroTime:this.zeroTime$.pipe(Ny(Zd)),position:i.timeUpdate$}).subscribe(({zeroTime:r,position:a})=>this.params.output.liveTime$.next(r+a*1e3),t)).add(Pt(this.video,this.params.desiredState.isLooped,t)).add(je(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(nt(this.video,this.params.desiredState.playbackRate,i.playbackRateState$,t)).add(i.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(i.loadedMetadata$.subscribe(this.params.output.loadedMetadataEvent$)).add(i.playing$.subscribe(this.params.output.firstFrameEvent$)).add(i.canplay$.subscribe(this.params.output.canplay$)).add(i.inPiP$.subscribe(this.params.output.inPiP$)).add(i.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(lt(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:r,min:a}})=>{this.dash.setAutoQualityLimits({max:r&&qy(r),min:a&&qy(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 Oy(r.to)}},t)).add(Uy(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,jD(["init"])).pipe(UD(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),qe(this.video)}createLiveDashPlayer(){let e=new Na({videoElement:this.video,videoState:this.videoState,liveOffset:this.liveOffset,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode,manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){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&&Zd(t)?t:Kt(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;_y(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;_y(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 jy=qa;var rx=U(Tt(),1);var Ce=(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 RC,assertNonNullable as LC,debounce as MC,ErrorCategory as ex,filter as Fp,filterChanged as nl,fromEvent as $C,isNonNullable as tx,map as Np,merge as ol,observableFrom as Up,once as ix,Subscription as DC}from"@vkontakte/videoplayer-shared/es2018";var Bu=class{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,i){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:i})}removeEventListener(e,t){if(!(e in this.listeners))return;let i=this.listeners[e];for(let r=0,a=i.length;r<a;r++)if(i[r].callback===t){i.splice(r,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;let i=this.listeners[e.type].slice();for(let r=0,a=i.length;r<a;r++){let n=i[r];try{n.callback.call(this,e)}catch(o){Promise.resolve().then(()=>{throw o})}n.options&&n.options.once&&this.removeEventListener(e.type,n.callback)}return!e.defaultPrevented}},Jr=class extends Bu{constructor(){super(),this.listeners||Bu.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)}},ja=class{constructor(){Object.defineProperty(this,"signal",{value:new Jr,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&&(ja.prototype[Symbol.toStringTag]="AbortController",Jr.prototype[Symbol.toStringTag]="AbortSignal");function Cu(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 ip(s){typeof s=="function"&&(s={fetch:s});let{fetch:e,Request:t=e.Request,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r=!1}=s;if(!Cu({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 Ha=Cu({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),Hy=Ha?ip({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,At=Ha?Hy.fetch:window.fetch,Hj=Ha?Hy.Request:window.Request,se=Ha?ja:window.AbortController,Wj=Ha?Jr:window.AbortSignal;var Cp=U(Wa(),1);var LT=U(RT(),1);import{ErrorCategory as Ga}from"@vkontakte/videoplayer-shared/es2018";var Vu=s=>{if(!s)return{id:"EmptyResponse",category:Ga.PARSER,message:"Empty response"};if(s.length<=2&&s.match(/^\d+$/))return{id:`UVError#${s}`,category:Ga.NETWORK,message:`UV Error ${s}`};let e=(0,LT.default)(s).substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:Ga.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:Ga.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:Ga.PARSER,message:"Response is valid XML, but parser failed"}};var ze=(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 $p,assertNonNullable as us,combine as ls,ErrorCategory as Jt,filter as Ju,filterChanged as An,flattenObject as kn,fromEvent as xi,getTraceSubscriptionMethod as dC,interval as Dp,isNonNullable as Rn,isNullable as GI,map as cs,merge as gr,now as Bp,Subject as Zu,Subscription as QI,tap as pC,throttle as hC,ValueSubject as he}from"@vkontakte/videoplayer-shared/es2018";var Fu=U(Tt(),1),as=U(Nt(),1),Nu=U(Wa(),1);var DB=(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)},BB=s=>window.clearTimeout(s),MT=s=>typeof s=="function"&&(s==null?void 0:s.toString().endsWith("{ [native code] }")),$T=!MT(window.requestIdleCallback)||!MT(window.cancelIdleCallback),Zr=$T?DB:window.requestIdleCallback,Xt=$T?BB:window.cancelIdleCallback;var OI=U(ka(),1);import{assertNever as CB,ErrorCategory as DT,Subject as BT}from"@vkontakte/videoplayer-shared/es2018";var VB=18,CT=!1;try{CT=j.browser.isSafari&&!!j.browser.safariVersion&&j.browser.safariVersion<=VB}catch(s){console.error(s)}var up=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:DT.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)};CT&&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:DT.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:CB(t)}}},VT=up;var es=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 Ni,assertNonNullable as ct,ErrorCategory as yi,fromEvent as Pp,getExponentialDelay as Ap,isNonNullable as ss,isNullable as Ge,now as _u,once as Z0,Subject as eC,Subscription as tC,ValueSubject as br}from"@vkontakte/videoplayer-shared/es2018";var K=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 ts=class extends K{};var Qa=class extends K{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 Ya=class extends K{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 Ka=class extends K{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ue=class extends K{constructor(e,t){super(e,t);let i=this.readUint32();this.version=i>>>24,this.flags=i&16777215}};var Xa=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 Ja=class extends K{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Za=class extends K{constructor(e,t){super(e,t),this.data=this.content}};var fr=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 en=class extends K{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var tn=class extends K{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var rn=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 sn=class extends ue{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var an=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 nn=class extends K{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var on=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 un=class extends K{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ln=class extends K{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var cn=class extends ue{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var dn=class extends K{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var pn=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 hn=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 fn=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 mn=class extends K{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var bn=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 gn=class extends K{constructor(e,t){super(e,t),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+78,this.content.byteLength-78))}};var _B={ftyp:Ya,moov:Ka,mvhd:Xa,moof:Ja,mdat:Za,sidx:fr,trak:en,mdia:nn,mfhd:cn,tkhd:on,traf:dn,tfhd:pn,tfdt:hn,trun:fn,minf:un,sv3d:tn,st3d:rn,prhd:sn,proj:ln,equi:an,uuid:Qa,stbl:mn,stsd:bn,avc1:gn,unknown:ts},Si=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=_B[e];return i?new i(t,new s):new ts(t,new s)}};var Fi=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{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 NB=new TextDecoder("ascii"),UB=s=>NB.decode(new DataView(s.buffer,s.byteOffset+4,4))==="ftyp",qB=s=>{let e=new fr(s,new Si),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})},jB=(s,e)=>{let i=new Si().parse(s),r=new Fi(i),a=r.findAll("moof"),n=e?r.findAll("uuid"):r.findAll("mdat");if(!(n.length&&a.length))return null;let o=a[0],u=n[n.length-1],l=o.source.byteOffset,c=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(s.buffer,l,c)},HB=s=>{let t=new Si().parse(s),i=new Fi(t),r={},a=i.findAll("uuid");return a.length?a[a.length-1]:r},WB=s=>{var r;let t=new Si().parse(s);return(r=new Fi(t).find("sidx"))==null?void 0:r.timescale},zB=(s,e)=>{let i=new Si().parse(s),a=new Fi(i).findAll("traf"),n=a[a.length-1].children.find(c=>c.type==="tfhd"),o=a[a.length-1].children.find(c=>c.type==="tfdt"),u=a[a.length-1].children.find(c=>c.type==="trun"),l=0;return u.sampleDuration.length?l=u.sampleDuration.reduce((c,h)=>c+h,0):l=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+l)/e*1e3},GB=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 Si().parse(s),r=new Fi(i);if(r.find("sv3d")){e.is3dVideo=!0;let n=r.find("st3d");n&&(e.stereoMode=n.stereoMode);let o=r.find("prhd");o&&(e.projectionData.pose.yaw=o.poseYawDegrees,e.projectionData.pose.pitch=o.posePitchDegrees,e.projectionData.pose.roll=o.poseRollDegrees);let u=r.find("equi");u&&(e.projectionData.bounds.top=u.projectionBoundsTop,e.projectionData.bounds.right=u.projectionBoundsRight,e.projectionData.bounds.bottom=u.projectionBoundsBottom,e.projectionData.bounds.left=u.projectionBoundsLeft)}return e},OT={validateData:UB,parseInit:GB,getIndexRange:()=>{},parseSegments:qB,parseFeedableSegmentChunk:jB,getChunkEndTime:zB,getServerLatencyTimestamps:HB,getTimescaleFromIndex:WB};var vn=U(Tt(),1);import{assertNonNullable as cp,isNonNullable as UT,isNullable as YB}from"@vkontakte/videoplayer-shared/es2018";import{assertNever as QB}from"@vkontakte/videoplayer-shared/es2018";var _T={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"}},FT=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=Sn(s,t),r=i in _T,a=r?_T[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=Sn(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}},Sn=(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},Ut=(s,e)=>{switch(e){case"int":return s.getInt8(0);case"uint":return Sn(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:QB(e)}},mr=(s,e)=>{let t=0;for(;t<s.byteLength;){let i=new DataView(s.buffer,s.byteOffset+t),r=FT(i);if(!e(r))return;r.type==="master"&&mr(r.value,e),t=r.value.byteOffset-s.byteOffset+r.valueSize}},NT=s=>{if(s.getUint32(0)!==440786851)return!1;let e,t,i,r=FT(s);return mr(r.value,({tag:a,type:n,value:o})=>(a===17143?e=Ut(o,n):a===17026?t=Ut(o,n):a===17029&&(i=Ut(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)};var qT=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],KB=[231,22612,22743,167,171,163,160,175],XB=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=Ut(f,p);l=Sn(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=Ut(f,p):h===17545?r=Ut(f,p):h===21420&&l===475249515?u=Ut(f,p):h===374648427?mr(f,({tag:g,type:S,value:y})=>g===30321?(d=Ut(y,S)===1,!1):!0):a&&n&&(0,vn.default)(qT,h)&&(o=!0),!o}),cp(e,"Failed to parse webm Segment start"),cp(t,"Failed to parse webm Segment end"),cp(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}}}},JB=s=>{if(YB(s.cuesSeekPosition))return;let e=s.segmentStart+s.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},ZB=(s,e)=>{let t=!1,i=!1,r=o=>UT(o.time)&&UT(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=Ut(l,u));break;case 183:break;case 241:n&&(n.position=Ut(l,u));break;default:t&&(0,vn.default)(qT,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}}})},e0=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,vn.default)(KB,i.tag)?(e+i.tagSize<=s.byteLength&&(e+=i.tagSize,t||(t=(0,vn.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},jT={validateData:NT,parseInit:XB,getIndexRange:JB,parseSegments:ZB,parseFeedableSegmentChunk:e0};var yn=s=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(s);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return jT;case"mp4":return OT}}throw new ReferenceError(`Unsupported mime type ${s}`)};var xp=U(bp(),1),$I=U(rr(),1),DI=U(gp(),1),BI=U(Nt(),1),Ep=U(dr(),1);var EI=U(Tt(),1),rs=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,EI.default)(["6E","7A","F4"],o)}}return!1};import{isNonNullable as X0,isNullable as LI}from"@vkontakte/videoplayer-shared/es2018";var Ou=s=>{if(s.includes("/")){let e=s.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(s)};var wI=s=>{var e;try{let t=Y0(),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 Y0(){let s="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",d=`^(?:(?<langtag>${`
|
|
118
|
-
(?<language>${`(?:[a-z]{2,3}(?:-${s})?|[a-z]{4}|[a-z]{5,8})`})
|
|
62
|
+
[selected audio track] ${S==null?void 0:S.id}
|
|
63
|
+
`}),S};var oe=a=>new URL(a).hostname;import{assertNever as hv,assertNonNullable as mv,combine as eL,debounce as tL,ErrorCategory as fv,filter as bv,filterChanged as iL,isNonNullable as dl,map as un,merge as gv,observableFrom as rL,once as aL,Subscription as sL,ValueSubject as pl,videoQualityToHeight as vv,videoSizeToQuality as nL}from"@vkontakte/videoplayer-shared/es2018";var lv=C(Dt(),1);var av=C(Be(),1),rv=a=>{if(a instanceof DOMException&&(0,av.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"))},ke=async(a,e)=>{let t=a.muted;try{await a.play()}catch(i){if(!rv(i))return!1;if(e&&e(),t)return console.warn(i),!1;a.muted=!0;try{await a.play()}catch(r){return rv(r)&&(a.muted=!1,console.warn(r)),!1}}return!0};import{isNonNullable as sn,isNullable as O$,assertNonNullable as Qr}from"@vkontakte/videoplayer-shared/es2018";var nv=C(ji(),1);import{isNonNullable as sv,assertNonNullable as an,now as D$}from"@vkontakte/videoplayer-shared/es2018";function ue(){return D$()}function ol(a){return ue()-a}function ul(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 ov(a,e,t){let i=(...r)=>{t.apply(null,r),a.removeEventListener(e,i)};a.addEventListener(e,i)}function Gi(a,e,t,i){let r=window.XMLHttpRequest,s,n,o,u=!1,l=0,c,d,h=!1,p="arraybuffer",m=7e3,b=2e3,g=()=>{if(u)return;an(c);let L=ol(c),k;if(L<b){k=b-L,setTimeout(g,k);return}b*=2,b>m&&(b=m),n&&n.abort(),n=new r,R()},v=L=>(s=L,U),S=L=>(d=L,U),y=()=>(p="json",U),I=()=>{if(!u){if(--l>=0){g(),i&&i();return}u=!0,d&&d(),t&&t()}},T=L=>(h=L,U),R=()=>{c=ue(),n=new r,n.open("get",a);let L=0,k,W=0,ae=()=>(an(c),Math.max(c,Math.max(k||0,W||0)));if(s&&n.addEventListener("progress",A=>{let B=ue();s.updateChunk&&A.loaded>L&&(s.updateChunk(ae(),A.loaded-L),L=A.loaded,k=B)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>I())),n.addEventListener("load",()=>{if(u)return;an(n);let A=n.status;if(A>=200&&A<300){let{response:B,responseType:Y}=n,E=B==null?void 0:B.byteLength;if(typeof E=="number"&&s){let $=E-L;$&&s.updateChunk&&s.updateChunk(ae(),$)}Y==="json"&&(!B||!(0,nv.default)(B).length)?I():(d&&d(),e(B))}else I()}),n.addEventListener("error",()=>{I()}),h){let A=()=>{an(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(W=ue(),n.removeEventListener("readystatechange",A))};n.addEventListener("readystatechange",A)}return n.responseType=p,n.send(),U},U={withBitrateReporting:v,withParallel:T,withJSONResponse:y,withRetryCount:L=>(l=L,U),withRetryInterval:(L,k)=>(sv(L)&&(b=L),sv(k)&&(m=k),U),withTimeout:L=>(o=L,U),withFinally:S,send:R,abort:()=>{n&&(n.abort(),n=void 0),u=!0,d&&d()}};return U}var Hr=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 uv=C(ji(),1);var jr=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=ue(),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=ue()-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=Gi(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=ue()}_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=ue();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,uv.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 B$}from"@vkontakte/videoplayer-shared/es2018";var nn=1e4,ll=3;var _$=6e4,N$=10,F$=1,q$=500,Gr=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 B$,this.chunkRateEstimator=new Hr(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=ul(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setAutoQualityLimits(e){this.autoQualityLimits=e}switchByName(e){let t;for(let i=0;i<this.manifest.length;++i)if(t=this.manifest[i],t.name===e){this._switchToQuality(t);return}}catchUp(){this.rep&&this.rep.stop(),this.currentManifestEntry&&(this.paused=!1,this._initPlayerWith(this.currentManifestEntry),this._notifyBuffering(!0))}stop(){this.params.videoElement.pause(),this.rep&&(this.rep.stop(),this.rep=null)}pause(){this.paused=!0,this.params.videoElement.pause(),this.videoPlayStarted=!1,this._notifyBuffering(!1)}play(){this.paused=!1;let e=this.lowLatency&&this._getBufferSizeSec()>this.sourceJitter+5;this.rep&&!e?(this.bufferStates=[],this.videoPlayStarted=!1,this.shouldPlay()?this._playVideoElement():this._notifyBuffering(!0)):this.catchUp()}startPlay(e,t){this.autoQuality=t,this._initPlayerWith(e)}destroy(){this.destroyed=!0,this.rep&&(this.rep.stop(),this.rep=null),this.manifestRequest&&this.manifestRequest.abort(),this.manifestRefetchTimer&&(clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=void 0)}reinit(e){this.manifestUrl=e,this.urlResolver=ul(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;!!e.error&&!this.destroyed&&(t(`Video element error: ${(r=e.error)==null?void 0:r.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{let i=this._getBufferSizeSec();!this.paused&&i<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(i+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){let{logger:e,videoElement:t}=this.params,i=t.buffered.length,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||{};!Qg({limits:this.autoQualityLimits,highestAvailableHeight:this.manifest[0].video.height,lowestAvailableHeight:(0,lv.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||sn(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=()=>{ov(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 jr(ll,nn,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},h=(I,T,R)=>{u&&u.abort(),u=Gi(this.urlResolver.resolve(I,!1),T,R,()=>this._retryCallback()).withTimeout(nn).withBitrateReporting(this.bitrateSwitcher).withRetryCount(ll).withFinally(()=>{u=null}).send()},p=(I,T,R)=>{Qr(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(I,!1),T,R,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},m=I=>{let T=i.playbackRate;i.playbackRate!==I&&(t(`Playback rate switch: ${T}=>${I}`),i.playbackRate=I)},b=I=>{this.lowLatency=I,t(`lowLatency changed to ${I}`),g()},g=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)m(1);else{let I=this._getBufferSizeSec();if(this.bufferStates.length<5){m(1);return}let R=ue()-1e4,q=0;for(let _=0;_<this.bufferStates.length;_++){let w=this.bufferStates[_];I=Math.min(I,w.buf),w.ts<R&&q++}this.bufferStates.splice(0,q),t(`update playback rate; minBuffer=${I} drop=${q} jitter=${this.sourceJitter}`);let O=I-F$;this.sourceJitter>=0?O-=this.sourceJitter/2:this.sourceJitter-=1,O>3?m(1.15):O>1?m(1.1):O>.3?m(1.05):m(1)}},v=I=>{let T,R=()=>T&&T.start?T.start.length:0,q=A=>T.start[A]/1e3,O=A=>T.dur[A]/1e3,_=A=>T.fragIndex+A,w=(A,B)=>({chunkIdx:_(A),startTS:q(A),dur:O(A),discontinuity:B}),U=()=>{let A=0;if(T&&T.dur){let B=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,Y=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,E=B;this.sourceJitter>1&&(E+=this.sourceJitter-1);let $=T.dur.length-1;for(;$>=0&&(E-=T.dur[$],!(E<=0));--$);A=Math.min($,T.dur.length-1-Y),A=Math.max(A,0)}return w(A,!0)},L=A=>{let B=R();if(!(B<=0)){if(sn(A)){for(let Y=0;Y<B;Y++)if(q(Y)>A)return w(Y)}return U()}},k=A=>{let B=R(),Y=A?A.chunkIdx+1:0,E=Y-T.fragIndex;if(!(B<=0)){if(!A||E<0||E-B>N$)return t(`Resync: offset=${E} bChunks=${B} chunk=`+JSON.stringify(A)),U();if(!(E>=B))return w(Y-T.fragIndex,!1)}},W=(A,B,Y)=>{l&&l.abort(),l=Gi(this.urlResolver.resolve(A,!0,this.lowLatency),B,Y,()=>this._retryCallback()).withTimeout(nn).withRetryCount(ll).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(A,B)=>{W(I,Y=>{if(!d())return;T=Y;let E=!!T.lowLatency;E!==this.lowLatency&&b(E);let $=0;for(let ce=0;ce<T.dur.length;++ce)$+=T.dur[ce];$>0&&(Qr(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(B))},()=>this._handleNetworkError())},nextChunk:k}},S=()=>{s=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),Qr(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:I=>{let{videoElement:T,logger:R}=this.params,q=v(e.jidxUrl),O,_,w,U,L=0,k,W,ae,A=()=>{k&&(clearTimeout(k),k=void 0);let Q=Math.max(q$,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),be=L+Q,Te=ue(),Ie=Math.min(1e4,be-Te);L=Te;let Xe=()=>{l||d()&&q.seek(()=>{d()&&(L=ue(),B(),A())})};Ie>0?k=window.setTimeout(()=>{this.paused?A():Xe()},Ie):Xe()},B=()=>{let Q;for(;Q=q.nextChunk(U);)U=Q,bi(Q);let be=q.nextChunk(w);if(be){if(w&&be.discontinuity){R("Detected discontinuity; restarting playback"),this.paused?A():(S(),this._initPlayerWith(e));return}ce(be)}else A()},Y=(Q,be)=>{if(!d()||!this.sourceBuffer)return;let Te,Ie,Xe,ot=yt=>{window.setTimeout(()=>{d()&&Y(Q,be)},yt)};if(this.sourceBuffer.updating)R("Source buffer is updating; delaying appendBuffer"),ot(100);else{let yt=ue(),jt=T.currentTime;!this.paused&&T.buffered.length>1&&W===jt&&yt-ae>500&&(R("Stall suspected; trying to fix"),this._fixupStall()),W!==jt&&(W=jt,ae=yt);let gi=this._getBufferSizeSec();if(gi>30)R(`Buffered ${gi} seconds; delaying appendBuffer`),ot(2e3);else try{this.sourceBuffer.appendBuffer(Q),this.videoPlayStarted?(this.bufferStates.push({ts:yt,buf:gi}),g(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),be&&be()}catch(sr){if(sr.name==="QuotaExceededError")R("QuotaExceededError; delaying appendBuffer"),Xe=this.sourceBuffer.buffered.length,Xe!==0&&(Te=this.sourceBuffer.buffered.start(0),Ie=jt,Ie-Te>4&&this.sourceBuffer.remove(Te,Ie-3)),ot(1e3);else throw sr}}},E=()=>{_&&O&&(R([`Appending chunk, sz=${_.byteLength}:`,JSON.stringify(w)]),Y(_,function(){_=null,B()}))},$=Q=>e.fragUrlTemplate.replace("%%id%%",Q.chunkIdx),ce=Q=>{d()&&p($(Q),(be,Te)=>{if(d()){if(Te/=1e3,_=be,w=Q,n=Q.startTS,Te){let Ie=Math.min(10,Q.dur/Te);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*Ie:Ie}E()}},()=>this._handleNetworkError())},bi=Q=>{d()&&(Qr(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve($(Q),!1)))},nt=Q=>{d()&&(e.cachedHeader=Q,Y(Q,()=>{O=!0,E()}))};s=!0,q.seek(Q=>{if(d()){if(L=ue(),!Q){A();return}U=Q,!O$(I)||Q.startTS>I?ce(Q):(w=Q,B())}},I),e.cachedHeader?nt(e.cachedHeader):h(e.headerUrl,nt,()=>this._handleNetworkError())},stop:S,getTimestampSec:()=>n},c}_switchToQuality(e){let{logger:t,playerCallback:i}=this.params,r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),sn(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,Qr(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return sn(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,i=d=>{if(!this.autoQuality)return;let h,p,m;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&d<this.bitrate&&(p=this._getBufferSizeSec(),m=d/this.bitrate,p>10&&m>.8||p>15&&m>.5||p>20&&m>.3)){e(`Not switching: buffer=${Math.floor(p)}; bitrate=${this.bitrate}; newRate=${Math.floor(d)}`);return}h=this._selectQuality(d),h?this._switchToQuality(h):e(`Could not find quality by bitrate ${d}`)},s={updateChunk:(h,p)=>{let m=ue();if(this.chunkRateEstimator.addInterval(h,m,p)){let g=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:p,duration:m-h,speed:g}),!0}},get:()=>{let h=this.chunkRateEstimator.getBitRate();return h?h*.85:0}},n=-1/0,o,u=!0,l=()=>{let d=s.get();if(d&&o&&this.autoQuality){if(u&&d>o&&ol(n)<3e4)return;i(d)}u=this.autoQuality};return{updateChunk:(d,h)=>{let p=s.updateChunk(d,h);return p&&l(),p},notifySwitch:d=>{let h=ue();d<o&&(n=h),o=d}}}_fetchManifest(e,t,i){this.manifestRequest=Gi(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(nn).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;ke(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))},_$))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var pv=C(Ci(),1);import{debounce as U$,filter as cv,fromEvent as H$,interval as j$,isHigher as Q$,isInvariantQuality as G$,isLower as W$,merge as Y$,Subject as dv,Subscription as z$}from"@vkontakte/videoplayer-shared/es2018";var cl=class{constructor(){this.onDroopedVideoFramesLimit$=new dv;this.subscription=new z$;this.playing=!1;this.tracks=[];this.forceChecker$=new dv;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&&!G$(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&&Q$(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(H$(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=j$(this.droppedFramesChecker.checkTime).pipe(cv(()=>this.playing),cv(()=>{let r=!!this.isForceCheckCounter;return r&&(this.isForceCheckCounter-=1),!r})),t=this.forceChecker$.pipe(U$(this.droppedFramesChecker.checkTime)),i=Y$(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,pv.default)(this.limitCounts).filter(([,s])=>s>=this.droppedFramesChecker.countLimit).sort(([s],[n])=>W$(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}},on=cl;import{map as K$,Observable as X$}from"@vkontakte/videoplayer-shared/es2018";import{fromEvent as J$}from"@vkontakte/videoplayer-shared/es2018";var Wr=()=>{var a;return!!((a=window.documentPictureInPicture)!=null&&a.window)||!!document.pictureInPictureElement};var Z$=(a,e)=>new X$(t=>{if(!window.IntersectionObserver)return;let i={root:null},r=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||Wr()))},{...i,...e});r.observe(a);let s=J$(document,"visibilitychange").pipe(K$(n=>!document.hidden||Wr())).subscribe(n=>t.next(n));return()=>{r.unobserve(a),s.unsubscribe()}}),Fe=Z$;var oL=["paused","playing","ready"],uL=["paused","playing","ready"],Yr=class{constructor(e){this.subscription=new sL;this.videoState=new D("stopped");this.representations$=new pl([]);this.droppedFramesManager=new on;this.maxSeekBackTime$=new pl(1/0);this.zeroTime$=new pl(void 0);this.liveOffset=new ui;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:fv.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=Ct(u.name))!=null?i:nL(u.video),d=u.bitrate/1e3,h={...u.video};if(!c)continue;let p={id:l,quality:c,bitrate:d,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=(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),dl(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,hl.default)(uL,e)&&(n||o)){this.prepare();return}if((r==null?void 0:r.to)!=="paused"&&s.state==="requested"&&(0,hl.default)(oL,e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(he(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(he(this.params.source.url,u))}return;default:return hv(e)}};this.textTracksManager=new Ne(e.source.url),this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=r=>{e.output.error$.next({id:"DashLiveProvider",category:fv.WTF,message:"DashLiveProvider internal logic error",thrown:r})};this.subscription.add(gv(this.videoState.stateChangeStarted$.pipe(un(r=>({transition:r,type:"start"}))),this.videoState.stateChangeEnded$.pipe(un(r=>({transition:r,type:"end"})))).subscribe(({transition:r,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(r)}`})})),this.video=Ee(e.container,e.tuning),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.subscription.add(this.dash.soundProhibitedEvent$.subscribe(this.params.output.soundProhibitedEvent$)),this.params.output.duration$.next(1/0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(oe(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=Ae(this.video);this.subscription.add(()=>i.destroy()),this.subscription.add(this.representations$.pipe(un(r=>r.map(({track:s})=>s)),bv(r=>!!r.length),aL()).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(iL(),un(r=>-r/1e3)).subscribe(this.params.output.duration$)).add(eL({zeroTime:this.zeroTime$.pipe(bv(dl)),position:i.timeUpdate$}).subscribe(({zeroTime:r,position:s})=>this.params.output.liveTime$.next(r+s*1e3),t)).add(it(this.video,this.params.desiredState.isLooped,t)).add(Pe(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(_e(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(Fe(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:r,min:s}})=>{this.dash.setAutoQualityLimits({max:r&&vv(r),min:s&&vv(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 hv(r.to)}},t)).add(gv(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,rL(["init"])).pipe(tL(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),xe(this.video)}createLiveDashPlayer(){let e=new Gr({videoElement:this.video,videoState:this.videoState,liveOffset:this.liveOffset,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode,manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){var l,c,d,h,p,m;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=(h=(d=this.params.desiredState.autoVideoTrackSwitching.getTransition())==null?void 0:d.to)!=null?h:this.params.desiredState.autoVideoTrackSwitching.getState(),r=!i&&dl(t)?t:Ot(e.map(({track:b})=>b),{container:this.video.getBoundingClientRect(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),s=r==null?void 0:r.id,n=this.params.desiredState.videoTrack.getTransition(),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 b=(m=e.find(({track:g})=>g.id===s))==null?void 0:m.representation;mv(b,"Representations missing"),this.dash.startPlay(b,i)}}setVideoTrack(e){var i;let t=(i=this.representations$.getValue().find(({track:r})=>r.id===e.id))==null?void 0:i.representation;mv(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(he(this.params.source.url,n)),r&&this.dash.pause(),this.liveOffset.resetTo(n,r)}};var Sv=Yr;var qy=C(Be(),1);var Wi=(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 HC,assertNonNullable as jC,debounce as QC,ErrorCategory as _y,filter as ec,filterChanged as Oa,fromEvent as GC,isNonNullable as Ny,map as tc,merge as Rn,observableFrom as ic,once as Fy,Subscription as WC}from"@vkontakte/videoplayer-shared/es2018";var ln=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}},Yi=class extends ln{constructor(){super(),this.listeners||ln.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)}},zr=class{constructor(){Object.defineProperty(this,"signal",{value:new Yi,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&&(zr.prototype[Symbol.toStringTag]="AbortController",Yi.prototype[Symbol.toStringTag]="AbortSignal");function cn(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 ml(a){typeof a=="function"&&(a={fetch:a});let{fetch:e,Request:t=e.Request,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r=!1}=a;if(!cn({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 h=new t(l,c);return d&&Object.defineProperty(h,"signal",{writable:!1,enumerable:!1,configurable:!0,value:d}),h},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 h=new Promise((p,m)=>{c.addEventListener("abort",()=>m(d),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([h,n(u,l)])}return n(u,l)},Request:s}}var Kr=cn({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),yv=Kr?ml({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,at=Kr?yv.fetch:window.fetch,uq=Kr?yv.Request:window.Request,me=Kr?zr:window.AbortController,lq=Kr?Yi:window.AbortSignal;var Kl=C(bl(),1);var nS=C(sS(),1);import{ErrorCategory as Jr}from"@vkontakte/videoplayer-shared/es2018";var oS=a=>{if(!a)return{id:"EmptyResponse",category:Jr.PARSER,message:"Empty response"};if(a.length<=2&&a.match(/^\d+$/))return{id:`UVError#${a}`,category:Jr.NETWORK,message:`UV Error ${a}`};let e=(0,nS.default)(a).substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:Jr.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:Jr.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:Jr.PARSER,message:"Response is valid XML, but parser failed"}};var Bt=(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 Wl,assertNonNullable as er,combine as tr,ErrorCategory as st,filter as In,filterChanged as Ca,flattenObject as Da,fromEvent as gt,getTraceSubscriptionMethod as PC,interval as Yl,isNonNullable as Va,isNullable as Ly,map as ir,merge as mi,now as zl,Subject as En,Subscription as My,tap as wC,throttle as AC,ValueSubject as Z}from"@vkontakte/videoplayer-shared/es2018";var pn=C(Be(),1),Ji=C(Dt(),1),hn=C(bl(),1);var WL=(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)},YL=a=>window.clearTimeout(a),uS=a=>typeof a=="function"&&(a==null?void 0:a.toString().endsWith("{ [native code] }")),lS=!uS(window.requestIdleCallback)||!uS(window.cancelIdleCallback),Tl=lS?WL:window.requestIdleCallback,Zr=lS?YL:window.cancelIdleCallback;var vy=C(Hs(),1);import{assertNever as zL,ErrorCategory as cS,Subject as dS}from"@vkontakte/videoplayer-shared/es2018";var KL=18,pS=!1;try{pS=N.browser.isSafari&&!!N.browser.safariVersion&&N.browser.safariVersion<=KL}catch(a){console.error(a)}var Il=class{constructor(e){this.bufferFull$=new dS;this.error$=new dS;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:cS.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)};pS&&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:cS.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:zL(t)}}},hS=Il;var El=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 Nt,assertNonNullable as Re,ErrorCategory as bt,fromEvent as Fl,getExponentialDelay as ql,isNonNullable as Xi,isNullable as fe,now as dn,once as pC,Subject as hC,Subscription as mC,ValueSubject as di}from"@vkontakte/videoplayer-shared/es2018";var H=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,s=e.byteOffset+this.cursor;this.size64=0,this.usertype=0,this.content=new DataView(e.buffer,s,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 zi=class extends H{};var ea=class extends H{constructor(t,i){super(t,i);this.ondemandPrefix="ondemandlivejson";this.ondemandDataReceivedKey="t-in";this.ondemandDataPreparedKey="t-out";let r=this.content.byteOffset,s=r+this.content.byteLength,n=new TextDecoder("ascii").decode(this.content.buffer.slice(r,s)).split(this.ondemandPrefix)[1],o=JSON.parse(n);this.serverDataReceivedTimestamp=o[this.ondemandDataReceivedKey],this.serverDataPreparedTime=o[this.ondemandDataPreparedKey]}};var ta=class extends H{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 ia=class extends H{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var J=class extends H{constructor(e,t){super(e,t);let i=this.readUint32();this.version=i>>>24,this.flags=i&16777215}};var ra=class extends J{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 aa=class extends H{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var sa=class extends H{constructor(e,t){super(e,t),this.data=this.content}};var li=class extends J{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(),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 na=class extends H{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var oa=class extends H{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ua=class extends J{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 la=class extends J{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var ca=class extends J{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var da=class extends H{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var pa=class extends J{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.trackId=this.readUint32(),this.cursor+=4,this.duration=this.readUint32(),this.cursor+=8,this.layer=this.readUint16(),this.alternateGroup=this.readUint16(),this.cursor+=2,this.cursor+=2,this.matrix=[[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()]],this.width=this.readUint32(),this.height=this.readUint32()}};var ha=class extends H{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ma=class extends H{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var fa=class extends J{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var ba=class extends H{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ga=class extends J{constructor(e,t){super(e,t),this.trackId=this.readUint32(),this.flags&1&&(this.baseDataOffset=this.readUint64()),this.flags&2&&(this.sampleDescriptionIndex=this.readUint32()),this.flags&8&&(this.defaultSampleDuration=this.readUint32()),this.flags&16&&(this.defaultSampleSize=this.readUint32()),this.flags&32&&(this.defaultSampleFlags=this.readUint32())}};var va=class extends J{constructor(t,i){super(t,i);this.baseMediaDecodeTime32=0;this.baseMediaDecodeTime64=BigInt(0);this.version===1?this.baseMediaDecodeTime64=this.readUint64():this.baseMediaDecodeTime32=this.readUint32()}get baseMediaDecodeTime(){return this.version===1?this.baseMediaDecodeTime64:this.baseMediaDecodeTime32}};var Sa=class extends J{constructor(t,i){super(t,i);this.sampleDuration=[];this.sampleSize=[];this.sampleFlags=[];this.sampleCompositionTimeOffset=[];this.optionalFields=0;this.sampleCount=this.readUint32(),this.flags&1&&(this.dataOffset=this.readUint32()),this.flags&4&&(this.firstSampleFlags=this.readUint32());for(let r=0;r<this.sampleCount;r++)this.flags&256&&this.sampleDuration.push(this.readUint32()),this.flags&512&&this.sampleSize.push(this.readUint32()),this.flags&1024&&this.sampleFlags.push(this.readUint32()),this.flags&2048&&this.sampleCompositionTimeOffset.push(this.readUint32())}};var ya=class extends H{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ta=class extends J{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 Ia=class extends H{constructor(e,t){super(e,t),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+78,this.content.byteLength-78))}};var JL={ftyp:ta,moov:ia,mvhd:ra,moof:aa,mdat:sa,sidx:li,trak:na,mdia:da,mfhd:fa,tkhd:pa,traf:ba,tfhd:ga,tfdt:va,trun:Sa,minf:ha,sv3d:oa,st3d:ua,prhd:la,proj:ma,equi:ca,uuid:ea,stbl:ya,stsd:Ta,avc1:Ia,unknown:zi},mt=class a{constructor(e={}){this.options={offset:0,...e}}parse(e){let t=[],i=this.options.offset;for(;i<e.byteLength;)try{let s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+i+4,4)),n=this.createBox(s,new DataView(e.buffer,e.byteOffset+i));if(!n.size)break;t.push(n),i+=n.size}catch(r){break}return t}createBox(e,t){let i=JL[e];return i?new i(t,new a):new zi(t,new a)}};var _t=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{var i,r,s;(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 eM=new TextDecoder("ascii"),tM=a=>eM.decode(new DataView(a.buffer,a.byteOffset+4,4))==="ftyp",iM=a=>{let e=new li(a,new mt),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})},rM=(a,e)=>{let i=new mt().parse(a),r=new _t(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)},aM=a=>{let t=new mt().parse(a),i=new _t(t),r={},s=i.findAll("uuid");return s.length?s[s.length-1]:r},sM=a=>{var r;let t=new mt().parse(a);return(r=new _t(t).find("sidx"))==null?void 0:r.timescale},nM=(a,e)=>{let i=new mt().parse(a),s=new _t(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,h)=>d+h,0):l=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+l)/e*1e3},oM=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 mt().parse(a),r=new _t(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},mS={validateData:tM,parseInit:oM,getIndexRange:()=>{},parseSegments:iM,parseFeedableSegmentChunk:rM,getChunkEndTime:nM,getServerLatencyTimestamps:aM,getTimescaleFromIndex:sM};var xa=C(Be(),1);import{assertNonNullable as Pl,isNonNullable as vS,isNullable as lM}from"@vkontakte/videoplayer-shared/es2018";import{assertNever as uM}from"@vkontakte/videoplayer-shared/es2018";var fS={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"}},bS=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=Ea(a,t),r=i in fS,s=r?fS[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=Ea(u),d=l*2**((o-1)*8)+c,h=t+o,p;return h+d>a.byteLength?p=new DataView(a.buffer,a.byteOffset+h):p=new DataView(a.buffer,a.byteOffset+h,d),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:s,tagHeaderSize:h,tagSize:h+d,value:p,valueSize:d}},Ea=(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},ze=(a,e)=>{switch(e){case"int":return a.getInt8(0);case"uint":return Ea(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:uM(e)}},ci=(a,e)=>{let t=0;for(;t<a.byteLength;){let i=new DataView(a.buffer,a.byteOffset+t),r=bS(i);if(!e(r))return;r.type==="master"&&ci(r.value,e),t=r.value.byteOffset-a.byteOffset+r.valueSize}},gS=a=>{if(a.getUint32(0)!==440786851)return!1;let e,t,i,r=bS(a);return ci(r.value,({tag:s,type:n,value:o})=>(s===17143?e=ze(o,n):s===17026?t=ze(o,n):s===17029&&(i=ze(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)};var SS=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],cM=[231,22612,22743,167,171,163,160,175],dM=a=>{let e,t,i,r,s=!1,n=!1,o=!1,u,l,c=!1,d=0;return ci(a,({tag:h,type:p,value:m,valueSize:b})=>{if(h===21419){let g=ze(m,p);l=Ea(g)}else h!==21420&&(l=void 0);return h===408125543?(e=m.byteOffset,t=m.byteOffset+b):h===357149030?s=!0:h===290298740?n=!0:h===2807729?i=ze(m,p):h===17545?r=ze(m,p):h===21420&&l===475249515?u=ze(m,p):h===374648427?ci(m,({tag:g,type:v,value:S})=>g===30321?(c=ze(S,v)===1,!1):!0):s&&n&&(0,xa.default)(SS,h)&&(o=!0),!o}),Pl(e,"Failed to parse webm Segment start"),Pl(t,"Failed to parse webm Segment end"),Pl(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}}}},pM=a=>{if(lM(a.cuesSeekPosition))return;let e=a.segmentStart+a.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},hM=(a,e)=>{let t=!1,i=!1,r=o=>vS(o.time)&&vS(o.position),s=[],n;return ci(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=ze(l,u));break;case 183:break;case 241:n&&(n.position=ze(l,u));break;default:t&&(0,xa.default)(SS,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}}})},mM=a=>{let e=0,t=!1;try{ci(a,i=>i.tag===524531317?i.tagSize<=a.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):(0,xa.default)(cM,i.tag)?(e+i.tagSize<=a.byteLength&&(e+=i.tagSize,t||(t=(0,xa.default)([163,160,175],i.tag))),!0):!1)}catch(i){}return e>0&&e<=a.byteLength&&t?new DataView(a.buffer,a.byteOffset,e):null},yS={validateData:gS,parseInit:dM,getIndexRange:pM,parseSegments:hM,parseFeedableSegmentChunk:mM};var Pa=a=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(a);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return yS;case"mp4":return mS}}throw new ReferenceError(`Unsupported mime type ${a}`)};var Bl=C(FS(),1),py=C(Ci(),1),hy=C(iy(),1),my=C(Dt(),1),_l=C(ji(),1);var ry=C(Be(),1),Ll=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,ry.default)(["6E","7A","F4"],o)}}return!1};import{isNonNullable as dC,isNullable as cy}from"@vkontakte/videoplayer-shared/es2018";var ay=a=>{if(a.includes("/")){let e=a.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(a)};var sy=a=>{var e;try{let t=lC(),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 lC(){let a="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",c=`^(?:(?<langtag>${`
|
|
64
|
+
(?<language>${`(?:[a-z]{2,3}(?:-${a})?|[a-z]{4}|[a-z]{5,8})`})
|
|
119
65
|
(-(?<script>[a-z]{4}))?
|
|
120
66
|
(-(?<region>(?:[a-z]{2}|[0-9]{3})))?
|
|
121
67
|
(?<variants>(?:-(?:[a-z0-9]{5,8}|[0-9][a-z0-9]{3}))*)
|
|
122
68
|
(?<extensions>(?:-[0-9a-wy-z](?:-[a-z0-9]{2,8})+)*)
|
|
123
69
|
(?:-(?<privateuse>(?:${e})))?
|
|
124
|
-
`})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(d,"i")}var vp=U(Nt(),1);import{videoSizeToQuality as K0}from"@vkontakte/videoplayer-shared/es2018";var PI=({id:s,width:e,height:t,bitrate:i,fps:r,quality:a,streamId:n})=>{var u;let o=(u=a?Yt(a):void 0)!=null?u:K0({width:e,height:t});return o&&{id:s,quality:o,bitrate:i,size:{width:e,height:t},fps:r,streamId:n}},AI=({id:s,bitrate:e})=>({id:s,bitrate:e}),kI=({language:s,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:s,label:e}),RI=({language:s,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:s,label:e}),yp=({id:s,language:e,label:t,codecs:i,isDefault:r})=>({id:s,language:e,label:t,codec:(0,vp.default)(i.split("."),0),isDefault:r}),Tp=({id:s,language:e,label:t,hdr:i,codecs:r})=>({id:s,language:e,hdr:i,label:t,codec:(0,vp.default)(r.split("."),0)}),Ip=s=>"url"in s,rt=s=>s.type==="template",Tn=s=>s instanceof DOMException&&(s.name==="AbortError"||s.code===20);var MI=s=>{if(!(s!=null&&s.startsWith("P")))return;let e=(n,o)=>{let u=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(u)?0:u)*o},i=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(s),r=(i==null?void 0:i[1])==="-"?-1:1,a={days:e(i==null?void 0:i[5],r),hours:e(i==null?void 0:i[6],r),minutes:e(i==null?void 0:i[7],r),seconds:e(i==null?void 0:i[8],r)};return a.days*24*60*60*1e3+a.hours*60*60*1e3+a.minutes*60*1e3+a.seconds*1e3},vi=(s,e)=>{let t=s;t=(0,xp.default)(t,"$$","$");let i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[r,a]of(0,$I.default)(i)){let n=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=(0,xp.default)(t,n,(o,u)=>LI(a)?o:LI(u)?a:(0,DI.default)(a,parseInt(u,10),"0"))}return t},CI=(s,e)=>{var k,P,O,$,M,G,q,w,N,A,x,D,oe,Oe,re,Y,ye,Te,Ie,_e,wt,Rt,Ht,ei,Li,Ts,Is,xs,Es,ws,Ps,As,ks,Rs,Ls,Ms,$s,Ds,Bs,Cs,Vs,Os,_s,Fs,Ns,Us,qs,js,Hs,Ws,zs,Gs,Qs,Ys,Ks,Xs,Js,Zs,ea,ta,ia;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 _,Ye;return(Ye=(_=ce.textContent)==null?void 0:_.trim())!=null?Ye:""}),o=(k=(0,BI.default)(n,0))!=null?k:"",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,y=a.getAttribute("mediaPresentationDuration"),v=[...a.getElementsByTagName("Period")],I=v.reduce((ce,_)=>({...ce,[_.id]:_.children}),{}),T=v.reduce((ce,_)=>({...ce,[_.id]:_.getAttribute("duration")}),{});y?S=MI(y):(0,Ep.default)(T).filter(ce=>ce).length&&!u?S=(0,Ep.default)(T).reduce((ce,_)=>{var Ye;return ce+((Ye=MI(_))!=null?Ye:0)},0):m&&(S=parseInt(m,10));let E=0,V=(O=(P=a.getAttribute("profiles"))==null?void 0:P.split(","))!=null?O:[];for(let ce of v.map(_=>_.id))for(let _ of I[ce]){let Ye=($=_.getAttribute("id"))!=null?$:"id"+(E++).toString(10),Lt=(M=_.getAttribute("mimeType"))!=null?M:"",Qi=(G=_.getAttribute("codecs"))!=null?G:"",Yi=(q=_.getAttribute("contentType"))!=null?q:Lt==null?void 0:Lt.split("/")[0],Bl=(N=(w=_.getAttribute("profiles"))==null?void 0:w.split(","))!=null?N:[],ra=(x=wI((A=_.getAttribute("lang"))!=null?A:""))!=null?x:{},ti=(Oe=(oe=(D=_.querySelector("Label"))==null?void 0:D.textContent)==null?void 0:oe.trim())!=null?Oe:void 0,Cl=_.querySelectorAll("Representation"),Vl=_.querySelector("SegmentTemplate"),Ol=(Y=(re=_.querySelector("Role"))==null?void 0:re.getAttribute("value"))!=null?Y:void 0,pt=Yi,W={id:Ye,language:ra.language,isDefault:Ol==="main",label:ti,codecs:Qi,hdr:pt==="video"&&rs(Qi),mime:Lt,representations:[]};for(let C of Cl){let Ae=(ye=C.getAttribute("lang"))!=null?ye:void 0,Mt=(Ie=(Te=ti!=null?ti:_.getAttribute("label"))!=null?Te:C.getAttribute("label"))!=null?Ie:void 0,ii=(Rt=(wt=(_e=C.querySelector("BaseURL"))==null?void 0:_e.textContent)==null?void 0:wt.trim())!=null?Rt:"",Ke=new URL(ii||o,e).toString(),ke=(Ht=C.getAttribute("mimeType"))!=null?Ht:Lt,ri=(Li=(ei=C.getAttribute("codecs"))!=null?ei:Qi)!=null?Li:"",si;if(Yi==="text"){let Re=C.getAttribute("id")||"",ai=((Ts=ra.privateuse)==null?void 0:Ts.includes("x-auto"))||Re.includes("_auto"),Xe=C.querySelector("SegmentTemplate");if(Xe){let $t={representationId:(Is=C.getAttribute("id"))!=null?Is:void 0,bandwidth:(xs=C.getAttribute("bandwidth"))!=null?xs:void 0},ni=parseInt((Es=C.getAttribute("bandwidth"))!=null?Es:"",10)/1e3,oi=(Ps=parseInt((ws=Xe.getAttribute("startNumber"))!=null?ws:"",10))!=null?Ps:1,ht=parseInt((As=Xe.getAttribute("timescale"))!=null?As:"",10),Ki=(ks=Xe.querySelectorAll("SegmentTimeline S"))!=null?ks:[],ft=Xe.getAttribute("media");if(!ft)continue;let ui=[],li=0,ci="",mt=0,Dt=oi,Z=0;for(let de of Ki){let Je=parseInt((Rs=de.getAttribute("d"))!=null?Rs:"",10),ae=parseInt((Ls=de.getAttribute("r"))!=null?Ls:"",10)||0,Le=parseInt((Ms=de.getAttribute("t"))!=null?Ms:"",10);Z=Number.isFinite(Le)?Le:Z;let Ze=Je/ht*1e3,Me=Z/ht*1e3;for(let me=0;me<ae+1;me++){let $e=vi(ft,{...$t,segmentNumber:Dt.toString(10),segmentTime:(Z+me*Je).toString(10)}),bt=(Me!=null?Me:0)+me*Ze,Ct=bt+Ze;Dt++,ui.push({time:{from:bt,to:Ct},url:$e})}Z+=(ae+1)*Je,li+=(ae+1)*Ze}mt=Z/ht*1e3,ci=vi(ft,{...$t,segmentNumber:Dt.toString(10),segmentTime:Z.toString(10)});let Bt={time:{from:mt,to:1/0},url:ci},xe={type:"template",baseUrl:Ke,segmentTemplateUrl:ft,initUrl:"",totalSegmentsDurationMs:li,segments:ui,nextSegmentBeyondManifest:Bt,timescale:ht};si={id:Re,kind:"text",segmentReference:xe,profiles:[],duration:S,bitrate:ni,mime:"",codecs:"",width:0,height:0,isAuto:ai}}else si={id:Re,isAuto:ai,kind:"text",url:Ke}}else{let Re=(Ds=($s=C.getAttribute("contentType"))!=null?$s:ke==null?void 0:ke.split("/")[0])!=null?Ds:Yi,ai=(Cs=(Bs=_.getAttribute("profiles"))==null?void 0:Bs.split(","))!=null?Cs:[],Xe=parseInt((Vs=C.getAttribute("width"))!=null?Vs:"",10),$t=parseInt((Os=C.getAttribute("height"))!=null?Os:"",10),ni=parseInt((_s=C.getAttribute("bandwidth"))!=null?_s:"",10)/1e3,oi=(Fs=C.getAttribute("frameRate"))!=null?Fs:"",ht=(Ns=C.getAttribute("quality"))!=null?Ns:void 0,Ki=oi?Ou(oi):void 0,ft=(Us=C.getAttribute("id"))!=null?Us:"id"+(E++).toString(10),ui=Re==="video"?`${$t}p`:Re==="audio"?`${ni}Kbps`:ri,li=`${ft}@${ui}`,ci=[...V,...Bl,...ai],mt,Dt=C.querySelector("SegmentBase"),Z=(qs=C.querySelector("SegmentTemplate"))!=null?qs:Vl;if(Dt){let xe=(Hs=(js=C.querySelector("SegmentBase Initialization"))==null?void 0:js.getAttribute("range"))!=null?Hs:"",[de,Je]=xe.split("-").map($e=>parseInt($e,10)),ae={from:de,to:Je},Le=(Ws=C.querySelector("SegmentBase"))==null?void 0:Ws.getAttribute("indexRange"),[Ze,Me]=Le?Le.split("-").map($e=>parseInt($e,10)):[],me=Le?{from:Ze,to:Me}:void 0;mt={type:"byteRange",url:Ke,initRange:ae,indexRange:me}}else if(Z){let xe={representationId:(zs=C.getAttribute("id"))!=null?zs:void 0,bandwidth:(Gs=C.getAttribute("bandwidth"))!=null?Gs:void 0},de=parseInt((Qs=Z.getAttribute("timescale"))!=null?Qs:"",10),Je=(Ys=Z.getAttribute("initialization"))!=null?Ys:"",ae=Z.getAttribute("media"),Le=(Xs=parseInt((Ks=Z.getAttribute("startNumber"))!=null?Ks:"",10))!=null?Xs:1,Ze=vi(Je,xe);if(!ae)throw new ReferenceError("No media attribute in SegmentTemplate");let Me=(Js=Z.querySelectorAll("SegmentTimeline S"))!=null?Js:[],me=[],$e=0,bt="",Ct=0;if(Me.length){let di=Le,pe=0;for(let gt of Me){let be=parseInt((Zs=gt.getAttribute("d"))!=null?Zs:"",10),et=parseInt((ea=gt.getAttribute("r"))!=null?ea:"",10)||0,pi=parseInt((ta=gt.getAttribute("t"))!=null?ta:"",10);pe=Number.isFinite(pi)?pi:pe;let Xi=be/de*1e3,Ji=pe/de*1e3;for(let hi=0;hi<et+1;hi++){let Fl=vi(ae,{...xe,segmentNumber:di.toString(10),segmentTime:(pe+hi*be).toString(10)}),sa=(Ji!=null?Ji:0)+hi*Xi,Nl=sa+Xi;di++,me.push({time:{from:sa,to:Nl},url:Fl})}pe+=(et+1)*be,$e+=(et+1)*Xi}Ct=pe/de*1e3,bt=vi(ae,{...xe,segmentNumber:di.toString(10),segmentTime:pe.toString(10)})}else if(X0(S)){let pe=parseInt((ia=Z.getAttribute("duration"))!=null?ia:"",10)/de*1e3,gt=Math.ceil(S/pe),be=0;for(let et=1;et<gt;et++){let pi=vi(ae,{...xe,segmentNumber:et.toString(10),segmentTime:be.toString(10)});me.push({time:{from:be,to:be+pe},url:pi}),be+=pe}Ct=be,bt=vi(ae,{...xe,segmentNumber:gt.toString(10),segmentTime:be.toString(10)})}let _l={time:{from:Ct,to:1/0},url:bt};mt={type:"template",baseUrl:Ke,segmentTemplateUrl:ae,initUrl:Ze,totalSegmentsDurationMs:$e,segments:me,nextSegmentBeyondManifest:_l,timescale:de}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Re||!ke)continue;let Bt={video:"video",audio:"audio",text:"text"}[Re];if(!Bt)continue;pt||(pt=Bt),si={id:li,kind:Bt,segmentReference:mt,profiles:ci,duration:S,bitrate:ni,mime:ke,codecs:ri,width:Xe,height:$t,fps:Ki,quality:ht}}W.language||(W.language=Ae),W.label||(W.label=Mt),W.mime||(W.mime=ke),W.codecs||(W.codecs=ri),W.hdr||(W.hdr=pt==="video"&&rs(ri)),W.representations.push(si)}if(pt){let C=r[pt].find(Ae=>Ae.id===W.id);if(C&&W.representations.every(Ae=>rt(Ae.segmentReference)))for(let Ae of C.representations){let Mt=W.representations.find(ke=>ke.id===Ae.id),ii=Mt==null?void 0:Mt.segmentReference,Ke=Ae.segmentReference;Ke.segments.push(...ii.segments),Ke.nextSegmentBeyondManifest=ii.nextSegmentBeyondManifest}else r[pt].push(W)}}return{duration:S,streams:r,baseUrls:n,live:g}};import{isNonNullable as VI}from"@vkontakte/videoplayer-shared/es2018";var z=(s,e)=>VI(s)&&VI(e)&&s.readyState==="open"&&J0(s,e);function J0(s,e){for(let t=0;t<s.activeSourceBuffers.length;++t)if(s.activeSourceBuffers[t]===e)return!0;return!1}var In=class{constructor(e,t,i,{fetcher:r,tuning:a,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new br(0);this.currentLowLatencySegmentLength$=new br(0);this.currentSegmentLength$=new br(0);this.onLastSegment$=new br(!1);this.fullyBuffered$=new br(!1);this.playingRepresentation$=new br(void 0);this.playingRepresentationInit$=new br(void 0);this.error$=new eC;this.gaps=[];this.subscription=new tC;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new se;this.switchAbortController=new se;this.destroyAbortController=new se;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=Ni(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);ct(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new VT(this.sourceBuffer),this.subscription.add(Pp(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:yi.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o!=null||(o={id:"SegmentEjection",category:yi.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),this.error$.next(o)})),this.subscription.add(Pp(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:yi.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o||!z(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,es(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);ct(i,"No init buffer for starting representation"),ct(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=Ni(this.destroyAbortController.signal,async function*(e,t=!1){if(!z(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);ct(i,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if(Ge(a)||Ge(r)?yield this.loadInit(i,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),ct(r,"No segments for starting representation"),a=this.initData.get(e),!(!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer||!z(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();ss(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=Ni(this.destroyAbortController.signal,async function*(e,t=!1){if(!z(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);ct(i,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if(Ge(a)||Ge(r)?yield this.loadInit(i,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),ct(r,"No segments for starting representation"),a=this.initData.get(e),!(!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer||!z(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();ss(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=Ni(this.destroyAbortController.signal,async function*(e){var u,l;let t=(u=(0,Nu.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||!rt(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);ct(r);let a=this.segments.get(i);ct(a,"No segments for starting representation");let n=this.initData.get(i);if(ct(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){!z(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new se,Ni(this.switchAbortController.signal,async function*(i,r=!1){this.switchingToRepresentationId=i;let a=this.representations.get(i);ct(a,`No such representation ${i}`);let n=this.segments.get(i),o=this.initData.get(i);if(Ge(o)||Ge(n)?yield this.loadInit(a,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(i),ct(n,"No segments for starting representation"),o=this.initData.get(i),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer||!z(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();ss(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(){!Ge(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 se,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(Ge(e)||Ge(this.downloadingRepresentationId)||Ge(this.playingRepresentationId)||Ge(this.sourceBuffer)||!z(this.mediaSource,this.sourceBuffer)||ss(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(ct(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;let r=i.find(d=>e>=d.time.from&&e<d.time.to);ss(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)&&es(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,Fu.default)(u,r))d="high";else{let c=(0,as.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,as.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;ss(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,Nu.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,Nu.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||!rt(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,as.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;ct(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(!rt(a))return;let n=(i=this.segments.get(r.id))!=null?i:[],o=n.find(l=>Math.floor(l.time.from)===Math.floor(e.time.from));if(o&&!isFinite(o.time.to)&&(o.time.to=e.time.to,t=o.time.to-o.time.from),!!!n.find(l=>Math.floor(l.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let l=Math.round(e.time.to*a.timescale/1e3).toString(10),d=vi(a.segmentTemplateUrl,{segmentTime:l});n.push({status:"none",time:{from:e.time.to,to:1/0},url:d})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){var a,n,o;let t=(n=(a=this.switchingToRepresentationId)!=null?a:this.downloadingRepresentationId)!=null?n:this.playingRepresentationId;if(!t)return;let i=this.segments.get(t);if(!i)return;let r=i.find(u=>u.time.from<=e&&u.time.to>=e);return(o=r==null?void 0:r.time.from)!=null?o:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)==null||e.destroy(),this.gapDetectionIdleCallback&&Xt&&Xt(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&Xt&&Xt(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=e.findIndex(({status:c,time:{from:h,to:p}},f)=>{let m=h<=i&&p>=i,g=h>i||m||f===0&&i===0,S=Math.min(this.forwardBufferTarget,this.bufferLimit),y=this.preloadOnly&&h<=i+S||p<=i+S;return(c==="none"||c==="partially_ejected"&&g&&y&&this.sourceBuffer&&z(this.mediaSource,this.sourceBuffer)&&!(ze(this.sourceBuffer.buffered,h)&&ze(this.sourceBuffer.buffered,p)))&&g&&y});if(r===-1)return[];if(t!=="byteRange")return e.slice(r,r+1);let a=e,n=0,o=0,u=[],l=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,d=this.preloadOnly?this.forwardBufferTarget:0;for(let c=r;c<a.length&&(n<=l||o<=d);c++){let h=a[c];if(n+=h.byte.to+1-h.byte.from,o+=h.time.to+1-h.time.from,h.status==="none"||h.status==="partially_ejected")u.push(h);else break}return u}async loadSegments(e,t,i="auto"){rt(t.segmentReference)?await this.loadTemplateSegment(e[0],t,i):await this.loadByteRangeSegments(e,t,i)}async loadTemplateSegment(e,t,i="auto"){e.status="downloading";let r={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(r);let{range:a,url:n,signal:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await Ni(o,async function*(){let d=Ap(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=_u(),!d)return;let c=new DataView(d),h=yn(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]),Tn(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())rt(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}async loadByteRangeSegments(e,t,i="auto"){if(!e.length)return;for(let u of e)u.status="downloading",this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:r,url:a,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(await Ni(n,async function*(){let u=Ap(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),Pp(window,"online").pipe(Z0()).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=_u(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),Tn(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(rt(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:(0,as.default)(e,0).byte.from,to:(0,as.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=_u(),await this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:a,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:yi.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!rt(t.segmentReference))throw new Error("Representation is not template type");let i=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&i.searchParams.set("low-latency","yes");let r=i.toString(),{signal:a}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,d)=>{if(!a.aborted)try{this.lastDataObtainedTimestampMs=_u();let c=this.onSomeTemplateDataLoaded({dataView:l,loaded:d,signal:a,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(c)}catch(c){this.error$.next({id:"SegmentFeeding",category:yi.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}}:void 0;return{url:r,signal:a,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,Fu.default)(e,t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:a}){if(!this.activeSegments.size||!z(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=yn(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||!z(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=yn(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(!(Ge(this.sourceBuffer)||!z(this.mediaSource,this.sourceBuffer))){!this.isLive&&j.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(ze(this.sourceBuffer.buffered,e.segment.time.from,100)&&ze(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:yi.VIDEO_PIPELINE,message:"Browser stuck on empty result of adding segment to source buffer"})),this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",Ip(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=Zr(()=>(0,OI.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?Ni(this.destroyAbortController.signal,async function*(){let o=Ap(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,yn(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&&rt(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:yi.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n}async dropBuffer(){for(let e of this.segments.values())for(let t of e)t.status="none";await this.pruneBuffer(0,1/0,!0)}async pruneBuffer(e,t,i=!1){if(!this.sourceBuffer||!z(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||Ge(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=Ip(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,Fu.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||!z(this.mediaSource,this.sourceBuffer))return!1;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;return this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!z(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}getForwardBufferDuration(e=this.getCurrentPosition()){return!this.sourceBuffer||!z(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||Ge(e)?0:Ce(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!(!this.sourceBuffer||!z(this.mediaSource,this.sourceBuffer))){if(this.tuning.useRefactoredSearchGap)for(let i=0;i<this.sourceBuffer.buffered.length;i++)this.gaps=this.gaps.filter(r=>this.sourceBuffer&&(Math.round(r.from)<Math.round(this.sourceBuffer.buffered.start(i)*1e3)||Math.round(r.to)>Math.round(this.sourceBuffer.buffered.end(i)*1e3)));for(let i of t){let r={representation:e,from:i.time.from,to:i.time.to};for(let 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||!z(this.mediaSource,this.sourceBuffer))){if(!this.tuning.useRefactoredSearchGap)for(let i=0;i<this.sourceBuffer.buffered.length;i++)this.gaps=this.gaps.filter(r=>this.sourceBuffer&&(Math.round(r.from)<Math.round(this.sourceBuffer.buffered.start(i)*1e3)||Math.round(r.to)>Math.round(this.sourceBuffer.buffered.end(i)*1e3)));this.gapDetectionIdleCallback=Zr(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:yi.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if(Ge(this.sourceBuffer)||!z(this.mediaSource,this.sourceBuffer)||Ge(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:yi.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}};var Ui=s=>{let e=new URL(s);return e.searchParams.set("quic","1"),e.toString()};var Uu=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 xn,assertNever as _I,fromEvent as FI,merge as iC,now as En,Subscription as rC,Subject as NI,ValueSubject as kp,flattenObject as ns,ErrorCategory as wn}from"@vkontakte/videoplayer-shared/es2018";var qu=s=>{let e=new URL(s);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var Hu=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:a=!1}){this.lastConnectionType$=new kp(void 0);this.lastConnectionReused$=new kp(void 0);this.lastRequestFirstBytes$=new kp(void 0);this.recoverableError$=new NI;this.error$=new NI;this.abortAllController=new se;this.subscription=new rC;this.fetchManifest=xn(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=Ui(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=qu(i));let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(ju);return r?(t.log("success",ns({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(r.headers),r.text()):(t.error("error",ns({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=xn(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 O,$;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 M=new URL(l,location.href);M.searchParams.append("bytes",`${i.from}-${i.to}`),l=M.toString();break}default:_I(t)}this.requestQuic&&(l=Ui(l));let h=this.abortAllController.signal,p;if(n){let M=new se;if(p=iC(FI(this.abortAllController.signal,"abort"),FI(n,"abort")).subscribe(()=>{try{M.abort()}catch(G){ju(G)}}),this.subscription.add(p),this.abortAllController.signal.aborted||n.aborted)try{M.abort()}catch(G){ju(G)}h=M.signal}let f=En();c.log("startRequest",ns({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=En();if(!m)return c.error("error",{message:"No response in request"}),c.end(),p==null||p.unsubscribe(),null;if((O=this.throughputEstimator)==null||O.addRawRtt(g-f),!m.ok||!m.body){p==null||p.unsubscribe();let M=`Fetch error ${m.status}: ${m.statusText}`;return c.error("error",{message:M}),c.end(),Promise.reject(new Error(`Fetch error ${m.status}: ${m.statusText}`))}if(this.onHeadersReceived(m.headers),!r&&!o){p==null||p.unsubscribe();let M=En(),G={requestStartedAt:f,requestEndedAt:M,duration:M-f};return c.log("endRequest",ns(G)),c.end(),m.arrayBuffer()}let[S,y]=m.body.tee(),v=S.getReader();o&&(($=this.throughputEstimator)==null||$.trackStream(y,u));let I=0,T=new Uint8Array(0),E=!1,V=M=>{p==null||p.unsubscribe(),E=!0,ju(M)},L=xn(h,async function*({done:M,value:G}){if(I===0&&this.lastRequestFirstBytes$.next(En()-f),h.aborted){p==null||p.unsubscribe();return}if(!M&&G){let q=new Uint8Array(T.length+G.length);q.set(T),q.set(G,T.length),T=q,I+=G.byteLength,r==null||r(new DataView(T.buffer),I),yield v==null?void 0:v.read().then(L,V)}}.bind(this));yield v==null?void 0:v.read().then(L,V),p==null||p.unsubscribe();let k=En(),P={failed:E,requestStartedAt:f,requestEndedAt:k,duration:k-f};return E?(c.error("endRequest",ns(P)),c.end(),null):(c.log("endRequest",ns(P)),c.end(),T.buffer)}.bind(this));this.fetchByteRangeRepresentation=xn(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 y=yield this.fetch(e.url,{range:f,priority:i,measureThroughput:!1});if(!y)return null;m=new DataView(y)}let g=t.parseSegments(m,p,f);return{init:p,dataView:new DataView(c),segments:g}}.bind(this));this.fetchTemplateRepresentation=xn(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}=Uu(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:_I(r)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}async doFetch(e,t){let i=await At(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:wn.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:wn.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:wn.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:wn.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${a})`,category:wn.FATAL})}}},ju=s=>{if(!Tn(s))throw s};var Ti=(s,e,t)=>t*e+(1-t)*s,Rp=(s,e)=>s.reduce((t,i)=>t+i,0)/e,UI=(s,e,t,i)=>{let r=0,a=t,n=Rp(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 sC,ValueSubject as qI}from"@vkontakte/videoplayer-shared/es2018";var qi=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 qI(e.initial),this.debounced$=new qI(e.initial);let t=(i=e.label)!=null?i:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new tt(`raw_${t}`),this.smoothedSeries$=new tt(`smoothed_${t}`),this.reportedSeries$=new tt(`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)&&(sC(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 Wu=class extends qi{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=Ti(this.slow,e,this.params.emaAlphaSlow),this.fast=Ti(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var zu=class extends qi{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=Rp(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Ti(this.emaSmoothed,e,this.params.emaAlpha);let i=UI(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}};var Gu=class extends qi{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?Ti(this.smoothed,t,this.params.emaAlpha):t}};var Ii=class{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new Wu({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new zu({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 Gu({initial:e,label:"liveEdgeDelay",...t})}};var os=(s,e)=>{s&&s.playbackRate!==e&&(s.playbackRate=e)};import{isNullable as aC,ValueSubject as nC}from"@vkontakte/videoplayer-shared/es2018";var Pn=class s{constructor(e,t){this.currentRepresentation$=new nC(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(!aC(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&&rt(t.segmentReference))}};var Yu=U(Nt(),1);import{assertNever as Ku}from"@vkontakte/videoplayer-shared/es2018";var jI=(s,{useHlsJs:e,useManagedMediaSource:t,useOldMSEDetection:i})=>{let{containers:r,protocols:a,codecs:n,nativeHlsSupported:o}=j.video,u=(n.h264||n.h265)&&n.aac,l=a.mse&&(!i||!!window.MediaStreamTrack)||a.mms&&t;return s.filter(d=>{switch(d){case"DASH_SEP":return l&&r.mp4&&u;case"DASH_WEBM":return l&&r.webm&&n.vp9&&n.opus;case"DASH_WEBM_AV1":return l&&r.webm&&n.av1&&n.opus;case"DASH_STREAMS":return l&&(r.mp4&&u||r.webm&&(n.vp9||n.av1)&&(n.opus||n.aac));case"DASH_LIVE":return l&&r.mp4&&u;case"DASH_LIVE_CMAF":return l&&r.mp4&&u&&r.cmaf;case"DASH_ONDEMAND":return l&&r.mp4&&u;case"HLS":case"HLS_ONDEMAND":return o||e&&l&&r.mp4&&u;case"HLS_LIVE":case"HLS_LIVE_CMAF":return o;case"MPEG":return r.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return a.webrtc&&a.ws&&n.h264&&(r.mp4||r.webm);default:return Ku(d)}})},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:Ku(s)}return[t,i]},HI=({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:Ku(e)}return j.video.nativeHlsSupported?[...i,"HLS","HLS_ONDEMAND","MPEG"]:[...i,"HLS","HLS_ONDEMAND","MPEG"]},WI=({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:Ku(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"]},Lp=s=>s?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],Xu=s=>{if(s.size===0)return;if(s.size===1){let t=s.values().next();return(0,Yu.default)(t.value.split("."),0)}for(let t of s){let i=(0,Yu.default)(t.split("."),0);if(i==="opus"||i==="vp09"||i==="av01")return i}let e=s.values().next();return(0,Yu.default)(e.value.split("."),0)};var fC=["timeupdate","progress","play","seeked","stalled","waiting"],mC=["timeupdate","progress","loadeddata","playing","seeked"];var el=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 H("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 Zu;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 Zu;this.fetcherError$=new Zu;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new Zu;this.gapWatchdogActive=!1;this.destroyController=new se;this.initManifest=$p(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:Jt.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=$p(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:Jt.NETWORK,message:"Failed to load manifest",thrown:u})});if(!e)return null;let t=null;try{t=CI(e!=null?e:"",this.manifestUrlString)}catch(u){let l=(n=Vu(e))!=null?n:{id:"ManifestParsing",category:Jt.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=xt())==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=Xu(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",kn(a)),a}.bind(this));this.initRepresentations=$p(this.destroyController.signal,async function*(e,t,i){var h;this.tracer.log("initRepresentationsStart",kn({initialVideo:e,initialAudio:t,sourceHls:i})),us(this.manifest),us(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let r=p=>{this.representationSubscription.add(xi(p,"error").pipe(Ju(f=>{var m;return!!((m=this.element)!=null&&m.played.length)})).subscribe(f=>{this.error$.next({id:"VideoSource",category:Jt.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:f})}))};this.source=this.tuning.useManagedMediaSource?hu():new MediaSource;let a=document.createElement("source");if(r(a),a.src=URL.createObjectURL(this.source),this.element.appendChild(a),this.tuning.useManagedMediaSource&&Wr())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 In("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],Rn(t)){let p=this.manifest.streams.audio.reduce((f,m)=>[...f,...m.representations],[]);this.audioBufferManager=new In("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}Pn.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new Pn(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(gr(...mC.map(p=>xi(this.element,p))).pipe(cs(p=>this.element?Ce(this.element.buffered,this.element.currentTime*1e3):0),An(),pC(p=>{p>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add(gr(xi(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe(An()).subscribe(f=>this.liveStreamEndTimestamp=Bp())),this.subscription.add(xi(this.element,"pause").subscribe(()=>{this.livePauseWatchdogSubscription=Dp(1e3).subscribe(f=>{let m=Bi(this.manifestUrlString,2);this.manifestUrlString=Se(this.manifestUrlString,m+1e3,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add(xi(this.element,"play").subscribe(f=>{var m;return(m=this.livePauseWatchdogSubscription)==null?void 0:m.unsubscribe()})),this.representationSubscription.add(ls({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(cs(({isActiveLive:f,isLowLatency:m})=>f&&m),An()).subscribe(f=>{this.isManualDecreasePlaybackInLive()||os(this.element,1)})),this.representationSubscription.add(ls({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(Ju(({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(ls({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(Ju(({isLive:f})=>f),An((f,m)=>m.bufferLength<f.bufferLength),cs(({rtt:f,bufferLength:m,segmentServerLatency:g})=>{let S=Bi(this.manifestUrlString,2);return(f/2+m+g+S)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(ls({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,y=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,v=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,I=f-S;if(this.isManualDecreasePlaybackInLive())return;let T=1;Math.abs(I)>y&&(T=1+Math.sign(I)*v),os(this.element,T)})),this.representationSubscription.add(this.bufferLength$.subscribe(f=>{var g,S;let m=0;if(f){let y=((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:y}))-y}this.liveLoadBufferLength$.getValue()!==m&&this.liveLoadBufferLength$.next(m)}));let p=0;this.representationSubscription.add(ls({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(hC(1e3)).subscribe(async({liveLoadBufferLength:f,bufferLength:m})=>{if(!this.element||this.isUpdatingLive)return;let g=this.element.playbackRate,S=Bi(this.manifestUrlString,2),y=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,v=Math.min(y,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*g),I=this.tuning.dashCmafLive.normalizedActualBufferOffset*g,T=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*g,E=isFinite(f)?f:m,V=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),L=y<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(L);let k="none";if(V?k="active_low_latency":this.isLowLatency$.getValue()&&L?(this.bufferManagers.forEach(P=>P.proceedLowLatencyLive()),k="active_low_latency"):S!==0&&E<v?k="live_forward_buffering":E<v+T&&(k="live_with_target_offset"),isFinite(f)&&(p=f>p?f:p),k==="live_forward_buffering"||k==="live_with_target_offset"){let P=p-(v+I),O=this.normolizeLiveOffset(Math.trunc(S+P/g)),$=Math.abs(O-S),M=0;!f||$<=this.tuning.dashCmafLive.offsetCalculationError?M=S:O>0&&$>this.tuning.dashCmafLive.offsetCalculationError&&(M=O),this.manifestUrlString=Se(this.manifestUrlString,M,2)}(k==="live_with_target_offset"||k==="live_forward_buffering")&&(p=0,await this.updateLive())},f=>{this.error$.next({id:"updateLive",category:Jt.VIDEO_PIPELINE,thrown:f,message:"Failed to update live with subscription"})}))}let l=gr(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe(cs(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),d=gr(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe(cs(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue()))),c=ls({allBuffersFull:l,someBufferEnded:d}).pipe(An(),cs(({allBuffersFull:p,someBufferEnded:f})=>p&&f),Ju(p=>p));if(this.representationSubscription.add(gr(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:Jt.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:f})}})),this.representationSubscription.add(gr(...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,m)=>{var g;p&&(this.timeoutSourceOpenId=setTimeout(()=>{var S;if(((S=this.source)==null?void 0:S.readyState)==="open"){f();return}this.tuning.dash.rejectOnSourceOpenTimeout?m(new Error("Timeout reject when wait sourceopen event")):f()},this.tuning.dash.sourceOpenTimeout)),(g=this.source)==null||g.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),f()},{once:!0})})}if(!this.isLive$.getValue()){let p=[(h=this.manifest.duration)!=null?h:0,...(0,Cp.default)((0,Cp.default)([...this.manifest.streams.audio,...this.manifest.streams.video],f=>f.representations),f=>{let m=[];return f.duration&&m.push(f.duration),rt(f.segmentReference)&&f.segmentReference.totalSegmentsDurationMs&&m.push(f.segmentReference.totalSegmentsDurationMs),m})];this.source.duration=Math.max(...p)/1e3}this.audioBufferManager&&Rn(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=Dp(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),n=>{this.error$.next({id:"GapWatchdog",category:Jt.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 Hu({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=Ii.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator}),this.initTracerSubscription()}async seekLive(e){var r,a,n;us(this.element);let t=this.liveStreamStatus$.getValue()!=="active"?Bp()-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(){us(this.element),this.state$.setState("running"),this.subscription.add(gr(...fC.map(e=>xi(this.element,e)),xi(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:Jt.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(xi(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(xi(this.element,"waiting").subscribe(()=>{var t;this.element&&this.element.readyState===2&&!this.element.seeking&&ze(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{var p,f,m,g,S,y,v,I,T,E,V;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=Bp(),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=(v=(y=this.videoBufferManager)==null?void 0:y.getForwardBufferDuration())!=null?v: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 L=this.normolizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(L).catch(k=>{this.error$.next({id:"stallIntervalCallback",category:Jt.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:k})}),r.liveLastOffset=L}else{let L=this.element.currentTime*1e3;(E=this.videoBufferManager)==null||E.maintain(L),(V=this.audioBufferManager)==null||V.maintain(L),r.position=L}this.tracer.log("stallIntervalCallback",kn(r))};(t=this.stallWatchdogSubscription)==null||t.unsubscribe(),this.stallWatchdogSubscription=Dp(50).subscribe(e,i=>{this.error$.next({id:"StallWatchdogCallback",category:Jt.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;us(this.element),us(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),ze(this.element.buffered,i)||await Promise.all([this.videoBufferManager.abort(),(o=this.audioBufferManager)==null?void 0:o.abort()]),!(GI(this.element)||GI(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),(u=this.audioBufferManager)==null||u.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",kn({requestedPosition:e,forcePrecise:t,position:i})))}warmUpMediaSourceIfNeeded(e=(t=>(t=this.element)==null?void 0:t.currentTime)()){var i;Rn(this.element)&&Rn(this.source)&&Rn(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=dC(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.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",kn(i)))}}};var tl=class{constructor(e,t){this.fov=e,this.orientation=t}};var il=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 KI=`attribute vec2 a_vertex;
|
|
70
|
+
`})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(c,"i")}var Cl=C(Dt(),1);import{videoSizeToQuality as cC}from"@vkontakte/videoplayer-shared/es2018";var ny=({id:a,width:e,height:t,bitrate:i,fps:r,quality:s,streamId:n})=>{var u;let o=(u=s?Ct(s):void 0)!=null?u:cC({width:e,height:t});return o&&{id:a,quality:o,bitrate:i,size:{width:e,height:t},fps:r,streamId:n}},oy=({id:a,bitrate:e})=>({id:a,bitrate:e}),uy=({language:a,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),ly=({language:a,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),Dl=({id:a,language:e,label:t,codecs:i,isDefault:r})=>({id:a,language:e,label:t,codec:(0,Cl.default)(i.split("."),0),isDefault:r}),Vl=({id:a,language:e,label:t,hdr:i,codecs:r})=>({id:a,language:e,hdr:i,label:t,codec:(0,Cl.default)(r.split("."),0)}),Ol=a=>"url"in a,ye=a=>a.type==="template",wa=a=>a instanceof DOMException&&(a.name==="AbortError"||a.code===20);var dy=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},ft=(a,e)=>{let t=a;t=(0,Bl.default)(t,"$$","$");let i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[r,s]of(0,py.default)(i)){let n=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=(0,Bl.default)(t,n,(o,u)=>cy(s)?o:cy(u)?s:(0,hy.default)(s,parseInt(u,10),"0"))}return t},fy=(a,e)=>{var _,w,U,L,k,W,ae,A,B,Y,E,$,ce,bi,nt,Q,be,Te,Ie,Xe,ot,yt,jt,gi,sr,Ec,xc,Pc,wc,Ac,kc,Rc,$c,Lc,Mc,Cc,Dc,Vc,Oc,Bc,_c,Nc,Fc,qc,Uc,Hc,jc,Qc,Gc,Wc,Yc,zc,Kc,Xc,Jc,Zc,ed,td,id,rd,ad;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(qe=>{var X,Qt;return(Qt=(X=qe.textContent)==null?void 0:X.trim())!=null?Qt:""}),o=(_=(0,my.default)(n,0))!=null?_:"",u=s.getAttribute("type")==="dynamic",l=s.getAttribute("availabilityStartTime"),c=s.getAttribute("publishTime"),d=s.getElementsByTagName("vk:Attrs")[0],h=d==null?void 0:d.getElementsByTagName("vk:XLatestSegmentPublishTime")[0].textContent,p=d==null?void 0:d.getElementsByTagName("vk:XStreamIsLive")[0].textContent,m=d==null?void 0:d.getElementsByTagName("vk:XStreamIsUnpublished")[0].textContent,b=d==null?void 0:d.getElementsByTagName("vk:XPlaybackDuration")[0].textContent,g;u&&(g={availabilityStartTime:l?new Date(l).getTime():0,publishTime:c?new Date(c).getTime():0,latestSegmentPublishTime:h?new Date(h).getTime():0,streamIsAlive:p==="yes",streamIsUnpublished:m==="yes"});let v,S=s.getAttribute("mediaPresentationDuration"),y=[...s.getElementsByTagName("Period")],I=y.reduce((qe,X)=>({...qe,[X.id]:X.children}),{}),T=y.reduce((qe,X)=>({...qe,[X.id]:X.getAttribute("duration")}),{});S?v=dy(S):(0,_l.default)(T).filter(qe=>qe).length&&!u?v=(0,_l.default)(T).reduce((qe,X)=>{var Qt;return qe+((Qt=dy(X))!=null?Qt:0)},0):b&&(v=parseInt(b,10));let R=0,q=(U=(w=s.getAttribute("profiles"))==null?void 0:w.split(","))!=null?U:[];for(let qe of y.map(X=>X.id))for(let X of I[qe]){let Qt=(L=X.getAttribute("id"))!=null?L:"id"+(R++).toString(10),nr=(k=X.getAttribute("mimeType"))!=null?k:"",Qn=(W=X.getAttribute("codecs"))!=null?W:"",Gn=(ae=X.getAttribute("contentType"))!=null?ae:nr==null?void 0:nr.split("/")[0],_T=(B=(A=X.getAttribute("profiles"))==null?void 0:A.split(","))!=null?B:[],sd=(E=sy((Y=X.getAttribute("lang"))!=null?Y:""))!=null?E:{},za=(bi=(ce=($=X.querySelector("Label"))==null?void 0:$.textContent)==null?void 0:ce.trim())!=null?bi:void 0,NT=X.querySelectorAll("Representation"),FT=X.querySelector("SegmentTemplate"),qT=(Q=(nt=X.querySelector("Role"))==null?void 0:nt.getAttribute("value"))!=null?Q:void 0,vi=Gn,te={id:Qt,language:sd.language,isDefault:qT==="main",label:za,codecs:Qn,hdr:vi==="video"&&Ll(Qn),mime:nr,representations:[]};for(let K of NT){let Tt=(be=K.getAttribute("lang"))!=null?be:void 0,or=(Ie=(Te=za!=null?za:X.getAttribute("label"))!=null?Te:K.getAttribute("label"))!=null?Ie:void 0,Ka=(yt=(ot=(Xe=K.querySelector("BaseURL"))==null?void 0:Xe.textContent)==null?void 0:ot.trim())!=null?yt:"",Gt=new URL(Ka||o,e).toString(),It=(jt=K.getAttribute("mimeType"))!=null?jt:nr,Xa=(sr=(gi=K.getAttribute("codecs"))!=null?gi:Qn)!=null?sr:"",Ja;if(Gn==="text"){let Et=K.getAttribute("id")||"",Za=((Ec=sd.privateuse)==null?void 0:Ec.includes("x-auto"))||Et.includes("_auto"),Wt=K.querySelector("SegmentTemplate");if(Wt){let ur={representationId:(xc=K.getAttribute("id"))!=null?xc:void 0,bandwidth:(Pc=K.getAttribute("bandwidth"))!=null?Pc:void 0},es=parseInt((wc=K.getAttribute("bandwidth"))!=null?wc:"",10)/1e3,ts=(kc=parseInt((Ac=Wt.getAttribute("startNumber"))!=null?Ac:"",10))!=null?kc:1,Si=parseInt((Rc=Wt.getAttribute("timescale"))!=null?Rc:"",10),Wn=($c=Wt.querySelectorAll("SegmentTimeline S"))!=null?$c:[],yi=Wt.getAttribute("media");if(!yi)continue;let is=[],rs=0,as="",Ti=0,lr=ts,ge=0;for(let Ue of Wn){let Yt=parseInt((Lc=Ue.getAttribute("d"))!=null?Lc:"",10),Oe=parseInt((Mc=Ue.getAttribute("r"))!=null?Mc:"",10)||0,xt=parseInt((Cc=Ue.getAttribute("t"))!=null?Cc:"",10);ge=Number.isFinite(xt)?xt:ge;let zt=Yt/Si*1e3,Pt=ge/Si*1e3;for(let Je=0;Je<Oe+1;Je++){let wt=ft(yi,{...ur,segmentNumber:lr.toString(10),segmentTime:(ge+Je*Yt).toString(10)}),Ii=(Pt!=null?Pt:0)+Je*zt,dr=Ii+zt;lr++,is.push({time:{from:Ii,to:dr},url:wt})}ge+=(Oe+1)*Yt,rs+=(Oe+1)*zt}Ti=ge/Si*1e3,as=ft(yi,{...ur,segmentNumber:lr.toString(10),segmentTime:ge.toString(10)});let cr={time:{from:Ti,to:1/0},url:as},ut={type:"template",baseUrl:Gt,segmentTemplateUrl:yi,initUrl:"",totalSegmentsDurationMs:rs,segments:is,nextSegmentBeyondManifest:cr,timescale:Si};Ja={id:Et,kind:"text",segmentReference:ut,profiles:[],duration:v,bitrate:es,mime:"",codecs:"",width:0,height:0,isAuto:Za}}else Ja={id:Et,isAuto:Za,kind:"text",url:Gt}}else{let Et=(Vc=(Dc=K.getAttribute("contentType"))!=null?Dc:It==null?void 0:It.split("/")[0])!=null?Vc:Gn,Za=(Bc=(Oc=X.getAttribute("profiles"))==null?void 0:Oc.split(","))!=null?Bc:[],Wt=parseInt((_c=K.getAttribute("width"))!=null?_c:"",10),ur=parseInt((Nc=K.getAttribute("height"))!=null?Nc:"",10),es=parseInt((Fc=K.getAttribute("bandwidth"))!=null?Fc:"",10)/1e3,ts=(qc=K.getAttribute("frameRate"))!=null?qc:"",Si=(Uc=K.getAttribute("quality"))!=null?Uc:void 0,Wn=ts?ay(ts):void 0,yi=(Hc=K.getAttribute("id"))!=null?Hc:"id"+(R++).toString(10),is=Et==="video"?`${ur}p`:Et==="audio"?`${es}Kbps`:Xa,rs=`${yi}@${is}`,as=[...q,..._T,...Za],Ti,lr=K.querySelector("SegmentBase"),ge=(jc=K.querySelector("SegmentTemplate"))!=null?jc:FT;if(lr){let ut=(Gc=(Qc=K.querySelector("SegmentBase Initialization"))==null?void 0:Qc.getAttribute("range"))!=null?Gc:"",[Ue,Yt]=ut.split("-").map(wt=>parseInt(wt,10)),Oe={from:Ue,to:Yt},xt=(Wc=K.querySelector("SegmentBase"))==null?void 0:Wc.getAttribute("indexRange"),[zt,Pt]=xt?xt.split("-").map(wt=>parseInt(wt,10)):[],Je=xt?{from:zt,to:Pt}:void 0;Ti={type:"byteRange",url:Gt,initRange:Oe,indexRange:Je}}else if(ge){let ut={representationId:(Yc=K.getAttribute("id"))!=null?Yc:void 0,bandwidth:(zc=K.getAttribute("bandwidth"))!=null?zc:void 0},Ue=parseInt((Kc=ge.getAttribute("timescale"))!=null?Kc:"",10),Yt=(Xc=ge.getAttribute("initialization"))!=null?Xc:"",Oe=ge.getAttribute("media"),xt=(Zc=parseInt((Jc=ge.getAttribute("startNumber"))!=null?Jc:"",10))!=null?Zc:1,zt=ft(Yt,ut);if(!Oe)throw new ReferenceError("No media attribute in SegmentTemplate");let Pt=(ed=ge.querySelectorAll("SegmentTimeline S"))!=null?ed:[],Je=[],wt=0,Ii="",dr=0;if(Pt.length){let ss=xt,He=0;for(let Ei of Pt){let Ze=parseInt((td=Ei.getAttribute("d"))!=null?td:"",10),Kt=parseInt((id=Ei.getAttribute("r"))!=null?id:"",10)||0,ns=parseInt((rd=Ei.getAttribute("t"))!=null?rd:"",10);He=Number.isFinite(ns)?ns:He;let Yn=Ze/Ue*1e3,zn=He/Ue*1e3;for(let os=0;os<Kt+1;os++){let HT=ft(Oe,{...ut,segmentNumber:ss.toString(10),segmentTime:(He+os*Ze).toString(10)}),nd=(zn!=null?zn:0)+os*Yn,jT=nd+Yn;ss++,Je.push({time:{from:nd,to:jT},url:HT})}He+=(Kt+1)*Ze,wt+=(Kt+1)*Yn}dr=He/Ue*1e3,Ii=ft(Oe,{...ut,segmentNumber:ss.toString(10),segmentTime:He.toString(10)})}else if(dC(v)){let He=parseInt((ad=ge.getAttribute("duration"))!=null?ad:"",10)/Ue*1e3,Ei=Math.ceil(v/He),Ze=0;for(let Kt=1;Kt<Ei;Kt++){let ns=ft(Oe,{...ut,segmentNumber:Kt.toString(10),segmentTime:Ze.toString(10)});Je.push({time:{from:Ze,to:Ze+He},url:ns}),Ze+=He}dr=Ze,Ii=ft(Oe,{...ut,segmentNumber:Ei.toString(10),segmentTime:Ze.toString(10)})}let UT={time:{from:dr,to:1/0},url:Ii};Ti={type:"template",baseUrl:Gt,segmentTemplateUrl:Oe,initUrl:zt,totalSegmentsDurationMs:wt,segments:Je,nextSegmentBeyondManifest:UT,timescale:Ue}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Et||!It)continue;let cr={video:"video",audio:"audio",text:"text"}[Et];if(!cr)continue;vi||(vi=cr),Ja={id:rs,kind:cr,segmentReference:Ti,profiles:as,duration:v,bitrate:es,mime:It,codecs:Xa,width:Wt,height:ur,fps:Wn,quality:Si}}te.language||(te.language=Tt),te.label||(te.label=or),te.mime||(te.mime=It),te.codecs||(te.codecs=Xa),te.hdr||(te.hdr=vi==="video"&&Ll(Xa)),te.representations.push(Ja)}if(vi){let K=r[vi].find(Tt=>Tt.id===te.id);if(K&&te.representations.every(Tt=>ye(Tt.segmentReference)))for(let Tt of K.representations){let or=te.representations.find(It=>It.id===Tt.id),Ka=or==null?void 0:or.segmentReference,Gt=Tt.segmentReference;Gt.segments.push(...Ka.segments),Gt.nextSegmentBeyondManifest=Ka.nextSegmentBeyondManifest}else r[vi].push(te)}}return{duration:v,streams:r,baseUrls:n,live:g}};var gy=C(Be(),1);import{isNonNullable as by}from"@vkontakte/videoplayer-shared/es2018";var re=(a,e)=>by(a)&&by(e)&&a.readyState==="open"&&(0,gy.default)([...a.activeSourceBuffers],e);var Aa=class{constructor(e,t,i,{fetcher:r,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new di(0);this.currentLowLatencySegmentLength$=new di(0);this.currentSegmentLength$=new di(0);this.onLastSegment$=new di(!1);this.fullyBuffered$=new di(!1);this.playingRepresentation$=new di(void 0);this.playingRepresentationInit$=new di(void 0);this.error$=new hC;this.gaps=[];this.subscription=new mC;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new me;this.switchAbortController=new me;this.destroyAbortController=new me;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=Nt(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);Re(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new hS(this.sourceBuffer),this.subscription.add(Fl(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:bt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o!=null||(o={id:"SegmentEjection",category:bt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),this.error$.next(o)})),this.subscription.add(Fl(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:bt.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o||!re(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,El(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);Re(i,"No init buffer for starting representation"),Re(r,"No segments for starting representation"),i instanceof ArrayBuffer&&(this.searchGaps(r,t),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s))}.bind(this));this.switchTo=Nt(this.destroyAbortController.signal,async function*(e,t=!1){if(!re(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);Re(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if(fe(s)||fe(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),Re(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!re(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();Xi(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=Nt(this.destroyAbortController.signal,async function*(e,t=!1){if(!re(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);Re(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if(fe(s)||fe(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),Re(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!re(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();Xi(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=Nt(this.destroyAbortController.signal,async function*(e){var u,l;let t=(u=(0,hn.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(m=>m.id===c);d&&this.representations.set(c,d);let h=this.representations.get(c);if(!h||!ye(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);Re(r);let s=this.segments.get(i);Re(s,"No segments for starting representation");let n=this.initData.get(i);if(Re(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer))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){!re(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new me,Nt(this.switchAbortController.signal,async function*(i,r=!1){this.switchingToRepresentationId=i;let s=this.representations.get(i);Re(s,`No such representation ${i}`);let n=this.segments.get(i),o=this.initData.get(i);if(fe(o)||fe(n)?yield this.loadInit(s,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(i),Re(n,"No segments for starting representation"),o=this.initData.get(i),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer||!re(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();Xi(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(){!fe(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 me,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(fe(e)||fe(this.downloadingRepresentationId)||fe(this.playingRepresentationId)||fe(this.sourceBuffer)||!re(this.mediaSource,this.sourceBuffer)||Xi(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(Re(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;let r=i.find(c=>e>=c.time.from&&e<c.time.to);Xi(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)&&El(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(h=>{this.handleAsyncError(h,"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,pn.default)(u,r))c="high";else{let d=(0,Ji.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,Ji.default)(i,-1);!this.isLive&&l&&(this.fullyBuffered$.next(l.time.to-e-this.getForwardBufferDuration(e)<n),this.onLastSegment$.next(e-l.time.from>0))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let i=0,r=this.isLive?this.liveInitialAdditionalOffset:0;for(let s of e)Math.trunc(s.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:s.time.from+r}),i=s.time.to;Xi(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,hn.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,hn.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||!ye(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,Ji.default)(c,-1))==null?void 0:s.time.to)!=null?n:0,h=u==null?void 0:u.findIndex(p=>d>=p.time.from+l&&d<=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,[...c,...p])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;Re(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 s=r.segmentReference;if(!ye(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=ft(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&&Zr&&Zr(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&Zr&&Zr(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=e.findIndex(({status:d,time:{from:h,to:p}},m)=>{let b=h<=i&&p>=i,g=h>i||b||m===0&&i===0,v=Math.min(this.forwardBufferTarget,this.bufferLimit),S=this.preloadOnly&&h<=i+v||p<=i+v;return(d==="none"||d==="partially_ejected"&&g&&S&&this.sourceBuffer&&re(this.mediaSource,this.sourceBuffer)&&!(Bt(this.sourceBuffer.buffered,h)&&Bt(this.sourceBuffer.buffered,p)))&&g&&S});if(r===-1)return[];if(t!=="byteRange")return e.slice(r,r+1);let s=e,n=0,o=0,u=[],l=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,c=this.preloadOnly?this.forwardBufferTarget:0;for(let d=r;d<s.length&&(n<=l||o<=c);d++){let h=s[d];if(n+=h.byte.to+1-h.byte.from,o+=h.time.to+1-h.time.from,h.status==="none"||h.status==="partially_ejected")u.push(h);else break}return u}async loadSegments(e,t,i="auto"){ye(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 Nt(o,async function*(){let c=ql(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,c))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let c=await this.fetcher.fetch(n,{range:s,signal:o,onProgress:u,priority:i,isLowLatency:this.isActiveLowLatency()});if(this.lastDataObtainedTimestampMs=dn(),!c)return;let d=new DataView(c),h=Pa(t.mime);if(!isFinite(r.segment.time.to)){let b=t.segmentReference.timescale;r.segment.time.to=h.getChunkEndTime(d,b)}u&&r.feedingBytes&&l?await Promise.all(l):await this.sourceBufferTaskQueue.append(d,o);let{serverDataReceivedTimestamp:p,serverDataPreparedTime:m}=h.getServerLatencyTimestamps(d);p&&m&&this.currentLiveSegmentServerLatency$.next(m-p),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(c){this.abortActiveSegments([e]),wa(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())ye(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 Nt(n,async function*(){let u=ql(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),Fl(window,"online").pipe(pC()).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}),this.lastDataObtainedTimestampMs=dn(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),wa(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(ye(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:(0,Ji.default)(e,0).byte.from,to:(0,Ji.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:i,range:r,signal:s,onProgress:async(o,u)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=dn(),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:bt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!ye(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=dn();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:bt.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,pn.default)(e,t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:s}){if(!this.activeSegments.size||!re(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=Pa(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||!re(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,h=d-c+1,p=c<r,m=d<=r;if(!p)continue;let b=Pa(o.mime);if(l.status==="downloading"&&m){l.status="downloaded";let g=new DataView(e.buffer,e.byteOffset+c,h);await this.sourceBufferTaskQueue.append(g,s)&&!s.aborted?this.onSegmentFullyAppended(u,t):await n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(l.status==="downloading"||l.status==="partially_fed")&&(u.loadedBytes=Math.min(h,r-c),u.loadedBytes>u.feedingBytes)){let g=new DataView(e.buffer,e.byteOffset+c+u.feedingBytes,u.loadedBytes-u.feedingBytes),v=u.loadedBytes===h?g:b.parseFeedableSegmentChunk(g);v!=null&&v.byteLength&&(l.status="partially_fed",u.feedingBytes+=v.byteLength,await this.sourceBufferTaskQueue.append(v,s)&&!s.aborted?(u.fedBytes+=v.byteLength,u.fedBytes===h&&this.onSegmentFullyAppended(u,t)):await n())}}}onSegmentFullyAppended(e,t){var i;if(!(fe(this.sourceBuffer)||!re(this.mediaSource,this.sourceBuffer))){!this.isLive&&N.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(Bt(this.sourceBuffer.buffered,e.segment.time.from,100)&&Bt(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:bt.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",Ol(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=Tl(()=>(0,vy.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?Nt(this.destroyAbortController.signal,async function*(){let o=ql(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,Pa(e.mime),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 h=c;this.isLive&&ye(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:bt.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||!re(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||fe(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:h}=u[c],p=l[l.length-1];p.to>=d?p.to=Math.max(p.to,h):l.push(u[c])}return l},o=u=>{var c;if(s>=t)return r;r.push({...u.time}),r=n(r);let l=Ol(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 h of this.segments.values())for(let p of h)(0,pn.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 h={time:{from:l,to:c},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 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||!re(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||!re(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||!re(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||fe(e)?0:Wi(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!(!this.sourceBuffer||!re(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||!re(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=Tl(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:bt.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if(fe(this.sourceBuffer)||!re(this.mediaSource,this.sourceBuffer)||fe(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:bt.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}};var ka=a=>{let e=new URL(a);return e.searchParams.set("quic","1"),e.toString()};var Sy=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 Ra,assertNever as Ty,fromEvent as Iy,merge as fC,now as $a,Subscription as bC,Subject as Ey,ValueSubject as Ul,flattenObject as Zi,ErrorCategory as La}from"@vkontakte/videoplayer-shared/es2018";var yy=a=>{let e=new URL(a);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var fn=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:s=!1}){this.lastConnectionType$=new Ul(void 0);this.lastConnectionReused$=new Ul(void 0);this.lastRequestFirstBytes$=new Ul(void 0);this.recoverableError$=new Ey;this.error$=new Ey;this.abortAllController=new me;this.subscription=new bC;this.fetchManifest=Ra(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=ka(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=yy(i));let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(mn);return r?(t.log("success",Zi({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(r.headers),r.text()):(t.error("error",Zi({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=Ra(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}={}){var U,L;let l=e,c=new Headers,d=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{c.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let k=new URL(l,location.href);k.searchParams.append("bytes",`${i.from}-${i.to}`),l=k.toString();break}default:Ty(t)}this.requestQuic&&(l=ka(l));let h=this.abortAllController.signal,p;if(n){let k=new me;if(p=fC(Iy(this.abortAllController.signal,"abort"),Iy(n,"abort")).subscribe(()=>{try{k.abort()}catch(W){mn(W)}}),this.subscription.add(p),this.abortAllController.signal.aborted||n.aborted)try{k.abort()}catch(W){mn(W)}h=k.signal}let m=$a();d.log("startRequest",Zi({url:l,priority:s,rangeMethod:t,range:i,isLowLatency:u,requestStartedAt:m}));let b=yield this.doFetch(l,{priority:s,headers:c,signal:h}),g=$a();if(!b)return d.error("error",{message:"No response in request"}),d.end(),p==null||p.unsubscribe(),null;if((U=this.throughputEstimator)==null||U.addRawRtt(g-m),!b.ok||!b.body){p==null||p.unsubscribe();let k=`Fetch error ${b.status}: ${b.statusText}`;return d.error("error",{message:k}),d.end(),Promise.reject(new Error(`Fetch error ${b.status}: ${b.statusText}`))}if(this.onHeadersReceived(b.headers),!r&&!o){p==null||p.unsubscribe();let k=$a(),W={requestStartedAt:m,requestEndedAt:k,duration:k-m};return d.log("endRequest",Zi(W)),d.end(),b.arrayBuffer()}let[v,S]=b.body.tee(),y=v.getReader();o&&((L=this.throughputEstimator)==null||L.trackStream(S,u));let I=0,T=new Uint8Array(0),R=!1,q=k=>{p==null||p.unsubscribe(),R=!0,mn(k)},O=Ra(h,async function*({done:k,value:W}){if(I===0&&this.lastRequestFirstBytes$.next($a()-m),h.aborted){p==null||p.unsubscribe();return}if(!k&&W){let ae=new Uint8Array(T.length+W.length);ae.set(T),ae.set(W,T.length),T=ae,I+=W.byteLength,r==null||r(new DataView(T.buffer),I),yield y==null?void 0:y.read().then(O,q)}}.bind(this));yield y==null?void 0:y.read().then(O,q),p==null||p.unsubscribe();let _=$a(),w={failed:R,requestStartedAt:m,requestEndedAt:_,duration:_-m};return R?(d.error("endRequest",Zi(w)),d.end(),null):(d.log("endRequest",Zi(w)),d.end(),T.buffer)}.bind(this));this.fetchByteRangeRepresentation=Ra(this.abortAllController.signal,async function*(e,t,i){var v;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 h=new DataView(d,r-n,s-n+1);if(!t.validateData(h))throw new Error("Invalid media file");let p=t.parseInit(h),m=(v=e.indexRange)!=null?v:t.getIndexRange(p);if(!m)throw new ReferenceError("No way to load representation index");let b;if(u)b=new DataView(d,m.from-n,m.to-m.from+1);else{let S=yield this.fetch(e.url,{range:m,priority:i,measureThroughput:!1});if(!S)return null;b=new DataView(S)}let g=t.parseSegments(b,p,m);return{init:p,dataView:new DataView(d),segments:g}}.bind(this));this.fetchTemplateRepresentation=Ra(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}=Sy(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:Ty(r)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}async doFetch(e,t){let i=await at(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:La.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:La.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:La.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:La.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${s})`,category:La.FATAL})}}},mn=a=>{if(!wa(a))throw a};var pi=(a,e,t)=>t*e+(1-t)*a,Hl=(a,e)=>a.reduce((t,i)=>t+i,0)/e,xy=(a,e,t,i)=>{let r=0,s=t,n=Hl(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 gC,ValueSubject as Py}from"@vkontakte/videoplayer-shared/es2018";var Ft=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 Py(e.initial),this.debounced$=new Py(e.initial);let t=(i=e.label)!=null?i:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new ve(`raw_${t}`),this.smoothedSeries$=new ve(`smoothed_${t}`),this.reportedSeries$=new ve(`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)&&(gC(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 bn=class extends Ft{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=pi(this.slow,e,this.params.emaAlphaSlow),this.fast=pi(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var gn=class extends Ft{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=Hl(this.pastMeasures,this.takenMeasures);this.emaSmoothed=pi(this.emaSmoothed,e,this.params.emaAlpha);let i=xy(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}};var vn=class extends Ft{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?pi(this.smoothed,t,this.params.emaAlpha):t}};var hi=class{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new bn({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new gn({initial:e,emaAlpha:i.emaAlpha,basisTrendChangeCount:i.basisTrendChangeCount,changeThreshold:i.changeThreshold,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"})}static getLiveBufferSmoothedValue(e,t){return new vn({initial:e,label:"liveEdgeDelay",...t})}};var jl=(a,e)=>{a&&a.playbackRate!==e&&(a.playbackRate=e)};import{isNullable as vC,ValueSubject as SC}from"@vkontakte/videoplayer-shared/es2018";var Ma=class a{constructor(e,t){this.currentRepresentation$=new SC(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(!vC(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&&ye(t.segmentReference))}};var yn=C(Dt(),1);import{assertNever as Tn}from"@vkontakte/videoplayer-shared/es2018";var wy=(a,{useHlsJs:e,useManagedMediaSource:t,useOldMSEDetection:i})=>{let{containers:r,protocols:s,codecs:n,nativeHlsSupported:o}=N.video,u=(n.h264||n.h265)&&n.aac,l=s.mse&&(!i||!!window.MediaStreamTrack)||s.mms&&t;return a.filter(c=>{switch(c){case"DASH_SEP":return l&&r.mp4&&u;case"DASH_WEBM":return l&&r.webm&&n.vp9&&n.opus;case"DASH_WEBM_AV1":return l&&r.webm&&n.av1&&n.opus;case"DASH_STREAMS":return l&&(r.mp4&&u||r.webm&&(n.vp9||n.av1)&&(n.opus||n.aac));case"DASH_LIVE":return l&&r.mp4&&u;case"DASH_LIVE_CMAF":return l&&r.mp4&&u&&r.cmaf;case"DASH_ONDEMAND":return l&&r.mp4&&u;case"HLS":case"HLS_ONDEMAND":return o||e&&l&&r.mp4&&u;case"HLS_LIVE":case"HLS_LIVE_CMAF":return o;case"MPEG":return r.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return s.webrtc&&s.ws&&n.h264&&(r.mp4||r.webm);default:return Tn(c)}})},Sn=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:Tn(a)}return[t,i]},Ay=({webmCodec:a,androidPreferredFormat:e,preferMultiStream:t})=>{let i=[...t?["DASH_STREAMS"]:[],...Sn(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",...Sn(a),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...Sn(a),"MPEG",...r,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...Sn(a),...r,"HLS","HLS_ONDEMAND"];default:Tn(e)}return N.video.nativeHlsSupported?[...i,"HLS","HLS_ONDEMAND","MPEG"]:[...i,"HLS","HLS_ONDEMAND","MPEG"]},ky=({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:Tn(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"]},Ql=a=>a?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],Ry=a=>{if(a.size===0)return;if(a.size===1){let t=a.values().next();return(0,yn.default)(t.value.split("."),0)}for(let t of a){let i=(0,yn.default)(t.split("."),0);if(i==="opus"||i==="vp09"||i==="av01")return i}let e=a.values().next();return(0,yn.default)(e.value.split("."),0)};var kC=["timeupdate","progress","play","seeked","stalled","waiting"],RC=["timeupdate","progress","loadeddata","playing","seeked"];var xn=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new My;this.representationSubscription=new My;this.state$=new D("none");this.currentVideoRepresentation$=new Z(void 0);this.currentVideoRepresentationInit$=new Z(void 0);this.currentAudioRepresentation$=new Z(void 0);this.currentVideoSegmentLength$=new Z(0);this.currentAudioSegmentLength$=new Z(0);this.error$=new En;this.lastConnectionType$=new Z(void 0);this.lastConnectionReused$=new Z(void 0);this.lastRequestFirstBytes$=new Z(void 0);this.currentLiveTextRepresentation$=new Z(null);this.isLive$=new Z(!1);this.isActiveLive$=new Z(!1);this.isLowLatency$=new Z(!1);this.liveDuration$=new Z(0);this.liveSeekableDuration$=new Z(0);this.liveAvailabilityStartTime$=new Z(0);this.liveStreamStatus$=new Z(void 0);this.bufferLength$=new Z(0);this.liveLatency$=new Z(void 0);this.liveLoadBufferLength$=new Z(0);this.livePositionFromPlayer$=new Z(0);this.currentStallDuration$=new Z(0);this.videoLastDataObtainedTimestamp$=new Z(0);this.fetcherRecoverableError$=new En;this.fetcherError$=new En;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new En;this.gapWatchdogActive=!1;this.destroyController=new me;this.initManifest=Wl(this.destroyController.signal,async function*(e,t,i){var r;this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=he(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:st.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=Wl(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:st.NETWORK,message:"Failed to load manifest",thrown:u})});if(!e)return null;let t=null;try{t=fy(e!=null?e:"",this.manifestUrlString)}catch(u){let l=(n=oS(e))!=null?n:{id:"ManifestParsing",category:st.PARSER,message:"Failed to parse MPD manifest",thrown:u};this.error$.next(l)}if(!t)return null;let i=(u,l,c)=>{var d,h,p,m;return!!((h=(d=this.element)==null?void 0:d.canPlayType)!=null&&h.call(d,l)&&((m=(p=Ye())==null?void 0:p.isTypeSupported)!=null&&m.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,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";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:m})=>i(u,p,m)),d=new Set(c.map(({codecs:p})=>p)),h=Ry(d);if(h&&(r[u]=c.filter(({codecs:p})=>p.startsWith(h))),u==="video"){let p=this.tuning.preferHDR,m=r.video.some(g=>g.hdr),b=r.video.some(g=>!g.hdr);N.display.isHDR&&p&&m?r.video=r.video.filter(g=>g.hdr):b&&(r.video=r.video.filter(g=>!g.hdr))}}let s={...t,streams:r};return this.tracer.log("updateManifestEnd",Da(s)),s}.bind(this));this.initRepresentations=Wl(this.destroyController.signal,async function*(e,t,i){var h;this.tracer.log("initRepresentationsStart",Da({initialVideo:e,initialAudio:t,sourceHls:i})),er(this.manifest),er(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let r=p=>{this.representationSubscription.add(gt(p,"error").pipe(In(m=>{var b;return!!((b=this.element)!=null&&b.played.length)})).subscribe(m=>{this.error$.next({id:"VideoSource",category:st.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:m})}))};this.source=this.tuning.useManagedMediaSource?kg():new MediaSource;let s=document.createElement("source");if(r(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&Ks())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,m)=>[...p,...m.representations],[]);if(this.videoBufferManager=new Aa("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],Va(t)){let p=this.manifest.streams.audio.reduce((m,b)=>[...m,...b.representations],[]);this.audioBufferManager=new Aa("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}Ma.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new Ma(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(...RC.map(p=>gt(this.element,p))).pipe(ir(p=>this.element?Wi(this.element.buffered,this.element.currentTime*1e3):0),Ca(),wC(p=>{p>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add(mi(gt(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe(Ca()).subscribe(m=>this.liveStreamEndTimestamp=zl())),this.subscription.add(gt(this.element,"pause").subscribe(()=>{this.livePauseWatchdogSubscription=Yl(1e3).subscribe(m=>{let b=js(this.manifestUrlString,2);this.manifestUrlString=he(this.manifestUrlString,b+1e3,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add(gt(this.element,"play").subscribe(m=>{var b;return(b=this.livePauseWatchdogSubscription)==null?void 0:b.unsubscribe()})),this.representationSubscription.add(tr({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(ir(({isActiveLive:m,isLowLatency:b})=>m&&b),Ca()).subscribe(m=>{this.isManualDecreasePlaybackInLive()||jl(this.element,1)})),this.representationSubscription.add(tr({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(In(({bufferLength:m,isActiveLive:b,isLowLatency:g})=>b&&g&&!!m)).subscribe(({bufferLength:m})=>this.liveBuffer.next(m))),this.representationSubscription.add(this.videoBufferManager.currentLowLatencySegmentLength$.subscribe(m=>{if(!this.isActiveLive$.getValue()&&!this.isLowLatency$.getValue()&&!m)return;let b=this.liveSeekableDuration$.getValue()-m/1e3;this.liveSeekableDuration$.next(Math.max(b,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+m/1e3)})),this.representationSubscription.add(tr({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(In(({isLive:m})=>m),Ca((m,b)=>b.bufferLength<m.bufferLength),ir(({rtt:m,bufferLength:b,segmentServerLatency:g})=>{let v=js(this.manifestUrlString,2);return(m/2+b+g+v)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(tr({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:m,isActiveLive:b,isLowLatency:g})=>{if(!g||!b)return;let v=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,S=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,y=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,I=m-v;if(this.isManualDecreasePlaybackInLive())return;let T=1;Math.abs(I)>S&&(T=1+Math.sign(I)*y),jl(this.element,T)})),this.representationSubscription.add(this.bufferLength$.subscribe(m=>{var g,v;let b=0;if(m){let S=((v=(g=this.element)==null?void 0:g.currentTime)!=null?v:0)*1e3;b=Math.min(...this.bufferManagers.map(I=>{var T,R;return(R=(T=I.getLiveSegmentsToLoadState(this.manifest))==null?void 0:T.to)!=null?R:S}))-S}this.liveLoadBufferLength$.getValue()!==b&&this.liveLoadBufferLength$.next(b)}));let p=0;this.representationSubscription.add(tr({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(AC(1e3)).subscribe(async({liveLoadBufferLength:m,bufferLength:b})=>{if(!this.element||this.isUpdatingLive)return;let g=this.element.playbackRate,v=js(this.manifestUrlString,2),S=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,y=Math.min(S,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*g),I=this.tuning.dashCmafLive.normalizedActualBufferOffset*g,T=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*g,R=isFinite(m)?m:b,q=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),O=S<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(O);let _="none";if(q?_="active_low_latency":this.isLowLatency$.getValue()&&O?(this.bufferManagers.forEach(w=>w.proceedLowLatencyLive()),_="active_low_latency"):v!==0&&R<y?_="live_forward_buffering":R<y+T&&(_="live_with_target_offset"),isFinite(m)&&(p=m>p?m:p),_==="live_forward_buffering"||_==="live_with_target_offset"){let w=p-(y+I),U=this.normolizeLiveOffset(Math.trunc(v+w/g)),L=Math.abs(U-v),k=0;!m||L<=this.tuning.dashCmafLive.offsetCalculationError?k=v:U>0&&L>this.tuning.dashCmafLive.offsetCalculationError&&(k=U),this.manifestUrlString=he(this.manifestUrlString,k,2)}(_==="live_with_target_offset"||_==="live_forward_buffering")&&(p=0,await this.updateLive())},m=>{this.error$.next({id:"updateLive",category:st.VIDEO_PIPELINE,thrown:m,message:"Failed to update live with subscription"})}))}let l=mi(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe(ir(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),c=mi(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe(ir(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue()))),d=tr({allBuffersFull:l,someBufferEnded:c}).pipe(Ca(),ir(({allBuffersFull:p,someBufferEnded:m})=>p&&m),In(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(m=>!m.updating))try{(p=this.source)==null||p.endOfStream()}catch(m){this.error$.next({id:"EndOfStream",category:st.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:m})}})),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((m,b)=>{var g;p&&(this.timeoutSourceOpenId=setTimeout(()=>{var v;if(((v=this.source)==null?void 0:v.readyState)==="open"){m();return}this.tuning.dash.rejectOnSourceOpenTimeout?b(new Error("Timeout reject when wait sourceopen event")):m()},this.tuning.dash.sourceOpenTimeout)),(g=this.source)==null||g.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),m()},{once:!0})})}if(!this.isLive$.getValue()){let p=[(h=this.manifest.duration)!=null?h:0,...(0,Kl.default)((0,Kl.default)([...this.manifest.streams.audio,...this.manifest.streams.video],m=>m.representations),m=>{let b=[];return m.duration&&b.push(m.duration),ye(m.segmentReference)&&m.segmentReference.totalSegmentsDurationMs&&b.push(m.segmentReference.totalSegmentsDurationMs),b})];this.source.duration=Math.max(...p)/1e3}this.audioBufferManager&&Va(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=Yl(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),n=>{this.error$.next({id:"GapWatchdog",category:st.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 fn({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=hi.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator}),this.initTracerSubscription()}async seekLive(e){var r,s,n;er(this.element);let t=this.liveStreamStatus$.getValue()!=="active"?zl()-this.liveStreamEndTimestamp:0,i=this.normolizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=he(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(){er(this.element),this.state$.setState("running"),this.subscription.add(mi(...kC.map(e=>gt(this.element,e)),gt(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:st.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(gt(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(gt(this.element,"waiting").subscribe(()=>{var t;this.element&&this.element.readyState===2&&!this.element.seeking&&Bt(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{var p,m,b,g,v,S,y,I,T,R,q;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=zl(),n=100,o=(b=(m=this.videoBufferManager)==null?void 0:m.lastDataObtainedTimestamp)!=null?b:0;this.videoLastDataObtainedTimestamp$.next(o);let u=(v=(g=this.audioBufferManager)==null?void 0:g.lastDataObtainedTimestamp)!=null?v:0,l=(y=(S=this.videoBufferManager)==null?void 0:S.getForwardBufferDuration())!=null?y:0,c=(T=(I=this.audioBufferManager)==null?void 0:I.getForwardBufferDuration())!=null?T:0,d=l<n&&s-o>this.tuning.dash.crashOnStallTWithoutDataTimeout,h=this.audioBufferManager&&c<n&&s-u>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((d||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 O=this.normolizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(O).catch(_=>{this.error$.next({id:"stallIntervalCallback",category:st.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:_})}),r.liveLastOffset=O}else{let O=this.element.currentTime*1e3;(R=this.videoBufferManager)==null||R.maintain(O),(q=this.audioBufferManager)==null||q.maintain(O),r.position=O}this.tracer.log("stallIntervalCallback",Da(r))};(t=this.stallWatchdogSubscription)==null||t.unsubscribe(),this.stallWatchdogSubscription=Yl(50).subscribe(e,i=>{this.error$.next({id:"StallWatchdogCallback",category:st.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;er(this.element),er(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),Bt(this.element.buffered,i)||await Promise.all([this.videoBufferManager.abort(),(o=this.audioBufferManager)==null?void 0:o.abort()]),!(Ly(this.element)||Ly(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),(u=this.audioBufferManager)==null||u.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",Da({requestedPosition:e,forcePrecise:t,position:i})))}warmUpMediaSourceIfNeeded(e=(t=>(t=this.element)==null?void 0:t.currentTime)()){var i;Va(this.element)&&Va(this.source)&&Va(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=PC(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.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",Da(i)))}}};var Pn=class{constructor(e,t){this.fov=e,this.orientation=t}};var wn=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 Cy=`attribute vec2 a_vertex;
|
|
125
71
|
attribute vec2 a_texel;
|
|
126
72
|
|
|
127
73
|
varying vec2 v_texel;
|
|
@@ -132,7 +78,7 @@ void main(void) {
|
|
|
132
78
|
// save texel vector to pass to fragment shader
|
|
133
79
|
v_texel = a_texel;
|
|
134
80
|
}
|
|
135
|
-
`;var
|
|
81
|
+
`;var Dy=`#ifdef GL_ES
|
|
136
82
|
precision highp float;
|
|
137
83
|
precision highp int;
|
|
138
84
|
#else
|
|
@@ -175,13 +121,6 @@ void main(void) {
|
|
|
175
121
|
// sample using new coordinates
|
|
176
122
|
gl_FragColor = texture2D(u_texture, tc);
|
|
177
123
|
}
|
|
178
|
-
`;var ds=class{constructor(e,t,i){this.videoInitialized=!1;this.active=!1;this.container=e,this.sourceVideoElement=t,this.params=i,this.canvas=this.createCanvas();let r=this.canvas.getContext("webgl");if(!r)throw new Error("Could not initialize WebGL context");this.gl=r,this.container.appendChild(this.canvas),this.camera=new tl(this.params.fov,this.params.orientation),this.cameraRotationManager=new il(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(KI,this.gl.VERTEX_SHADER),i=this.createShader(XI,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 SC,now as Ln,once as vC,Subscription as yC,ValueSubject as Vp,isNonNullable as TC,safeStorage as JI,filterChanged as IC}from"@vkontakte/videoplayer-shared/es2018";var rl="stalls_manager_metrics",ZI="stalls_manager_abr_params",Op=class{constructor(){this.isSeeked$=new Vp(!1);this.isBuffering$=new Vp(!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 yC;this.severeStallOccurred$=new Vp(!1)}connect(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.subscribe(e)}get videoMaxQualityLimit(){return this.maxQualityLimit}get predictedThroughput(){return this.predictedThroughputWithoutData}get abrTuningParams(){return{...this.abrParams,...this.getStoredData(ZI)}}set lastVideoTrackSelected(e){var t;((t=this.lastUniqueVideoTrackSelected)==null?void 0:t.id)!==e.id&&(this.lastUniqueVideoTrackSelected=e,this.lastUniqueVideoTrackSelectedTimestamp=Ln(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe(),this.currentStallDuration$.getValue()!==0&&this.updateStallData();let e=(Ln()-this.providerStartWatchingTimestamp-this.sumStallsDuration)/1e3,t=this.sumStallsDuration;this.addStallInfoToHistory(e,t),this.updateStoredAbrParams()}updateStoredAbrParams(){let e=[],t=this.getStoredData(rl,"[]");if(t.length<this.tuning.stallsMetricsHistoryLength)return;if(this.tuning.useTotalStallsDurationPerTvt){let r=t.reduce((o,u)=>o+u.tvt,0),n=t.reduce((o,u)=>o+u.stallsDuration,0)/r;e.push(this.calculateOptimalAbrParams(n))}if(this.tuning.useAverageStallsDurationPerTvt){let r=t.reduce((a,n)=>a+n.stallsDurationPerTvt,0)/t.length;e.push(this.calculateOptimalAbrParams(r))}this.tuning.useEmaStallsDurationPerTvt&&e.push(this.calculateOptimalAbrParams(t[t.length-1].stallsDurationPerTvtSmoothed));let i={bitrateFactorAtEmptyBuffer:Math.max(...e.map(r=>r.bitrateFactorAtEmptyBuffer)),bitrateFactorAtFullBuffer:Math.max(...e.map(r=>r.bitrateFactorAtFullBuffer)),containerSizeFactor:Math.min(...e.map(r=>r.containerSizeFactor))};this.setStoredData(rl,[]),this.setStoredData(ZI,i)}calculateOptimalAbrParams(e){let{targetStallsDurationPerTvt:t,deviationStallsDurationPerTvt:i,criticalStallsDurationPerTvt:r,abrAdjustingSpeed:a}=this.tuning,n=this.abrTuningParams;return e<t-i?n={bitrateFactorAtEmptyBuffer:Math.max(n.bitrateFactorAtEmptyBuffer-a,this.abrParams.minBitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.max(n.bitrateFactorAtFullBuffer-a,this.abrParams.minBitrateFactorAtFullBuffer),containerSizeFactor:Math.min(n.containerSizeFactor+a,this.abrParams.maxContainerSizeFactor)}:e>t+i&&(n={bitrateFactorAtEmptyBuffer:Math.min(n.bitrateFactorAtEmptyBuffer+a,this.abrParams.maxBitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.min(n.bitrateFactorAtFullBuffer+a,this.abrParams.maxBitrateFactorAtFullBuffer),containerSizeFactor:Math.max(n.containerSizeFactor-a,this.abrParams.minContainerSizeFactor)}),e>r&&(n={bitrateFactorAtEmptyBuffer:Math.max(n.bitrateFactorAtEmptyBuffer,this.abrParams.bitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.max(n.bitrateFactorAtFullBuffer,this.abrParams.bitrateFactorAtFullBuffer),containerSizeFactor:Math.min(n.containerSizeFactor,this.abrParams.containerSizeFactor)}),n}getStoredData(e,t="{}"){var i;return JSON.parse((i=JI.get(e))!=null?i:t)}setStoredData(e,t){JI.set(e,JSON.stringify(t))}addStallInfoToHistory(e,t){if(e<this.tuning.minTvtToBeCounted||e>this.tuning.maxTvtToBeCounted||e*1e3<t)return;let i=this.getStoredData(rl,"[]"),r=t/e,a=i.length?Ti(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(rl,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(vC()).subscribe(t=>this.providerStartWatchingTimestamp=Ln())),this.subscription.add(this.currentStallDuration$.pipe(IC()).subscribe(t=>{let{stallDurationNoDataBeforeQualityDecrease:i,stallCountBeforeQualityDecrease:r,resetQualityRestrictionTimeout:a,ignoreStallsOnSeek:n}=this.tuning;if(SC(this.lastUniqueVideoTrackSelected)||n&&this.isSeeked$.getValue())return;let o=this.rtt$.getValue(),u=this.throughput$.getValue(),l=this.videoLastDataObtainedTimestamp$.getValue(),d=Ln(),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,TC(this.lastUniqueVideoTrackSelected.bitrate)&&u>this.lastUniqueVideoTrackSelected.bitrate&&(this.predictedThroughputWithoutData=this.lastUniqueVideoTrackSelected.bitrate)),!t&&Ln()-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}))}},sl=Op;import{combine as xC,map as EC,observeElementSize as wC,Subscription as PC,ValueSubject as _p,noop as AC}from"@vkontakte/videoplayer-shared/es2018";var al=class{constructor(){this.subscription=new PC;this.pipSize$=new _p(void 0);this.videoSize$=new _p(void 0);this.elementSize$=new _p(void 0);this.pictureInPictureWindowRemoveEventListener=AC}connect({observableVideo:e,video:t}){let i=r=>{let a=r.target;this.pipSize$.next({width:a.width,height:a.height})};this.subscription.add(wC(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(xC({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(EC(({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 Sr=class{constructor(e){this.subscription=new DC;this.videoState=new H("stopped");this.droppedFramesManager=new Xr;this.stallsManager=new sl;this.elementSizeManager=new al;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"),R(this.params.desiredState.playbackState,"stopped",!0));return}switch(e){case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();return;case"ready":t==="paused"?(this.videoState.setState("paused"),R(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="ready"&&R(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):t==="playing"&&this.video.paused?this.playIfAllowed():(i==null?void 0:i.to)==="playing"&&R(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&R(this.params.desiredState.playbackState,"paused");return;default:return RC(e)}}};this.init3DScene=e=>{var i,r,a;if(this.scene3D)return;this.scene3D=new ds(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((i=e.projectionData)==null?void 0:i.pose.yaw)||0,y:((r=e.projectionData)==null?void 0:r.pose.pitch)||0,z:((a=e.projectionData)==null?void 0:a.pose.roll)||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSizeManager.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.textTracksManager=new ot(e.source.url),this.params=e,this.video=Ue(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(we(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 el({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,i=He(this.video);this.subscription.add(()=>i.destroy());let r=this.constructor.name,a=o=>{e.error$.next({id:r,category:ex.WTF,message:`${r} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:i,genericErrorListener:a,connect:(o,u)=>this.subscription.add(o.subscribe(u,a))}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:a}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(Fp(l=>!!l.length),ix()).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(Np(l=>l.to.state!=="none"),nl());this.stallsManager.connect({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(Fp(tx),ix()),e.firstBytesEvent$),a(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),a(this.videoState.stateChangeEnded$.pipe(Np(l=>l.to)),this.params.output.playbackState$),this.subscription.add(i.loopExpected$.subscribe(l=>{t.seekState.setState({state:"requested",position:0,forcePrecise:!1})})),this.subscription.add(i.looped$.subscribe(()=>this.player.warmUpMediaSourceIfNeeded(),r)),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(Pt(this.video,t.isLooped,r)),this.subscription.add(je(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(nt(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),a(lt(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),R(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),R(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:l})=>{if(l==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let d=this.player.getStreams();if(LC(d,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let h=[];for(let p of d.audio){h.push(yp(p));let f=[];for(let m of p.representations){let g=AI(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(Tp(h));let p=[];for(let f of h.representations){let m=PI({...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=kI(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(ol(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$,$C(this.video,"progress")).pipe(Fp(()=>this.videoTracksMap.size>0)).subscribe(async()=>{let l=this.player.state$.getState(),d=this.player.state$.getTransition();if(!(0,rx.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});tx(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(nl()).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(Tp(h))},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(nl()).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(yp(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(Np(({to:l})=>l==="ready"),nl());this.subscription.add(ol(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,Up(["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(ol(o,this.player.state$.stateChangeEnded$,Up(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let u=ol(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Up(["init"])).pipe(MC(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){var P,O,$,M,G,q,w,N,A,x,D,oe,Oe;if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?Va:Ca,t=this.params.tuning.useNewAutoSelectVideoTrack?Ru:ku,i=this.params.tuning.useNewAutoSelectVideoTrack?Kt:Au,{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:re})=>re===o),d=a.currentVideoTrack$.getValue(),c=((M=($=r.videoStream.getState())!=null?$:l&&((O=this.videoTracksMap.get(l))==null?void 0:O.stream))!=null?M:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!c)return;let h=[...this.videoStreamsMap.keys()].find(({id:re})=>re===c.id),p=h&&this.videoStreamsMap.get(h);if(!p)return;let f=Ce(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),y=(G=r.audioStream.getState())!=null?G:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,v=(q=[...this.audioStreamsMap.keys()].find(({id:re})=>re===(y==null?void 0:y.id)))!=null?q:this.audioStreamsMap.keys().next().value,I=0;if(v){if(l&&!n){let re=e(l,p,(w=this.audioStreamsMap.get(v))!=null?w:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);I=Math.max(I,(N=re==null?void 0:re.bitrate)!=null?N:-1/0)}if(d){let re=e(d,p,(A=this.audioStreamsMap.get(v))!=null?A:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);I=Math.max(I,(x=re==null?void 0:re.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,V=v&&t(E,p,(D=this.audioStreamsMap.get(v))!=null?D:[],{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=(oe=this.videoTracksMap.get(E))==null?void 0:oe.representation,k=V&&((Oe=this.audioTracksMap.get(V))==null?void 0:Oe.representation);if(L&&k)return[L,k];if(L&&!k&&this.audioTracksMap.size===0)return[L,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){We(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),R(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:ex.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),qe(this.video),this.tracer.end()}};var Mn=class extends Sr{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 qp,merge as sx,filter as ax,filterChanged as BC,isNullable as jp,map as nx,ValueSubject as Hp,isNonNullable as CC}from"@vkontakte/videoplayer-shared/es2018";var $n=class extends Sr{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 Hp(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(qp({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(ax(o=>CC(o))).subscribe(o=>t.isLiveEnded$.next(o!=="active"&&t.position$.getValue()===0))).add(qp({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:sx(i.playbackRateState$,new Hp(1))}).pipe(ax(({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||jp(l)||(e=o-l)})).add(qp({time:t.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:sx(i.playbackRateState$,new Hp(1))}).pipe(BC((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||jp(o)||jp(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=RI(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 wV,assertNonNullable as PV,debounce as AV,ErrorCategory as Vx,filter as Ox,filterChanged as gl,fromEvent as kV,isNonNullable as _x,map as ph,merge as Sl,observableFrom as hh,once as Fx,Subscription as RV}from"@vkontakte/videoplayer-shared/es2018";var ch=U(Wa(),1);import{abortable as nh,assertNonNullable as bs,combine as gs,ErrorCategory as Zt,filter as hl,filterChanged as po,flattenObject as ho,fromEvent as Ai,getTraceSubscriptionMethod as fV,interval as oh,isNonNullable as fo,isNullable as Cx,map as Ss,merge as xr,now as uh,Subject as fl,Subscription as lh,tap as mV,throttle as bV,ValueSubject as fe}from"@vkontakte/videoplayer-shared/es2018";var ll=U(Tt(),1),fs=U(Nt(),1),cl=U(Wa(),1);var Lx=U(ka(),1);import{assertNever as VC,ErrorCategory as ox,Subject as ux}from"@vkontakte/videoplayer-shared/es2018";var OC=18,lx=!1;try{lx=j.browser.isSafari&&!!j.browser.safariVersion&&j.browser.safariVersion<=OC}catch(s){console.error(s)}var Wp=class{constructor(e){this.bufferFull$=new ux;this.error$=new ux;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:ox.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)};lx&&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:ox.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:VC(t)}}},cx=Wp;import{abortable as Hi,assertNonNullable as dt,ErrorCategory as Pi,fromEvent as ih,getExponentialDelay as rh,isNonNullable as hs,isNullable as Qe,now as ul,once as aV,Subject as nV,Subscription as oV,ValueSubject as Ir}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),i>e.byteLength-e.byteOffset&&(this.size32=NaN);let r=this.size32?this.size32-8:void 0,a=e.byteOffset+this.cursor;this.size64=0,this.usertype=0,this.content=new DataView(e.buffer,a,r)}get id(){return this.type}get size(){return this.size32}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t="ascii"){let r=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,r}readUint8(){let e=this.source.getUint8(this.cursor);return this.cursor+=1,e}readUint16(){let e=this.source.getUint16(this.cursor);return this.cursor+=2,e}readUint32(){let e=this.source.getUint32(this.cursor);return this.cursor+=4,e}readUint64(){let e=this.source.getBigInt64(this.cursor);return this.cursor+=8,e}};var ps=class extends X{};var Dn=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 Bn=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 Cn=class extends X{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var le=class extends X{constructor(e,t){super(e,t);let i=this.readUint32();this.version=i>>>24,this.flags=i&16777215}};var Vn=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 On=class extends X{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var _n=class extends X{constructor(e,t){super(e,t),this.data=this.content}};var vr=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 Fn=class extends X{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Nn=class extends X{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Un=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 qn=class extends le{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var jn=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 Hn=class extends X{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Wn=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 zn=class extends X{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Gn=class extends X{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 Yn=class extends X{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Kn=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 Xn=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 Jn=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 Zn=class extends X{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var eo=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 to=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 FC={ftyp:Bn,moov:Cn,mvhd:Vn,moof:On,mdat:_n,sidx:vr,trak:Fn,mdia:Hn,mfhd:Qn,tkhd:Wn,traf:Yn,tfhd:Kn,tfdt:Xn,trun:Jn,minf:zn,sv3d:Nn,st3d:Un,prhd:qn,proj:Gn,equi:jn,uuid:Dn,stbl:Zn,stsd:eo,avc1:to,unknown:ps},Ei=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=FC[e];return i?new i(t,new s):new ps(t,new s)}};var ji=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 UC=new TextDecoder("ascii"),qC=s=>UC.decode(new DataView(s.buffer,s.byteOffset+4,4))==="ftyp",jC=s=>{let e=new vr(s,new Ei),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})},HC=(s,e)=>{let i=new Ei().parse(s),r=new ji(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)},WC=s=>{let t=new Ei().parse(s),i=new ji(t),r={},a=i.findAll("uuid");return a.length?a[a.length-1]:r},zC=s=>{var r;let t=new Ei().parse(s);return(r=new ji(t).find("sidx"))==null?void 0:r.timescale},GC=(s,e)=>{let i=new Ei().parse(s),a=new ji(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},QC=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 Ei().parse(s),r=new ji(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},dx={validateData:qC,parseInit:QC,getIndexRange:()=>{},parseSegments:jC,parseFeedableSegmentChunk:HC,getChunkEndTime:GC,getServerLatencyTimestamps:WC,getTimescaleFromIndex:zC};var ro=U(Tt(),1);import{assertNonNullable as Gp,isNonNullable as mx,isNullable as KC}from"@vkontakte/videoplayer-shared/es2018";import{assertNever as YC}from"@vkontakte/videoplayer-shared/es2018";var px={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"}},hx=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=io(s,t),r=i in px,a=r?px[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=io(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}},io=(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},qt=(s,e)=>{switch(e){case"int":return s.getInt8(0);case"uint":return io(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:YC(e)}},yr=(s,e)=>{let t=0;for(;t<s.byteLength;){let i=new DataView(s.buffer,s.byteOffset+t),r=hx(i);if(!e(r))return;r.type==="master"&&yr(r.value,e),t=r.value.byteOffset-s.byteOffset+r.valueSize}},fx=s=>{if(s.getUint32(0)!==440786851)return!1;let e,t,i,r=hx(s);return yr(r.value,({tag:a,type:n,value:o})=>(a===17143?e=qt(o,n):a===17026?t=qt(o,n):a===17029&&(i=qt(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)};var bx=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],XC=[231,22612,22743,167,171,163,160,175],JC=s=>{let e,t,i,r,a=!1,n=!1,o=!1,u,l,d=!1,c=0;return yr(s,({tag:h,type:p,value:f,valueSize:m})=>{if(h===21419){let g=qt(f,p);l=io(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=qt(f,p):h===17545?r=qt(f,p):h===21420&&l===475249515?u=qt(f,p):h===374648427?yr(f,({tag:g,type:S,value:y})=>g===30321?(d=qt(y,S)===1,!1):!0):a&&n&&(0,ro.default)(bx,h)&&(o=!0),!o}),Gp(e,"Failed to parse webm Segment start"),Gp(t,"Failed to parse webm Segment end"),Gp(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}}}},ZC=s=>{if(KC(s.cuesSeekPosition))return;let e=s.segmentStart+s.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},eV=(s,e)=>{let t=!1,i=!1,r=o=>mx(o.time)&&mx(o.position),a=[],n;return yr(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=qt(l,u));break;case 183:break;case 241:n&&(n.position=qt(l,u));break;default:t&&(0,ro.default)(bx,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}}})},tV=s=>{let e=0,t=!1;try{yr(s,i=>i.tag===524531317?i.tagSize<=s.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):(0,ro.default)(XC,i.tag)?(e+i.tagSize<=s.byteLength&&(e+=i.tagSize,t||(t=(0,ro.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},gx={validateData:fx,parseInit:JC,getIndexRange:ZC,parseSegments:eV,parseFeedableSegmentChunk:tV};var so=s=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(s);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return gx;case"mp4":return dx}}throw new ReferenceError(`Unsupported mime type ${s}`)};var Zp=U(bp(),1),Px=U(rr(),1),Ax=U(gp(),1),kx=U(Nt(),1),eh=U(dr(),1);import{isNonNullable as sV,isNullable as Ex}from"@vkontakte/videoplayer-shared/es2018";var Sx=s=>{var e;try{let t=iV(),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 iV(){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 Yp=U(Nt(),1);import{videoSizeToQuality as rV}from"@vkontakte/videoplayer-shared/es2018";var vx=({id:s,width:e,height:t,bitrate:i,fps:r,quality:a,streamId:n})=>{var u;let o=(u=a?Yt(a):void 0)!=null?u:rV({width:e,height:t});return o&&{id:s,quality:o,bitrate:i,size:{width:e,height:t},fps:r,streamId:n}},yx=({id:s,bitrate:e})=>({id:s,bitrate:e}),Tx=({language:s,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:s,label:e}),Ix=({language:s,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:s,label:e}),Kp=({id:s,language:e,label:t,codecs:i,isDefault:r})=>({id:s,language:e,label:t,codec:(0,Yp.default)(i.split("."),0),isDefault:r}),Xp=({id:s,language:e,label:t,hdr:i,codecs:r})=>({id:s,language:e,hdr:i,label:t,codec:(0,Yp.default)(r.split("."),0)}),Jp=s=>"url"in s,st=s=>s.type==="template",ao=s=>s instanceof DOMException&&(s.name==="AbortError"||s.code===20);var xx=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},Tr=(s,e)=>{for(let t of s)if(e(t))return t;return null};var wx=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},wi=(s,e)=>{let t=s;t=(0,Zp.default)(t,"$$","$");let i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[r,a]of(0,Px.default)(i)){let n=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=(0,Zp.default)(t,n,(o,u)=>Ex(a)?o:Ex(u)?a:(0,Ax.default)(a,parseInt(u,10),"0"))}return t},Rx=(s,e)=>{var k,P,O,$,M,G,q,w,N,A,x,D,oe,Oe,re,Y,ye,Te,Ie,_e,wt,Rt,Ht,ei,Li,Ts,Is,xs,Es,ws,Ps,As,ks,Rs,Ls,Ms,$s,Ds,Bs,Cs,Vs,Os,_s,Fs,Ns,Us,qs,js,Hs,Ws,zs,Gs,Qs,Ys,Ks,Xs,Js,Zs,ea,ta,ia;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 _,Ye;return(Ye=(_=ce.textContent)==null?void 0:_.trim())!=null?Ye:""}),o=(k=(0,kx.default)(n,0))!=null?k:"",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,y=a.getAttribute("mediaPresentationDuration"),v=[...a.getElementsByTagName("Period")],I=v.reduce((ce,_)=>({...ce,[_.id]:_.children}),{}),T=v.reduce((ce,_)=>({...ce,[_.id]:_.getAttribute("duration")}),{});y?S=wx(y):(0,eh.default)(T).filter(ce=>ce).length&&!u?S=(0,eh.default)(T).reduce((ce,_)=>{var Ye;return ce+((Ye=wx(_))!=null?Ye:0)},0):m&&(S=parseInt(m,10));let E=0,V=(O=(P=a.getAttribute("profiles"))==null?void 0:P.split(","))!=null?O:[];for(let ce of v.map(_=>_.id))for(let _ of I[ce]){let Ye=($=_.getAttribute("id"))!=null?$:"id"+(E++).toString(10),Lt=(M=_.getAttribute("mimeType"))!=null?M:"",Qi=(G=_.getAttribute("codecs"))!=null?G:"",Yi=(q=_.getAttribute("contentType"))!=null?q:Lt==null?void 0:Lt.split("/")[0],Bl=(N=(w=_.getAttribute("profiles"))==null?void 0:w.split(","))!=null?N:[],ra=(x=Sx((A=_.getAttribute("lang"))!=null?A:""))!=null?x:{},ti=(Oe=(oe=(D=_.querySelector("Label"))==null?void 0:D.textContent)==null?void 0:oe.trim())!=null?Oe:void 0,Cl=_.querySelectorAll("Representation"),Vl=_.querySelector("SegmentTemplate"),Ol=(Y=(re=_.querySelector("Role"))==null?void 0:re.getAttribute("value"))!=null?Y:void 0,pt=Yi,W={id:Ye,language:ra.language,isDefault:Ol==="main",label:ti,codecs:Qi,hdr:pt==="video"&&rs(Qi),mime:Lt,representations:[]};for(let C of Cl){let Ae=(ye=C.getAttribute("lang"))!=null?ye:void 0,Mt=(Ie=(Te=ti!=null?ti:_.getAttribute("label"))!=null?Te:C.getAttribute("label"))!=null?Ie:void 0,ii=(Rt=(wt=(_e=C.querySelector("BaseURL"))==null?void 0:_e.textContent)==null?void 0:wt.trim())!=null?Rt:"",Ke=new URL(ii||o,e).toString(),ke=(Ht=C.getAttribute("mimeType"))!=null?Ht:Lt,ri=(Li=(ei=C.getAttribute("codecs"))!=null?ei:Qi)!=null?Li:"",si;if(Yi==="text"){let Re=C.getAttribute("id")||"",ai=((Ts=ra.privateuse)==null?void 0:Ts.includes("x-auto"))||Re.includes("_auto"),Xe=C.querySelector("SegmentTemplate");if(Xe){let $t={representationId:(Is=C.getAttribute("id"))!=null?Is:void 0,bandwidth:(xs=C.getAttribute("bandwidth"))!=null?xs:void 0},ni=parseInt((Es=C.getAttribute("bandwidth"))!=null?Es:"",10)/1e3,oi=(Ps=parseInt((ws=Xe.getAttribute("startNumber"))!=null?ws:"",10))!=null?Ps:1,ht=parseInt((As=Xe.getAttribute("timescale"))!=null?As:"",10),Ki=(ks=Xe.querySelectorAll("SegmentTimeline S"))!=null?ks:[],ft=Xe.getAttribute("media");if(!ft)continue;let ui=[],li=0,ci="",mt=0,Dt=oi,Z=0;for(let de of Ki){let Je=parseInt((Rs=de.getAttribute("d"))!=null?Rs:"",10),ae=parseInt((Ls=de.getAttribute("r"))!=null?Ls:"",10)||0,Le=parseInt((Ms=de.getAttribute("t"))!=null?Ms:"",10);Z=Number.isFinite(Le)?Le:Z;let Ze=Je/ht*1e3,Me=Z/ht*1e3;for(let me=0;me<ae+1;me++){let $e=wi(ft,{...$t,segmentNumber:Dt.toString(10),segmentTime:(Z+me*Je).toString(10)}),bt=(Me!=null?Me:0)+me*Ze,Ct=bt+Ze;Dt++,ui.push({time:{from:bt,to:Ct},url:$e})}Z+=(ae+1)*Je,li+=(ae+1)*Ze}mt=Z/ht*1e3,ci=wi(ft,{...$t,segmentNumber:Dt.toString(10),segmentTime:Z.toString(10)});let Bt={time:{from:mt,to:1/0},url:ci},xe={type:"template",baseUrl:Ke,segmentTemplateUrl:ft,initUrl:"",totalSegmentsDurationMs:li,segments:ui,nextSegmentBeyondManifest:Bt,timescale:ht};si={id:Re,kind:"text",segmentReference:xe,profiles:[],duration:S,bitrate:ni,mime:"",codecs:"",width:0,height:0,isAuto:ai}}else si={id:Re,isAuto:ai,kind:"text",url:Ke}}else{let Re=(Ds=($s=C.getAttribute("contentType"))!=null?$s:ke==null?void 0:ke.split("/")[0])!=null?Ds:Yi,ai=(Cs=(Bs=_.getAttribute("profiles"))==null?void 0:Bs.split(","))!=null?Cs:[],Xe=parseInt((Vs=C.getAttribute("width"))!=null?Vs:"",10),$t=parseInt((Os=C.getAttribute("height"))!=null?Os:"",10),ni=parseInt((_s=C.getAttribute("bandwidth"))!=null?_s:"",10)/1e3,oi=(Fs=C.getAttribute("frameRate"))!=null?Fs:"",ht=(Ns=C.getAttribute("quality"))!=null?Ns:void 0,Ki=oi?Ou(oi):void 0,ft=(Us=C.getAttribute("id"))!=null?Us:"id"+(E++).toString(10),ui=Re==="video"?`${$t}p`:Re==="audio"?`${ni}Kbps`:ri,li=`${ft}@${ui}`,ci=[...V,...Bl,...ai],mt,Dt=C.querySelector("SegmentBase"),Z=(qs=C.querySelector("SegmentTemplate"))!=null?qs:Vl;if(Dt){let xe=(Hs=(js=C.querySelector("SegmentBase Initialization"))==null?void 0:js.getAttribute("range"))!=null?Hs:"",[de,Je]=xe.split("-").map($e=>parseInt($e,10)),ae={from:de,to:Je},Le=(Ws=C.querySelector("SegmentBase"))==null?void 0:Ws.getAttribute("indexRange"),[Ze,Me]=Le?Le.split("-").map($e=>parseInt($e,10)):[],me=Le?{from:Ze,to:Me}:void 0;mt={type:"byteRange",url:Ke,initRange:ae,indexRange:me}}else if(Z){let xe={representationId:(zs=C.getAttribute("id"))!=null?zs:void 0,bandwidth:(Gs=C.getAttribute("bandwidth"))!=null?Gs:void 0},de=parseInt((Qs=Z.getAttribute("timescale"))!=null?Qs:"",10),Je=(Ys=Z.getAttribute("initialization"))!=null?Ys:"",ae=Z.getAttribute("media"),Le=(Xs=parseInt((Ks=Z.getAttribute("startNumber"))!=null?Ks:"",10))!=null?Xs:1,Ze=wi(Je,xe);if(!ae)throw new ReferenceError("No media attribute in SegmentTemplate");let Me=(Js=Z.querySelectorAll("SegmentTimeline S"))!=null?Js:[],me=[],$e=0,bt="",Ct=0;if(Me.length){let di=Le,pe=0;for(let gt of Me){let be=parseInt((Zs=gt.getAttribute("d"))!=null?Zs:"",10),et=parseInt((ea=gt.getAttribute("r"))!=null?ea:"",10)||0,pi=parseInt((ta=gt.getAttribute("t"))!=null?ta:"",10);pe=Number.isFinite(pi)?pi:pe;let Xi=be/de*1e3,Ji=pe/de*1e3;for(let hi=0;hi<et+1;hi++){let Fl=wi(ae,{...xe,segmentNumber:di.toString(10),segmentTime:(pe+hi*be).toString(10)}),sa=(Ji!=null?Ji:0)+hi*Xi,Nl=sa+Xi;di++,me.push({time:{from:sa,to:Nl},url:Fl})}pe+=(et+1)*be,$e+=(et+1)*Xi}Ct=pe/de*1e3,bt=wi(ae,{...xe,segmentNumber:di.toString(10),segmentTime:pe.toString(10)})}else if(sV(S)){let pe=parseInt((ia=Z.getAttribute("duration"))!=null?ia:"",10)/de*1e3,gt=Math.ceil(S/pe),be=0;for(let et=1;et<gt;et++){let pi=wi(ae,{...xe,segmentNumber:et.toString(10),segmentTime:be.toString(10)});me.push({time:{from:be,to:be+pe},url:pi}),be+=pe}Ct=be,bt=wi(ae,{...xe,segmentNumber:gt.toString(10),segmentTime:be.toString(10)})}let _l={time:{from:Ct,to:1/0},url:bt};mt={type:"template",baseUrl:Ke,segmentTemplateUrl:ae,initUrl:Ze,totalSegmentsDurationMs:$e,segments:me,nextSegmentBeyondManifest:_l,timescale:de}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Re||!ke)continue;let Bt={video:"video",audio:"audio",text:"text"}[Re];if(!Bt)continue;pt||(pt=Bt),si={id:li,kind:Bt,segmentReference:mt,profiles:ci,duration:S,bitrate:ni,mime:ke,codecs:ri,width:Xe,height:$t,fps:Ki,quality:ht}}W.language||(W.language=Ae),W.label||(W.label=Mt),W.mime||(W.mime=ke),W.codecs||(W.codecs=ri),W.hdr||(W.hdr=pt==="video"&&rs(ri)),W.representations.push(si)}if(pt){let C=r[pt].find(Ae=>Ae.id===W.id);if(C&&W.representations.every(Ae=>st(Ae.segmentReference)))for(let Ae of C.representations){let Mt=W.representations.find(ke=>ke.id===Ae.id),ii=Mt==null?void 0:Mt.segmentReference,Ke=Ae.segmentReference;Ke.segments.push(...ii.segments),Ke.nextSegmentBeyondManifest=ii.nextSegmentBeyondManifest}else r[pt].push(W)}}return{duration:S,streams:r,baseUrls:n,live:g}};var no=class{constructor(e,t,i,{fetcher:r,tuning:a,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new Ir(0);this.currentLowLatencySegmentLength$=new Ir(0);this.currentSegmentLength$=new Ir(0);this.onLastSegment$=new Ir(!1);this.fullyBuffered$=new Ir(!1);this.playingRepresentation$=new Ir(void 0);this.playingRepresentationInit$=new Ir(void 0);this.error$=new nV;this.gaps=[];this.subscription=new oV;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new se;this.switchAbortController=new se;this.destroyAbortController=new se;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=Hi(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);dt(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new cx(this.sourceBuffer),this.subscription.add(ih(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:Pi.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o!=null||(o={id:"SegmentEjection",category:Pi.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),this.error$.next(o)})),this.subscription.add(ih(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:Pi.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o||!z(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,es(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=Ce(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);dt(i,"No init buffer for starting representation"),dt(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=Hi(this.destroyAbortController.signal,async function*(e,t=!1){if(!z(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);dt(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),dt(r,"No segments for starting representation"),a=this.initData.get(e),!(!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer||!z(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();hs(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=Hi(this.destroyAbortController.signal,async function*(e,t=!1){if(!z(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);dt(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),dt(r,"No segments for starting representation"),a=this.initData.get(e),!(!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer||!z(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();hs(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=Hi(this.destroyAbortController.signal,async function*(e){var u,l;let t=(u=(0,cl.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||!st(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);dt(r);let a=this.segments.get(i);dt(a,"No segments for starting representation");let n=this.initData.get(i);if(dt(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){!z(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new se,Hi(this.switchAbortController.signal,async function*(i,r=!1){this.switchingToRepresentationId=i;let a=this.representations.get(i);dt(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),dt(n,"No segments for starting representation"),o=this.initData.get(i),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer||!z(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();hs(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 se,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(Qe(e)||Qe(this.downloadingRepresentationId)||Qe(this.playingRepresentationId)||Qe(this.sourceBuffer)||!z(this.mediaSource,this.sourceBuffer)||hs(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(dt(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;let r=i.find(d=>e>=d.time.from&&e<d.time.to);hs(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=Ce(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)&&es(this.sourceBuffer.buffered)>=this.bufferLimit){let d=Ce(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,ll.default)(u,r))d="high";else{let c=(0,fs.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)&&Ce(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let l=(0,fs.default)(i,-1);!this.isLive&&l&&(this.fullyBuffered$.next(l.time.to-e-Ce(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}),i=a.time.to;hs(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,cl.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,cl.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||!st(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,fs.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;dt(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(!st(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=wi(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;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)==null||e.destroy(),this.gapDetectionIdleCallback&&Xt&&Xt(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&Xt&&Xt(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){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=e.findIndex(({status:c,time:{from:h,to:p}},f)=>{let m=h<=i&&p>=i,g=h>i||m||f===0&&i===0,S=Math.min(this.forwardBufferTarget,this.bufferLimit),y=this.preloadOnly&&h<=i+S||p<=i+S;return(c==="none"||c==="partially_ejected"&&g&&y&&this.sourceBuffer&&z(this.mediaSource,this.sourceBuffer)&&!(ze(this.sourceBuffer.buffered,h)&&ze(this.sourceBuffer.buffered,p)))&&g&&y});if(r===-1)return null;if(t!=="byteRange")return e.slice(r,r+1);let a=e,n=0,o=0,u=[],l=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,d=this.preloadOnly?this.forwardBufferTarget:0;for(let c=r;c<a.length&&(n<=l||o<=d);c++){let h=a[c];if(n+=h.byte.to+1-h.byte.from,o+=h.time.to+1-h.time.from,h.status==="none"||h.status==="partially_ejected")u.push(h);else break}return u}async loadSegments(e,t,i="auto"){st(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 Hi(o,async function*(){let d=rh(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=ul(),!d)return;let c=new DataView(d),h=so(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]),ao(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())st(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 Hi(n,async function*(){let u=rh(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),ih(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=ul(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),ao(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(st(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:(0,fs.default)(e,0).byte.from,to:(0,fs.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=ul(),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:Pi.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!st(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=ul();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:Pi.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,ll.default)(e,t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:a}){if(!this.activeSegments.size||!z(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=so(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||!z(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:so(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)||!z(this.mediaSource,this.sourceBuffer))){!this.isLive&&j.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(ze(this.sourceBuffer.buffered,e.segment.time.from,100)&&ze(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:Pi.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",Jp(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=Zr(()=>(0,Lx.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?Hi(this.destroyAbortController.signal,async function*(){let o=rh(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,so(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&&st(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:Pi.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||!z(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||Qe(e))return!1;let r=[],a=0,n=o=>{var l;if(a>=t)return;r.push({...o.time});let u=Jp(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,ll.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=xx(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||!z(this.mediaSource,this.sourceBuffer))return!1;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;return this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!z(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}getBufferedTo(){return!this.sourceBuffer||!z(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length?null:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}getForwardBufferDuration(e=this.getCurrentPosition()){return!this.sourceBuffer||!z(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||Qe(e)?0:Ce(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!this.sourceBuffer||!z(this.mediaSource,this.sourceBuffer))return;if(this.tuning.useRefactoredSearchGap)for(let r=0;r<this.sourceBuffer.buffered.length;r++)this.gaps=this.gaps.filter(a=>this.sourceBuffer&&(Math.round(a.from)<Math.round(this.sourceBuffer.buffered.start(r)*1e3)||Math.round(a.to)>Math.round(this.sourceBuffer.buffered.end(r)*1e3)));let i={representation:e,from:t.time.from,to:t.time.to};for(let r=0;r<this.sourceBuffer.buffered.length;r++){let a=this.sourceBuffer.buffered.start(r)*1e3,n=this.sourceBuffer.buffered.end(r)*1e3;if(!(n<=t.time.from||a>=t.time.to)){if(a<=t.time.from&&n>=t.time.to){i=void 0;break}n>t.time.from&&n<t.time.to&&(i.from=n),a<t.time.to&&a>t.time.from&&(i.to=a)}}i&&i.to-i.from>1&&!this.gaps.some(r=>i&&r.from===i.from&&r.to===i.to)&&this.gaps.push(i)}detectGapsWhenIdle(e,t){if(!(this.gapDetectionIdleCallback||!this.sourceBuffer||!z(this.mediaSource,this.sourceBuffer))){if(!this.tuning.useRefactoredSearchGap)for(let i=0;i<this.sourceBuffer.buffered.length;i++)this.gaps=this.gaps.filter(r=>this.sourceBuffer&&(Math.round(r.from)<Math.round(this.sourceBuffer.buffered.start(i)*1e3)||Math.round(r.to)>Math.round(this.sourceBuffer.buffered.end(i)*1e3)));this.gapDetectionIdleCallback=Zr(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:Pi.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if(Qe(this.sourceBuffer)||!z(this.mediaSource,this.sourceBuffer)||Qe(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:Pi.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}};import{abortable as oo,assertNever as Mx,fromEvent as $x,merge as uV,now as uo,Subject as Dx,ValueSubject as sh,flattenObject as ms,ErrorCategory as lo,SubscriptionRemovable as lV}from"@vkontakte/videoplayer-shared/es2018";var pl=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:a=!1}){this.lastConnectionType$=new sh(void 0);this.lastConnectionReused$=new sh(void 0);this.lastRequestFirstBytes$=new sh(void 0);this.recoverableError$=new Dx;this.error$=new Dx;this.abortAllController=new se;this.subscription=new lV;this.fetchManifest=oo(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=Ui(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=qu(i));let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(dl);return r?(t.log("success",ms({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(r.headers),r.text()):(t.error("error",ms({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=oo(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 $,M,G;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 q=new URL(l,location.href);q.searchParams.append("bytes",`${i.from}-${i.to}`),l=q.toString();break}default:Mx(t)}this.requestQuic&&(l=Ui(l));let h=this.abortAllController.signal,p;if(n){let q=new se;if(p=uV($x(this.abortAllController.signal,"abort"),$x(n,"abort")).subscribe(()=>{try{q.abort()}catch(w){dl(w)}}),this.abortAllController.signal.aborted||n.aborted)try{q.abort()}catch(w){dl(w)}h=q.signal}let f=uo();c.log("startRequest",ms({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=uo();if(!m)return c.error("error",{message:"No response in request"}),c.end(),this.unsubscribeAbortSubscription(p),null;if(($=this.throughputEstimator)==null||$.addRawRtt(g-f),!m.ok||!m.body){this.unsubscribeAbortSubscription(p);let q=`Fetch error ${m.status}: ${m.statusText}`;return c.error("error",{message:q}),c.end(),Promise.reject(new Error(`Fetch error ${m.status}: ${m.statusText}`))}if(this.onHeadersReceived(m.headers),!r&&!o){this.unsubscribeAbortSubscription(p);let q=uo(),w={requestStartedAt:f,requestEndedAt:q,duration:q-f};return c.log("endRequest",ms(w)),c.end(),m.arrayBuffer()}let S=m.body;if(o){let q;[S,q]=m.body.tee(),(M=this.throughputEstimator)==null||M.trackStream(q,u)}let y=S.getReader(),v,I=parseInt((G=m.headers.get("content-length"))!=null?G:"",10);Number.isFinite(I)&&(v=I),!v&&i&&(v=i.to-i.from+1);let T=0,E=v?new Uint8Array(v):new Uint8Array(0),V=!1,L=q=>{this.unsubscribeAbortSubscription(p),V=!0,dl(q)},k=oo(h,async function*({done:q,value:w}){if(T===0&&this.lastRequestFirstBytes$.next(uo()-f),h.aborted){this.unsubscribeAbortSubscription(p);return}if(!q&&w){if(v)E.set(w,T),T+=w.byteLength;else{let N=new Uint8Array(E.length+w.length);N.set(E),N.set(w,E.length),E=N,T+=w.byteLength}r==null||r(new DataView(E.buffer),T),yield y==null?void 0:y.read().then(k,L)}}.bind(this));yield y==null?void 0:y.read().then(k,L),this.unsubscribeAbortSubscription(p);let P=uo(),O={failed:V,requestStartedAt:f,requestEndedAt:P,duration:P-f};return V?(c.error("endRequest",ms(O)),c.end(),null):(c.log("endRequest",ms(O)),c.end(),E.buffer)}.bind(this));this.fetchByteRangeRepresentation=oo(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 y=yield this.fetch(e.url,{range:f,priority:i,measureThroughput:!1});if(!y)return null;m=new DataView(y)}let g=t.parseSegments(m,p,f);return{init:p,dataView:new DataView(c),segments:g}}.bind(this));this.fetchTemplateRepresentation=oo(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}=Uu(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:Mx(r)}}destroy(){this.abortAllController.abort(),this.tracer.end(),this.subscription.unsubscribe()}async doFetch(e,t){let i=await At(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:lo.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:lo.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:lo.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:lo.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${a})`,category:lo.FATAL})}}unsubscribeAbortSubscription(e){e&&(e.unsubscribe(),this.subscription.remove(e))}},dl=s=>{if(!ao(s))throw s};import{isNullable as cV,ValueSubject as dV}from"@vkontakte/videoplayer-shared/es2018";var co=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&&st(t.segmentReference))}};var gV=["timeupdate","progress","play","seeked","stalled","waiting"],SV=["timeupdate","progress","loadeddata","playing","seeked"];var ml=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new lh;this.representationSubscription=new lh;this.state$=new H("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 fl;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 fl;this.fetcherError$=new fl;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new fl;this.gapWatchdogActive=!1;this.destroyController=new se;this.initManifest=nh(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:Zt.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=nh(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:Zt.NETWORK,message:"Failed to load manifest",thrown:u})});if(!e)return null;let t=null;try{t=Rx(e!=null?e:"",this.manifestUrlString)}catch(u){let l=(n=Vu(e))!=null?n:{id:"ManifestParsing",category:Zt.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=xt())==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=Xu(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",ho(a)),a}.bind(this));this.initRepresentations=nh(this.destroyController.signal,async function*(e,t,i){var h;this.tracer.log("initRepresentationsStart",ho({initialVideo:e,initialAudio:t,sourceHls:i})),bs(this.manifest),bs(this.element),this.representationSubscription.unsubscribe(),this.representationSubscription=new lh,this.state$.startTransitionTo("representations_ready");let r=p=>{this.representationSubscription.add(Ai(p,"error").pipe(hl(f=>{var m;return!!((m=this.element)!=null&&m.played.length)})).subscribe(f=>{this.error$.next({id:"VideoSource",category:Zt.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:f})}))};this.source=this.tuning.useManagedMediaSource?hu():new MediaSource;let a=document.createElement("source");if(r(a),a.src=URL.createObjectURL(this.source),this.element.appendChild(a),this.tuning.useManagedMediaSource&&Wr())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 no("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],fo(t)){let p=this.manifest.streams.audio.reduce((f,m)=>[...f,...m.representations],[]);this.audioBufferManager=new no("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}co.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new co(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(xr(...SV.map(p=>Ai(this.element,p))).pipe(Ss(p=>this.element?Ce(this.element.buffered,this.element.currentTime*1e3):0),po(),mV(p=>{p>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add(xr(Ai(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe(po()).subscribe(f=>this.liveStreamEndTimestamp=uh())),this.subscription.add(Ai(this.element,"pause").subscribe(()=>{this.livePauseWatchdogSubscription=oh(1e3).subscribe(f=>{let m=Bi(this.manifestUrlString,2);this.manifestUrlString=Se(this.manifestUrlString,m+1e3,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add(Ai(this.element,"play").subscribe(f=>{var m;return(m=this.livePauseWatchdogSubscription)==null?void 0:m.unsubscribe()})),this.representationSubscription.add(gs({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(Ss(({isActiveLive:f,isLowLatency:m})=>f&&m),po()).subscribe(f=>{this.isManualDecreasePlaybackInLive()||os(this.element,1)})),this.representationSubscription.add(gs({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(hl(({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(gs({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(hl(({isLive:f})=>f),po((f,m)=>m.bufferLength<f.bufferLength),Ss(({rtt:f,bufferLength:m,segmentServerLatency:g})=>{let S=Bi(this.manifestUrlString,2);return(f/2+m+g+S)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(gs({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,y=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,v=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,I=f-S;if(this.isManualDecreasePlaybackInLive())return;let T=1;Math.abs(I)>y&&(T=1+Math.sign(I)*v),os(this.element,T)})),this.representationSubscription.add(this.bufferLength$.subscribe(f=>{var g,S;let m=0;if(f){let y=((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:y}))-y}this.liveLoadBufferLength$.getValue()!==m&&this.liveLoadBufferLength$.next(m)}));let p=0;this.representationSubscription.add(gs({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(bV(1e3)).subscribe(async({liveLoadBufferLength:f,bufferLength:m})=>{if(!this.element||this.isUpdatingLive)return;let g=this.element.playbackRate,S=Bi(this.manifestUrlString,2),y=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,v=Math.min(y,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*g),I=this.tuning.dashCmafLive.normalizedActualBufferOffset*g,T=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*g,E=isFinite(f)?f:m,V=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),L=y<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(L);let k="none";if(V?k="active_low_latency":this.isLowLatency$.getValue()&&L?(this.bufferManagers.forEach(P=>P.proceedLowLatencyLive()),k="active_low_latency"):S!==0&&E<v?k="live_forward_buffering":E<v+T&&(k="live_with_target_offset"),isFinite(f)&&(p=f>p?f:p),k==="live_forward_buffering"||k==="live_with_target_offset"){let P=p-(v+I),O=this.normolizeLiveOffset(Math.trunc(S+P/g)),$=Math.abs(O-S),M=0;!f||$<=this.tuning.dashCmafLive.offsetCalculationError?M=S:O>0&&$>this.tuning.dashCmafLive.offsetCalculationError&&(M=O),this.manifestUrlString=Se(this.manifestUrlString,M,2)}(k==="live_with_target_offset"||k==="live_forward_buffering")&&(p=0,await this.updateLive())},f=>{this.error$.next({id:"updateLive",category:Zt.VIDEO_PIPELINE,thrown:f,message:"Failed to update live with subscription"})}))}let l=xr(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe(Ss(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),d=xr(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe(Ss(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue()))),c=gs({allBuffersFull:l,someBufferEnded:d}).pipe(po(),Ss(({allBuffersFull:p,someBufferEnded:f})=>p&&f),hl(p=>p));if(this.representationSubscription.add(xr(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:Zt.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:f})}})),this.representationSubscription.add(xr(...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,m)=>{var g;p&&(this.timeoutSourceOpenId=setTimeout(()=>{var S;if(((S=this.source)==null?void 0:S.readyState)==="open"){f();return}this.tuning.dash.rejectOnSourceOpenTimeout?m(new Error("Timeout reject when wait sourceopen event")):f()},this.tuning.dash.sourceOpenTimeout)),(g=this.source)==null||g.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),f()},{once:!0})})}if(!this.isLive$.getValue()){let p=[(h=this.manifest.duration)!=null?h:0,...(0,ch.default)((0,ch.default)([...this.manifest.streams.audio,...this.manifest.streams.video],f=>f.representations),f=>{let m=[];return f.duration&&m.push(f.duration),st(f.segmentReference)&&f.segmentReference.totalSegmentsDurationMs&&m.push(f.segmentReference.totalSegmentsDurationMs),m})];this.source.duration=Math.max(...p)/1e3}this.audioBufferManager&&fo(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=oh(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),n=>{this.error$.next({id:"GapWatchdog",category:Zt.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 pl({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=Ii.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator}),this.initTracerSubscription()}async seekLive(e){var r,a,n;bs(this.element);let t=this.liveStreamStatus$.getValue()!=="active"?uh()-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(){bs(this.element),this.state$.setState("running"),this.subscription.add(xr(...gV.map(e=>Ai(this.element,e)),Ai(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:Zt.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(Ai(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(Ai(this.element,"waiting").subscribe(()=>{var t;this.element&&this.element.readyState===HTMLMediaElement.HAVE_CURRENT_DATA&&!this.element.seeking&&ze(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{var p,f,m,g,S,y,v,I,T,E,V;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=uh(),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=(v=(y=this.videoBufferManager)==null?void 0:y.getForwardBufferDuration())!=null?v: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 L=this.normolizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(L).catch(k=>{this.error$.next({id:"stallIntervalCallback",category:Zt.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:k})}),r.liveLastOffset=L}else{let L=this.element.currentTime*1e3;(E=this.videoBufferManager)==null||E.maintain(L),(V=this.audioBufferManager)==null||V.maintain(L),r.position=L}this.tracer.log("stallIntervalCallback",ho(r))};(t=this.stallWatchdogSubscription)==null||t.unsubscribe(),this.stallWatchdogSubscription=oh(50).subscribe(e,i=>{this.error$.next({id:"StallWatchdogCallback",category:Zt.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;bs(this.element),bs(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),ze(this.element.buffered,i)||await Promise.all([this.videoBufferManager.abort(),(o=this.audioBufferManager)==null?void 0:o.abort()]),!(Cx(this.element)||Cx(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),(u=this.audioBufferManager)==null||u.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",ho({requestedPosition:e,forcePrecise:t,position:i})))}warmUpMediaSourceIfNeeded(e=(t=>(t=this.element)==null?void 0:t.currentTime)()){var i;fo(this.element)&&fo(this.source)&&fo(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();this.isJumpGapAfterSeekLive&&!t&&this.element.currentTime>e&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let i=this.element.currentTime*1e3,r=null,a=this.element.readyState===HTMLMediaElement.HAVE_METADATA?this.tuning.endGapTolerance:0;for(let n of this.bufferManagers)for(let o of n.gaps)n.playingRepresentation$.getValue()===o.representation&&o.from-a<=i&&o.to+a>i&&(this.element.duration*1e3-o.to<this.tuning.endGapTolerance?r=1/0:(r===null||o.to>r)&&(r=o.to));if(r!==null){let n=r+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,n===1/0?this.forceEnded$.next():(this.element.currentTime=n/1e3,this.tracer.log("jumpGap",ho({isJumpGapAfterSeekLive:this.isJumpGapAfterSeekLive,isActiveLowLatency:t,initialCurrentTime:this.element.currentTime,jumpTo:n,resultCurrentTime:this.element.currentTime})))}}};import{combine as vV,map as yV,observeElementSize as TV,Subscription as IV,ValueSubject as dh,noop as xV}from"@vkontakte/videoplayer-shared/es2018";var bl=class{constructor(){this.subscription=new IV;this.pipSize$=new dh(void 0);this.videoSize$=new dh(void 0);this.elementSize$=new dh(void 0);this.pictureInPictureWindowRemoveEventListener=xV}connect({observableVideo:e,video:t}){let i=r=>{let a=r.target;this.pipSize$.next({width:a.width,height:a.height})};this.subscription.add(TV(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(vV({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(yV(({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 Er=class{constructor(e){this.subscription=new RV;this.videoState=new H("stopped");this.droppedFramesManager=new Xr;this.stallsManager=new sl;this.elementSizeManager=new bl;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"),R(this.params.desiredState.playbackState,"stopped",!0));return}switch(e){case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();return;case"ready":t==="paused"?(this.videoState.setState("paused"),R(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="ready"&&R(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):t==="playing"&&this.video.paused?this.playIfAllowed():(i==null?void 0:i.to)==="playing"&&R(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&R(this.params.desiredState.playbackState,"paused");return;default:return wV(e)}}};this.init3DScene=e=>{var i,r,a;if(this.scene3D)return;this.scene3D=new ds(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((i=e.projectionData)==null?void 0:i.pose.yaw)||0,y:((r=e.projectionData)==null?void 0:r.pose.pitch)||0,z:((a=e.projectionData)==null?void 0:a.pose.roll)||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSizeManager.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.textTracksManager=new ot(e.source.url),this.params=e,this.video=Ue(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(we(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 ml({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,i=He(this.video);this.subscription.add(()=>i.destroy());let r=this.constructor.name,a=o=>{e.error$.next({id:r,category:Vx.WTF,message:`${r} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:i,genericErrorListener:a,connect:(o,u)=>this.subscription.add(o.subscribe(u,a))}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:a}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(Ox(l=>!!l.length),Fx()).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(ph(l=>l.to.state!=="none"),gl());this.stallsManager.connect({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(Ox(_x),Fx()),e.firstBytesEvent$),a(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),a(this.videoState.stateChangeEnded$.pipe(ph(l=>l.to)),this.params.output.playbackState$),this.subscription.add(i.loopExpected$.subscribe(l=>{t.seekState.setState({state:"requested",position:0,forcePrecise:!1})})),this.subscription.add(i.looped$.subscribe(()=>this.player.warmUpMediaSourceIfNeeded(),r)),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(Pt(this.video,t.isLooped,r)),this.subscription.add(je(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(nt(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),a(lt(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),R(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),R(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:l})=>{if(l==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let d=this.player.getStreams();if(PV(d,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let h=[];for(let p of d.audio){h.push(Kp(p));let f=[];for(let m of p.representations){let g=yx(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(Xp(h));let p=[];for(let f of h.representations){let m=vx({...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=Tx(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(Sl(this.player.currentStallDuration$,this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,t.videoStream.stateChangeStarted$,t.audioStream.stateChangeStarted$,this.elementSizeManager.getObservable(),this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,kV(this.video,"progress")).subscribe(async()=>{let l=this.player.state$.getState(),d=this.player.state$.getTransition();if(l!=="manifest_ready"&&l!=="running"||d)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState()),this.selectVideoAudioRepresentations();let{video:c,audio:h}=this.selectedRepresentations;if(!c)return;let p=Tr(this.videoTracksMap.keys(),m=>{var g;return((g=this.videoTracksMap.get(m))==null?void 0:g.representation.id)===c.id});_x(p)&&(this.stallsManager.lastVideoTrackSelected=p);let f=this.params.desiredState.autoVideoTrackLimits.getTransition();if(f&&this.params.output.autoVideoTrackLimits$.next(f.to),l==="manifest_ready")await this.player.initRepresentations(c.id,h==null?void 0:h.id,this.params.sourceHls);else if(await this.player.switchRepresentation("video",c.id),h){let m=!!t.audioStream.getTransition();await this.player.switchRepresentation("audio",h.id,m)}},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(gl()).subscribe(l=>{let d=Tr(this.videoTracksMap.entries(),([,{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(Xp(h))},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(gl()).subscribe(l=>{let d=Tr(this.audioTracksMap.entries(),([,{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(Kp(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(ph(({to:l})=>l==="ready"),gl());this.subscription.add(Sl(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,hh(["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(Sl(o,this.player.state$.stateChangeEnded$,hh(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let u=Sl(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,hh(["init"])).pipe(AV(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){var L,k,P,O,$,M,G,q,w,N,A,x;if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?Va:Ca,t=this.params.tuning.useNewAutoSelectVideoTrack?Ru:ku,i=this.params.tuning.useNewAutoSelectVideoTrack?Kt:Au,{desiredState:r,output:a}=this.params,n=r.autoVideoTrackSwitching.getState(),o=(L=r.videoTrack.getState())==null?void 0:L.id,u=Tr(this.videoTracksMap.keys(),D=>D.id===o),l=a.currentVideoTrack$.getValue(),d=((O=(P=r.videoStream.getState())!=null?P:u&&((k=this.videoTracksMap.get(u))==null?void 0:k.stream))!=null?O:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!d)return;let c=Tr(this.videoStreamsMap.keys(),D=>D.id===d.id),h=c&&this.videoStreamsMap.get(c);if(!h)return;let p=Ce(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=($=r.audioStream.getState())!=null?$:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,y=(S==null?void 0:S.id)&&Tr(this.audioStreamsMap.keys(),D=>D.id===S.id)||this.audioStreamsMap.keys().next().value,v=0;if(y){if(u&&!n){let D=e(u,h,(M=this.audioStreamsMap.get(y))!=null?M:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);v=Math.max(v,(G=D==null?void 0:D.bitrate)!=null?G:-1/0)}if(l){let D=e(l,h,(q=this.audioStreamsMap.get(y))!=null?q:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);v=Math.max(v,(w=D==null?void 0:D.bitrate)!=null?w:-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:v,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=y&&t(I,h,(N=this.audioStreamsMap.get(y))!=null?N:[],{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=(A=this.videoTracksMap.get(I))==null?void 0:A.representation,V=T&&((x=this.audioTracksMap.get(T))==null?void 0:x.representation);E&&V?(this.selectedRepresentations.video=E,this.selectedRepresentations.audio=V):E&&!V&&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(){We(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),R(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Vx.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),qe(this.video),this.tracer.end()}};var mo=class extends Er{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 fh,merge as Nx,filter as Ux,filterChanged as LV,isNullable as mh,map as qx,ValueSubject as bh,isNonNullable as MV}from"@vkontakte/videoplayer-shared/es2018";var bo=class extends Er{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 bh(1);a(i.playbackRateState$,n),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(r.isLowLatency.stateChangeEnded$.pipe(qx(o=>o.to)).subscribe(this.player.isLowLatency$)).add(fh({liveBufferTime:t.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(qx(({liveBufferTime:o,liveAvailabilityStartTime:u})=>o&&u?o+u:void 0)).subscribe(t.liveTime$)).add(this.player.liveStreamStatus$.pipe(Ux(o=>MV(o))).subscribe(o=>t.isLiveEnded$.next(o!=="active"&&t.position$.getValue()===0))).add(fh({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:Nx(i.playbackRateState$,new bh(1))}).pipe(Ux(({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||mh(l)||(e=o-l)})).add(fh({time:t.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:Nx(i.playbackRateState$,new bh(1))}).pipe(LV((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||mh(o)||mh(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=Ix(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 Hx=U(ka(),1);import{assertNever as go,assertNonNullable as jx,debounce as $V,ErrorCategory as vl,filter as DV,isNonNullable as BV,isNullable as CV,map as yl,merge as VV,Observable as OV,observableFrom as _V,Subscription as FV,videoSizeToQuality as NV}from"@vkontakte/videoplayer-shared/es2018";var jt={};var vs=(s,e)=>new OV(t=>{let i=(r,a)=>t.next(a);return s.on(e,i),()=>s.off(e,i)}),So=class{constructor(e){this.subscription=new FV;this.videoState=new H("initializing");this.trackLevels=new Map;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(e!=="initializing")switch((i==null?void 0:i.to)!=="paused"&&r.state==="requested"&&this.seek(r.position),t){case"stopped":switch(e){case"stopped":break;case"ready":case"playing":case"paused":this.stop();break;default:go(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:go(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:go(e)}break;case"paused":switch(e){case"paused":break;case"stopped":this.prepare();break;case"ready":this.videoState.setState("paused"),R(this.params.desiredState.playbackState,"paused");break;case"playing":this.pause();break;default:go(e)}break;default:go(t)}};this.textTracksManager=new ot(e.source.url),this.video=Ue(e.container,e.tuning),this.params=e,this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(we(this.params.source.url)),this.loadHlsJs()}destroy(){var e,t;this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),(e=this.hls)==null||e.detachMedia(),(t=this.hls)==null||t.destroy(),this.params.output.element$.next(void 0),qe(this.video)}loadHlsJs(){let e=!1,t=r=>{e||this.params.output.error$.next({id:r==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:vl.NETWORK,message:"Failed to load Hls.js",thrown:r}),e=!0},i=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);(0,Hx.default)(import("hls.js").then(r=>{e||(jt.Hls=r.default,jt.Events=r.default.Events,this.init())},t),()=>{window.clearTimeout(i),e=!0})}init(){jx(jt.Hls,"hls.js not loaded"),this.hls=new jt.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){jx(jt.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,i=l=>{t.error$.next({id:"HlsJsProvider",category:vl.WTF,message:"HlsJsProvider internal logic error",thrown:l})},r=He(this.video);this.subscription.add(()=>r.destroy());let a=(l,d)=>this.subscription.add(l.subscribe(d,i));a(r.timeUpdate$,t.position$),a(r.durationChange$,t.duration$),a(r.ended$,t.endedEvent$),a(r.looped$,t.loopedEvent$),a(r.error$,t.error$),a(r.isBuffering$,t.isBuffering$),a(r.currentBuffer$,t.currentBuffer$),a(r.loadStart$,t.firstBytesEvent$),a(r.loadedMetadata$,t.loadedMetadataEvent$),a(r.playing$,t.firstFrameEvent$),a(r.canplay$,t.canplay$),a(r.seeked$,t.seekedEvent$),a(r.inPiP$,t.inPiP$),a(r.inFullscreen$,t.inFullscreen$),this.subscription.add(Pt(this.video,e.isLooped,i)),this.subscription.add(je(this.video,e.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(nt(this.video,e.playbackRate,r.playbackRateState$,i)),a(lt(this.video),t.elementVisible$),a(this.videoState.stateChangeEnded$.pipe(yl(l=>l.to)),this.params.output.playbackState$),this.subscription.add(vs(this.hls,jt.Events.ERROR).subscribe(l=>{var d;l.fatal&&t.error$.next({id:["HlsJsFatal",l.type,l.details].join("_"),category:vl.WTF,message:`HlsJs fatal ${l.type} ${l.details}, ${(d=l.err)==null?void 0:d.message} ${l.reason}`,thrown:l.error})})),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),R(e.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),R(e.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())==null?void 0:l.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),a(vs(this.hls,jt.Events.MANIFEST_PARSED).pipe(yl(({levels:l})=>l.reduce((d,c)=>{var y,v;let h=c.name||c.height.toString(10),{width:p,height:f}=c,m=(v=Yt((y=c.attrs.QUALITY)!=null?y:""))!=null?v:NV({width:p,height:f});if(!m)return d;let g=c.attrs["FRAME-RATE"]?parseFloat(c.attrs["FRAME-RATE"]):void 0,S={id:h.toString(),quality:m,bitrate:c.bitrate/1e3,size:{width:p,height:f},fps:g};return this.trackLevels.set(h,{track:S,level:c}),d.push(S),d},[]))),t.availableVideoTracks$),a(vs(this.hls,jt.Events.MANIFEST_PARSED),l=>{if(l.subtitleTracks.length>0){let d=[];for(let c of l.subtitleTracks){let h=c.name,p=c.attrs.URI||"",f=c.lang;d.push({id:h,url:p,language:f,type:"internal"})}e.internalTextTracks.startTransitionTo(d)}}),a(vs(this.hls,jt.Events.LEVEL_LOADING).pipe(yl(({url:l})=>we(l))),t.hostname$),a(vs(this.hls,jt.Events.FRAG_CHANGED),l=>{var h,p,f,m;let{video:d,audio:c}=l.frag.elementaryStreams;t.currentVideoSegmentLength$.next((((h=d==null?void 0:d.endPTS)!=null?h:0)-((p=d==null?void 0:d.startPTS)!=null?p:0))*1e3),t.currentAudioSegmentLength$.next((((f=c==null?void 0:c.endPTS)!=null?f:0)-((m=c==null?void 0:c.startPTS)!=null?m:0))*1e3)}),this.subscription.add(Ci(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,l=>{this.hls.nextLevel=l?-1:this.hls.currentLevel,this.hls.loadLevel=l?-1:this.hls.loadLevel},{onError:i}));let n=l=>{var d;return(d=Array.from(this.trackLevels.values()).find(({level:c})=>c===l))==null?void 0:d.track},o=vs(this.hls,jt.Events.LEVEL_SWITCHED).pipe(yl(({level:l})=>n(this.hls.levels[l])));o.pipe(DV(BV)).subscribe(t.currentVideoTrack$,i),this.subscription.add(Ci(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),l=>{var f;if(CV(l))return;let d=(f=this.trackLevels.get(l.id))==null?void 0:f.level;if(!d)return;let c=this.hls.levels.indexOf(d),h=this.hls.currentLevel,p=this.hls.levels[h];!p||d.bitrate>p.bitrate?this.hls.nextLevel=c:(this.hls.loadLevel=c,this.hls.loadLevel=c)},{changed$:o,onError:i})),a(r.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);let u=VV(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,_V(["init"])).pipe($V(0));this.subscription.add(u.subscribe(this.syncPlayback,i))}prepare(){this.videoState.startTransitionTo("ready"),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}async playIfAllowed(){this.videoState.startTransitionTo("playing"),await We(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:vl.DOM,thrown:t}))||(this.videoState.setState("paused"),R(this.params.desiredState.playbackState,"paused",!0))}pause(){this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.hls.stopLoad(),this.hls.detachMedia(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"),R(this.params.desiredState.playbackState,"stopped",!0)}};var Wx="X-Playback-Duration",gh=async s=>{var r;let e=await At(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(Wx)?parseInt(e.headers.get(Wx),10):void 0};import{assertNever as XV,combine as JV,debounce as ZV,ErrorCategory as xl,filter as eO,filterChanged as tO,isNonNullable as Qx,isNullable as El,map as Yx,merge as iO,observableFrom as rO,Subscription as sO,ValueSubject as yh,VideoQuality as aO}from"@vkontakte/videoplayer-shared/es2018";var vh=U(Yc(),1);import{videoSizeToQuality as UV,getExponentialDelay as qV}from"@vkontakte/videoplayer-shared/es2018";var jV=s=>{let e=null;if(s.QUALITY&&(e=Yt(s.QUALITY)),!e&&s.RESOLUTION){let[t,i]=s.RESOLUTION.split("x").map(r=>parseInt(r,10));e=UV({width:t,height:i})}return e!=null?e:null},HV=(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,vh.default)(l[1].split(",").map(y=>y.split("="))),h=(a=c.QUALITY)!=null?a:`stream-${c.BANDWIDTH}`,p=jV(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[y,v]=c.RESOLUTION.split("x").map(I=>parseInt(I,10));y&&v&&(g={width:y,height:v})}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,vh.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}},WV=s=>new Promise(e=>{setTimeout(()=>{e()},s)}),Sh=0,zx=async(s,e=s,t,i)=>{let a=await(await At(s,i)).text();Sh+=1;try{let{qualityManifests:n,textTracks:o}=HV(a,e);return{qualityManifests:n,textTracks:o}}catch(n){if(Sh<=t.manifestRetryMaxCount)return await WV(qV(Sh-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),zx(s,e,t)}return{qualityManifests:[],textTracks:[]}},Tl=zx;import{isNonNullable as zV,Subscription as GV,throttle as QV,ValueSubject as Gx,Subject as YV,ErrorCategory as KV}from"@vkontakte/videoplayer-shared/es2018";var Il=class{constructor(e,t,i,r,a){this.subscription=new GV;this.abortControllers={destroy:new se,nextManifest:null};this.prepareUrl=void 0;this.currentTextTrackData=null;this.availableTextTracks$=new Gx(null);this.getCurrentTime$=new Gx(null);this.error$=new YV;this.params={fetchManifestData:i,sourceUrl:r,downloadThreshold:a},this.subscription.add(e.pipe(QV(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 At(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(zV(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 se;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:KV.WTF,thrown:t,message:e})}};var vo=class{constructor(e){this.subscription=new sO;this.videoState=new H("stopped");this.textTracksManager=null;this.liveTextManager=null;this.manifests$=new yh([]);this.liveOffset=new pr;this.manifestStartTime$=new yh(void 0);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),R(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(a||n||o){let d=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(d),this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((r==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"?R(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),R(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&R(this.params.desiredState.playbackState,"playing");return;case"paused":if(i==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let d=this.liveOffset.getTotalOffset();d>=this.maxSeekBackTime$.getValue()&&(d=0,this.liveOffset.resetTo(d)),this.liveOffset.resume(),this.params.output.position$.next(-d/1e3),this.prepare()}else(r==null?void 0:r.to)==="paused"&&(R(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return XV(t)}};var i;this.params=e,this.video=Ue(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:aO.INVARIANT,url:this.params.source.url};let t=(r,a)=>Tl(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 Il(this.params.output.liveTime$,this.video,t,this.params.source.url,this.params.tuning.hlsLiveNewTextManagerDownloadThreshold):this.textTracksManager=new ot(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:xl.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:xl.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(we(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new yh((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:xl.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},r=He(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(je(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(nt(this.video,t.playbackRate,r.playbackRateState$,i)),a(lt(this.video),e.elementVisible$),this.liveTextManager?(a(this.liveTextManager.getCurrentTime$,this.params.output.getCurrentTime$),a(this.liveTextManager.error$,this.params.output.error$)):this.textTracksManager&&this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),R(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),R(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{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(tO(),Yx(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&&Qx(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(we(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(eO(Qx)),currentTime:r.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),i)),this.subscription.add(this.manifests$.pipe(Yx(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=iO(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,rO(["init"])).pipe(ZV(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),qe(this.video)}prepare(){var o,u,l;let e=this.selectManifest();if(El(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(),gh(n).then(d=>{var c;if(!El(d))this.maxSeekBackTime$.next(d);else{let h=(c=this.params.source.maxSeekBackTime)!=null?c:this.maxSeekBackTime$.getValue();(El(h)||!isFinite(h))&&At(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();gh(g).then(S=>{El(S)||this.maxSeekBackTime$.next(S)})}}).catch(()=>{})}})}playIfAllowed(){We(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),R(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:xl.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 nO,debounce as oO,ErrorCategory as Th,fromEvent as Ih,isNonNullable as uO,isNullable as lO,map as Kx,merge as Xx,observableFrom as Jx,Subscription as cO,ValueSubject as dO,VideoQuality as pO}from"@vkontakte/videoplayer-shared/es2018";var yo=class{constructor(e){this.subscription=new cO;this.videoState=new H("stopped");this.manifests$=new dO([]);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),R(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(a||n||o){let d=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(d);let{currentTime:c}=this.video;this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:c*1e3,forcePrecise:!0});return}switch((r==null?void 0:r.to)!=="paused"&&l.state==="requested"&&this.seek(l.position),t){case"ready":i==="ready"?R(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),R(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&R(this.params.desiredState.playbackState,"playing");return;case"paused":i==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&R(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return nO(t)}};this.textTracksManager=new ot(e.source.url),this.params=e,this.video=Ue(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:pO.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(we(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),Tl(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:Th.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:Th.WTF,message:"HlsProvider internal logic error",thrown:o})},r=He(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(Kx(o=>o.to)),this.params.output.playbackState$),this.subscription.add(Pt(this.video,t.isLooped,i)),this.subscription.add(je(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(nt(this.video,t.playbackRate,r.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),R(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),R(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&&uO(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(we(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.subscription.add(this.manifests$.pipe(Kx(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(Xx(Ih(o,"addtrack"),Ih(o,"removetrack"),Ih(o,"change"),Jx(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},i))}let n=Xx(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,Jx(["init"])).pipe(oO(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),qe(this.video)}prepare(){var a,n;let e=this.selectManifest();if(lO(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(){We(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),R(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Th.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var tE=U(rr(),1),xh=U(dr(),1),iE=U(Nt(),1);import{assertNever as hO,assertNonNullable as Zx,debounce as fO,ErrorCategory as eE,isHigherOrEqual as mO,isLowerOrEqual as bO,isNonNullable as gO,merge as SO,observableFrom as vO,Subscription as yO,map as TO}from"@vkontakte/videoplayer-shared/es2018";var To=class{constructor(e){this.subscription=new yO;this.videoState=new H("stopped");this.trackUrls={};this.textTracksManager=new ot;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),R(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let a=this.params.desiredState.autoVideoTrackLimits.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.seekState.getState();if(a&&e!=="ready"&&!n){this.handleQualityLimitTransition(a.to);return}if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(n){let{currentTime:u}=this.video;this.prepare(),o.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:u*1e3,forcePrecise:!0});return}switch((i==null?void 0:i.to)!=="paused"&&o.state==="requested"&&this.seek(o.position),e){case"ready":t==="ready"?R(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),R(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(i==null?void 0:i.to)==="playing"&&R(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&R(this.params.desiredState.playbackState,"paused");return;default:return hO(e)}};this.params=e,this.video=Ue(e.container,e.tuning),this.params.output.element$.next(this.video),(0,tE.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,xh.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:eE.WTF,message:"MpegProvider internal logic error",thrown:o})},r=He(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(TO(o=>o.to)),this.params.output.playbackState$),this.subscription.add(Pt(this.video,t.isLooped,i)),this.subscription.add(je(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(nt(this.video,t.playbackRate,r.playbackRateState$,i)),a(lt(this.video),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),R(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),R(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{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&&gO(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.textTracksManager.connect(this.video,t,e);let n=SO(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,vO(["init"])).pipe(fO(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),qe(this.video)}prepare(){var i;let e=(i=this.params.desiredState.videoTrack.getState())==null?void 0:i.id;Zx(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];Zx(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=Ui(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(we(t))}playIfAllowed(){We(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),R(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:eE.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=Kt(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,xh.default)(this.trackUrls).map(c=>c.track);if(!r||!a||zr(e,n[0].quality,(d=(0,iE.default)(n,-1))==null?void 0:d.quality)){i();return}let o=e.max?bO(r,e.max):!0,u=e.min?mO(r,e.min):!0;o&&u||i(e)}};import{assertNever as sE,debounce as wO,merge as aE,observableFrom as PO,Subscription as AO,map as nE,ValueSubject as kO,ErrorCategory as wh,VideoQuality as RO}from"@vkontakte/videoplayer-shared/es2018";import{ErrorCategory as IO}from"@vkontakte/videoplayer-shared/es2018";var rE=["stun:videostun.mycdn.me:80"],xO=1e3,EO=3,Eh=()=>null,wl=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=Eh;this.externalStopCallback=Eh;this.externalErrorCallback=Eh;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:rE}]};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:IO.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),xO)}normalizeOptions(e={}){let t={stunServerList:rE,maxRetryNumber:EO,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var Io=class{constructor(e){this.videoState=new H("stopped");this.maxSeekBackTime$=new kO(0);this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.pause(),this.video.srcObject=null,this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),R(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let a=this.params.desiredState.videoTrack.getTransition();if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(a){this.prepare();return}switch(e){case"ready":t==="paused"?(this.videoState.setState("paused"),R(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(i==null?void 0:i.to)==="playing"&&R(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&R(this.params.desiredState.playbackState,"paused");return;default:return sE(e)}};this.subscription=new AO,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=Ue(e.container,e.tuning),this.liveStreamClient=new wl(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),qe(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,i=n=>{e.error$.next({id:"WebRTCLiveProvider",category:wh.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};this.subscription.add(aE(this.videoState.stateChangeStarted$.pipe(nE(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(nE(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})}));let r=He(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(lt(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(je(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 sE(n.to)}},i)).add(aE(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,PO(["init"])).pipe(wO(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(we(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:RO.INVARIANT}),this.video.srcObject=e,R(this.params.desiredState.playbackState,"playing")}onLiveStreamStop(){this.videoState.startTransitionTo("stopped"),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.params.output.endedEvent$.next()}onLiveStreamError(e){this.onLiveStreamStop(),this.params.output.error$.next({id:"WebRTC stream runtime error",category:wh.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){We(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),R(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:wh.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var xo=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 wo,assertNonNullable as Wi,ErrorCategory as Pl,filter as pE,isNonNullable as hE,isNullable as VO,map as OO,merge as _O,once as FO,Subject as Ve,Subscription as fE,ValueSubject as Q,flattenObject as mE}from"@vkontakte/videoplayer-shared/es2018";import{Observable as LO,map as oE,Subscription as MO,Subject as $O}from"@vkontakte/videoplayer-shared/es2018";var uE=s=>new LO(e=>{let t=new MO,i=s.desiredPlaybackState$.stateChangeStarted$.pipe(oE(({from:l,to:d})=>`${l}-${d}`)),r=s.desiredPlaybackState$.stateChangeEnded$,a=s.providerChanged$.pipe(oE(({type:l})=>l!==void 0)),n=new $O,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 DO,Subscription as BO,combine as CO,filter as cE,once as dE}from"@vkontakte/videoplayer-shared/es2018";function lE(){return new(window.AudioContext||window.webkitAudioContext)}var Eo=class Eo{constructor(e,t,i,r){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=i;this.volumeMultiplier=r;this.destroyController=new se;this.subscriptions=new BO;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe(cE(a=>!!a.type),dE()).subscribe(({type:a})=>this.subscribe(a)))}subscribe(e){j.browser.isSafari&&e!=="MPEG"||this.subscriptions.add(CO({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(cE(({playbackState:t,video:i,volume:{muted:r,volume:a}})=>t==="playing"&&!!i&&!r&&!!a),dE()).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=lE();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:Eo.errorId,category:DO.VIDEO_PIPELINE,message:(t=e==null?void 0:e.message)!=null?t:`${Eo.errorId} exception`,thrown:e})}};Eo.errorId="VolumeMultiplierManager";var ys=Eo;var NO={chunkDuration:5e3,maxParallelRequests:5},Po=class{constructor(e){this.current$=new Q({type:void 0});this.providerError$=new Ve;this.noAvailableProvidersError$=new Ve;this.volumeMultiplierError$=new Ve;this.providerOutput={position$:new Q(0),duration$:new Q(1/0),volume$:new Q({muted:!1,volume:1}),availableVideoStreams$:new Q([]),currentVideoStream$:new Q(void 0),availableVideoTracks$:new Q([]),currentVideoTrack$:new Q(void 0),availableAudioStreams$:new Q([]),currentAudioStream$:new Q(void 0),availableAudioTracks$:new Q([]),currentVideoSegmentLength$:new Q(0),currentAudioSegmentLength$:new Q(0),isAudioAvailable$:new Q(!0),autoVideoTrackLimitingAvailable$:new Q(!1),autoVideoTrackLimits$:new Q(void 0),currentBuffer$:new Q(void 0),isBuffering$:new Q(!0),error$:new Ve,fetcherError$:new Ve,fetcherRecoverableError$:new Ve,warning$:new Ve,willSeekEvent$:new Ve,soundProhibitedEvent$:new Ve,seekedEvent$:new Ve,loopedEvent$:new Ve,endedEvent$:new Ve,firstBytesEvent$:new Ve,loadedMetadataEvent$:new Ve,firstFrameEvent$:new Ve,canplay$:new Ve,isLive$:new Q(void 0),isLiveEnded$:new Q(null),isLowLatency$:new Q(!1),canChangePlaybackSpeed$:new Q(!0),liveTime$:new Q(void 0),liveBufferTime$:new Q(void 0),liveLatency$:new Q(void 0),severeStallOccurred$:new Ve,availableTextTracks$:new Q([]),currentTextTrack$:new Q(void 0),hostname$:new Q(void 0),httpConnectionType$:new Q(void 0),httpConnectionReused$:new Q(void 0),inPiP$:new Q(!1),inFullscreen$:new Q(!1),element$:new Q(void 0),elementVisible$:new Q(!0),availableSources$:new Q(void 0),is3DVideo$:new Q(!1),playbackState$:new Q(""),getCurrentTime$:new Q(null)};this.subscription=new fE;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=jI([...WI(this.params.tuning),...HI(this.params.tuning)],this.params.tuning).filter(l=>hE(e.sources[l])),{forceFormat:i,formatsToAvoid:r}=this.params.tuning,a=[];i?a=[i]:r.length?a=[...t.filter(l=>!(0,Ph.default)(r,l)),...t.filter(l=>(0,Ph.default)(r,l))]:a=t,this.log({message:`Selected formats: ${a.join(" > ")}`}),this.tracer.log("Selected formats",mE(a)),this.screenFormatsIterator=new xo(a);let n=[...Lp(!0),...Lp(!1)];this.chromecastFormatsIterator=new xo(n.filter(l=>hE(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:o=1,tuning:{useVolumeMultiplier:u}}=this.params;u&&o!==1&&ys.isSupported()&&(this.volumeMultiplierManager=new ys(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(VO(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:Pl.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 wo(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 Wi(u),this.params.tuning.useNewDashProvider?new mo({...o,source:u,sourceHls:l}):new Mn({...o,source:u,sourceHls:l})}case"DASH_LIVE_CMAF":{let u=this.applyFailoverHost(t[e]);return Wi(u),this.params.tuning.useNewDashProvider?new bo({...o,source:u}):new $n({...o,source:u})}case"HLS":case"HLS_ONDEMAND":{let u=this.applyFailoverHost(t[e]);return Wi(u),j.video.nativeHlsSupported||!this.params.tuning.useHlsJs?new yo({...o,source:u}):new So({...o,source:u})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let u=this.applyFailoverHost(t[e]);return Wi(u),new vo({...o,source:u,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let u=this.applyFailoverHost(t[e]);return Wi(u),new To({...o,source:u})}case"DASH_LIVE":{let u=this.applyFailoverHost(t[e]);return Wi(u),new jy({...o,source:u,config:{...NO,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let u=this.applyFailoverHost(t[e]);return Wi(u),new Io({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 wo(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 Wi(o),new Ra({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 wo(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return wo(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 wo(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,gE.default)((0,bE.default)(e).map(([r,a])=>[r,i(a)]))}initProviderErrorHandling(){let e=new fE,t=!1,i=0;return e.add(_O(this.providerOutput.error$.pipe(pE(r=>!this.params.tuning.ignoreAudioRendererError||!r.message||!/AUDIO_RENDERER_ERROR/ig.test(r.message))),uE({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(OO(r=>({id:`ProviderHangup:${r}`,category:Pl.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(pE(({to:a})=>a==="playing"),FO()).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===Pl.NETWORK,u=r.category===Pl.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"))}this.tracer.error("providerError",mE(n))})),e}};import{fromEvent as Al,once as UO,combine as qO,Subscription as SE,ValueSubject as Ah,map as jO,filter as HO,isNonNullable as kl,now as Et,safeStorage as kh}from"@vkontakte/videoplayer-shared/es2018";var WO=5e3,vE="one_video_throughput",yE="one_video_rtt",ki=window.navigator.connection,TE=()=>{let s=ki==null?void 0:ki.downlink;if(kl(s)&&s!==10)return s*1e3},IE=()=>{let s=ki==null?void 0:ki.rtt;if(kl(s)&&s!==3e3)return s},xE=(s,e,t)=>{let i=t*8,r=i/s;return i/(r+e)},Rh=class s{constructor(e){this.subscription=new SE;this.concurrentDownloads=new Set;var r,a;this.tuningConfig=e;let t=s.load(vE)||(e.useBrowserEstimation?TE():void 0)||WO,i=(a=(r=s.load(yE))!=null?r:e.useBrowserEstimation?IE():void 0)!=null?a:0;if(this.throughput$=new Ah(t),this.rtt$=new Ah(i),this.rttAdjustedThroughput$=new Ah(xE(t,i,e.rttPenaltyRequestSize)),this.throughput=Ii.getSmoothedValue(t,-1,e),this.rtt=Ii.getSmoothedValue(i,1,e),e.useBrowserEstimation){let n=()=>{let u=TE();u&&this.throughput.next(u);let l=IE();kl(l)&&this.rtt.next(l)};ki&&"onchange"in ki&&this.subscription.add(Al(ki,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{kh.set(vE,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{kh.set(yE,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(qO({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(jO(({throughput:n,rtt:o})=>xE(n,o,e.rttPenaltyRequestSize)),HO(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=Et(),r=new SE;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add(Al(e,"progress").pipe(UO()).subscribe(a=>{t=a.loaded,i=Et()}));break;case 1:case 0:r.add(Al(e,"loadstart").subscribe(()=>{t=0,i=Et()}));break}r.add(Al(e,"loadend").subscribe(a=>{if(e.status===200){let n=a.loaded,o=Et(),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=Et(),n=0,o=Et(),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,Et()-a,1),this.concurrentDownloads.delete(e);else if(c){if(t){let h=Et();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=Et()}else n+=c.byteLength;o=Et()}else r+=c.byteLength,n+=c.byteLength,n>=this.tuningConfig.streamMinSampleSize&&Et()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,Et()-o,this.concurrentDownloads.size),n=0,o=Et());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=kh.get(e);if(kl(t))return(i=parseInt(t,10))!=null?i:void 0}},EE=Rh;import{fillWithDefault as zO,VideoQuality as Rl}from"@vkontakte/videoplayer-shared/es2018";var wE={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:Rl.Q_4320P,activeVideoAreaThreshold:.1,highQualityLimit:Rl.Q_720P,trafficSavingLimit:Rl.Q_480P},stallsManager:{stallDurationNoDataBeforeQualityDecrease:500,stallDurationToBeCount:100,stallCountBeforeQualityDecrease:3,resetQualityRestrictionTimeout:1e4,ignoreStallsOnSeek:!1,stallsMetricsHistoryLength:5,maxPossibleStallDuration:3e4,minTvtToBeCounted:0,maxTvtToBeCounted:3*60*60,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:Rl.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,rejectOnSourceOpenTimeout:!1},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,maxLiveDuration:7200,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:250,playbackCatchupSpeedup:.05,isActiveOnDefault:!1,bufferEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:"07A4434E",useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"dash",preferCMAF:!1,preferWebRTC:!1,preferMultiStream:!1,preferHDR:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,seekNearDurationBias:1,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useHlsJs:!1,useNativeHLSTextTracks:!1,useManagedMediaSource:!0,useNewSwitchTo:!1,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,useLazyInit:!1},PE=s=>{var e;return{...zO(s,wE),configName:[...(e=s.configName)!=null?e:[],...wE.configName]}};import{assertNonNullable as Ll,combine as Ri,ErrorCategory as Ml,filter as Pe,filterChanged as ee,fromEvent as Mh,isNonNullable as LE,isNullable as ZO,Logger as e_,map as J,mapTo as ME,merge as zi,now as $l,once as kt,Subject as ie,Subscription as $E,tap as $h,ValueSubject as B,isHigher as t_,isInvariantQuality as DE,flattenObject as Gi,throttle as Dh,getTraceSubscriptionMethod as BE,Tracer as i_,InternalsExposure as r_}from"@vkontakte/videoplayer-shared/es2018";import{merge as GO,map as QO,filter as AE,isNonNullable as YO}from"@vkontakte/videoplayer-shared/es2018";var Lh=({seekState:s,position$:e})=>GO(s.stateChangeEnded$.pipe(QO(({to:t})=>{var i;return t.state==="none"?void 0:((i=t.position)!=null?i:NaN)/1e3}),AE(YO)),e.pipe(AE(()=>s.getState().state==="none")));import{assertNonNullable as KO}from"@vkontakte/videoplayer-shared/es2018";var kE=s=>{let e=typeof s.container=="string"?document.getElementById(s.container):s.container;return KO(e,`Wrong container or containerId {${s.container}}`),e};import{filter as XO,once as JO}from"@vkontakte/videoplayer-shared/es2018";var RE=(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(XO(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 F=class F{constructor(e={configName:[]},t=i_.createRootTracer(!1)){this.subscription=new $E;this.logger=new e_;this.abrLogger=this.logger.createComponentLog("ABR");this.internalsExposure=null;this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new B(!1);this.hasLiveOffsetByPausedTimer=0;this.playerInitRequest=0;this.playerInited=new B(!1);this.wasSetStartedQuality=!1;this.desiredState={playbackState:new H("stopped"),seekState:new H({state:"none"}),volume:new H({volume:1,muted:!1}),videoTrack:new H(void 0),videoStream:new H(void 0),audioStream:new H(void 0),autoVideoTrackSwitching:new H(!0),autoVideoTrackLimits:new H({}),isLooped:new H(!1),isLowLatency:new H(!1),playbackRate:new H(1),externalTextTracks:new H([]),internalTextTracks:new H([]),currentTextTrack:new H(void 0),textTrackCuesSettings:new H({}),cameraOrientation:new H({x:0,y:0})};this.info={playbackState$:new B(void 0),position$:new B(0),duration$:new B(1/0),muted$:new B(!1),volume$:new B(1),availableVideoStreams$:new B([]),currentVideoStream$:new B(void 0),availableQualities$:new B([]),availableQualitiesFps$:new B({}),currentQuality$:new B(void 0),isAutoQualityEnabled$:new B(!0),autoQualityLimitingAvailable$:new B(!1),autoQualityLimits$:new B({}),predefinedQualityLimitType$:new B("unknown"),availableAudioStreams$:new B([]),currentAudioStream$:new B(void 0),availableAudioTracks$:new B([]),isAudioAvailable$:new B(!0),currentPlaybackRate$:new B(1),currentBuffer$:new B({start:0,end:0}),isBuffering$:new B(!0),isStalled$:new B(!1),isEnded$:new B(!1),isLooped$:new B(!1),isLive$:new B(void 0),isLiveEnded$:new B(null),canChangePlaybackSpeed$:new B(void 0),atLiveEdge$:new B(void 0),atLiveDurationEdge$:new B(void 0),liveTime$:new B(void 0),liveBufferTime$:new B(void 0),liveLatency$:new B(void 0),currentFormat$:new B(void 0),availableTextTracks$:new B([]),currentTextTrack$:new B(void 0),throughputEstimation$:new B(void 0),rttEstimation$:new B(void 0),videoBitrate$:new B(void 0),hostname$:new B(void 0),httpConnectionType$:new B(void 0),httpConnectionReused$:new B(void 0),surface$:new B("none"),chromecastState$:new B("NOT_AVAILABLE"),chromecastDeviceName$:new B(void 0),intrinsicVideoSize$:new B(void 0),availableSources$:new B(void 0),is3DVideo$:new B(!1),currentVideoSegmentLength$:new B(0),currentAudioSegmentLength$:new B(0)};this.events={inited$:new ie,ready$:new ie,started$:new ie,playing$:new ie,paused$:new ie,stopped$: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 B(void 0),tuningConfigName$:new B([]),enableDebugTelemetry$:new B(!1),dumpTelemetry:my,getCurrentTime$:new B(null)};if(this.initLogs(),this.tuning=PE(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new Bo({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new EE(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new r_("CORE"),this.internalsExposure.expose({player:this})),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return F.withErrorCatching(this)}static withWaitInit(e=!1){return(t,i,r)=>{let a=r.value;return r.value=function(...n){return this.subscription.add(this.playerInited.pipe(Pe(o=>!!o),kt()).subscribe(()=>{e&&!this.providerContainer&&this.createProviderContainer(this.config),a.apply(this,n)})),this},r}}static withErrorCatching(e){return new Proxy(e,{get:(t,i,r)=>{let a=Reflect.get(t,i,r);return typeof a!="function"?a:(...n)=>{try{return a.apply(t,n)}catch(o){let u=n.map(c=>JSON.stringify(c,(h,p)=>{let f=typeof p;return(0,CE.default)(["number","string","boolean"],f)?p:p===null?null:`<${f}>`})),l=`Player.${String(i)}`,d=`Exception calling ${l} (${u.join(", ")})`;throw e.events.fatalError$.next({id:l,category:Ml.WTF,message:d,thrown:o}),o}}}})}createProviderContainer(e){var t,i;this.providerContainer=new Po({sources:e.sources,meta:(t=e.meta)!=null?t:{},failoverHosts:(i=e.failoverHosts)!=null?i:[],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.initProviderDebugTelemetry(),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.providerContainer.init()}initVideo(e){var a;this.config=e,(a=this.internalsExposure)==null||a.expose({config:e,logger:this.logger,tuning:this.tuning});let t=()=>{var u;let{container:n,...o}=e;this.tracer.log("initVideo",Gi(o)),this.domContainer=kE(e),this.chromecastInitializer.contentId=(u=e.meta)==null?void 0:u.videoId,this.initTracerSubscription(),console.log(`Core SDK useLazyInit = ${this.tuning.useLazyInit}`),this.tuning.useLazyInit||this.createProviderContainer(e),this.setLiveLowLatency(this.tuning.dashCmafLive.lowLatency.isActiveOnDefault),this.setMuted(this.tuning.isAudioDisabled),this.initBasicDebugTelemetry(),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(Pe(n=>!!n),kt()).subscribe(()=>{console.log("Core SDK async start"),i()}):i()};return this.isNotActiveTabCase()?(this.tracer.log("request play from hidden tab"),Mh(document,"visibilitychange").pipe(kt()).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(){let e=this.desiredState.playbackState;return this.tracer.log("prepare",{currentPlayBackState:e.getState()}),e.getState()==="stopped"&&e.startTransitionTo("ready"),this}play(){let e=this.desiredState.playbackState;return this.tracer.log("play",{currentPlayBackState:e.getState()}),e.getState()!=="playing"&&e.startTransitionTo("playing"),this}pause(){let e=this.desiredState.playbackState;return this.tracer.log("pause",{currentPlayBackState:e.getState()}),e.getState()!=="paused"&&e.startTransitionTo("paused"),this}stop(){let e=this.desiredState.playbackState;return this.tracer.log("stop",{currentPlayBackState:e.getState()}),e.getState()!=="stopped"&&e.startTransitionTo("stopped"),this}seekTime(e,t=!0){let i=this.info.duration$.getValue(),r=this.info.isLive$.getValue(),a=e;return 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){let t=this.info.duration$.getValue();return this.tracer.log("seekPercent",{percent:e,duration:t}),isFinite(t)&&this.seekTime(Math.abs(t)*e,!1),this}setVolume(e,t){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;return 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){var n;let t=this.desiredState.volume,i=this.tuning.isAudioDisabled||e,r=t.getTransition(),a=(n=r==null?void 0:r.to.volume)!=null?n:this.info.volume$.getValue();return this.tracer.log("setMuted",{isMuted:e,nextMuted:i,volume:a,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue()}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setMuted(i):t.startTransitionTo({volume:a,muted:i}),this}setVideoStream(e){return this.desiredState.videoStream.startTransitionTo(e),this}setAudioStream(e){return this.desiredState.audioStream.startTransitionTo(e),this}setQuality(e){Ll(this.providerContainer);let t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();return 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(Pe(i=>i.length>0),kt()).subscribe(i=>{this.setVideoTrackIdByQuality(i,e)}):this.explicitInitialQuality=e:t.length>0&&this.setVideoTrackIdByQuality(t,e),this}setAutoQuality(e){return this.tracer.log("setAutoQuality",{enable:e}),this.desiredState.autoVideoTrackSwitching.startTransitionTo(e),this}setAutoQualityLimits(e){return this.tracer.log("setAutoQualityLimits",Gi(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPredefinedQualityLimits(e){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}}return this.setAutoQualityLimits(r),this}setPlaybackRate(e){var i;Ll(this.providerContainer);let t=(i=this.providerContainer)==null?void 0:i.providerOutput.element$.getValue();return this.tracer.log("setPlaybackRate",{playbackRate:e,isVideoElementAvailable:!!t}),t&&(this.desiredState.playbackRate.setState(e),t.playbackRate=e),this}setExternalTextTracks(e){return e.length&&this.tracer.log("setExternalTextTracks",Gi(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t}))),this}selectTextTrack(e){var t;return RE(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.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.tracer.log("setLooped",{isLooped:e}),this.desiredState.isLooped.startTransitionTo(e),this}toggleChromecast(){this.tracer.log("toggleChromecast"),this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){let i=this.getScene3D();return this.tracer.log("startCameraManualRotation",{isScene3DAvailable:!!i,mx:e,my:t}),i&&i.startCameraManualRotation(e,t),this}stopCameraManualRotation(e=!1){let t=this.getScene3D();return this.tracer.log("stopCameraManualRotation",{isScene3DAvailable:!!t,immediate:e}),t&&t.stopCameraManualRotation(e),this}moveCameraFocusPX(e,t){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})}return this}holdCamera(){let e=this.getScene3D();return e&&e.holdCamera(),this}releaseCamera(){let e=this.getScene3D();return e&&e.releaseCamera(),this}getExactTime(){if(!this.providerContainer)return 0;let e=this.providerContainer.providerOutput.element$.getValue();if(ZO(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),i=t.state==="none"?void 0:t.position;return LE(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(zi(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(J(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(J(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(J(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(J(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(J(e=>e.to)).subscribe(e=>{this.info.autoQualityLimits$.next(e);let{highQualityLimit:t,trafficSavingLimit:i}=this.tuning.autoTrackSelection;this.info.predefinedQualityLimitType$.next(Gd(e,t,i))})),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(Pe(({from:e})=>e==="stopped"),kt()).subscribe(()=>{this.initedAt=$l(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case"ready":this.events.ready$.next();break;case"playing":this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case"paused":this.events.paused$.next();break;case"stopped":this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case"paused":this.events.willPause$.next();break;case"playing":this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case"stopped":this.events.willStop$.next();break;default:}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("willSeekEvent",Gi(n)),n.state==="requested"?this.desiredState.seekState.setState({...n,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:Ml.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe(kt()).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",Gi(n)),n.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe(J(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(J(n=>n.destination),ee()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(Ri({availableVideoTracks:e.providerOutput.availableVideoTracks$,currentVideoStream:e.providerOutput.currentVideoStream$}).pipe(J(({availableVideoTracks:n,currentVideoStream:o})=>n.filter(u=>o?o.id===u.streamId:!0).map(({quality:u})=>u).sort((u,l)=>DE(u)?1:DE(l)?-1:t_(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(ee()).subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.pipe(Pe(n=>LE(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(ee((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe(ee((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(ee()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(ee()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(ee()).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(J(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($h(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(Ri({hasLiveOffsetByPaused:zi(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(J(n=>n.to),ee(),J(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(Ri({atLiveEdge:Ri({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Lh({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(J(({isLive:n,position:o,isLowLatency:u})=>{let l=this.getActiveLiveDelay(u);return n&&Math.abs(o)<l/1e3}),ee(),$h(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(J(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add(Ri({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(J(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),ee(),$h(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(J(n=>n.muted),ee()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(J(n=>n.volume),ee()).subscribe(this.info.volume$)).add(Lh({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(zi(e.providerOutput.endedEvent$.pipe(ME(!0)),e.providerOutput.seekedEvent$.pipe(ME(!1))).pipe(ee()).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(J(n=>({id:n?`No${n}`:"NoProviders",category:Ml.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(kt(),J(n=>n!=null?n:$l()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(kt(),J(()=>$l()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(kt(),J(()=>$l()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$)).add(e.providerOutput.availableSources$.subscribe(this.info.availableSources$));let t=new B(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let i=new B(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(Pe(({to:n})=>n==="playing"),kt()).subscribe(()=>i.next(!1)));let r=0,a=zi(e.providerOutput.isBuffering$,t,i).pipe(J(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||i.getValue();return n&&!o}),ee());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(zi(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(zi(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(J(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 $E;this.subscription.add(t),this.subscription.add(e.current$.pipe(ee((i,r)=>i.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(Pe(i=>i.length>0),kt()).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=Kt(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(zi(this.desiredState.videoTrack.stateChangeStarted$.pipe(J(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(J(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(J(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(J(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(J(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(J(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(J(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(J(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(J(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$))}initBasicDebugTelemetry(){fy(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(e=>hy(e)),this.events.fatalError$.subscribe(new tt("fatalError")),this.events.managedError$.subscribe(new tt("managedError")),this.info.currentBuffer$.subscribe(new tt("buffer"))].forEach(e=>this.subscription.add(e)),Ba("codecs",j.video.supportedCodecs)}initProviderDebugTelemetry(){var t;let e=(t=this.providerContainer)==null?void 0:t.providerOutput;Ll(this.providerContainer),Ll(e),[this.providerContainer.current$.subscribe(({type:i})=>Ba("provider",i)),e.duration$.subscribe(i=>Ba("duration",i)),e.availableVideoTracks$.pipe(Pe(i=>!!i.length),kt()).subscribe(i=>Ba("tracks",i)),e.position$.subscribe(new tt("position")),e.currentVideoTrack$.pipe(J(i=>i==null?void 0:i.quality)).subscribe(new tt("quality")),e.isBuffering$.subscribe(new tt("isBuffering"))].forEach(i=>this.subscription.add(i))}initTracerSubscription(){let e=BE(this.tracer.log.bind(this.tracer)),t=BE(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(ee()).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(Ri({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe(Pe(({currentQuality:i,videoBitrate:r})=>!!i&&!!r),ee((i,r)=>i.currentQuality===r.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe(Pe(i=>i>0),ee()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe(Pe(i=>i>0),ee()).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(Ri({currentBuffer:this.info.currentBuffer$.pipe(Pe(i=>i.end>0),ee((i,r)=>i.end===r.end&&i.start===r.start)),position:this.info.position$.pipe(ee())}).pipe(Dh(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe(ee()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe(ee()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe(ee()).subscribe(e("canChangePlaybackSpeed"))).add(Ri({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(Pe(({liveTime:i,liveBufferTime:r})=>!!i&&!!r),Dh(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(ee(),Pe(i=>i===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(ee(),Pe(i=>i===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe(ee()).subscribe(e("muted"))).add(this.info.volume$.pipe(ee()).subscribe(e("volume"))).add(this.info.isEnded$.pipe(ee(),Pe(i=>i===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add(Ri({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(Pe(({throughputEstimation:i,rtt:r})=>!!i&&!!r),Dh(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(ee(),Pe(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:Ml.DOM,message:String(r)})})};this.subscription.add(zi(Mh(document,"visibilitychange"),Mh(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",Gi({quality:t,availableTracks:Gi(e),track:Gi(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&&!Ua()}};ne([F.withWaitInit(!0)],F.prototype,"prepare",1),ne([F.withWaitInit(!0)],F.prototype,"play",1),ne([F.withWaitInit(!1)],F.prototype,"pause",1),ne([F.withWaitInit(!1)],F.prototype,"stop",1),ne([F.withWaitInit(!1)],F.prototype,"seekTime",1),ne([F.withWaitInit(!1)],F.prototype,"seekPercent",1),ne([F.withWaitInit(!1)],F.prototype,"setVolume",1),ne([F.withWaitInit(!1)],F.prototype,"setMuted",1),ne([F.withWaitInit(!0)],F.prototype,"setVideoStream",1),ne([F.withWaitInit(!0)],F.prototype,"setAudioStream",1),ne([F.withWaitInit(!0)],F.prototype,"setQuality",1),ne([F.withWaitInit(!1)],F.prototype,"setAutoQuality",1),ne([F.withWaitInit(!1)],F.prototype,"setAutoQualityLimits",1),ne([F.withWaitInit(!1)],F.prototype,"setPredefinedQualityLimits",1),ne([F.withWaitInit(!0)],F.prototype,"setPlaybackRate",1),ne([F.withWaitInit(!1)],F.prototype,"setExternalTextTracks",1),ne([F.withWaitInit(!1)],F.prototype,"selectTextTrack",1),ne([F.withWaitInit(!1)],F.prototype,"setTextTrackCueSettings",1),ne([F.withWaitInit(!1)],F.prototype,"setLooped",1),ne([F.withWaitInit(!1)],F.prototype,"startCameraManualRotation",1),ne([F.withWaitInit(!1)],F.prototype,"stopCameraManualRotation",1),ne([F.withWaitInit(!1)],F.prototype,"moveCameraFocusPX",1),ne([F.withWaitInit(!1)],F.prototype,"holdCamera",1),ne([F.withWaitInit(!1)],F.prototype,"releaseCamera",1);var Dl=F;import{Subscription as Hee,Observable as Wee,Subject as zee,ValueSubject as Gee,VideoQuality as Qee}from"@vkontakte/videoplayer-shared/es2018";var Yee=`@vkontakte/videoplayer-core@${Ch}`;export{Ao as ChromecastState,ql as HttpConnectionType,Wee as Observable,at as PlaybackState,Dl as Player,ko as PredefinedQualityLimits,Yee as SDK_VERSION,zee as Subject,Hee as Subscription,jl as Surface,Ch as VERSION,Gee as ValueSubject,fi as VideoFormat,Qee as VideoQuality,j as clientChecker,$a as isMobile};
|
|
124
|
+
`;var An=class{constructor(e,t,i){this.videoInitialized=!1;this.active=!1;this.container=e,this.sourceVideoElement=t,this.params=i,this.canvas=this.createCanvas();let 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 Pn(this.params.fov,this.params.orientation),this.cameraRotationManager=new wn(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(Cy,this.gl.VERTEX_SHADER),i=this.createShader(Dy,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,h=t+r;return[s,n,o,u,l,c,d,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 MC,now as Vy,Subscription as CC,filter as DC,combine as Oy,debounce as VC,ValueSubject as Xl,isNonNullable as OC}from"@vkontakte/videoplayer-shared/es2018";var Jl=class{constructor(){this.isSeeked$=new Xl(!1);this.isBuffering$=new Xl(!1);this.currentStallsCount=0;this.maxQualityLimit=void 0;this.lastUniqueVideoTrackSelectedTimestamp=0;this.predictedThroughputWithoutData=0;this.subscription=new CC;this.severeStallOccurred$=new Xl(!1)}connect(e){this.currentStallDuration$=e.currentStallDuration$,this.videoLastDataObtainedTimestamp$=e.videoLastDataObtainedTimestamp$,this.throughput$=e.throughput$,this.rtt$=e.rtt$,this.qualityLimitsOnStall=e.qualityLimitsOnStall,this.subscription.add(e.isSeeked$.subscribe(this.isSeeked$)),this.subscription.add(e.isBuffering$.subscribe(this.isBuffering$)),this.subscription.add(e.looped$.subscribe(t=>this.currentStallsCount=0)),this.subscription.add(Oy({isBuffering:this.isBuffering$,isSeeked:this.isSeeked$}).pipe(VC(this.qualityLimitsOnStall.stallDurationToBeCount),DC(({isBuffering:t,isSeeked:i})=>t&&!i)).subscribe(t=>{this.currentStallsCount++})),this.subscription.add(Oy({currentStallDuration:this.currentStallDuration$}).subscribe(({currentStallDuration:t})=>{let{stallDurationNoDataBeforeQualityDecrease:i,stallCountBeforeQualityDecrease:r,resetQualityRestrictionTimeout:s,ignoreStallsOnSeek:n}=this.qualityLimitsOnStall;if(MC(this.lastUniqueVideoTrackSelected)||n&&this.isSeeked$.getValue())return;let o=this.rtt$.getValue(),u=this.throughput$.getValue(),l=this.videoLastDataObtainedTimestamp$.getValue(),c=Vy(),d=r&&this.currentStallsCount>=r,h=i&&c-this.lastUniqueVideoTrackSelectedTimestamp>=i+o&&c-l>=i+o&&t>=i;(d||h)&&(this.severeStallOccurred$.next(!0),window.clearTimeout(this.qualityRestrictionTimer),this.maxQualityLimit=this.lastUniqueVideoTrackSelected.quality,OC(this.lastUniqueVideoTrackSelected.bitrate)&&u>this.lastUniqueVideoTrackSelected.bitrate&&(this.predictedThroughputWithoutData=this.lastUniqueVideoTrackSelected.bitrate)),t||(this.severeStallOccurred$.next(!1),window.clearTimeout(this.qualityRestrictionTimer),this.qualityRestrictionTimer=window.setTimeout(()=>{this.maxQualityLimit=void 0,this.predictedThroughputWithoutData=0},s))}))}get videoMaxQualityLimit(){return this.maxQualityLimit}get predictedThroughput(){return this.predictedThroughputWithoutData}set lastVideoTrackSelected(e){var t;((t=this.lastUniqueVideoTrackSelected)==null?void 0:t.id)!==e.id&&(this.lastUniqueVideoTrackSelected=e,this.lastUniqueVideoTrackSelectedTimestamp=Vy(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe()}},By=Jl;import{combine as BC,map as _C,observeElementSize as NC,Subscription as FC,ValueSubject as Zl,noop as qC}from"@vkontakte/videoplayer-shared/es2018";var kn=class{constructor(){this.subscription=new FC;this.pipSize$=new Zl(void 0);this.videoSize$=new Zl(void 0);this.elementSize$=new Zl(void 0);this.pictureInPictureWindowRemoveEventListener=qC}connect({observableVideo:e,video:t}){let i=r=>{let s=r.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add(NC(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(BC({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(_C(({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 WC;this.videoState=new D("stopped");this.droppedFramesManager=new on;this.stallsManager=new By;this.elementSizeManager=new kn;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Ur;this.audioTrackSwitchHistory=new Ur;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"),P(this.params.desiredState.playbackState,"stopped",!0));return}switch(e){case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();return;case"ready":t==="paused"?(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="ready"&&P(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):t==="playing"&&this.video.paused?this.playIfAllowed():(i==null?void 0:i.to)==="playing"&&P(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&P(this.params.desiredState.playbackState,"paused");return;default:return HC(e)}}};this.init3DScene=e=>{var i,r,s;if(this.scene3D)return;this.scene3D=new An(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((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 Ne(e.source.url),this.params=e,this.video=Ee(e.container,e.tuning),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(oe(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 xn({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,i=Ae(this.video);this.subscription.add(()=>i.destroy());let r=this.constructor.name,s=o=>{e.error$.next({id:r,category:_y.WTF,message:`${r} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:i,genericErrorListener:s,connect:(o,u)=>this.subscription.add(o.subscribe(u,s))}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:s}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(ec(l=>!!l.length),Fy()).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(tc(l=>l.to.state!=="none"),Oa());this.stallsManager.connect({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$.pipe(Oa()),videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,qualityLimitsOnStall:this.params.tuning.dash.qualityLimitsOnStall,isBuffering$:i.isBuffering$,looped$:i.looped$}),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(this.player.error$,e.error$),s(this.player.fetcherRecoverableError$,e.fetcherRecoverableError$),s(this.player.fetcherError$,e.fetcherError$),s(this.player.lastConnectionType$,e.httpConnectionType$),s(this.player.lastConnectionReused$,e.httpConnectionReused$),s(this.player.isLive$,e.isLive$),s(this.player.lastRequestFirstBytes$.pipe(ec(Ny),Fy()),e.firstBytesEvent$),s(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),s(this.videoState.stateChangeEnded$.pipe(tc(l=>l.to)),this.params.output.playbackState$),this.subscription.add(i.loopExpected$.subscribe(l=>{t.seekState.setState({state:"requested",position:0,forcePrecise:!1})})),this.subscription.add(i.looped$.subscribe(()=>this.player.warmUpMediaSourceIfNeeded(),r)),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(it(this.video,t.isLooped,r)),this.subscription.add(Pe(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(_e(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),s(Fe(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),P(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),P(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.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(jC(c,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let h=[];for(let p of c.audio){h.push(Dl(p));let m=[];for(let b of p.representations){let g=oy(b);m.push(g),this.audioTracksMap.set(g,{stream:p,representation:b})}this.audioStreamsMap.set(p,m)}this.params.output.availableAudioStreams$.next(h)}let d=[];for(let h of c.video){d.push(Vl(h));let p=[];for(let m of h.representations){let b=ny({...m,streamId:h.id});b&&(p.push(b),this.videoTracksMap.set(b,{stream:h,representation:m}))}this.videoStreamsMap.set(h,p)}this.params.output.availableVideoStreams$.next(d);for(let h of c.text)for(let p of h.representations){let m=uy(h,p);this.textTracksMap.set(m,{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(Rn(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$,GC(this.video,"progress")).pipe(ec(()=>this.videoTracksMap.size>0)).subscribe(async()=>{let l=this.player.state$.getState(),c=this.player.state$.getTransition();if(!(0,qy.default)(["manifest_ready","running"],l)||c)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let d=this.selectVideoAudioRepresentations();if(!d)return;let[h,p]=d,m=[...this.videoTracksMap.keys()].find(g=>{var v;return((v=this.videoTracksMap.get(g))==null?void 0:v.representation.id)===h.id});Ny(m)&&(this.stallsManager.lastVideoTrackSelected=m);let b=this.params.desiredState.autoVideoTrackLimits.getTransition();if(b&&this.params.output.autoVideoTrackLimits$.next(b.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(Oa()).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:h}]=c,p=this.params.desiredState.videoStream.getTransition();p&&p.to&&p.to.id===h.id&&this.params.desiredState.videoStream.setState(p.to),e.currentVideoTrack$.next(d),e.currentVideoStream$.next(Vl(h))},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(Oa()).subscribe(l=>{let c=[...this.audioTracksMap.entries()].find(([,{representation:m}])=>m.id===l);if(!c){e.currentAudioStream$.next(void 0);return}let[d,{stream:h}]=c,p=this.params.desiredState.audioStream.getTransition();p&&p.to&&p.to.id===h.id&&this.params.desiredState.audioStream.setState(p.to),e.currentAudioStream$.next(Dl(h))},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(h){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${h}`})}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(tc(({to:l})=>l==="ready"),Oa());this.subscription.add(Rn(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,ic(["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(Rn(o,this.player.state$.stateChangeEnded$,ic(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let u=Rn(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,ic(["init"])).pipe(QC(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){var q,O,_,w,U,L,k,W,ae,A,B,Y,E;if(this.player.isStreamEnded)return;let{desiredState:e,output:t}=this.params,i=e.autoVideoTrackSwitching.getState(),r=(q=e.videoTrack.getState())==null?void 0:q.id,n=[...this.videoTracksMap.keys()].find(({id:$})=>$===r),o=t.currentVideoTrack$.getValue(),u=((w=(_=e.videoStream.getState())!=null?_:n&&((O=this.videoTracksMap.get(n))==null?void 0:O.stream))!=null?w:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!u)return;let l=[...this.videoStreamsMap.keys()].find(({id:$})=>$===u.id),c=l&&this.videoStreamsMap.get(l);if(!c)return;let d=Wi(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=i?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let p=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,m=Math.min(d/Math.min(h,p||1/0),1),b=(U=e.audioStream.getState())!=null?U:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,g=(L=[...this.audioStreamsMap.keys()].find(({id:$})=>$===(b==null?void 0:b.id)))!=null?L:this.audioStreamsMap.keys().next().value,v=0;if(g){if(n&&!i){let $=rn(n,c,(k=this.audioStreamsMap.get(g))!=null?k:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);v=Math.max(v,(W=$==null?void 0:$.bitrate)!=null?W:-1/0)}if(o){let $=rn(o,c,(ae=this.audioStreamsMap.get(g))!=null?ae:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);v=Math.max(v,(A=$==null?void 0:$.bitrate)!=null?A:-1/0)}}let S=Ot(c,{container:this.elementSizeManager.getValue(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:v,forwardBufferHealth:m,current:o,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,stallsVideoMaxQualityLimit:this.stallsManager.videoMaxQualityLimit,stallsPredictedThroughput:this.stallsManager.predictedThroughput,abrLogger:this.params.dependencies.abrLogger}),y=i?S!=null?S:n:n!=null?n:S,I=g&&iv(y,c,(B=this.audioStreamsMap.get(g))!=null?B:[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:m,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),T=(Y=this.videoTracksMap.get(y))==null?void 0:Y.representation,R=I&&((E=this.audioTracksMap.get(I))==null?void 0:E.representation);if(T&&R)return[T,R];if(T&&!R&&this.audioTracksMap.size===0)return[T,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){ke(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:_y.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.stallsManager.destroy(),this.elementSizeManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),this.params.output.currentVideoStream$.next(void 0),xe(this.video),this.tracer.end()}};var Ba=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 rc,merge as Uy,filter as Hy,filterChanged as YC,isNullable as ac,map as jy,ValueSubject as sc,isNonNullable as zC}from"@vkontakte/videoplayer-shared/es2018";var _a=class extends fi{constructor(e){super(e),this.textTracksManager.destroy()}subscribe(){super.subscribe();let e=-1,{output:t,observableVideo:i,desiredState:r,connect:s}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),s(i.timeUpdate$,t.liveBufferTime$),s(this.player.liveSeekableDuration$,t.duration$),s(this.player.liveLatency$,t.liveLatency$);let n=new sc(1);s(i.playbackRateState$,n),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(r.isLowLatency.stateChangeEnded$.pipe(jy(o=>o.to)).subscribe(this.player.isLowLatency$)).add(rc({liveBufferTime:t.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(jy(({liveBufferTime:o,liveAvailabilityStartTime:u})=>o&&u?o+u:void 0)).subscribe(t.liveTime$)).add(this.player.liveStreamStatus$.pipe(Hy(o=>zC(o))).subscribe(o=>t.isLiveEnded$.next(o!=="active"&&t.position$.getValue()===0))).add(rc({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:Uy(i.playbackRateState$,new sc(1))}).pipe(Hy(({liveStreamStatus:o,liveDuration:u})=>o==="active"&&!!u)).subscribe(({liveDuration:o,playbackRate:u})=>{let l=t.liveBufferTime$.getValue(),c=t.position$.getValue(),{playbackCatchupSpeedup:d}=this.params.tuning.dashCmafLive.lowLatency;c||u<1-d||this.video.paused||ac(l)||(e=o-l)})).add(rc({time:t.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:Uy(i.playbackRateState$,new sc(1))}).pipe(YC((o,u)=>this.player.liveStreamStatus$.getValue()==="active"?o.liveDuration===u.liveDuration:o.time===u.time)).subscribe(({time:o,liveDuration:u,playbackRate:l})=>{let c=t.position$.getValue(),{playbackCatchupSpeedup:d}=this.params.tuning.dashCmafLive.lowLatency;if(!c&&!this.video.paused&&l>=1-d||ac(o)||ac(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=ly(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 Gy=C(Hs(),1);import{assertNever as Na,assertNonNullable as Qy,debounce as KC,ErrorCategory as $n,filter as XC,isNonNullable as JC,isNullable as ZC,map as Ln,merge as eD,Observable as tD,observableFrom as iD,Subscription as rD,videoSizeToQuality as aD}from"@vkontakte/videoplayer-shared/es2018";var Ke={};var rr=(a,e)=>new tD(t=>{let i=(r,s)=>t.next(s);return a.on(e,i),()=>a.off(e,i)}),Fa=class{constructor(e){this.subscription=new rD;this.videoState=new D("initializing");this.trackLevels=new Map;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(e!=="initializing")switch((i==null?void 0:i.to)!=="paused"&&r.state==="requested"&&this.seek(r.position),t){case"stopped":switch(e){case"stopped":break;case"ready":case"playing":case"paused":this.stop();break;default:Na(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:Na(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:Na(e)}break;case"paused":switch(e){case"paused":break;case"stopped":this.prepare();break;case"ready":this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused");break;case"playing":this.pause();break;default:Na(e)}break;default:Na(t)}};this.textTracksManager=new Ne(e.source.url),this.video=Ee(e.container,e.tuning),this.params=e,this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(oe(this.params.source.url)),this.loadHlsJs()}destroy(){var e,t;this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),(e=this.hls)==null||e.detachMedia(),(t=this.hls)==null||t.destroy(),this.params.output.element$.next(void 0),xe(this.video)}loadHlsJs(){let e=!1,t=r=>{e||this.params.output.error$.next({id:r==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:$n.NETWORK,message:"Failed to load Hls.js",thrown:r}),e=!0},i=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);(0,Gy.default)(import("hls.js").then(r=>{e||(Ke.Hls=r.default,Ke.Events=r.default.Events,this.init())},t),()=>{window.clearTimeout(i),e=!0})}init(){Qy(Ke.Hls,"hls.js not loaded"),this.hls=new Ke.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){Qy(Ke.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,i=l=>{t.error$.next({id:"HlsJsProvider",category:$n.WTF,message:"HlsJsProvider internal logic error",thrown:l})},r=Ae(this.video);this.subscription.add(()=>r.destroy());let s=(l,c)=>this.subscription.add(l.subscribe(c,i));s(r.timeUpdate$,t.position$),s(r.durationChange$,t.duration$),s(r.ended$,t.endedEvent$),s(r.looped$,t.loopedEvent$),s(r.error$,t.error$),s(r.isBuffering$,t.isBuffering$),s(r.currentBuffer$,t.currentBuffer$),s(r.loadStart$,t.firstBytesEvent$),s(r.loadedMetadata$,t.loadedMetadataEvent$),s(r.playing$,t.firstFrameEvent$),s(r.canplay$,t.canplay$),s(r.seeked$,t.seekedEvent$),s(r.inPiP$,t.inPiP$),s(r.inFullscreen$,t.inFullscreen$),this.subscription.add(it(this.video,e.isLooped,i)),this.subscription.add(Pe(this.video,e.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(_e(this.video,e.playbackRate,r.playbackRateState$,i)),s(Fe(this.video),t.elementVisible$),s(this.videoState.stateChangeEnded$.pipe(Ln(l=>l.to)),this.params.output.playbackState$),this.subscription.add(rr(this.hls,Ke.Events.ERROR).subscribe(l=>{var c;l.fatal&&t.error$.next({id:["HlsJsFatal",l.type,l.details].join("_"),category:$n.WTF,message:`HlsJs fatal ${l.type} ${l.details}, ${(c=l.err)==null?void 0:c.message} ${l.reason}`,thrown:l.error})})),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),P(e.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),P(e.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())==null?void 0:l.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),s(rr(this.hls,Ke.Events.MANIFEST_PARSED).pipe(Ln(({levels:l})=>l.reduce((c,d)=>{var S,y;let h=d.name||d.height.toString(10),{width:p,height:m}=d,b=(y=Ct((S=d.attrs.QUALITY)!=null?S:""))!=null?y:aD({width:p,height:m});if(!b)return c;let g=d.attrs["FRAME-RATE"]?parseFloat(d.attrs["FRAME-RATE"]):void 0,v={id:h.toString(),quality:b,bitrate:d.bitrate/1e3,size:{width:p,height:m},fps:g};return this.trackLevels.set(h,{track:v,level:d}),c.push(v),c},[]))),t.availableVideoTracks$),s(rr(this.hls,Ke.Events.MANIFEST_PARSED),l=>{if(l.subtitleTracks.length>0){let c=[];for(let d of l.subtitleTracks){let h=d.name,p=d.attrs.URI||"",m=d.lang;c.push({id:h,url:p,language:m,type:"internal"})}e.internalTextTracks.startTransitionTo(c)}}),s(rr(this.hls,Ke.Events.LEVEL_LOADING).pipe(Ln(({url:l})=>oe(l))),t.hostname$),s(rr(this.hls,Ke.Events.FRAG_CHANGED),l=>{var h,p,m,b;let{video:c,audio:d}=l.frag.elementaryStreams;t.currentVideoSegmentLength$.next((((h=c==null?void 0:c.endPTS)!=null?h:0)-((p=c==null?void 0:c.startPTS)!=null?p:0))*1e3),t.currentAudioSegmentLength$.next((((m=d==null?void 0:d.endPTS)!=null?m:0)-((b=d==null?void 0:d.startPTS)!=null?b:0))*1e3)}),this.subscription.add($t(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,l=>{this.hls.nextLevel=l?-1:this.hls.currentLevel,this.hls.loadLevel=l?-1:this.hls.loadLevel},{onError:i}));let n=l=>{var c;return(c=Array.from(this.trackLevels.values()).find(({level:d})=>d===l))==null?void 0:c.track},o=rr(this.hls,Ke.Events.LEVEL_SWITCHED).pipe(Ln(({level:l})=>n(this.hls.levels[l])));o.pipe(XC(JC)).subscribe(t.currentVideoTrack$,i),this.subscription.add($t(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),l=>{var m;if(ZC(l))return;let c=(m=this.trackLevels.get(l.id))==null?void 0:m.level;if(!c)return;let d=this.hls.levels.indexOf(c),h=this.hls.currentLevel,p=this.hls.levels[h];!p||c.bitrate>p.bitrate?this.hls.nextLevel=d:(this.hls.loadLevel=d,this.hls.loadLevel=d)},{changed$:o,onError:i})),s(r.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);let u=eD(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,iD(["init"])).pipe(KC(0));this.subscription.add(u.subscribe(this.syncPlayback,i))}prepare(){this.videoState.startTransitionTo("ready"),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}async playIfAllowed(){this.videoState.startTransitionTo("playing"),await ke(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:$n.DOM,thrown:t}))||(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused",!0))}pause(){this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.hls.stopLoad(),this.hls.detachMedia(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"),P(this.params.desiredState.playbackState,"stopped",!0)}};var Wy="X-Playback-Duration",nc=async a=>{var r;let e=await at(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(Wy)?parseInt(e.headers.get(Wy),10):void 0};import{assertNever as fD,combine as bD,debounce as gD,ErrorCategory as Dn,filter as vD,filterChanged as SD,isNonNullable as Ky,isNullable as Vn,map as Xy,merge as yD,observableFrom as TD,Subscription as ID,ValueSubject as lc,VideoQuality as ED}from"@vkontakte/videoplayer-shared/es2018";var uc=C(au(),1);import{videoSizeToQuality as sD,getExponentialDelay as nD}from"@vkontakte/videoplayer-shared/es2018";var oD=a=>{let e=null;if(a.QUALITY&&(e=Ct(a.QUALITY)),!e&&a.RESOLUTION){let[t,i]=a.RESOLUTION.split("x").map(r=>parseInt(r,10));e=sD({width:t,height:i})}return e!=null?e:null},uD=(a,e)=>{var s,n;let t=a.split(`
|
|
125
|
+
`),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,uc.default)(l[1].split(",").map(S=>S.split("="))),h=(s=d.QUALITY)!=null?s:`stream-${d.BANDWIDTH}`,p=oD(d),m;d.BANDWIDTH&&(m=parseInt(d.BANDWIDTH,10)/1e3||void 0),!m&&d["AVERAGE-BANDWIDTH"]&&(m=parseInt(d["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let b=d["FRAME-RATE"]?parseFloat(d["FRAME-RATE"]):void 0,g;if(d.RESOLUTION){let[S,y]=d.RESOLUTION.split("x").map(I=>parseInt(I,10));S&&y&&(g={width:S,height:y})}let v=new URL(t[++o],e).toString();p&&i.push({id:h,quality:p,url:v,bandwidth:m,size:g,fps:b})}if(c){let d=(0,uc.default)(c[1].split(",").map(b=>{let g=b.indexOf("=");return[b.substring(0,g),b.substring(g+1)]}).map(([b,g])=>[b,g.replace(/^"|"$/g,"")])),h=(n=d.URI)==null?void 0:n.replace(/playlist$/,"subtitles.vtt"),p=d.LANGUAGE,m=d.NAME;h&&p&&r.push({type:"internal",id:p,label:m,language:p,url:h,isAuto:!1})}}}if(!i.length)throw new Error("Empty manifest");return{qualityManifests:i,textTracks:r}},lD=a=>new Promise(e=>{setTimeout(()=>{e()},a)}),oc=0,Yy=async(a,e=a,t,i)=>{let s=await(await at(a,i)).text();oc+=1;try{let{qualityManifests:n,textTracks:o}=uD(s,e);return{qualityManifests:n,textTracks:o}}catch(n){if(oc<=t.manifestRetryMaxCount)return await lD(nD(oc-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),Yy(a,e,t)}return{qualityManifests:[],textTracks:[]}},Mn=Yy;import{isNonNullable as cD,Subscription as dD,throttle as pD,ValueSubject as zy,Subject as hD,ErrorCategory as mD}from"@vkontakte/videoplayer-shared/es2018";var Cn=class{constructor(e,t,i,r,s){this.subscription=new dD;this.abortControllers={destroy:new me,nextManifest:null};this.prepareUrl=void 0;this.currentTextTrackData=null;this.availableTextTracks$=new zy(null);this.getCurrentTime$=new zy(null);this.error$=new hD;this.params={fetchManifestData:i,sourceUrl:r,downloadThreshold:s},this.subscription.add(e.pipe(pD(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 at(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(`
|
|
126
|
+
`),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(),h=new Date(i.programDateTime).valueOf();i.segmentStartTime=h-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(cD(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 me;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:mD.WTF,thrown:t,message:e})}};var qa=class{constructor(e){this.subscription=new ID;this.videoState=new D("stopped");this.textTracksManager=null;this.liveTextManager=null;this.manifests$=new lc([]);this.liveOffset=new ui;this.manifestStartTime$=new lc(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"),P(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(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"?P(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),P(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&P(this.params.desiredState.playbackState,"playing");return;case"paused":if(i==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let 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"&&(P(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return fD(t)}};var i;this.params=e,this.video=Ee(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:ED.INVARIANT,url:this.params.source.url};let t=(r,s)=>Mn(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 Cn(this.params.output.liveTime$,this.video,t,this.params.source.url,this.params.tuning.hlsLiveNewTextManagerDownloadThreshold):this.textTracksManager=new Ne(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:Dn.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:Dn.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(oe(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new lc((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(h=>h.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsLiveProvider",category:Dn.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},r=Ae(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(Pe(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(_e(this.video,t.playbackRate,r.playbackRateState$,i)),s(Fe(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"),P(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),P(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(SD(),Xy(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&&Ky(l.to)){let d=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let h=this.manifests$.getValue().find(p=>p.id===d);h&&(this.params.output.currentVideoTrack$.next(h),this.params.output.hostname$.next(oe(h.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(bD({startTime:this.manifestStartTime$.pipe(vD(Ky)),currentTime:r.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),i)),this.subscription.add(this.manifests$.pipe(Xy(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:h})=>({id:u,quality:l,size:c,fps:h,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,i));let n=yD(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,TD(["init"])).pipe(gD(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),xe(this.video)}prepare(){var o,u,l;let e=this.selectManifest();if(Vn(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[h,p]of[[c,"mq"],[d,"lq"]]){let m=String(parseFloat(h||""));p&&h&&r.searchParams.set(p,m)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,n=he(r.toString(),this.liveOffset.getTotalOffset(),s);(l=this.liveTextManager)==null||l.prepare(n),this.video.setAttribute("src",n),this.video.load(),nc(n).then(c=>{var d;if(!Vn(c))this.maxSeekBackTime$.next(c);else{let h=(d=this.params.source.maxSeekBackTime)!=null?d:this.maxSeekBackTime$.getValue();(Vn(h)||!isFinite(h))&&at(n).then(p=>p.text()).then(p=>{var b;let m=(b=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(p))==null?void 0:b[1];if(m){let g=new URL(m,n).toString();nc(g).then(v=>{Vn(v)||this.maxSeekBackTime$.next(v)})}}).catch(()=>{})}})}playIfAllowed(){ke(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),P(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Dn.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3),this.params.output.seekedEvent$.next()}generateLiveUrl(){let e=he(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 xD,debounce as PD,ErrorCategory as cc,fromEvent as dc,isNonNullable as wD,isNullable as AD,map as Jy,merge as Zy,observableFrom as eT,Subscription as kD,ValueSubject as RD,VideoQuality as $D}from"@vkontakte/videoplayer-shared/es2018";var Ua=class{constructor(e){this.subscription=new kD;this.videoState=new D("stopped");this.manifests$=new RD([]);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"),P(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(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"?P(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&P(this.params.desiredState.playbackState,"playing");return;case"paused":i==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&P(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return xD(t)}};this.textTracksManager=new Ne(e.source.url),this.params=e,this.video=Ee(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:$D.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(oe(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),Mn(he(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:cc.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(h=>h.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsProvider",category:cc.WTF,message:"HlsProvider internal logic error",thrown:o})},r=Ae(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(Jy(o=>o.to)),this.params.output.playbackState$),this.subscription.add(it(this.video,t.isLooped,i)),this.subscription.add(Pe(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(_e(this.video,t.playbackRate,r.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),P(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),P(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{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&&wD(l.to)){let m=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let b=this.manifests$.getValue().find(g=>g.id===m);b&&(this.params.output.currentVideoTrack$.next(b),this.params.output.hostname$.next(oe(b.url)))}let d=this.params.desiredState.playbackRate.getState(),h=(p=this.params.output.element$.getValue())==null?void 0:p.playbackRate;if(d!==h){let m=this.params.output.element$.getValue();m&&(this.params.desiredState.playbackRate.setState(d),m.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(Jy(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:h})=>({id:u,quality:l,size:c,fps:h,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,i)),!N.device.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(Zy(dc(o,"addtrack"),dc(o,"removetrack"),dc(o,"change"),eT(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},i))}let n=Zy(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,eT(["init"])).pipe(PD(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),xe(this.video)}prepare(){var s,n;let e=this.selectManifest();if(AD(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(){ke(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:cc.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var rT=C(Ci(),1),pc=C(ji(),1),aT=C(Dt(),1);import{assertNever as LD,assertNonNullable as tT,debounce as MD,ErrorCategory as iT,isHigherOrEqual as CD,isLowerOrEqual as DD,isNonNullable as VD,merge as OD,observableFrom as BD,Subscription as _D,map as ND}from"@vkontakte/videoplayer-shared/es2018";var Ha=class{constructor(e){this.subscription=new _D;this.videoState=new D("stopped");this.trackUrls={};this.textTracksManager=new Ne;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"),P(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"?P(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(i==null?void 0:i.to)==="playing"&&P(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&P(this.params.desiredState.playbackState,"paused");return;default:return LD(e)}};this.params=e,this.video=Ee(e.container,e.tuning),this.params.output.element$.next(this.video),(0,rT.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,pc.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:iT.WTF,message:"MpegProvider internal logic error",thrown:o})},r=Ae(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(ND(o=>o.to)),this.params.output.playbackState$),this.subscription.add(it(this.video,t.isLooped,i)),this.subscription.add(Pe(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(_e(this.video,t.playbackRate,r.playbackRateState$,i)),s(Fe(this.video),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),P(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),P(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{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&&VD(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 h=this.params.output.element$.getValue();h&&(this.params.desiredState.playbackRate.setState(c),h.playbackRate=c)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.textTracksManager.connect(this.video,t,e);let n=OD(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,BD(["init"])).pipe(MD(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),xe(this.video)}prepare(){var i;let e=(i=this.params.desiredState.videoTrack.getState())==null?void 0:i.id;tT(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];tT(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=ka(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(oe(t))}playIfAllowed(){ke(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:iT.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 h=Ot(n,{container:this.video.getBoundingClientRect(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,limits:d,abrLogger:this.params.dependencies.abrLogger});t(h)},r=(l=this.params.output.currentVideoTrack$.getValue())==null?void 0:l.quality,s=!!(e.max||e.min),n=(0,pc.default)(this.trackUrls).map(d=>d.track);if(!r||!s||qr({limits:e,lowestAvailableQuality:(c=(0,aT.default)(n,-1))==null?void 0:c.quality,highestAvailableQuality:n[0].quality})){i();return}let o=e.max?DD(r,e.max):!0,u=e.min?CD(r,e.min):!0;o&&u||i(e)}};import{assertNever as nT,debounce as HD,merge as oT,observableFrom as jD,Subscription as QD,map as uT,ValueSubject as GD,ErrorCategory as mc,VideoQuality as WD}from"@vkontakte/videoplayer-shared/es2018";import{ErrorCategory as FD}from"@vkontakte/videoplayer-shared/es2018";var sT=["stun:videostun.mycdn.me:80"],qD=1e3,UD=3,hc=()=>null,On=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=hc;this.externalStopCallback=hc;this.externalErrorCallback=hc;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:sT}]};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:FD.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),qD)}normalizeOptions(e={}){let t={stunServerList:sT,maxRetryNumber:UD,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var ja=class{constructor(e){this.videoState=new D("stopped");this.maxSeekBackTime$=new GD(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"),P(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"),P(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(i==null?void 0:i.to)==="playing"&&P(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&P(this.params.desiredState.playbackState,"paused");return;default:return nT(e)}};this.subscription=new QD,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=Ee(e.container,e.tuning),this.liveStreamClient=new On(this.params.source.url,{maxRetryNumber:this.params.tuning.webrtc.connectionRetryMaxNumber,errorChanel:this.params.output.error$}),this.liveStreamClient.onStart(this.onLiveStreamStart.bind(this)),this.liveStreamClient.onStop(this.onLiveStreamStop.bind(this)),this.liveStreamClient.onError(this.onLiveStreamError.bind(this)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),xe(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,i=n=>{e.error$.next({id:"WebRTCLiveProvider",category:mc.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};this.subscription.add(oT(this.videoState.stateChangeStarted$.pipe(uT(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(uT(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})}));let r=Ae(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(Fe(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(Pe(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 nT(n.to)}},i)).add(oT(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,jD(["init"])).pipe(HD(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(oe(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:WD.INVARIANT}),this.video.srcObject=e,P(this.params.desiredState.playbackState,"playing")}onLiveStreamStop(){this.videoState.startTransitionTo("stopped"),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.params.output.endedEvent$.next()}onLiveStreamError(e){this.onLiveStreamStop(),this.params.output.error$.next({id:"WebRTC stream runtime error",category:mc.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){ke(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:mc.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var Qa=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 Wa,assertNonNullable as qt,ErrorCategory as Bn,filter as mT,isNonNullable as fT,isNullable as e0,map as t0,merge as i0,once as r0,Subject as le,Subscription as bT,ValueSubject as V,flattenObject as gT}from"@vkontakte/videoplayer-shared/es2018";import{Observable as YD,map as lT,Subscription as zD,Subject as KD}from"@vkontakte/videoplayer-shared/es2018";var cT=a=>new YD(e=>{let t=new zD,i=a.desiredPlaybackState$.stateChangeStarted$.pipe(lT(({from:l,to:c})=>`${l}-${c}`)),r=a.desiredPlaybackState$.stateChangeEnded$,s=a.providerChanged$.pipe(lT(({type:l})=>l!==void 0)),n=new KD,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 XD,Subscription as JD,combine as ZD,filter as pT,once as hT}from"@vkontakte/videoplayer-shared/es2018";function dT(){return new(window.AudioContext||window.webkitAudioContext)}var Ga=class Ga{constructor(e,t,i,r){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=i;this.volumeMultiplier=r;this.destroyController=new me;this.subscriptions=new JD;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe(pT(s=>!!s.type),hT()).subscribe(({type:s})=>this.subscribe(s)))}subscribe(e){N.browser.isSafari&&e!=="MPEG"||this.subscriptions.add(ZD({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(pT(({playbackState:t,video:i,volume:{muted:r,volume:s}})=>t==="playing"&&!!i&&!r&&!!s),hT()).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=dT();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:Ga.errorId,category:XD.VIDEO_PIPELINE,message:(t=e==null?void 0:e.message)!=null?t:`${Ga.errorId} exception`,thrown:e})}};Ga.errorId="VolumeMultiplierManager";var ar=Ga;var a0={chunkDuration:5e3,maxParallelRequests:5},Ya=class{constructor(e){this.current$=new V({type:void 0});this.providerError$=new le;this.noAvailableProvidersError$=new le;this.volumeMultiplierError$=new le;this.providerOutput={position$:new V(0),duration$:new V(1/0),volume$:new V({muted:!1,volume:1}),availableVideoStreams$:new V([]),currentVideoStream$:new V(void 0),availableVideoTracks$:new V([]),currentVideoTrack$:new V(void 0),availableAudioStreams$:new V([]),currentAudioStream$:new V(void 0),availableAudioTracks$:new V([]),currentVideoSegmentLength$:new V(0),currentAudioSegmentLength$:new V(0),isAudioAvailable$:new V(!0),autoVideoTrackLimitingAvailable$:new V(!1),autoVideoTrackLimits$:new V(void 0),currentBuffer$:new V(void 0),isBuffering$:new V(!0),error$:new le,fetcherError$:new le,fetcherRecoverableError$:new le,warning$:new le,willSeekEvent$:new le,soundProhibitedEvent$:new le,seekedEvent$:new le,loopedEvent$:new le,endedEvent$:new le,firstBytesEvent$:new le,loadedMetadataEvent$:new le,firstFrameEvent$:new le,canplay$:new le,isLive$:new V(void 0),isLiveEnded$:new V(null),isLowLatency$:new V(!1),canChangePlaybackSpeed$:new V(!0),liveTime$:new V(void 0),liveBufferTime$:new V(void 0),liveLatency$:new V(void 0),severeStallOccurred$:new le,availableTextTracks$:new V([]),currentTextTrack$:new V(void 0),hostname$:new V(void 0),httpConnectionType$:new V(void 0),httpConnectionReused$:new V(void 0),inPiP$:new V(!1),inFullscreen$:new V(!1),element$:new V(void 0),elementVisible$:new V(!0),availableSources$:new V(void 0),is3DVideo$:new V(!1),playbackState$:new V(""),getCurrentTime$:new V(null)};this.subscription=new bT;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=wy([...ky(this.params.tuning),...Ay(this.params.tuning)],this.params.tuning).filter(l=>fT(e.sources[l])),{forceFormat:i,formatsToAvoid:r}=this.params.tuning,s=[];i?s=[i]:r.length?s=[...t.filter(l=>!(0,fc.default)(r,l)),...t.filter(l=>(0,fc.default)(r,l))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",gT(s)),this.screenFormatsIterator=new Qa(s);let n=[...Ql(!0),...Ql(!1)];this.chromecastFormatsIterator=new Qa(n.filter(l=>fT(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:o=1,tuning:{useVolumeMultiplier:u}}=this.params;u&&o!==1&&ar.isSupported()&&(this.volumeMultiplierManager=new ar(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(e0(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:Bn.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");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})}e.destroy();let s=this.providerOutput.isBuffering$;s.getValue()||s.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),this.tracer.log("createProvider",{destination:e,format:t}),e){case"SCREEN":return this.createScreenProvider(t);case"CHROMECAST":return this.createChromecastProvider(t);default:return Wa(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 qt(u),new Ba({...o,source:u,sourceHls:l})}case"DASH_LIVE_CMAF":{let u=this.applyFailoverHost(t[e]);return qt(u),new _a({...o,source:u})}case"HLS":case"HLS_ONDEMAND":{let u=this.applyFailoverHost(t[e]);return qt(u),N.video.nativeHlsSupported||!this.params.tuning.useHlsJs?new Ua({...o,source:u}):new Fa({...o,source:u})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let u=this.applyFailoverHost(t[e]);return qt(u),new qa({...o,source:u,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let u=this.applyFailoverHost(t[e]);return qt(u),new Ha({...o,source:u})}case"DASH_LIVE":{let u=this.applyFailoverHost(t[e]);return qt(u),new Sv({...o,source:u,config:{...a0,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let u=this.applyFailoverHost(t[e]);return qt(u),new ja({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 Wa(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 qt(o),new Vr({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 Wa(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return Wa(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 Wa(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,ST.default)((0,vT.default)(e).map(([r,s])=>[r,i(s)]))}initProviderErrorHandling(){let e=new bT,t=!1,i=0;return e.add(i0(this.providerOutput.error$.pipe(mT(r=>!this.params.tuning.ignoreAudioRendererError||!r.message||!/AUDIO_RENDERER_ERROR/ig.test(r.message))),cT({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(t0(r=>({id:`ProviderHangup:${r}`,category:Bn.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(mT(({to:s})=>s==="playing"),r0()).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===Bn.NETWORK,u=r.category===Bn.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"))}this.tracer.error("providerError",gT(n))})),e}};import{fromEvent as _n,once as s0,combine as n0,Subscription as yT,ValueSubject as bc,map as o0,filter as u0,isNonNullable as Nn,now as Ve,safeStorage as gc}from"@vkontakte/videoplayer-shared/es2018";var l0=5e3,TT="one_video_throughput",IT="one_video_rtt",vt=window.navigator.connection,ET=()=>{let a=vt==null?void 0:vt.downlink;if(Nn(a)&&a!==10)return a*1e3},xT=()=>{let a=vt==null?void 0:vt.rtt;if(Nn(a)&&a!==3e3)return a},PT=(a,e,t)=>{let i=t*8,r=i/a;return i/(r+e)},vc=class a{constructor(e){this.subscription=new yT;this.concurrentDownloads=new Set;var r,s;this.tuningConfig=e;let t=a.load(TT)||(e.useBrowserEstimation?ET():void 0)||l0,i=(s=(r=a.load(IT))!=null?r:e.useBrowserEstimation?xT():void 0)!=null?s:0;if(this.throughput$=new bc(t),this.rtt$=new bc(i),this.rttAdjustedThroughput$=new bc(PT(t,i,e.rttPenaltyRequestSize)),this.throughput=hi.getSmoothedValue(t,-1,e),this.rtt=hi.getSmoothedValue(i,1,e),e.useBrowserEstimation){let n=()=>{let u=ET();u&&this.throughput.next(u);let l=xT();Nn(l)&&this.rtt.next(l)};vt&&"onchange"in vt&&this.subscription.add(_n(vt,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{gc.set(TT,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{gc.set(IT,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(n0({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(o0(({throughput:n,rtt:o})=>PT(n,o,e.rttPenaltyRequestSize)),u0(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=Ve(),r=new yT;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add(_n(e,"progress").pipe(s0()).subscribe(s=>{t=s.loaded,i=Ve()}));break;case 1:case 0:r.add(_n(e,"loadstart").subscribe(()=>{t=0,i=Ve()}));break}r.add(_n(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=Ve(),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=Ve(),n=0,o=Ve(),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,Ve()-s,1),this.concurrentDownloads.delete(e);else if(d){if(t){let h=Ve();if(h-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||h-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let m=o-s;m&&this.addRawSpeed(n,m,1,t),n=d.byteLength,s=Ve()}else n+=d.byteLength;o=Ve()}else r+=d.byteLength,n+=d.byteLength,n>=this.tuningConfig.streamMinSampleSize&&Ve()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,Ve()-o,this.concurrentDownloads.size),n=0,o=Ve());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=gc.get(e);if(Nn(t))return(i=parseInt(t,10))!=null?i:void 0}},wT=vc;import{fillWithDefault as c0,VideoQuality as Fn}from"@vkontakte/videoplayer-shared/es2018";var AT={configName:["core"],throughputEstimator:{type:"EmaAndMa",emaAlphaSlow:.2,emaAlphaFast:.7,emaAlpha:.45,basisTrendChangeCount:10,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1*1024*1024,streamMinSampleSize:10*1024,streamMinSampleTime:300,deviationDepth:20,deviationFactor:.5,lowLatency:{continuesByteSequenceInterval:50,maxLastEvaluationTimeout:300}},autoTrackSelection:{bitrateFactorAtEmptyBuffer:2.8,bitrateAudioFactorAtEmptyBuffer:10,bitrateFactorAtFullBuffer:2,bitrateAudioFactorAtFullBuffer:7,minVideoAudioRatio:5,minAvailableThroughputAudioRatio:5,usePixelRatio:!0,pixelRatioMultiplier:void 0,pixelRatioLogBase:3,pixelRatioLogCoefficients:[1,0,1],limitByContainer:!0,containerSizeFactor:1.3,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldownIncreaseQuality:15e3,trackCooldownDecreaseQuality:3e3,backgroundVideoQualityLimit:Fn.Q_4320P,activeVideoAreaThreshold:.1,highQualityLimit:Fn.Q_720P,trafficSavingLimit:Fn.Q_480P},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:Fn.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,seekBiasInTheEnd:2e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,crashOnStallTimeout:25e3,crashOnStallTWithoutDataTimeout:5e3,enableSubSegmentBufferFeeding:!0,bufferEmptinessTolerance:100,useFetchPriorityHints:!0,qualityLimitsOnStall:{stallDurationNoDataBeforeQualityDecrease:500,stallDurationToBeCount:100,stallCountBeforeQualityDecrease:3,resetQualityRestrictionTimeout:1e4,ignoreStallsOnSeek:!1},enableBaseUrlSupport:!0,maxSegmentRetryCount:5,sourceOpenTimeout:1e3,rejectOnSourceOpenTimeout:!1},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,maxLiveDuration:7200,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:250,playbackCatchupSpeedup:.05,isActiveOnDefault:!1,bufferEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:"07A4434E",useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"dash",preferCMAF:!1,preferWebRTC:!1,preferMultiStream:!1,preferHDR:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,seekNearDurationBias:1,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useHlsJs:!1,useNativeHLSTextTracks:!1,useManagedMediaSource:!0,useNewSwitchTo:!1,useSafariEndlessRequestBugfix:!0,useRefactoredSearchGap:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,audioVideoSyncRate:20,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50},useVolumeMultiplier:!1,ignoreAudioRendererError:!1,useEnableSubtitlesParam:!1,useOldMSEDetection:!1,useHlsLiveNewTextManager:!1,exposeInternalsToGlobal:!1,hlsLiveNewTextManagerDownloadThreshold:4e3,disableYandexPiP:!1,asyncResolveClientChecker:!1,autostartOnlyIfVisible:!1},kT=a=>{var e;return{...c0(a,AT),configName:[...(e=a.configName)!=null?e:[],...AT.configName]}};import{assertNonNullable as qn,combine as St,ErrorCategory as Un,filter as M,filterChanged as G,fromEvent as yc,isNonNullable as MT,isNullable as g0,Logger as v0,map as j,mapTo as CT,merge as Ut,now as Hn,once as F,Subject as z,Subscription as DT,tap as Tc,ValueSubject as x,isHigher as S0,isInvariantQuality as VT,flattenObject as Ht,throttle as Ic,getTraceSubscriptionMethod as OT,Tracer as y0,InternalsExposure as T0}from"@vkontakte/videoplayer-shared/es2018";import{merge as d0,map as p0,filter as RT,isNonNullable as h0}from"@vkontakte/videoplayer-shared/es2018";var Sc=({seekState:a,position$:e})=>d0(a.stateChangeEnded$.pipe(p0(({to:t})=>{var i;return t.state==="none"?void 0:((i=t.position)!=null?i:NaN)/1e3}),RT(h0)),e.pipe(RT(()=>a.getState().state==="none")));import{assertNonNullable as m0}from"@vkontakte/videoplayer-shared/es2018";var $T=a=>{let e=typeof a.container=="string"?document.getElementById(a.container):a.container;return m0(e,`Wrong container or containerId {${a.container}}`),e};import{filter as f0,once as b0}from"@vkontakte/videoplayer-shared/es2018";var LT=(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(f0(r=>r.length>0),b0()).subscribe(r=>{r.find(i)&&e.startTransitionTo(a)}):(a===void 0||t!=null&&t.getValue().find(i))&&e.startTransitionTo(a)};var jn=class{constructor(e={configName:[]},t=y0.createRootTracer(!1)){this.subscription=new DT;this.logger=new v0;this.abrLogger=this.logger.createComponentLog("ABR");this.internalsExposure=null;this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new x(!1);this.hasLiveOffsetByPausedTimer=0;this.playerInitRequest=0;this.playerInited=new x(!1);this.wasSetStartedQuality=!1;this.desiredState={playbackState:new D("stopped"),seekState:new D({state:"none"}),volume:new D({volume:1,muted:!1}),videoTrack:new D(void 0),videoStream:new D(void 0),audioStream:new D(void 0),autoVideoTrackSwitching:new D(!0),autoVideoTrackLimits:new D({}),isLooped:new D(!1),isLowLatency:new D(!1),playbackRate:new D(1),externalTextTracks:new D([]),internalTextTracks:new D([]),currentTextTrack:new D(void 0),textTrackCuesSettings:new D({}),cameraOrientation:new D({x:0,y:0})};this.info={playbackState$:new x(void 0),position$:new x(0),duration$:new x(1/0),muted$:new x(!1),volume$:new x(1),availableVideoStreams$:new x([]),currentVideoStream$:new x(void 0),availableQualities$:new x([]),availableQualitiesFps$:new x({}),currentQuality$:new x(void 0),isAutoQualityEnabled$:new x(!0),autoQualityLimitingAvailable$:new x(!1),autoQualityLimits$:new x({}),predefinedQualityLimitType$:new x("unknown"),availableAudioStreams$:new x([]),currentAudioStream$:new x(void 0),availableAudioTracks$:new x([]),isAudioAvailable$:new x(!0),currentPlaybackRate$:new x(1),currentBuffer$:new x({start:0,end:0}),isBuffering$:new x(!0),isStalled$:new x(!1),isEnded$:new x(!1),isLooped$:new x(!1),isLive$:new x(void 0),isLiveEnded$:new x(null),canChangePlaybackSpeed$:new x(void 0),atLiveEdge$:new x(void 0),atLiveDurationEdge$:new x(void 0),liveTime$:new x(void 0),liveBufferTime$:new x(void 0),liveLatency$:new x(void 0),currentFormat$:new x(void 0),availableTextTracks$:new x([]),currentTextTrack$:new x(void 0),throughputEstimation$:new x(void 0),rttEstimation$:new x(void 0),videoBitrate$:new x(void 0),hostname$:new x(void 0),httpConnectionType$:new x(void 0),httpConnectionReused$:new x(void 0),surface$:new x("none"),chromecastState$:new x("NOT_AVAILABLE"),chromecastDeviceName$:new x(void 0),intrinsicVideoSize$:new x(void 0),availableSources$:new x(void 0),is3DVideo$:new x(!1),currentVideoSegmentLength$:new x(0),currentAudioSegmentLength$:new x(0)};this.events={inited$:new z,ready$:new z,started$:new z,playing$:new z,paused$:new z,stopped$:new z,willStart$:new z,willResume$:new z,willPause$:new z,willStop$:new z,willDestruct$:new z,watchCoverageRecord$:new z,watchCoverageLive$:new z,managedError$:new z,fatalError$:new z,fetcherRecoverableError$:new z,ended$:new z,looped$:new z,seeked$:new z,willSeek$:new z,autoplaySoundProhibited$:new z,firstBytes$:new z,loadedMetadata$:new z,firstFrame$:new z,canplay$:new z,log$:new z,fetcherError$:new z,severeStallOccured$:new z};this.experimental={element$:new x(void 0),tuningConfigName$:new x([]),enableDebugTelemetry$:new x(!1),dumpTelemetry:Hg,getCurrentTime$:new x(null)};if(this.initLogs(),this.tuning=kT(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new fs({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new wT(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new T0("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(h=>JSON.stringify(h,(p,m)=>{let b=typeof m;return(0,BT.default)(["number","string","boolean"],b)?m:m===null?null:`<${b}>`})),c=`Player.${String(r)}`,d=`Exception calling ${c} (${l.join(", ")})`;throw this.events.fatalError$.next({id:c,category:Un.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});let t=()=>{var u,l,c;let{container:n,...o}=e;this.tracer.log("initVideo",Ht(o)),this.domContainer=$T(e),this.chromecastInitializer.contentId=(u=e.meta)==null?void 0:u.videoId,this.providerContainer=new Ya({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.setMuted(this.tuning.isAudioDisabled),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(M(n=>!!n),F()).subscribe(()=>{console.log("Core SDK async start"),i()}):i()};return this.isNotActiveTabCase()?(this.tracer.log("request play from hidden tab"),yc(document,"visibilitychange").pipe(F()).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(M(e=>!!e),F()).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(M(e=>!!e),F()).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(M(e=>!!e),F()).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(M(e=>!!e),F()).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(M(i=>!!i),F()).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(M(t=>!!t),F()).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(M(i=>!!i),F()).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){return this.subscription.add(this.playerInited.pipe(M(t=>!!t),F()).subscribe(()=>{var n;let t=this.desiredState.volume,i=this.tuning.isAudioDisabled||e,r=t.getTransition(),s=(n=r==null?void 0:r.to.volume)!=null?n:this.info.volume$.getValue();this.tracer.log("setMuted",{isMuted:e,nextMuted:i,volume:s,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue()}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setMuted(i):t.startTransitionTo({volume:s,muted:i})})),this}setVideoStream(e){return this.subscription.add(this.playerInited.pipe(M(t=>!!t),F()).subscribe(()=>{this.desiredState.videoStream.startTransitionTo(e)})),this}setAudioStream(e){return this.subscription.add(this.playerInited.pipe(M(t=>!!t),F()).subscribe(()=>{this.desiredState.audioStream.startTransitionTo(e)})),this}setQuality(e){return this.subscription.add(this.playerInited.pipe(M(t=>!!t),F()).subscribe(()=>{qn(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(M(i=>i.length>0),F()).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(M(t=>!!t),F()).subscribe(()=>{this.tracer.log("setAutoQuality",{enable:e}),this.desiredState.autoVideoTrackSwitching.startTransitionTo(e)})),this}setAutoQualityLimits(e){return this.subscription.add(this.playerInited.pipe(M(t=>!!t),F()).subscribe(()=>{this.tracer.log("setAutoQualityLimits",Ht(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e)})),this}setPredefinedQualityLimits(e){return this.subscription.add(this.playerInited.pipe(M(t=>!!t),F()).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(M(t=>!!t),F()).subscribe(()=>{var i;qn(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(M(t=>!!t),F()).subscribe(()=>{e.length&&this.tracer.log("setExternalTextTracks",Ht(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t})))})),this}selectTextTrack(e){return this.subscription.add(this.playerInited.pipe(M(t=>!!t),F()).subscribe(()=>{var t;LT(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(M(t=>!!t),F()).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(M(t=>!!t),F()).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(M(i=>!!i),F()).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(M(t=>!!t),F()).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(M(i=>!!i),F()).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(M(e=>e),F()).subscribe(()=>{let e=this.getScene3D();e&&e.holdCamera()})),this}releaseCamera(){return this.subscription.add(this.playerInited.pipe(M(e=>!!e),F()).subscribe(()=>{let e=this.getScene3D();e&&e.releaseCamera()})),this}getExactTime(){if(!this.providerContainer)return 0;let e=this.providerContainer.providerOutput.element$.getValue();if(g0(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),i=t.state==="none"?void 0:t.position;return MT(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(Ut(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(j(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(j(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(j(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(j(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(j(e=>e.to)).subscribe(e=>{this.info.autoQualityLimits$.next(e);let{highQualityLimit:t,trafficSavingLimit:i}=this.tuning.autoTrackSelection;this.info.predefinedQualityLimitType$.next(il({limits:e,highQualityLimit:t,trafficSavingLimit:i}))})),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(M(({from:e})=>e==="stopped"),F()).subscribe(()=>{this.initedAt=Hn(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case"ready":this.events.ready$.next();break;case"playing":this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case"paused":this.events.paused$.next();break;case"stopped":this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case"paused":this.events.willPause$.next();break;case"playing":this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case"stopped":this.events.willStop$.next();break;default:}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("willSeekEvent",Ht(n)),n.state==="requested"?this.desiredState.seekState.setState({...n,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:Un.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe(F()).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",Ht(n)),n.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe(j(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(j(n=>n.destination),G()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(St({availableVideoTracks:e.providerOutput.availableVideoTracks$,currentVideoStream:e.providerOutput.currentVideoStream$}).pipe(j(({availableVideoTracks:n,currentVideoStream:o})=>n.filter(u=>o?o.id===u.streamId:!0).map(({quality:u})=>u).sort((u,l)=>VT(u)?1:VT(l)?-1:S0(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(G()).subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.pipe(M(n=>MT(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(G((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe(G((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(G()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(G()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(G()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.autoVideoTrackLimits$.subscribe(n=>{this.desiredState.autoVideoTrackLimits.setState(n!=null?n:{})})).add(e.providerOutput.currentBuffer$.pipe(j(n=>n?{start:n.from,end:n.to}:{start:0,end:0})).subscribe(this.info.currentBuffer$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.isLiveEnded$.pipe(Tc(n=>n&&this.stop())).subscribe(this.info.isLiveEnded$)).add(e.providerOutput.canChangePlaybackSpeed$.subscribe(this.info.canChangePlaybackSpeed$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.liveBufferTime$.subscribe(this.info.liveBufferTime$)).add(e.providerOutput.liveLatency$.subscribe(this.info.liveLatency$)).add(St({hasLiveOffsetByPaused:Ut(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(j(n=>n.to),G(),j(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(St({atLiveEdge:St({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Sc({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(j(({isLive:n,position:o,isLowLatency:u})=>{let l=this.getActiveLiveDelay(u);return n&&Math.abs(o)<l/1e3}),G(),Tc(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(j(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add(St({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(j(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),G(),Tc(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(j(n=>n.muted),G()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(j(n=>n.volume),G()).subscribe(this.info.volume$)).add(Sc({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(Ut(e.providerOutput.endedEvent$.pipe(CT(!0)),e.providerOutput.seekedEvent$.pipe(CT(!1))).pipe(G()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.providerOutput.fetcherRecoverableError$.subscribe(this.events.fetcherRecoverableError$)).add(e.providerOutput.fetcherError$.subscribe(this.events.fatalError$)).add(e.volumeMultiplierError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe(j(n=>({id:n?`No${n}`:"NoProviders",category:Un.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(F(),j(n=>n!=null?n:Hn()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(F(),j(()=>Hn()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(F(),j(()=>Hn()-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 x(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let i=new x(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(M(({to:n})=>n==="playing"),F()).subscribe(()=>i.next(!1)));let r=0,s=Ut(e.providerOutput.isBuffering$,t,i).pipe(j(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||i.getValue();return n&&!o}),G());this.subscription.add(s.subscribe(n=>{n?r=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(r),this.info.isStalled$.next(!1))})),this.subscription.add(Ut(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(Ut(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(j(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 DT;this.subscription.add(t),this.subscription.add(e.current$.pipe(G((i,r)=>i.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(M(i=>i.length>0),F()).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=Ot(e,{container:this.domContainer.getBoundingClientRect(),panelSize:this.config.panelSize,estimatedThroughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),playbackRate:this.info.currentPlaybackRate$.getValue(),forwardBufferHealth:0,abrLogger:this.abrLogger})),this.desiredState.videoTrack.startTransitionTo(t),this.info.currentQuality$.next(t.quality),this.info.videoBitrate$.next(t.bitrate)}initLogs(){this.subscription.add(Ut(this.desiredState.videoTrack.stateChangeStarted$.pipe(j(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(j(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(j(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(j(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(j(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(j(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(j(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(j(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(j(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;qn(this.providerContainer),qn(e),Ug(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(i=>qg(i)),this.providerContainer.current$.subscribe(({type:i})=>Fr("provider",i)),e.duration$.subscribe(i=>Fr("duration",i)),e.availableVideoTracks$.pipe(M(i=>!!i.length),F()).subscribe(i=>Fr("tracks",i)),this.events.fatalError$.subscribe(new ve("fatalError")),this.events.managedError$.subscribe(new ve("managedError")),e.position$.subscribe(new ve("position")),e.currentVideoTrack$.pipe(j(i=>i==null?void 0:i.quality)).subscribe(new ve("quality")),this.info.currentBuffer$.subscribe(new ve("buffer")),e.isBuffering$.subscribe(new ve("isBuffering"))].forEach(i=>this.subscription.add(i)),Fr("codecs",N.video.supportedCodecs)}initTracerSubscription(){let e=OT(this.tracer.log.bind(this.tracer)),t=OT(this.tracer.error.bind(this.tracer));this.subscription.add(this.info.playbackState$.subscribe(e("playbackState"))).add(this.info.isLooped$.subscribe(e("isLooped"))).add(this.info.currentPlaybackRate$.pipe(G()).subscribe(e("currentPlaybackRate"))).add(this.info.isAutoQualityEnabled$.subscribe(e("isAutoQualityEnabled"))).add(this.info.autoQualityLimits$.subscribe(e("autoQualityLimits"))).add(this.info.currentFormat$.subscribe(e("currentFormat"))).add(this.info.availableQualities$.subscribe(e("availableQualities"))).add(this.info.availableQualitiesFps$.subscribe(e("availableQualitiesFps"))).add(this.info.availableAudioTracks$.subscribe(e("availableAudioTracks"))).add(this.info.isAudioAvailable$.subscribe(e("isAudioAvailable"))).add(St({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe(M(({currentQuality:i,videoBitrate:r})=>!!i&&!!r),G((i,r)=>i.currentQuality===r.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe(M(i=>i>0),G()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe(M(i=>i>0),G()).subscribe(e("currentAudioSegmentLength"))).add(this.info.hostname$.subscribe(e("hostname"))).add(this.info.currentTextTrack$.subscribe(e("currentTextTrack"))).add(this.info.availableTextTracks$.subscribe(e("availableTextTracks"))).add(this.info.autoQualityLimitingAvailable$.subscribe(e("autoQualityLimitingAvailable"))).add(St({currentBuffer:this.info.currentBuffer$.pipe(M(i=>i.end>0),G((i,r)=>i.end===r.end&&i.start===r.start)),position:this.info.position$.pipe(G())}).pipe(Ic(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe(G()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe(G()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe(G()).subscribe(e("canChangePlaybackSpeed"))).add(St({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(M(({liveTime:i,liveBufferTime:r})=>!!i&&!!r),Ic(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(G(),M(i=>i===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(G(),M(i=>i===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe(G()).subscribe(e("muted"))).add(this.info.volume$.pipe(G()).subscribe(e("volume"))).add(this.info.isEnded$.pipe(G(),M(i=>i===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add(St({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(M(({throughputEstimation:i,rtt:r})=>!!i&&!!r),Ic(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(G(),M(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:Un.DOM,message:String(r)})})};this.subscription.add(Ut(yc(document,"visibilitychange"),yc(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",Ht({quality:t,availableTracks:Ht(e),track:Ht(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&&!Wr()}};import{Subscription as m5,Observable as f5,Subject as b5,ValueSubject as g5,VideoQuality as v5}from"@vkontakte/videoplayer-shared/es2018";var S5=`@vkontakte/videoplayer-core@${ud}`;export{us as ChromecastState,Kn as HttpConnectionType,f5 as Observable,$e as PlaybackState,jn as Player,ls as PredefinedQualityLimits,S5 as SDK_VERSION,b5 as Subject,m5 as Subscription,Xn as Surface,ud as VERSION,g5 as ValueSubject,lt as VideoFormat,v5 as VideoQuality,N as clientChecker,_r as isMobile};
|