@vkontakte/videoplayer-core 2.0.136-dev.b3347749.0 → 2.0.136-dev.b7a1035a.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 +36 -36
- package/es2015.esm.js +36 -36
- package/es2018.cjs.js +44 -44
- package/es2018.esm.js +44 -44
- package/es2024.cjs.js +43 -43
- package/es2024.esm.js +45 -45
- package/esnext.cjs.js +43 -43
- package/esnext.esm.js +45 -45
- package/evergreen.esm.js +44 -44
- package/package.json +2 -2
- package/types/index.d.ts +1 -0
- package/types/player/Player.d.ts +1 -0
- package/types/player/types.d.ts +4 -0
- package/types/providers/DashProvider/lib/buffer.d.ts +1 -0
- package/types/providers/DashProvider/lib/fetcher.d.ts +1 -0
- package/types/providers/DashProvider/lib/player.d.ts +4 -0
- package/types/providers/DashProviderNew/lib/buffer.d.ts +1 -0
- package/types/providers/DashProviderNew/lib/fetcher.d.ts +1 -0
- package/types/providers/DashProviderNew/lib/player.d.ts +4 -0
- package/types/providers/ProviderContainer/utils/formatsSupport.d.ts +0 -2
- package/types/providers/types.d.ts +1 -0
- package/types/providers/utils/parsers/mpeg/BoxModel.d.ts +4 -4
- package/types/providers/utils/parsers/mpeg/box.d.ts +7 -7
- package/types/providers/utils/parsers/mpeg/boxes/index.d.ts +25 -25
- package/types/providers/utils/parsers/mpeg/boxes/uuid.d.ts +13 -6
- package/types/utils/tuningConfig.d.ts +2 -0
- package/types/utils/videoFormat.d.ts +6 -1
package/es2018.esm.js
CHANGED
|
@@ -1,85 +1,85 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @vkontakte/videoplayer-core v2.0.136-dev.
|
|
3
|
-
*
|
|
2
|
+
* @vkontakte/videoplayer-core v2.0.136-dev.b7a1035a.0
|
|
3
|
+
* Mon, 28 Jul 2025 10:52:47 GMT
|
|
4
4
|
* https://st.mycdn.me/static/vkontakte-videoplayer/2-0-136/doc/
|
|
5
5
|
*/
|
|
6
|
-
var BE=Object.create;var Cp=Object.defineProperty;var VE=Object.getOwnPropertyDescriptor;var _E=Object.getOwnPropertyNames;var OE=Object.getPrototypeOf,FE=Object.prototype.hasOwnProperty;var b=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports);var NE=(a,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of _E(e))!FE.call(a,r)&&r!==t&&Cp(a,r,{get:()=>e[r],enumerable:!(i=VE(e,r))||i.enumerable});return a};var N=(a,e,t)=>(t=a!=null?BE(OE(a)):{},NE(e||!a||!a.__esModule?Cp(t,"default",{value:a,enumerable:!0}):t,a));var oe=b((pu,Vp)=>{"use strict";var Gr=function(a){return a&&a.Math===Math&&a};Vp.exports=Gr(typeof globalThis=="object"&&globalThis)||Gr(typeof window=="object"&&window)||Gr(typeof self=="object"&&self)||Gr(typeof global=="object"&&global)||Gr(typeof pu=="object"&&pu)||function(){return this}()||Function("return this")()});var pe=b((NV,_p)=>{"use strict";_p.exports=function(a){try{return!!a()}catch(e){return!0}}});var Wr=b((UV,Op)=>{"use strict";var UE=pe();Op.exports=!UE(function(){var a=function(){}.bind();return typeof a!="function"||a.hasOwnProperty("prototype")})});var hu=b((qV,qp)=>{"use strict";var qE=Wr(),Up=Function.prototype,Fp=Up.apply,Np=Up.call;qp.exports=typeof Reflect=="object"&&Reflect.apply||(qE?Np.bind(Fp):function(){return Np.apply(Fp,arguments)})});var he=b((HV,Qp)=>{"use strict";var Hp=Wr(),jp=Function.prototype,fu=jp.call,HE=Hp&&jp.bind.bind(fu,fu);Qp.exports=Hp?HE:function(a){return function(){return fu.apply(a,arguments)}}});var pi=b((jV,Wp)=>{"use strict";var Gp=he(),jE=Gp({}.toString),QE=Gp("".slice);Wp.exports=function(a){return QE(jE(a),8,-1)}});var mu=b((QV,zp)=>{"use strict";var GE=pi(),WE=he();zp.exports=function(a){if(GE(a)==="Function")return WE(a)}});var ue=b((GV,Yp)=>{"use strict";var bu=typeof document=="object"&&document.all;Yp.exports=typeof bu=="undefined"&&bu!==void 0?function(a){return typeof a=="function"||a===bu}:function(a){return typeof a=="function"}});var Ne=b((WV,Kp)=>{"use strict";var zE=pe();Kp.exports=!zE(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var Ue=b((zV,Xp)=>{"use strict";var YE=Wr(),Ks=Function.prototype.call;Xp.exports=YE?Ks.bind(Ks):function(){return Ks.apply(Ks,arguments)}});var gu=b(eh=>{"use strict";var Jp={}.propertyIsEnumerable,Zp=Object.getOwnPropertyDescriptor,KE=Zp&&!Jp.call({1:2},1);eh.f=KE?function(e){var t=Zp(this,e);return!!t&&t.enumerable}:Jp});var zr=b((KV,th)=>{"use strict";th.exports=function(a,e){return{enumerable:!(a&1),configurable:!(a&2),writable:!(a&4),value:e}}});var rh=b((XV,ih)=>{"use strict";var XE=he(),JE=pe(),ZE=pi(),Su=Object,ex=XE("".split);ih.exports=JE(function(){return!Su("z").propertyIsEnumerable(0)})?function(a){return ZE(a)==="String"?ex(a,""):Su(a)}:Su});var Yr=b((JV,ah)=>{"use strict";ah.exports=function(a){return a==null}});var jt=b((ZV,sh)=>{"use strict";var tx=Yr(),ix=TypeError;sh.exports=function(a){if(tx(a))throw new ix("Can't call method on "+a);return a}});var hi=b((e_,nh)=>{"use strict";var rx=rh(),ax=jt();nh.exports=function(a){return rx(ax(a))}});var Le=b((t_,oh)=>{"use strict";var sx=ue();oh.exports=function(a){return typeof a=="object"?a!==null:sx(a)}});var fi=b((i_,uh)=>{"use strict";uh.exports={}});var At=b((r_,ch)=>{"use strict";var vu=fi(),yu=oe(),nx=ue(),lh=function(a){return nx(a)?a:void 0};ch.exports=function(a,e){return arguments.length<2?lh(vu[a])||lh(yu[a]):vu[a]&&vu[a][e]||yu[a]&&yu[a][e]}});var Kr=b((a_,dh)=>{"use strict";var ox=he();dh.exports=ox({}.isPrototypeOf)});var mi=b((s_,fh)=>{"use strict";var ux=oe(),ph=ux.navigator,hh=ph&&ph.userAgent;fh.exports=hh?String(hh):""});var Iu=b((n_,yh)=>{"use strict";var vh=oe(),Tu=mi(),mh=vh.process,bh=vh.Deno,gh=mh&&mh.versions||bh&&bh.version,Sh=gh&&gh.v8,it,Xs;Sh&&(it=Sh.split("."),Xs=it[0]>0&&it[0]<4?1:+(it[0]+it[1]));!Xs&&Tu&&(it=Tu.match(/Edge\/(\d+)/),(!it||it[1]>=74)&&(it=Tu.match(/Chrome\/(\d+)/),it&&(Xs=+it[1])));yh.exports=Xs});var Eu=b((o_,Ih)=>{"use strict";var Th=Iu(),lx=pe(),cx=oe(),dx=cx.String;Ih.exports=!!Object.getOwnPropertySymbols&&!lx(function(){var a=Symbol("symbol detection");return!dx(a)||!(Object(a)instanceof Symbol)||!Symbol.sham&&Th&&Th<41})});var xu=b((u_,Eh)=>{"use strict";var px=Eu();Eh.exports=px&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var wu=b((l_,xh)=>{"use strict";var hx=At(),fx=ue(),mx=Kr(),bx=xu(),gx=Object;xh.exports=bx?function(a){return typeof a=="symbol"}:function(a){var e=hx("Symbol");return fx(e)&&mx(e.prototype,gx(a))}});var Xr=b((c_,wh)=>{"use strict";var Sx=String;wh.exports=function(a){try{return Sx(a)}catch(e){return"Object"}}});var pt=b((d_,Ah)=>{"use strict";var vx=ue(),yx=Xr(),Tx=TypeError;Ah.exports=function(a){if(vx(a))return a;throw new Tx(yx(a)+" is not a function")}});var Jr=b((p_,Ph)=>{"use strict";var Ix=pt(),Ex=Yr();Ph.exports=function(a,e){var t=a[e];return Ex(t)?void 0:Ix(t)}});var kh=b((h_,Rh)=>{"use strict";var Au=Ue(),Pu=ue(),Ru=Le(),xx=TypeError;Rh.exports=function(a,e){var t,i;if(e==="string"&&Pu(t=a.toString)&&!Ru(i=Au(t,a))||Pu(t=a.valueOf)&&!Ru(i=Au(t,a))||e!=="string"&&Pu(t=a.toString)&&!Ru(i=Au(t,a)))return i;throw new xx("Can't convert object to primitive value")}});var rt=b((f_,Lh)=>{"use strict";Lh.exports=!0});var Dh=b((m_,Mh)=>{"use strict";var $h=oe(),wx=Object.defineProperty;Mh.exports=function(a,e){try{wx($h,a,{value:e,configurable:!0,writable:!0})}catch(t){$h[a]=e}return e}});var Zr=b((b_,Vh)=>{"use strict";var Ax=rt(),Px=oe(),Rx=Dh(),Ch="__core-js_shared__",Bh=Vh.exports=Px[Ch]||Rx(Ch,{});(Bh.versions||(Bh.versions=[])).push({version:"3.43.0",mode:Ax?"pure":"global",copyright:"\xA9 2014-2025 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.43.0/LICENSE",source:"https://github.com/zloirock/core-js"})});var ku=b((g_,Oh)=>{"use strict";var _h=Zr();Oh.exports=function(a,e){return _h[a]||(_h[a]=e||{})}});var ji=b((S_,Fh)=>{"use strict";var kx=jt(),Lx=Object;Fh.exports=function(a){return Lx(kx(a))}});var at=b((v_,Nh)=>{"use strict";var $x=he(),Mx=ji(),Dx=$x({}.hasOwnProperty);Nh.exports=Object.hasOwn||function(e,t){return Dx(Mx(e),t)}});var Lu=b((y_,Uh)=>{"use strict";var Cx=he(),Bx=0,Vx=Math.random(),_x=Cx(1.1.toString);Uh.exports=function(a){return"Symbol("+(a===void 0?"":a)+")_"+_x(++Bx+Vx,36)}});var ye=b((T_,Hh)=>{"use strict";var Ox=oe(),Fx=ku(),qh=at(),Nx=Lu(),Ux=Eu(),qx=xu(),Qi=Ox.Symbol,$u=Fx("wks"),Hx=qx?Qi.for||Qi:Qi&&Qi.withoutSetter||Nx;Hh.exports=function(a){return qh($u,a)||($u[a]=Ux&&qh(Qi,a)?Qi[a]:Hx("Symbol."+a)),$u[a]}});var Wh=b((I_,Gh)=>{"use strict";var jx=Ue(),jh=Le(),Qh=wu(),Qx=Jr(),Gx=kh(),Wx=ye(),zx=TypeError,Yx=Wx("toPrimitive");Gh.exports=function(a,e){if(!jh(a)||Qh(a))return a;var t=Qx(a,Yx),i;if(t){if(e===void 0&&(e="default"),i=jx(t,a,e),!jh(i)||Qh(i))return i;throw new zx("Can't convert object to primitive value")}return e===void 0&&(e="number"),Gx(a,e)}});var Mu=b((E_,zh)=>{"use strict";var Kx=Wh(),Xx=wu();zh.exports=function(a){var e=Kx(a,"string");return Xx(e)?e:e+""}});var Js=b((x_,Kh)=>{"use strict";var Jx=oe(),Yh=Le(),Du=Jx.document,Zx=Yh(Du)&&Yh(Du.createElement);Kh.exports=function(a){return Zx?Du.createElement(a):{}}});var Cu=b((w_,Xh)=>{"use strict";var ew=Ne(),tw=pe(),iw=Js();Xh.exports=!ew&&!tw(function(){return Object.defineProperty(iw("div"),"a",{get:function(){return 7}}).a!==7})});var ef=b(Zh=>{"use strict";var rw=Ne(),aw=Ue(),sw=gu(),nw=zr(),ow=hi(),uw=Mu(),lw=at(),cw=Cu(),Jh=Object.getOwnPropertyDescriptor;Zh.f=rw?Jh:function(e,t){if(e=ow(e),t=uw(t),cw)try{return Jh(e,t)}catch(i){}if(lw(e,t))return nw(!aw(sw.f,e,t),e[t])}});var Bu=b((P_,tf)=>{"use strict";var dw=pe(),pw=ue(),hw=/#|\.prototype\./,ea=function(a,e){var t=mw[fw(a)];return t===gw?!0:t===bw?!1:pw(e)?dw(e):!!e},fw=ea.normalize=function(a){return String(a).replace(hw,".").toLowerCase()},mw=ea.data={},bw=ea.NATIVE="N",gw=ea.POLYFILL="P";tf.exports=ea});var Gi=b((R_,af)=>{"use strict";var rf=mu(),Sw=pt(),vw=Wr(),yw=rf(rf.bind);af.exports=function(a,e){return Sw(a),e===void 0?a:vw?yw(a,e):function(){return a.apply(e,arguments)}}});var Vu=b((k_,sf)=>{"use strict";var Tw=Ne(),Iw=pe();sf.exports=Tw&&Iw(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var ht=b((L_,nf)=>{"use strict";var Ew=Le(),xw=String,ww=TypeError;nf.exports=function(a){if(Ew(a))return a;throw new ww(xw(a)+" is not an object")}});var bi=b(uf=>{"use strict";var Aw=Ne(),Pw=Cu(),Rw=Vu(),Zs=ht(),of=Mu(),kw=TypeError,_u=Object.defineProperty,Lw=Object.getOwnPropertyDescriptor,Ou="enumerable",Fu="configurable",Nu="writable";uf.f=Aw?Rw?function(e,t,i){if(Zs(e),t=of(t),Zs(i),typeof e=="function"&&t==="prototype"&&"value"in i&&Nu in i&&!i[Nu]){var r=Lw(e,t);r&&r[Nu]&&(e[t]=i.value,i={configurable:Fu in i?i[Fu]:r[Fu],enumerable:Ou in i?i[Ou]:r[Ou],writable:!1})}return _u(e,t,i)}:_u:function(e,t,i){if(Zs(e),t=of(t),Zs(i),Pw)try{return _u(e,t,i)}catch(r){}if("get"in i||"set"in i)throw new kw("Accessors not supported");return"value"in i&&(e[t]=i.value),e}});var Wi=b((M_,lf)=>{"use strict";var $w=Ne(),Mw=bi(),Dw=zr();lf.exports=$w?function(a,e,t){return Mw.f(a,e,Dw(1,t))}:function(a,e,t){return a[e]=t,a}});var de=b((D_,df)=>{"use strict";var ta=oe(),Cw=hu(),Bw=mu(),Vw=ue(),_w=ef().f,Ow=Bu(),zi=fi(),Fw=Gi(),Yi=Wi(),cf=at();Zr();var Nw=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 Cw(a,this,arguments)};return e.prototype=a.prototype,e};df.exports=function(a,e){var t=a.target,i=a.global,r=a.stat,s=a.proto,n=i?ta:r?ta[t]:ta[t]&&ta[t].prototype,o=i?zi:zi[t]||Yi(zi,t,{})[t],u=o.prototype,l,d,c,f,p,h,m,g,S;for(f in e)l=Ow(i?f:t+(r?".":"#")+f,a.forced),d=!l&&n&&cf(n,f),h=o[f],d&&(a.dontCallGetSet?(S=_w(n,f),m=S&&S.value):m=n[f]),p=d&&m?m:e[f],!(!l&&!s&&typeof h==typeof p)&&(a.bind&&d?g=Fw(p,ta):a.wrap&&d?g=Nw(p):s&&Vw(p)?g=Bw(p):g=p,(a.sham||p&&p.sham||h&&h.sham)&&Yi(g,"sham",!0),Yi(o,f,g),s&&(c=t+"Prototype",cf(zi,c)||Yi(zi,c,{}),Yi(zi[c],f,p),a.real&&u&&(l||!u[f])&&Yi(u,f,p)))}});var hf=b((C_,pf)=>{"use strict";var Uw=Math.ceil,qw=Math.floor;pf.exports=Math.trunc||function(e){var t=+e;return(t>0?qw:Uw)(t)}});var ia=b((B_,ff)=>{"use strict";var Hw=hf();ff.exports=function(a){var e=+a;return e!==e||e===0?0:Hw(e)}});var bf=b((V_,mf)=>{"use strict";var jw=ia(),Qw=Math.max,Gw=Math.min;mf.exports=function(a,e){var t=jw(a);return t<0?Qw(t+e,0):Gw(t,e)}});var Uu=b((__,gf)=>{"use strict";var Ww=ia(),zw=Math.min;gf.exports=function(a){var e=Ww(a);return e>0?zw(e,9007199254740991):0}});var Ki=b((O_,Sf)=>{"use strict";var Yw=Uu();Sf.exports=function(a){return Yw(a.length)}});var qu=b((F_,yf)=>{"use strict";var Kw=hi(),Xw=bf(),Jw=Ki(),vf=function(a){return function(e,t,i){var r=Kw(e),s=Jw(r);if(s===0)return!a&&-1;var n=Xw(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}};yf.exports={includes:vf(!0),indexOf:vf(!1)}});var ra=b((N_,Tf)=>{"use strict";Tf.exports=function(){}});var If=b(()=>{"use strict";var Zw=de(),eA=qu().includes,tA=pe(),iA=ra(),rA=tA(function(){return!Array(1).includes()});Zw({target:"Array",proto:!0,forced:rA},{includes:function(e){return eA(this,e,arguments.length>1?arguments[1]:void 0)}});iA("includes")});var Qt=b((H_,Ef)=>{"use strict";var aA=At();Ef.exports=aA});var wf=b((j_,xf)=>{"use strict";If();var sA=Qt();xf.exports=sA("Array","includes")});var Pf=b((Q_,Af)=>{"use strict";var nA=wf();Af.exports=nA});var ze=b((G_,Rf)=>{"use strict";var oA=Pf();Rf.exports=oA});var rn=b((aO,Vf)=>{"use strict";var mA=ku(),bA=Lu(),Bf=mA("keys");Vf.exports=function(a){return Bf[a]||(Bf[a]=bA(a))}});var Of=b((sO,_f)=>{"use strict";var gA=pe();_f.exports=!gA(function(){function a(){}return a.prototype.constructor=null,Object.getPrototypeOf(new a)!==a.prototype})});var an=b((nO,Nf)=>{"use strict";var SA=at(),vA=ue(),yA=ji(),TA=rn(),IA=Of(),Ff=TA("IE_PROTO"),Qu=Object,EA=Qu.prototype;Nf.exports=IA?Qu.getPrototypeOf:function(a){var e=yA(a);if(SA(e,Ff))return e[Ff];var t=e.constructor;return vA(t)&&e instanceof t?t.prototype:e instanceof Qu?EA:null}});var sn=b((oO,Uf)=>{"use strict";Uf.exports={}});var jf=b((uO,Hf)=>{"use strict";var xA=he(),Gu=at(),wA=hi(),AA=qu().indexOf,PA=sn(),qf=xA([].push);Hf.exports=function(a,e){var t=wA(a),i=0,r=[],s;for(s in t)!Gu(PA,s)&&Gu(t,s)&&qf(r,s);for(;e.length>i;)Gu(t,s=e[i++])&&(~AA(r,s)||qf(r,s));return r}});var Wu=b((lO,Qf)=>{"use strict";Qf.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var zu=b((cO,Gf)=>{"use strict";var RA=jf(),kA=Wu();Gf.exports=Object.keys||function(e){return RA(e,kA)}});var Yu=b((dO,Xf)=>{"use strict";var zf=Ne(),LA=pe(),Yf=he(),$A=an(),MA=zu(),DA=hi(),CA=gu().f,Kf=Yf(CA),BA=Yf([].push),VA=zf&&LA(function(){var a=Object.create(null);return a[2]=2,!Kf(a,2)}),Wf=function(a){return function(e){for(var t=DA(e),i=MA(t),r=VA&&$A(t)===null,s=i.length,n=0,o=[],u;s>n;)u=i[n++],(!zf||(r?u in t:Kf(t,u)))&&BA(o,a?[u,t[u]]:t[u]);return o}};Xf.exports={entries:Wf(!0),values:Wf(!1)}});var Jf=b(()=>{"use strict";var _A=de(),OA=Yu().entries;_A({target:"Object",stat:!0},{entries:function(e){return OA(e)}})});var em=b((fO,Zf)=>{"use strict";Jf();var FA=fi();Zf.exports=FA.Object.entries});var im=b((mO,tm)=>{"use strict";var NA=em();tm.exports=NA});var Xi=b((bO,rm)=>{"use strict";var UA=im();rm.exports=UA});var gi=b((gO,am)=>{"use strict";am.exports={}});var om=b((SO,nm)=>{"use strict";var qA=oe(),HA=ue(),sm=qA.WeakMap;nm.exports=HA(sm)&&/native code/.test(String(sm))});var Zu=b((vO,cm)=>{"use strict";var jA=om(),lm=oe(),QA=Le(),GA=Wi(),Ku=at(),Xu=Zr(),WA=rn(),zA=sn(),um="Object already initialized",Ju=lm.TypeError,YA=lm.WeakMap,nn,aa,on,KA=function(a){return on(a)?aa(a):nn(a,{})},XA=function(a){return function(e){var t;if(!QA(e)||(t=aa(e)).type!==a)throw new Ju("Incompatible receiver, "+a+" required");return t}};jA||Xu.state?(st=Xu.state||(Xu.state=new YA),st.get=st.get,st.has=st.has,st.set=st.set,nn=function(a,e){if(st.has(a))throw new Ju(um);return e.facade=a,st.set(a,e),e},aa=function(a){return st.get(a)||{}},on=function(a){return st.has(a)}):(Si=WA("state"),zA[Si]=!0,nn=function(a,e){if(Ku(a,Si))throw new Ju(um);return e.facade=a,GA(a,Si,e),e},aa=function(a){return Ku(a,Si)?a[Si]:{}},on=function(a){return Ku(a,Si)});var st,Si;cm.exports={set:nn,get:aa,has:on,enforce:KA,getterFor:XA}});var il=b((yO,pm)=>{"use strict";var el=Ne(),JA=at(),dm=Function.prototype,ZA=el&&Object.getOwnPropertyDescriptor,tl=JA(dm,"name"),eP=tl&&function(){}.name==="something",tP=tl&&(!el||el&&ZA(dm,"name").configurable);pm.exports={EXISTS:tl,PROPER:eP,CONFIGURABLE:tP}});var fm=b(hm=>{"use strict";var iP=Ne(),rP=Vu(),aP=bi(),sP=ht(),nP=hi(),oP=zu();hm.f=iP&&!rP?Object.defineProperties:function(e,t){sP(e);for(var i=nP(t),r=oP(t),s=r.length,n=0,o;s>n;)aP.f(e,o=r[n++],i[o]);return e}});var rl=b((IO,mm)=>{"use strict";var uP=At();mm.exports=uP("document","documentElement")});var ol=b((EO,Im)=>{"use strict";var lP=ht(),cP=fm(),bm=Wu(),dP=sn(),pP=rl(),hP=Js(),fP=rn(),gm=">",Sm="<",sl="prototype",nl="script",ym=fP("IE_PROTO"),al=function(){},Tm=function(a){return Sm+nl+gm+a+Sm+"/"+nl+gm},vm=function(a){a.write(Tm("")),a.close();var e=a.parentWindow.Object;return a=null,e},mP=function(){var a=hP("iframe"),e="java"+nl+":",t;return a.style.display="none",pP.appendChild(a),a.src=String(e),t=a.contentWindow.document,t.open(),t.write(Tm("document.F=Object")),t.close(),t.F},un,ln=function(){try{un=new ActiveXObject("htmlfile")}catch(e){}ln=typeof document!="undefined"?document.domain&&un?vm(un):mP():vm(un);for(var a=bm.length;a--;)delete ln[sl][bm[a]];return ln()};dP[ym]=!0;Im.exports=Object.create||function(e,t){var i;return e!==null?(al[sl]=lP(e),i=new al,al[sl]=null,i[ym]=e):i=ln(),t===void 0?i:cP.f(i,t)}});var Ji=b((xO,Em)=>{"use strict";var bP=Wi();Em.exports=function(a,e,t,i){return i&&i.enumerable?a[e]=t:bP(a,e,t),a}});var dl=b((wO,Am)=>{"use strict";var gP=pe(),SP=ue(),vP=Le(),yP=ol(),xm=an(),TP=Ji(),IP=ye(),EP=rt(),cl=IP("iterator"),wm=!1,Pt,ul,ll;[].keys&&(ll=[].keys(),"next"in ll?(ul=xm(xm(ll)),ul!==Object.prototype&&(Pt=ul)):wm=!0);var xP=!vP(Pt)||gP(function(){var a={};return Pt[cl].call(a)!==a});xP?Pt={}:EP&&(Pt=yP(Pt));SP(Pt[cl])||TP(Pt,cl,function(){return this});Am.exports={IteratorPrototype:Pt,BUGGY_SAFARI_ITERATORS:wm}});var cn=b((AO,Rm)=>{"use strict";var wP=ye(),AP=wP("toStringTag"),Pm={};Pm[AP]="z";Rm.exports=String(Pm)==="[object z]"});var sa=b((PO,km)=>{"use strict";var PP=cn(),RP=ue(),dn=pi(),kP=ye(),LP=kP("toStringTag"),$P=Object,MP=dn(function(){return arguments}())==="Arguments",DP=function(a,e){try{return a[e]}catch(t){}};km.exports=PP?dn:function(a){var e,t,i;return a===void 0?"Undefined":a===null?"Null":typeof(t=DP(e=$P(a),LP))=="string"?t:MP?dn(e):(i=dn(e))==="Object"&&RP(e.callee)?"Arguments":i}});var $m=b((RO,Lm)=>{"use strict";var CP=cn(),BP=sa();Lm.exports=CP?{}.toString:function(){return"[object "+BP(this)+"]"}});var na=b((kO,Dm)=>{"use strict";var VP=cn(),_P=bi().f,OP=Wi(),FP=at(),NP=$m(),UP=ye(),Mm=UP("toStringTag");Dm.exports=function(a,e,t,i){var r=t?a:a&&a.prototype;r&&(FP(r,Mm)||_P(r,Mm,{configurable:!0,value:e}),i&&!VP&&OP(r,"toString",NP))}});var Bm=b((LO,Cm)=>{"use strict";var qP=dl().IteratorPrototype,HP=ol(),jP=zr(),QP=na(),GP=gi(),WP=function(){return this};Cm.exports=function(a,e,t,i){var r=e+" Iterator";return a.prototype=HP(qP,{next:jP(+!i,t)}),QP(a,r,!1,!0),GP[r]=WP,a}});var _m=b(($O,Vm)=>{"use strict";var zP=he(),YP=pt();Vm.exports=function(a,e,t){try{return zP(YP(Object.getOwnPropertyDescriptor(a,e)[t]))}catch(i){}}});var Fm=b((MO,Om)=>{"use strict";var KP=Le();Om.exports=function(a){return KP(a)||a===null}});var Um=b((DO,Nm)=>{"use strict";var XP=Fm(),JP=String,ZP=TypeError;Nm.exports=function(a){if(XP(a))return a;throw new ZP("Can't set "+JP(a)+" as a prototype")}});var pl=b((CO,qm)=>{"use strict";var eR=_m(),tR=Le(),iR=jt(),rR=Um();qm.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var a=!1,e={},t;try{t=eR(Object.prototype,"__proto__","set"),t(e,[]),a=e instanceof Array}catch(i){}return function(r,s){return iR(r),rR(s),tR(r)&&(a?t(r,s):r.__proto__=s),r}}():void 0)});var Zm=b((BO,Jm)=>{"use strict";var aR=de(),sR=Ue(),pn=rt(),Km=il(),nR=ue(),oR=Bm(),Hm=an(),jm=pl(),uR=na(),lR=Wi(),hl=Ji(),cR=ye(),Qm=gi(),Xm=dl(),dR=Km.PROPER,pR=Km.CONFIGURABLE,Gm=Xm.IteratorPrototype,hn=Xm.BUGGY_SAFARI_ITERATORS,oa=cR("iterator"),Wm="keys",ua="values",zm="entries",Ym=function(){return this};Jm.exports=function(a,e,t,i,r,s,n){oR(t,e,i);var o=function(S){if(S===r&&f)return f;if(!hn&&S&&S in d)return d[S];switch(S){case Wm:return function(){return new t(this,S)};case ua:return function(){return new t(this,S)};case zm:return function(){return new t(this,S)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,d=a.prototype,c=d[oa]||d["@@iterator"]||r&&d[r],f=!hn&&c||o(r),p=e==="Array"&&d.entries||c,h,m,g;if(p&&(h=Hm(p.call(new a)),h!==Object.prototype&&h.next&&(!pn&&Hm(h)!==Gm&&(jm?jm(h,Gm):nR(h[oa])||hl(h,oa,Ym)),uR(h,u,!0,!0),pn&&(Qm[u]=Ym))),dR&&r===ua&&c&&c.name!==ua&&(!pn&&pR?lR(d,"name",ua):(l=!0,f=function(){return sR(c,this)})),r)if(m={values:o(ua),keys:s?f:o(Wm),entries:o(zm)},n)for(g in m)(hn||l||!(g in d))&&hl(d,g,m[g]);else aR({target:e,proto:!0,forced:hn||l},m);return(!pn||n)&&d[oa]!==f&&hl(d,oa,f,{name:r}),Qm[e]=f,m}});var tb=b((VO,eb)=>{"use strict";eb.exports=function(a,e){return{value:a,done:e}}});var ml=b((_O,nb)=>{"use strict";var hR=hi(),fl=ra(),ib=gi(),ab=Zu(),fR=bi().f,mR=Zm(),fn=tb(),bR=rt(),gR=Ne(),sb="Array Iterator",SR=ab.set,vR=ab.getterFor(sb);nb.exports=mR(Array,"Array",function(a,e){SR(this,{type:sb,target:hR(a),index:0,kind:e})},function(){var a=vR(this),e=a.target,t=a.index++;if(!e||t>=e.length)return a.target=null,fn(void 0,!0);switch(a.kind){case"keys":return fn(t,!1);case"values":return fn(e[t],!1)}return fn([t,e[t]],!1)},"values");var rb=ib.Arguments=ib.Array;fl("keys");fl("values");fl("entries");if(!bR&&gR&&rb.name!=="values")try{fR(rb,"name",{value:"values"})}catch(a){}});var ub=b((OO,ob)=>{"use strict";var yR=ye(),TR=gi(),IR=yR("iterator"),ER=Array.prototype;ob.exports=function(a){return a!==void 0&&(TR.Array===a||ER[IR]===a)}});var bl=b((FO,cb)=>{"use strict";var xR=sa(),lb=Jr(),wR=Yr(),AR=gi(),PR=ye(),RR=PR("iterator");cb.exports=function(a){if(!wR(a))return lb(a,RR)||lb(a,"@@iterator")||AR[xR(a)]}});var pb=b((NO,db)=>{"use strict";var kR=Ue(),LR=pt(),$R=ht(),MR=Xr(),DR=bl(),CR=TypeError;db.exports=function(a,e){var t=arguments.length<2?DR(a):e;if(LR(t))return $R(kR(t,a));throw new CR(MR(a)+" is not iterable")}});var mb=b((UO,fb)=>{"use strict";var BR=Ue(),hb=ht(),VR=Jr();fb.exports=function(a,e,t){var i,r;hb(a);try{if(i=VR(a,"return"),!i){if(e==="throw")throw t;return t}i=BR(i,a)}catch(s){r=!0,i=s}if(e==="throw")throw t;if(r)throw i;return hb(i),t}});var bn=b((qO,vb)=>{"use strict";var _R=Gi(),OR=Ue(),FR=ht(),NR=Xr(),UR=ub(),qR=Ki(),bb=Kr(),HR=pb(),jR=bl(),gb=mb(),QR=TypeError,mn=function(a,e){this.stopped=a,this.result=e},Sb=mn.prototype;vb.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=_R(e,i),l,d,c,f,p,h,m,g=function(v){return l&&gb(l,"normal"),new mn(!0,v)},S=function(v){return r?(FR(v),o?u(v[0],v[1],g):u(v[0],v[1])):o?u(v,g):u(v)};if(s)l=a.iterator;else if(n)l=a;else{if(d=jR(a),!d)throw new QR(NR(a)+" is not iterable");if(UR(d)){for(c=0,f=qR(a);f>c;c++)if(p=S(a[c]),p&&bb(Sb,p))return p;return new mn(!1)}l=HR(a,d)}for(h=s?a.next:l.next;!(m=OR(h,l)).done;){try{p=S(m.value)}catch(v){gb(l,"throw",v)}if(typeof p=="object"&&p&&bb(Sb,p))return p}return new mn(!1)}});var Tb=b((HO,yb)=>{"use strict";var GR=Ne(),WR=bi(),zR=zr();yb.exports=function(a,e,t){GR?WR.f(a,e,zR(0,t)):a[e]=t}});var Ib=b(()=>{"use strict";var YR=de(),KR=bn(),XR=Tb();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 xb=b((GO,Eb)=>{"use strict";ml();Ib();var JR=fi();Eb.exports=JR.Object.fromEntries});var Ab=b((WO,wb)=>{"use strict";wb.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 Rb=b(()=>{"use strict";ml();var ZR=Ab(),ek=oe(),tk=na(),Pb=gi();for(gn in ZR)tk(ek[gn],gn),Pb[gn]=Pb.Array;var gn});var Lb=b((KO,kb)=>{"use strict";var ik=xb();Rb();kb.exports=ik});var gl=b((XO,$b)=>{"use strict";var rk=Lb();$b.exports=rk});var Mb=b(()=>{"use strict"});var Sl=b((eF,Db)=>{"use strict";var la=oe(),ak=mi(),sk=pi(),Sn=function(a){return ak.slice(0,a.length)===a};Db.exports=function(){return Sn("Bun/")?"BUN":Sn("Cloudflare-Workers")?"CLOUDFLARE":Sn("Deno/")?"DENO":Sn("Node.js/")?"NODE":la.Bun&&typeof Bun.version=="string"?"BUN":la.Deno&&typeof Deno.version=="object"?"DENO":sk(la.process)==="process"?"NODE":la.window&&la.document?"BROWSER":"REST"}()});var vn=b((tF,Cb)=>{"use strict";var nk=Sl();Cb.exports=nk==="NODE"});var Vb=b((iF,Bb)=>{"use strict";var ok=bi();Bb.exports=function(a,e,t){return ok.f(a,e,t)}});var Fb=b((rF,Ob)=>{"use strict";var uk=At(),lk=Vb(),ck=ye(),dk=Ne(),_b=ck("species");Ob.exports=function(a){var e=uk(a);dk&&e&&!e[_b]&&lk(e,_b,{configurable:!0,get:function(){return this}})}});var Ub=b((aF,Nb)=>{"use strict";var pk=Kr(),hk=TypeError;Nb.exports=function(a,e){if(pk(e,a))return a;throw new hk("Incorrect invocation")}});var yl=b((sF,qb)=>{"use strict";var fk=he(),mk=ue(),vl=Zr(),bk=fk(Function.toString);mk(vl.inspectSource)||(vl.inspectSource=function(a){return bk(a)});qb.exports=vl.inspectSource});var Il=b((nF,Wb)=>{"use strict";var gk=he(),Sk=pe(),Hb=ue(),vk=sa(),yk=At(),Tk=yl(),jb=function(){},Qb=yk("Reflect","construct"),Tl=/^\s*(?:class|function)\b/,Ik=gk(Tl.exec),Ek=!Tl.test(jb),ca=function(e){if(!Hb(e))return!1;try{return Qb(jb,[],e),!0}catch(t){return!1}},Gb=function(e){if(!Hb(e))return!1;switch(vk(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return Ek||!!Ik(Tl,Tk(e))}catch(t){return!0}};Gb.sham=!0;Wb.exports=!Qb||Sk(function(){var a;return ca(ca.call)||!ca(Object)||!ca(function(){a=!0})||a})?Gb:ca});var Yb=b((oF,zb)=>{"use strict";var xk=Il(),wk=Xr(),Ak=TypeError;zb.exports=function(a){if(xk(a))return a;throw new Ak(wk(a)+" is not a constructor")}});var El=b((uF,Xb)=>{"use strict";var Kb=ht(),Pk=Yb(),Rk=Yr(),kk=ye(),Lk=kk("species");Xb.exports=function(a,e){var t=Kb(a).constructor,i;return t===void 0||Rk(i=Kb(t)[Lk])?e:Pk(i)}});var Zb=b((lF,Jb)=>{"use strict";var $k=he();Jb.exports=$k([].slice)});var tg=b((cF,eg)=>{"use strict";var Mk=TypeError;eg.exports=function(a,e){if(a<e)throw new Mk("Not enough arguments");return a}});var xl=b((dF,ig)=>{"use strict";var Dk=mi();ig.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(Dk)});var Dl=b((pF,dg)=>{"use strict";var qe=oe(),Ck=hu(),Bk=Gi(),rg=ue(),Vk=at(),cg=pe(),ag=rl(),_k=Zb(),sg=Js(),Ok=tg(),Fk=xl(),Nk=vn(),Ll=qe.setImmediate,$l=qe.clearImmediate,Uk=qe.process,wl=qe.Dispatch,qk=qe.Function,ng=qe.MessageChannel,Hk=qe.String,Al=0,da={},og="onreadystatechange",pa,vi,Pl,Rl;cg(function(){pa=qe.location});var Ml=function(a){if(Vk(da,a)){var e=da[a];delete da[a],e()}},kl=function(a){return function(){Ml(a)}},ug=function(a){Ml(a.data)},lg=function(a){qe.postMessage(Hk(a),pa.protocol+"//"+pa.host)};(!Ll||!$l)&&(Ll=function(e){Ok(arguments.length,1);var t=rg(e)?e:qk(e),i=_k(arguments,1);return da[++Al]=function(){Ck(t,void 0,i)},vi(Al),Al},$l=function(e){delete da[e]},Nk?vi=function(a){Uk.nextTick(kl(a))}:wl&&wl.now?vi=function(a){wl.now(kl(a))}:ng&&!Fk?(Pl=new ng,Rl=Pl.port2,Pl.port1.onmessage=ug,vi=Bk(Rl.postMessage,Rl)):qe.addEventListener&&rg(qe.postMessage)&&!qe.importScripts&&pa&&pa.protocol!=="file:"&&!cg(lg)?(vi=lg,qe.addEventListener("message",ug,!1)):og in sg("script")?vi=function(a){ag.appendChild(sg("script"))[og]=function(){ag.removeChild(this),Ml(a)}}:vi=function(a){setTimeout(kl(a),0)});dg.exports={set:Ll,clear:$l}});var fg=b((hF,hg)=>{"use strict";var pg=oe(),jk=Ne(),Qk=Object.getOwnPropertyDescriptor;hg.exports=function(a){if(!jk)return pg[a];var e=Qk(pg,a);return e&&e.value}});var Cl=b((fF,bg)=>{"use strict";var mg=function(){this.head=null,this.tail=null};mg.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}}};bg.exports=mg});var Sg=b((mF,gg)=>{"use strict";var Gk=mi();gg.exports=/ipad|iphone|ipod/i.test(Gk)&&typeof Pebble!="undefined"});var yg=b((bF,vg)=>{"use strict";var Wk=mi();vg.exports=/web0s(?!.*chrome)/i.test(Wk)});var Pg=b((gF,Ag)=>{"use strict";var er=oe(),zk=fg(),Tg=Gi(),Bl=Dl().set,Yk=Cl(),Kk=xl(),Xk=Sg(),Jk=yg(),Vl=vn(),Ig=er.MutationObserver||er.WebKitMutationObserver,Eg=er.document,xg=er.process,yn=er.Promise,Fl=zk("queueMicrotask"),Zi,_l,Ol,Tn,wg;Fl||(ha=new Yk,fa=function(){var a,e;for(Vl&&(a=xg.domain)&&a.exit();e=ha.get();)try{e()}catch(t){throw ha.head&&Zi(),t}a&&a.enter()},!Kk&&!Vl&&!Jk&&Ig&&Eg?(_l=!0,Ol=Eg.createTextNode(""),new Ig(fa).observe(Ol,{characterData:!0}),Zi=function(){Ol.data=_l=!_l}):!Xk&&yn&&yn.resolve?(Tn=yn.resolve(void 0),Tn.constructor=yn,wg=Tg(Tn.then,Tn),Zi=function(){wg(fa)}):Vl?Zi=function(){xg.nextTick(fa)}:(Bl=Tg(Bl,er),Zi=function(){Bl(fa)}),Fl=function(a){ha.head||Zi(),ha.add(a)});var ha,fa;Ag.exports=Fl});var kg=b((SF,Rg)=>{"use strict";Rg.exports=function(a,e){try{arguments.length===1?console.error(a):console.error(a,e)}catch(t){}}});var In=b((vF,Lg)=>{"use strict";Lg.exports=function(a){try{return{error:!1,value:a()}}catch(e){return{error:!0,value:e}}}});var yi=b((yF,$g)=>{"use strict";var Zk=oe();$g.exports=Zk.Promise});var tr=b((TF,Bg)=>{"use strict";var eL=oe(),ma=yi(),tL=ue(),iL=Bu(),rL=yl(),aL=ye(),Mg=Sl(),sL=rt(),Nl=Iu(),Dg=ma&&ma.prototype,nL=aL("species"),Ul=!1,Cg=tL(eL.PromiseRejectionEvent),oL=iL("Promise",function(){var a=rL(ma),e=a!==String(ma);if(!e&&Nl===66||sL&&!(Dg.catch&&Dg.finally))return!0;if(!Nl||Nl<51||!/native code/.test(a)){var t=new ma(function(s){s(1)}),i=function(s){s(function(){},function(){})},r=t.constructor={};if(r[nL]=i,Ul=t.then(function(){})instanceof i,!Ul)return!0}return!e&&(Mg==="BROWSER"||Mg==="DENO")&&!Cg});Bg.exports={CONSTRUCTOR:oL,REJECTION_EVENT:Cg,SUBCLASSING:Ul}});var ir=b((IF,_g)=>{"use strict";var Vg=pt(),uL=TypeError,lL=function(a){var e,t;this.promise=new a(function(i,r){if(e!==void 0||t!==void 0)throw new uL("Bad Promise constructor");e=i,t=r}),this.resolve=Vg(e),this.reject=Vg(t)};_g.exports.f=function(a){return new lL(a)}});var rS=b(()=>{"use strict";var cL=de(),dL=rt(),An=vn(),Gt=oe(),pL=fi(),nr=Ue(),Og=Ji(),Fg=pl(),hL=na(),fL=Fb(),mL=pt(),wn=ue(),bL=Le(),gL=Ub(),SL=El(),jg=Dl().set,Gl=Pg(),vL=kg(),yL=In(),TL=Cl(),Qg=Zu(),Pn=yi(),Wl=tr(),Gg=ir(),Rn="Promise",Wg=Wl.CONSTRUCTOR,IL=Wl.REJECTION_EVENT,EL=Wl.SUBCLASSING,ql=Qg.getterFor(Rn),xL=Qg.set,rr=Pn&&Pn.prototype,Ti=Pn,En=rr,zg=Gt.TypeError,Hl=Gt.document,zl=Gt.process,jl=Gg.f,wL=jl,AL=!!(Hl&&Hl.createEvent&&Gt.dispatchEvent),Yg="unhandledrejection",PL="rejectionhandled",Ng=0,Kg=1,RL=2,Yl=1,Xg=2,xn,Ug,Jg,qg,Zg=function(a){var e;return bL(a)&&wn(e=a.then)?e:!1},eS=function(a,e){var t=e.value,i=e.state===Kg,r=i?a.ok:a.fail,s=a.resolve,n=a.reject,o=a.domain,u,l,d;try{r?(i||(e.rejection===Xg&&LL(e),e.rejection=Yl),r===!0?u=t:(o&&o.enter(),u=r(t),o&&(o.exit(),d=!0)),u===a.promise?n(new zg("Promise-chain cycle")):(l=Zg(u))?nr(l,u,s,n):s(u)):n(t)}catch(c){o&&!d&&o.exit(),n(c)}},tS=function(a,e){a.notified||(a.notified=!0,Gl(function(){for(var t=a.reactions,i;i=t.get();)eS(i,a);a.notified=!1,e&&!a.rejection&&kL(a)}))},iS=function(a,e,t){var i,r;AL?(i=Hl.createEvent("Event"),i.promise=e,i.reason=t,i.initEvent(a,!1,!0),Gt.dispatchEvent(i)):i={promise:e,reason:t},!IL&&(r=Gt["on"+a])?r(i):a===Yg&&vL("Unhandled promise rejection",t)},kL=function(a){nr(jg,Gt,function(){var e=a.facade,t=a.value,i=Hg(a),r;if(i&&(r=yL(function(){An?zl.emit("unhandledRejection",t,e):iS(Yg,e,t)}),a.rejection=An||Hg(a)?Xg:Yl,r.error))throw r.value})},Hg=function(a){return a.rejection!==Yl&&!a.parent},LL=function(a){nr(jg,Gt,function(){var e=a.facade;An?zl.emit("rejectionHandled",e):iS(PL,e,a.value)})},ar=function(a,e,t){return function(i){a(e,i,t)}},sr=function(a,e,t){a.done||(a.done=!0,t&&(a=t),a.value=e,a.state=RL,tS(a,!0))},Ql=function(a,e,t){if(!a.done){a.done=!0,t&&(a=t);try{if(a.facade===e)throw new zg("Promise can't be resolved itself");var i=Zg(e);i?Gl(function(){var r={done:!1};try{nr(i,e,ar(Ql,r,a),ar(sr,r,a))}catch(s){sr(r,s,a)}}):(a.value=e,a.state=Kg,tS(a,!1))}catch(r){sr({done:!1},r,a)}}};if(Wg&&(Ti=function(e){gL(this,En),mL(e),nr(xn,this);var t=ql(this);try{e(ar(Ql,t),ar(sr,t))}catch(i){sr(t,i)}},En=Ti.prototype,xn=function(e){xL(this,{type:Rn,done:!1,notified:!1,parent:!1,reactions:new TL,rejection:!1,state:Ng,value:null})},xn.prototype=Og(En,"then",function(e,t){var i=ql(this),r=jl(SL(this,Ti));return i.parent=!0,r.ok=wn(e)?e:!0,r.fail=wn(t)&&t,r.domain=An?zl.domain:void 0,i.state===Ng?i.reactions.add(r):Gl(function(){eS(r,i)}),r.promise}),Ug=function(){var a=new xn,e=ql(a);this.promise=a,this.resolve=ar(Ql,e),this.reject=ar(sr,e)},Gg.f=jl=function(a){return a===Ti||a===Jg?new Ug(a):wL(a)},!dL&&wn(Pn)&&rr!==Object.prototype)){qg=rr.then,EL||Og(rr,"then",function(e,t){var i=this;return new Ti(function(r,s){nr(qg,i,r,s)}).then(e,t)},{unsafe:!0});try{delete rr.constructor}catch(a){}Fg&&Fg(rr,En)}cL({global:!0,constructor:!0,wrap:!0,forced:Wg},{Promise:Ti});Jg=pL.Promise;hL(Ti,Rn,!1,!0);fL(Rn)});var uS=b((wF,oS)=>{"use strict";var $L=ye(),sS=$L("iterator"),nS=!1;try{aS=0,Kl={next:function(){return{done:!!aS++}},return:function(){nS=!0}},Kl[sS]=function(){return this},Array.from(Kl,function(){throw 2})}catch(a){}var aS,Kl;oS.exports=function(a,e){try{if(!e&&!nS)return!1}catch(r){return!1}var t=!1;try{var i={};i[sS]=function(){return{next:function(){return{done:t=!0}}}},a(i)}catch(r){}return t}});var Xl=b((AF,lS)=>{"use strict";var ML=yi(),DL=uS(),CL=tr().CONSTRUCTOR;lS.exports=CL||!DL(function(a){ML.all(a).then(void 0,function(){})})});var cS=b(()=>{"use strict";var BL=de(),VL=Ue(),_L=pt(),OL=ir(),FL=In(),NL=bn(),UL=Xl();BL({target:"Promise",stat:!0,forced:UL},{all:function(e){var t=this,i=OL.f(t),r=i.resolve,s=i.reject,n=FL(function(){var o=_L(t.resolve),u=[],l=0,d=1;NL(e,function(c){var f=l++,p=!1;d++,VL(o,t,c).then(function(h){p||(p=!0,u[f]=h,--d||r(u))},s)}),--d||r(u)});return n.error&&s(n.value),i.promise}})});var pS=b(()=>{"use strict";var qL=de(),HL=rt(),jL=tr().CONSTRUCTOR,Zl=yi(),QL=At(),GL=ue(),WL=Ji(),dS=Zl&&Zl.prototype;qL({target:"Promise",proto:!0,forced:jL,real:!0},{catch:function(a){return this.then(void 0,a)}});!HL&&GL(Zl)&&(Jl=QL("Promise").prototype.catch,dS.catch!==Jl&&WL(dS,"catch",Jl,{unsafe:!0}));var Jl});var hS=b(()=>{"use strict";var zL=de(),YL=Ue(),KL=pt(),XL=ir(),JL=In(),ZL=bn(),e$=Xl();zL({target:"Promise",stat:!0,forced:e$},{race:function(e){var t=this,i=XL.f(t),r=i.reject,s=JL(function(){var n=KL(t.resolve);ZL(e,function(o){YL(n,t,o).then(i.resolve,r)})});return s.error&&r(s.value),i.promise}})});var fS=b(()=>{"use strict";var t$=de(),i$=ir(),r$=tr().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 ec=b((BF,mS)=>{"use strict";var a$=ht(),s$=Le(),n$=ir();mS.exports=function(a,e){if(a$(a),s$(e)&&e.constructor===a)return e;var t=n$.f(a),i=t.resolve;return i(e),t.promise}});var SS=b(()=>{"use strict";var o$=de(),u$=At(),bS=rt(),l$=yi(),gS=tr().CONSTRUCTOR,c$=ec(),d$=u$("Promise"),p$=bS&&!gS;o$({target:"Promise",stat:!0,forced:bS||gS},{resolve:function(e){return c$(p$&&this===d$?l$:this,e)}})});var vS=b(()=>{"use strict";rS();cS();pS();hS();fS();SS()});var ES=b(()=>{"use strict";var h$=de(),f$=rt(),kn=yi(),m$=pe(),TS=At(),IS=ue(),b$=El(),yS=ec(),g$=Ji(),ic=kn&&kn.prototype,S$=!!kn&&m$(function(){ic.finally.call({then:function(){}},function(){})});h$({target:"Promise",proto:!0,real:!0,forced:S$},{finally:function(a){var e=b$(this,TS("Promise")),t=IS(a);return this.then(t?function(i){return yS(e,a()).then(function(){return i})}:a,t?function(i){return yS(e,a()).then(function(){throw i})}:a)}});!f$&&IS(kn)&&(tc=TS("Promise").prototype.finally,ic.finally!==tc&&g$(ic,"finally",tc,{unsafe:!0}));var tc});var wS=b((qF,xS)=>{"use strict";Mb();vS();ES();var v$=Qt();xS.exports=v$("Promise","finally")});var PS=b((HF,AS)=>{"use strict";var y$=wS();AS.exports=y$});var Ln=b((jF,RS)=>{"use strict";var T$=PS();RS.exports=T$});var US=b(()=>{"use strict";var B$=de(),V$=Yu().values;B$({target:"Object",stat:!0},{values:function(e){return V$(e)}})});var HS=b((RN,qS)=>{"use strict";US();var _$=fi();qS.exports=_$.Object.values});var QS=b((kN,jS)=>{"use strict";var O$=HS();jS.exports=O$});var ur=b((LN,GS)=>{"use strict";var F$=QS();GS.exports=F$});var lv=b(()=>{"use strict";var uM=de(),lM=ji(),cM=Ki(),dM=ia(),pM=ra();uM({target:"Array",proto:!0},{at:function(e){var t=lM(this),i=cM(t),r=dM(e),s=r>=0?r:i+r;return s<0||s>=i?void 0:t[s]}});pM("at")});var dv=b((FU,cv)=>{"use strict";lv();var hM=Qt();cv.exports=hM("Array","at")});var hv=b((NU,pv)=>{"use strict";var fM=dv();pv.exports=fM});var gt=b((UU,fv)=>{"use strict";var mM=hv();fv.exports=mM});var wc=b((M1,Yv)=>{"use strict";var YM=pi();Yv.exports=Array.isArray||function(e){return YM(e)==="Array"}});var Xv=b((D1,Kv)=>{"use strict";var KM=TypeError,XM=9007199254740991;Kv.exports=function(a){if(a>XM)throw KM("Maximum allowed index exceeded");return a}});var ey=b((C1,Zv)=>{"use strict";var JM=wc(),ZM=Ki(),eD=Xv(),tD=Gi(),Jv=function(a,e,t,i,r,s,n,o){for(var u=r,l=0,d=n?tD(n,o):!1,c,f;l<i;)l in t&&(c=d?d(t[l],l,e):t[l],s>0&&JM(c)?(f=ZM(c),u=Jv(a,e,c,f,u,s-1)-1):(eD(u+1),a[u]=c),u++),l++;return u};Zv.exports=Jv});var ay=b((B1,ry)=>{"use strict";var ty=wc(),iD=Il(),rD=Le(),aD=ye(),sD=aD("species"),iy=Array;ry.exports=function(a){var e;return ty(a)&&(e=a.constructor,iD(e)&&(e===iy||ty(e.prototype))?e=void 0:rD(e)&&(e=e[sD],e===null&&(e=void 0))),e===void 0?iy:e}});var ny=b((V1,sy)=>{"use strict";var nD=ay();sy.exports=function(a,e){return new(nD(a))(e===0?0:e)}});var oy=b(()=>{"use strict";var oD=de(),uD=ey(),lD=pt(),cD=ji(),dD=Ki(),pD=ny();oD({target:"Array",proto:!0},{flatMap:function(e){var t=cD(this),i=dD(t),r;return lD(e),r=pD(t,0),r.length=uD(r,t,t,i,0,1,e,arguments.length>1?arguments[1]:void 0),r}})});var uy=b(()=>{"use strict";var hD=ra();hD("flatMap")});var cy=b((U1,ly)=>{"use strict";oy();uy();var fD=Qt();ly.exports=fD("Array","flatMap")});var py=b((q1,dy)=>{"use strict";var mD=cy();dy.exports=mD});var $a=b((H1,hy)=>{"use strict";var bD=py();hy.exports=bD});var Ma=b((j1,fy)=>{"use strict";var gD=sa(),SD=String;fy.exports=function(a){if(gD(a)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return SD(a)}});var Ac=b((Q1,my)=>{"use strict";my.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 Sy=b((G1,gy)=>{"use strict";var vD=he(),yD=jt(),TD=Ma(),Rc=Ac(),by=vD("".replace),ID=RegExp("^["+Rc+"]+"),ED=RegExp("(^|[^"+Rc+"])["+Rc+"]+$"),Pc=function(a){return function(e){var t=TD(yD(e));return a&1&&(t=by(t,ID,"")),a&2&&(t=by(t,ED,"$1")),t}};gy.exports={start:Pc(1),end:Pc(2),trim:Pc(3)}});var Iy=b((W1,Ty)=>{"use strict";var xD=il().PROPER,wD=pe(),vy=Ac(),yy="\u200B\x85\u180E";Ty.exports=function(a){return wD(function(){return!!vy[a]()||yy[a]()!==yy||xD&&vy[a].name!==a})}});var kc=b((z1,Ey)=>{"use strict";var AD=Sy().start,PD=Iy();Ey.exports=PD("trimStart")?function(){return AD(this)}:"".trimStart});var wy=b(()=>{"use strict";var RD=de(),xy=kc();RD({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==xy},{trimLeft:xy})});var Py=b(()=>{"use strict";wy();var kD=de(),Ay=kc();kD({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==Ay},{trimStart:Ay})});var ky=b((Z1,Ry)=>{"use strict";Py();var LD=Qt();Ry.exports=LD("String","trimLeft")});var $y=b((eH,Ly)=>{"use strict";var $D=ky();Ly.exports=$D});var Dy=b((tH,My)=>{"use strict";var MD=$y();My.exports=MD});var zy=b(()=>{"use strict"});var Yy=b(()=>{"use strict"});var Xy=b((VQ,Ky)=>{"use strict";var tC=Le(),iC=pi(),rC=ye(),aC=rC("match");Ky.exports=function(a){var e;return tC(a)&&((e=a[aC])!==void 0?!!e:iC(a)==="RegExp")}});var eT=b((_Q,Zy)=>{"use strict";var sC=oe(),nC=pe(),Jy=sC.RegExp,oC=!nC(function(){var a=!0;try{Jy(".","d")}catch(u){a=!1}var e={},t="",i=a?"dgimsy":"gimsy",r=function(u,l){Object.defineProperty(e,u,{get:function(){return t+=l,!0}})},s={dotAll:"s",global:"g",ignoreCase:"i",multiline:"m",sticky:"y"};a&&(s.hasIndices="d");for(var n in s)r(n,s[n]);var o=Object.getOwnPropertyDescriptor(Jy.prototype,"flags").get.call(e);return o!==i||t!==i});Zy.exports={correct:oC}});var iT=b((OQ,tT)=>{"use strict";var uC=ht();tT.exports=function(){var a=uC(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 sT=b((FQ,aT)=>{"use strict";var lC=Ue(),cC=at(),dC=Kr(),rT=eT(),pC=iT(),hC=RegExp.prototype;aT.exports=rT.correct?function(a){return a.flags}:function(a){return!rT.correct&&dC(hC,a)&&!cC(a,"flags")?lC(pC,a):a.flags}});var oT=b((NQ,nT)=>{"use strict";var Cc=he(),fC=ji(),mC=Math.floor,Mc=Cc("".charAt),bC=Cc("".replace),Dc=Cc("".slice),gC=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,SC=/\$([$&'`]|\d{1,2})/g;nT.exports=function(a,e,t,i,r,s){var n=t+a.length,o=i.length,u=SC;return r!==void 0&&(r=fC(r),u=gC),bC(s,u,function(l,d){var c;switch(Mc(d,0)){case"$":return"$";case"&":return a;case"`":return Dc(e,0,t);case"'":return Dc(e,n);case"<":c=r[Dc(d,1,-1)];break;default:var f=+d;if(f===0)return l;if(f>o){var p=mC(f/10);return p===0?l:p<=o?i[p-1]===void 0?Mc(d,1):i[p-1]+Mc(d,1):l}c=i[f-1]}return c===void 0?"":c})}});var cT=b(()=>{"use strict";var vC=de(),yC=Ue(),Vc=he(),uT=jt(),TC=ue(),IC=Le(),EC=Xy(),Tr=Ma(),xC=Jr(),wC=sT(),AC=oT(),PC=ye(),RC=rt(),kC=PC("replace"),LC=TypeError,Bc=Vc("".indexOf),$C=Vc("".replace),lT=Vc("".slice),MC=Math.max;vC({target:"String",proto:!0},{replaceAll:function(e,t){var i=uT(this),r,s,n,o,u,l,d,c,f,p,h=0,m="";if(IC(e)){if(r=EC(e),r&&(s=Tr(uT(wC(e))),!~Bc(s,"g")))throw new LC("`.replaceAll` does not allow non-global regexes");if(n=xC(e,kC),n)return yC(n,e,i,t);if(RC&&r)return $C(Tr(i),e,t)}for(o=Tr(i),u=Tr(e),l=TC(t),l||(t=Tr(t)),d=u.length,c=MC(1,d),f=Bc(o,u);f!==-1;)p=l?Tr(t(u,f,o)):AC(u,o,f,[],void 0,t),m+=lT(o,h,f)+p,h=f+d,f=f+c>o.length?-1:Bc(o,u,f+c);return h<o.length&&(m+=lT(o,h)),m}})});var pT=b((HQ,dT)=>{"use strict";zy();Yy();cT();var DC=Qt();dT.exports=DC("String","replaceAll")});var fT=b((jQ,hT)=>{"use strict";var CC=pT();hT.exports=CC});var bT=b((QQ,mT)=>{"use strict";var BC=fT();mT.exports=BC});var ST=b((GQ,gT)=>{"use strict";var VC=ia(),_C=Ma(),OC=jt(),FC=RangeError;gT.exports=function(e){var t=_C(OC(this)),i="",r=VC(e);if(r<0||r===1/0)throw new FC("Wrong number of repetitions");for(;r>0;(r>>>=1)&&(t+=t))r&1&&(i+=t);return i}});var ET=b((WQ,IT)=>{"use strict";var TT=he(),NC=Uu(),vT=Ma(),UC=ST(),qC=jt(),HC=TT(UC),jC=TT("".slice),QC=Math.ceil,yT=function(a){return function(e,t,i){var r=vT(qC(e)),s=NC(t),n=r.length,o=i===void 0?" ":vT(i),u,l;return s<=n||o===""?r:(u=s-n,l=HC(o,QC(u/o.length)),l.length>u&&(l=jC(l,0,u)),a?r+l:l+r)}};IT.exports={start:yT(!1),end:yT(!0)}});var wT=b((zQ,xT)=>{"use strict";var GC=mi();xT.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(GC)});var AT=b(()=>{"use strict";var WC=de(),zC=ET().start,YC=wT();WC({target:"String",proto:!0,forced:YC},{padStart:function(e){return zC(this,e,arguments.length>1?arguments[1]:void 0)}})});var RT=b((XQ,PT)=>{"use strict";AT();var KC=Qt();PT.exports=KC("String","padStart")});var LT=b((JQ,kT)=>{"use strict";var XC=RT();kT.exports=XC});var MT=b((ZQ,$T)=>{"use strict";var JC=LT();$T.exports=JC});var Bp="2.0.136-dev.b3347749.0";var ke=(r=>(r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused",r))(ke||{}),wt=(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))(wt||{});var zs=(r=>(r.NOT_AVAILABLE="NOT_AVAILABLE",r.AVAILABLE="AVAILABLE",r.CONNECTING="CONNECTING",r.CONNECTED="CONNECTED",r))(zs||{}),cu=(i=>(i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic",i))(cu||{});var du=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(du||{}),Ys=(i=>(i.TRAFFIC_SAVING="traffic_saving",i.HIGH_QUALITY="high_quality",i.UNKNOWN="unknown",i))(Ys||{});var PE=N(ze(),1);import{assertNever as Cf,assertNonNullable as uA,isNonNullable as en,ValueSubject as Hu,Subject as lA,Subscription as cA,merge as dA,observableFrom as pA,fromEvent as Lf,map as $f,tap as Mf,filterChanged as hA,isNullable as ju,ErrorCategory as Df}from"@vkontakte/videoplayer-shared/es2018";var kf=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 tn=class{constructor(e){this.connection$=new Hu(void 0);this.castState$=new Hu("NOT_AVAILABLE");this.errorEvent$=new lA;this.realCastState$=new Hu("NOT_AVAILABLE");this.subscription=new cA;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=en((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||kf("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:Df.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(){en(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();ju(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();ju(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(Lf(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 Cf(r.sessionState)}})).add(dA(Lf(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(Mf(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),$f(r=>r.castState)),pA([i.getCastState()])).pipe(hA(),$f(fA),Mf(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{var o,u;let s=r==="CONNECTED",n=en(this.connection$.getValue());if(s&&!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;(ju(c)||c===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:l,castDevice:d}))}else!s&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(r==="CONNECTED"?en(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:Df.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:s})}}},fA=a=>{switch(a){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return"NOT_AVAILABLE";case cast.framework.CastState.NOT_CONNECTED:return"AVAILABLE";case cast.framework.CastState.CONNECTING:return"CONNECTING";case cast.framework.CastState.CONNECTED:return"CONNECTED";default:return Cf(a)}};var qd=N(ze(),1),uE=N(Xi(),1),lE=N(gl(),1);var OS=N(Ln(),1);import{assertNever as kS}from"@vkontakte/videoplayer-shared/es2018";var le=(a,e=0,t=0)=>{switch(t){case 0:return a.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case 1:{if(e===0)return a;let i=new URL(a);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}case 2:{let i=new URL(a);return!i.searchParams.get("offset_p")&&e===0?a:(i.searchParams.set("offset_p",e.toFixed(0)),i.toString())}default:kS(t)}return a},Wt=(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:kS(e)}};var L=(a,e,t=!1)=>{let i=a.getTransition();(t||!i||i.to===e)&&a.setState(e)};import{isNonNullable as I$,Subject as $n,merge as LS}from"@vkontakte/videoplayer-shared/es2018";var H=class{constructor(e){this.transitionStarted$=new $n;this.transitionEnded$=new $n;this.transitionUpdated$=new $n;this.forceChanged$=new $n;this.stateChangeStarted$=LS(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=LS(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 E$}from"@vkontakte/videoplayer-shared/es2018";var $S=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 E$(a)}};import{assertNever as or,assertNonNullable as Ii,debounce as MS,ErrorCategory as DS,fromEvent as Ei,isNonNullable as CS,map as BS,merge as VS,observableFrom as x$,Subject as w$,Subscription as rc,timeout as A$,getHighestQuality as P$}from"@vkontakte/videoplayer-shared/es2018";var R$=5,k$=5,L$=500,_S=7e3,ba=class{constructor(e){this.subscription=new rc;this.loadMediaTimeoutSubscription=new rc;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(),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:or(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:or(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:or(e)}break}default:or(i)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next($S(e.format)),this.params.output.isAudioAvailable$.next(!0),this.handleRemoteVolumeChange({volume:this.params.connection.remotePlayer.volumeLevel,muted:this.params.connection.remotePlayer.isMuted});let t=this.params.connection.session.getMediaSession();t&&this.restoreSession(t),this.subscribe()}destroy(){this.log({message:"[destroy]"}),this.subscription.unsubscribe()}subscribe(){this.subscription.add(this.loadMediaTimeoutSubscription);let e=new rc;this.subscription.add(e),this.subscription.add(VS(this.videoState.stateChangeStarted$.pipe(BS(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe(BS(r=>`stateChangeEnded$ ${JSON.stringify(r)}`))).subscribe(r=>this.log({message:`[videoState] ${r}`})));let t=(r,s)=>this.subscription.add(r.subscribe(s));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{let r=new w$;e.add(r.pipe(MS(L$)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add(Ei(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(Ei(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(Ei(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(Ei(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t(Ei(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<k$&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),L(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:or(n)}}),t(Ei(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t(Ei(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});let i=VS(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,x$(["init"])).pipe(MS(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"),L(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),L(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"),L(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"),L(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"&&L(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){var r,s;let t=this.params.output.volume$.getValue(),i={volume:(r=e.volume)!=null?r:t.volume,muted:(s=e.muted)!=null?s:t.muted};(i.volume!==t.volume||i.muted!==i.muted)&&this.params.output.volume$.next(i)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:i}=this.params.connection;t.currentTime=e,i.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){var l;let t=this.params.source,i,r,s;switch(e){case"MPEG":{let d=t[e];Ii(d);let c=P$(Object.keys(d));Ii(c);let f=d[c];Ii(f),i=f,r="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let d=t[e];Ii(d),i=d.url,r="application/x-mpegurl",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":{let d=t[e];Ii(d),i=d.url,r="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let d=t[e];Ii(d),i=d.url,r="application/dash+xml",s=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let d=t[e];Ii(d),i=le(d.url),r="application/x-mpegurl",s=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let d="Unsupported format for Chromecast",c=new Error(d);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:DS.VIDEO_PIPELINE,message:d,thrown:c}),c}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return or(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 CS(o)&&(n.metadata.title=o),CS(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(A$(_S).subscribe(()=>s(`timeout(${_S})`)))});(0,OS.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:DS.VIDEO_PIPELINE,message:s,thrown:r})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var Ec=N(ze(),1);import{clearVideoElement as NS}from"@vkontakte/videoplayer-shared/es2018";import{clearVideoElement as $$}from"@vkontakte/videoplayer-shared/es2018";var FS=a=>{try{a.pause(),a.playbackRate=0,$$(a),a.remove()}catch(e){console.error(e)}};import{fromEvent as M$,Subscription as D$}from"@vkontakte/videoplayer-shared/es2018";var ac=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)}},sc=window.WeakMap?new WeakMap:new ac,nc=window.WeakMap?new WeakMap:new Map,C$=(a,e=20)=>{let t=0;return M$(a,"ratechange").subscribe(i=>{t++,t>=e&&(a.currentTime=a.currentTime,t=0)})},$e=(a,{audioVideoSyncRate:e,disableYandexPiP:t})=>{let i=a.querySelector("video"),r=!!i;i?NS(i):(i=document.createElement("video"),a.appendChild(i)),sc.set(i,r);let s=new D$;return s.add(C$(i,e)),nc.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},Me=a=>{let e=nc.get(a);e==null||e.unsubscribe(),nc.delete(a);let t=sc.get(a);sc.delete(a),t?NS(a):FS(a)};var uc=N(ur(),1);import{assertNonNullable as Sa,isNonNullable as mt,isNullable as q$,fromEvent as lr,merge as WS,observableFrom as zS,filterChanged as YS,map as va,Subject as KS,Subscription as H$,ValueSubject as j$,ErrorCategory as Q$}from"@vkontakte/videoplayer-shared/es2018";import{isNonNullable as oc,isNullable as N$,Subscription as U$}from"@vkontakte/videoplayer-shared/es2018";var Mn=(a,e,t,{equal:i=(n,o)=>n===o,changed$:r,onError:s}={})=>{let n=a.getState(),o=e(),u=N$(r),l=new U$;return r&&l.add(r.subscribe(d=>{let c=a.getState();i(d,c)&&a.setState(d)},s)),i(o,n)||(t(n),u&&a.setState(n)),l.add(a.stateChangeStarted$.subscribe(d=>{t(d.to),u&&a.setState(d.to)},s)),l},ft=(a,e,t)=>Mn(e,()=>a.loop,i=>{oc(i)&&(a.loop=i)},{onError:t}),De=(a,e,t,i)=>Mn(e,()=>({muted:a.muted,volume:a.volume}),r=>{oc(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}),Ye=(a,e,t,i)=>Mn(e,()=>a.playbackRate,r=>{oc(r)&&(a.playbackRate=r)},{changed$:t,onError:i}),ga=Mn;var G$=a=>["__",a.language,a.label].join("|"),W$=(a,e)=>{if(a.id===e)return!0;let[t,i,r]=e.split("|");return a.language===i&&a.label===r},lc=class a{constructor(e){this.available$=new KS;this.current$=new j$(void 0);this.error$=new KS;this.subscription=new H$;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:Q$.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(ga(t.internalTextTracks,()=>(0,uc.default)(this.internalTracks),s=>{mt(s)&&this.setInternal(s)},{equal:(s,n)=>mt(s)&&mt(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(va(s=>s.filter(({type:n})=>n==="internal"))),onError:r})),this.subscription.add(ga(t.externalTextTracks,()=>(0,uc.default)(this.externalTracks),s=>{mt(s)&&this.setExternal(s)},{equal:(s,n)=>mt(s)&&mt(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(va(s=>s.filter(({type:n})=>n==="external"))),onError:r})),this.subscription.add(ga(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(ga(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){Sa(this.video);let{textTracks:e}=this.video;this.subscription.add(lr(e,"addtrack").subscribe(()=>{let i=this.current$.getValue();i&&this.select(i)})),this.subscription.add(WS(lr(e,"addtrack"),lr(e,"removetrack"),zS(["init"])).pipe(va(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),YS((i,r)=>i.length===r.length&&i.every(({id:s},n)=>s===r[n].id))).subscribe(this.available$)),this.subscription.add(WS(lr(e,"change"),zS(["init"])).pipe(va(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),va(i=>i&&this.htmlTextTrackToITextTrack(i).id),YS()).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(lr(e,"addtrack").subscribe(i=>{var s,n;(s=i.track)==null||s.addEventListener("cuechange",t);let r=o=>{var l,d,c,f,p;let u=(d=(l=o.target)==null?void 0:l.cues)!=null?d:null;u&&u.length&&(this.applyCueSettings((f=(c=o.target)==null?void 0:c.cues)!=null?f:null),(p=o.target)==null||p.removeEventListener("cuechange",r))};(n=i.track)==null||n.addEventListener("cuechange",r)})),this.subscription.add(lr(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;mt(t.align)&&(r.align=t.align),mt(t.position)&&(r.position=t.position),mt(t.size)&&(r.size=t.size),mt(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){Sa(this.video);let t=[...this.video.textTracks];return e?t:t.filter(a.isHealthyTrack)}htmlTextTrackToITextTrack(e){var o,u,l,d,c;let{language:t,label:i}=e,r=e.id?e.id:G$(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:(d=this.externalTracks.get(r))==null?void 0:d.url}:{id:r,type:"internal",isAuto:n,language:t,label:i,url:(c=this.internalTracks.get(r))==null?void 0:c.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(i=>i.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){let t=[...this.externalTracks];e.filter(({id:i,language:r,isAuto:s})=>!this.internalTracks.has(i)&&!t.some(([,n])=>n.language===r&&n.isAuto===s)).forEach(i=>this.attach(i)),Array.from(this.internalTracks).filter(([i])=>!e.find(r=>r.id===i)).forEach(([,i])=>this.detach(i))}select(e){Sa(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(q$(e)||!W$(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){Sa(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){Sa(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)}},Ke=lc;var xi=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 XS=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},cc=a=>{let e=XS(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},JS=a=>{let e=XS(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)};import{fromEvent as Ae,map as bt,merge as Fn,filterChanged as nv,isNonNullable as ov,Subject as iM,filter as pc,mapTo as hc,combine as rM,once as aM,throttle as sM,ErrorCategory as nM,ValueSubject as uv,Subscription as oM}from"@vkontakte/videoplayer-shared/es2018";var z$=3,ZS=(a,e,t=z$)=>{let i=0,r=0;for(let s=0;s<a.length;s++){let n=a.start(s),o=a.end(s);if(n<=e&&e<=o){if(i=n,r=o,!t)return{from:i,to:r};for(let u=s-1;u>=0;u--)a.end(u)+t>=i&&(i=a.start(u));for(let u=s+1;u<a.length;u++)a.start(u)-t<=r&&(r=a.end(u))}}return{from:i,to:r}};var Dn=class{constructor(){this._isMiuiBrowser=!1}get current(){return this._current}get isChrome(){return this.current==="Chrome"}get isFirefox(){return this.current==="Firefox"}get isSafari(){return this.current==="Safari"}get isOpera(){return this.current==="Opera"}get isEdge(){return this.current==="Edge"}get isYandex(){return this.current==="Yandex"}get isSamsungBrowser(){return this.current==="SamsungBrowser"}get currentVersion(){return this._current_version}get chromeVersion(){return this._chromeVersion}get firefoxVersion(){return this._firefoxVersion}get safariVersion(){return this._safariVersion}get operaVersion(){return this._operaVersion}get edgeVersion(){return this._edgeVersion}get yandexVersion(){return this._yandexVersion}get isMiuiBrowser(){return this._isMiuiBrowser}detect(){let{userAgent:e}=navigator;try{let t=/yabrowser/i.test(e)?"Yandex":void 0,i=/samsungbrowser/i.test(e)?"SamsungBrowser":void 0,r=/chrome|crios/i.test(e)?"Chrome":void 0,s=/chromium/i.test(e)?"Chromium":void 0,n=/firefox|fxios/i.test(e)?"Firefox":void 0,o=/webkit|safari|khtml/i.test(e)?"Safari":void 0,u=/opr\//i.test(e)?"Opera":void 0,l=/edg/i.test(e)?"Edge":void 0;this._isMiuiBrowser=/(XiaoMi)|(MiuiBrowser)/i.test(e),this._current=t||i||n||u||l||r||s||o||"Rest"}catch(t){console.error(t)}this.isChrome&&this.detectChromeVersion(),this.isFirefox&&this.detectFirefoxVersion(),this.isSafari&&this.detectSafariVersion(),this.isOpera&&this.detectOperaVersion(),this.isEdge&&this.detectEdgeVersion(),this.isYandex&&this.detectYandexVersion()}detectVersion(e){try{let{userAgent:t}=window.navigator,i=t.match(e);if(!i)return;let r=i[1],s=parseInt(r,10);if(!isNaN(s))return this._current_version=s,s}catch(t){console.error(t)}}detectChromeVersion(){this._chromeVersion=this.detectVersion(/Chrome\/(\d+\.\d+)/)}detectFirefoxVersion(){this._firefoxVersion=this.detectVersion(/Firefox\/(\d+\.\d+)/)}detectSafariVersion(){this._safariVersion=this.detectVersion(/Version\/(\d+)/)}detectOperaVersion(){this._operaVersion=this.detectVersion(/OPR\/(\d+\.\d+)/)}detectEdgeVersion(){this._edgeVersion=this.detectVersion(/Edg\/(\d+\.\d+)/)}detectYandexVersion(){this._yandexVersion=this.detectVersion(/YaBrowser\/(\d+\.\d+\.\d+)/)}};var ev=N(ze(),1);var ya=()=>{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 Cn=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,ev.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=ya()}catch(t){console.error(t)}this.detectDevice(e),this.detectHighEntropyValues(),this.isIOS&&this.detectIOSVersion()}async detectHighEntropyValues(){let{userAgentData:e}=navigator;if(e!=null&&e.getHighEntropyValues){let t=await e.getHighEntropyValues(["architecture","bitness","brands","mobile","platform","formFactor","model","platformVersion","wow64"]);this._highEntropyValues=t}}detectDevice(e){try{let t=/android/i.test(e)?"Android":void 0,i=/iphone/i.test(e)?"iPhone":void 0,r=/ipad/i.test(e)?"iPad":void 0,s=/ipod/i.test(e)?"iPod":void 0,n=/mac/i.test(e)?"Mac":void 0,o=/webOS|BlackBerry|IEMobile|Opera Mini/i.test(e)?"RestMobile":void 0;this._current=t||i||r||s||o||n||"Desktop"}catch(t){console.error(t)}}detectIOSVersion(){try{if(this._highEntropyValues.platformVersion){let s=this._highEntropyValues.platformVersion.split(".").slice(0,2).join("."),n=parseFloat(s);this._iosVersion=n;return}let{userAgent:e}=window.navigator,t=e.match(/OS (\d+(_\d+)?)/i);if(!t)return;let i=t[1].replace(/_/g,".");if(!i)return;let r=parseFloat(i);if(isNaN(r))return;this._iosVersion=r}catch(e){console.error(e)}}};var Bn=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 He=()=>window.ManagedMediaSource||window.MediaSource,cr=()=>{var a,e;return!!(window.ManagedMediaSource&&((e=(a=window.ManagedSourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},tv=()=>{var a,e;return!!(window.MediaSource&&((e=(a=window.SourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},Vn=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var Y$=document.createElement("video"),K$='video/mp4; codecs="avc1.42000a,mp4a.40.2"',X$='video/mp4; codecs="hev1.1.6.L93.B0"',iv='video/webm; codecs="vp09.00.10.08"',rv='video/webm; codecs="av01.0.00M.08"',J$='audio/mp4; codecs="mp4a.40.2"',Z$='audio/webm; codecs="opus"',av,eM=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:rv}}),window.navigator.mediaCapabilities.decodingInfo({...a,video:{...a.video,contentType:iv}})]);av={DASH_WEBM_AV1:e,DASH_WEBM:t}};eM().catch(a=>{console.log(Y$),console.error(a)});var _n=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 av}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,d,c,f,p,h,m,g,S,v,y,I;this._video=document.createElement("video");try{this._protocols={mms:cr(),mse:tv(),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=!!((d=(l=He())==null?void 0:l.isTypeSupported)!=null&&d.call(l,K$)),x=!!((f=(c=He())==null?void 0:c.isTypeSupported)!=null&&f.call(c,X$)),V=!!((h=(p=He())==null?void 0:p.isTypeSupported)!=null&&h.call(p,J$));this._codecs={h264:T,h265:x,vp9:!!((g=(m=He())==null?void 0:m.isTypeSupported)!=null&&g.call(m,iv)),av1:!!((v=(S=He())==null?void 0:S.isTypeSupported)!=null&&v.call(S,rv)),aac:V,opus:!!((I=(y=He())==null?void 0:y.isTypeSupported)!=null&&I.call(y,Z$)),mpeg:(T||x)&&V},this._nativeHlsSupported=this._protocols.hls&&this._containers.mp4}catch(T){console.error(T)}try{this.destroyVideoElement()}catch(T){console.error("Error destroying video element:",T)}}destroyVideoElement(){var t;if(!this._video)return;if(this._video.pause(),this._video.currentTime=0,this._video.removeAttribute("src"),this._video.src="",this._video.load(),this._video.remove){this._video.remove(),this._video=null;return}this._video.parentNode&&this._video.parentNode.removeChild(this._video);let e=this._video.cloneNode(!1);(t=this._video.parentNode)==null||t.replaceChild(e,this._video),this._video=null}};var sv="audio/mpeg",On=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,sv))},this._codecs={mp3:!!((r=(i=He())==null?void 0:i.isTypeSupported)!=null&&r.call(i,sv))}}catch(s){console.error(s)}try{this.destroyAudioElement()}catch(s){console.error("Error destroying audio element:",s)}}destroyAudioElement(){var t;if(!this._audio)return;if(this._audio.pause(),this._audio.currentTime=0,this._audio.removeAttribute("src"),this._audio.src="",this._audio.load(),this._audio.remove){this._audio.remove(),this._audio=null;return}this._audio.parentNode&&this._audio.parentNode.removeChild(this._audio);let e=this._audio.cloneNode(!1);(t=this._audio.parentNode)==null||t.replaceChild(e,this._audio),this._audio=null}};import{ValueSubject as tM}from"@vkontakte/videoplayer-shared/es2018";var dc=class{constructor(){this.isInited$=new tM(!1);this._displayChecker=new Bn,this._deviceChecker=new Cn(this._displayChecker),this._browserChecker=new Dn,this._videoChecker=new _n(this._deviceChecker,this._browserChecker),this._audioChecker=new On,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)}},U=new dc;var Ce=a=>{let e=P=>Ae(a,P).pipe(hc(void 0)),t=new oM,i=()=>t.unsubscribe(),r=Fn(Ae(a,"progress"),Ae(a,"timeupdate")).pipe(bt(()=>ZS(a.buffered,a.currentTime))),s=U.browser.isSafari?rM({play:e("play").pipe(aM()),playing:e("playing")}).pipe(hc(void 0)):e("playing"),n=Ae(a,"volumechange").pipe(bt(()=>({muted:a.muted,volume:a.volume}))),o=Ae(a,"ratechange").pipe(bt(()=>a.playbackRate)),u=Ae(a,"error").pipe(pc(()=>!!(a.error||a.played.length)),bt(()=>{var B;let P=a.error;return{id:P?`MediaError#${P.code}`:"HtmlVideoError",category:nM.VIDEO_PIPELINE,message:P?P.message:"Error event from HTML video element",thrown:(B=a.error)!=null?B:void 0}})),l=Ae(a,"timeupdate").pipe(bt(()=>a.currentTime)),d=["waiting","seeking","seeked","timeupdate"],c=new iM,f=.3,p;t.add(Fn(...d.map(P=>Ae(a,P))).subscribe(P=>{let B=a.currentTime;a.loop&&ov(p)&&ov(B)&&p>=a.duration-f&&B<=f&&c.next(p),p=B}));let h=e("pause").pipe(pc(()=>!a.error&&p!==a.duration)),m=Ae(a,"enterpictureinpicture"),g=Ae(a,"leavepictureinpicture"),S=new uv(JS(a));t.add(m.subscribe(()=>S.next(!0))),t.add(g.subscribe(()=>S.next(!1)));let v=new uv(cc(a)),y=Ae(a,"fullscreenchange");t.add(y.pipe(bt(()=>cc(a))).subscribe(v));let I=.1,T=1e3,x=Ae(a,"timeupdate").pipe(bt(P=>a.duration-a.currentTime<I),nv()),V=Fn(x.pipe(pc(P=>!a.loop&&P)),Ae(a,"ended")).pipe(sM(T),hc(void 0)),w=Fn(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(P=>Ae(a,P)),x.pipe(bt(P=>({type:P?"ended":"unknown"})))).pipe(bt(P=>U.browser.isFirefox&&P.type==="ended"?a.readyState<2:a.readyState<3),nv());return{playing$:s,pause$:h,canplay$:e("canplay"),ended$:V,looped$:c,error$:u,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:l,durationChange$:Ae(a,"durationchange").pipe(bt(()=>a.duration)),isBuffering$:w,currentBuffer$:r,volumeState$:n,playbackRateState$:o,inPiP$:S,inFullscreen$:v,enterPip$:m,leavePip$:g,destroy:i}};import{VideoQuality as zt}from"@vkontakte/videoplayer-shared/es2018";var Yt=a=>{switch(a){case"mobile":return zt.Q_144P;case"lowest":return zt.Q_240P;case"low":return zt.Q_360P;case"sd":case"medium":return zt.Q_480P;case"hd":case"high":return zt.Q_720P;case"fullhd":case"full":return zt.Q_1080P;case"quadhd":case"quad":return zt.Q_1440P;case"ultrahd":case"ultra":return zt.Q_2160P}};var Re=N(gt(),1),bc=N(ze(),1),wi=N(Xi(),1);import{isNonNullable as J,isNullable as jn,now as xv,isHigher as Qn,isHigherOrEqual as pr,isInvariantQuality as Gn,isLowerOrEqual as hr,videoSizeToQuality as wv,assertNotEmptyArray as Wn,assertNonNullable as Av}from"@vkontakte/videoplayer-shared/es2018";var fc=!1,kt={},mv=a=>{fc=a},bv=()=>{kt={}},gv=a=>{a(kt)},Ta=(a,e)=>{var t;fc&&(kt.meta=(t=kt.meta)!=null?t:{},kt.meta[a]=e)},Pe=class{constructor(e){this.name=e}next(e){var i,r;if(!fc)return;kt.series=(i=kt.series)!=null?i:{};let t=(r=kt.series[this.name])!=null?r:[];t.push([Date.now(),e]),kt.series[this.name]=t}};import{isHigher as bM,isHigherOrEqual as WU,isLower as Sv,isLowerOrEqual as zU,isNonNullable as Nn,isNullable as gM,videoHeightToQuality as Un}from"@vkontakte/videoplayer-shared/es2018";function mc(a,e,t){return!a.max&&a.min===e?"high_quality":!a.min&&a.max===t?"traffic_saving":"unknown"}function qn(a,e,t){return!!a&&mc(a,e,t)==="high_quality"}function dr(a,e,t){return gM(a)||Nn(a.min)&&Nn(a.max)&&Sv(a.max,a.min)||Nn(a.min)&&e&&bM(a.min,e)||Nn(a.max)&&t&&Sv(a.max,t)}function vv({limits:a,highestAvailableHeight:e,lowestAvailableHeight:t}){return dr({max:a!=null&&a.max?Un(a.max):void 0,min:a!=null&&a.min?Un(a.min):void 0},e?Un(e):void 0,t?Un(t):void 0)}var Pv=new Pe("best_bitrate"),zn=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t;var fr=a=>(e,t)=>a*(Number(e.bitrate)-Number(t.bitrate)),Kt=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=xv()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},Yn='Assertion "ABR Tracks is empty array" failed',Hn=new WeakMap,yv=new WeakMap,Tv=new WeakMap,Ia=(a,e,t,i)=>{var u;let r=[...e].sort(fr(1)),s=[...t].sort(fr(1)),n=s.filter(l=>J(l.bitrate)&&J(a.bitrate)?a.bitrate/l.bitrate>i:!0),o=(u=(0,Re.default)(s,Math.round(s.length*r.indexOf(a)/(r.length+1))))!=null?u:(0,Re.default)(s,-1);return o&&(0,bc.default)(n,o)?o:n.length?(0,Re.default)(n,-1):(0,Re.default)(s,0)},Ea=(a,e,t,i)=>{var u;let r=Hn.get(e);r||(r=[...e].sort(fr(1)),Hn.set(e,r));let s=Hn.get(t);s||(s=[...t].sort(fr(1)),Hn.set(t,s));let n=Tv.get(a);n||(n=s.filter(l=>J(l.bitrate)&&J(a.bitrate)?a.bitrate/l.bitrate>i:!0),Tv.set(a,n));let o=(u=(0,Re.default)(s,Math.round(s.length*r.indexOf(a)/(r.length+1))))!=null?u:(0,Re.default)(s,-1);return o&&(0,bc.default)(n,o)?o:n.length?(0,Re.default)(n,-1):(0,Re.default)(s,0)},Iv=a=>"quality"in a,Kn=(a,e,t,i)=>{var n;let r=J((n=i==null?void 0:i.last)==null?void 0:n.bitrate)&&J(t==null?void 0:t.bitrate)&&i.last.bitrate<t.bitrate?a.trackCooldownIncreaseQuality:a.trackCooldownDecreaseQuality,s=t&&i&&i.history[t.id]&&xv()-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=Iv(o)?"video":"audio",l=Iv(o)?o.quality:o.bitrate;return e({message:`
|
|
6
|
+
var UE=Object.create;var Op=Object.defineProperty;var qE=Object.getOwnPropertyDescriptor;var jE=Object.getOwnPropertyNames;var HE=Object.getPrototypeOf,QE=Object.prototype.hasOwnProperty;var g=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports);var GE=(a,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of jE(e))!QE.call(a,r)&&r!==t&&Op(a,r,{get:()=>e[r],enumerable:!(i=qE(e,r))||i.enumerable});return a};var O=(a,e,t)=>(t=a!=null?UE(HE(a)):{},GE(e||!a||!a.__esModule?Op(t,"default",{value:a,enumerable:!0}):t,a));var oe=g((hu,Np)=>{"use strict";var Wr=function(a){return a&&a.Math===Math&&a};Np.exports=Wr(typeof globalThis=="object"&&globalThis)||Wr(typeof window=="object"&&window)||Wr(typeof self=="object"&&self)||Wr(typeof global=="object"&&global)||Wr(typeof hu=="object"&&hu)||function(){return this}()||Function("return this")()});var pe=g((QV,Up)=>{"use strict";Up.exports=function(a){try{return!!a()}catch(e){return!0}}});var zr=g((GV,qp)=>{"use strict";var WE=pe();qp.exports=!WE(function(){var a=function(){}.bind();return typeof a!="function"||a.hasOwnProperty("prototype")})});var fu=g((WV,Gp)=>{"use strict";var zE=zr(),Qp=Function.prototype,jp=Qp.apply,Hp=Qp.call;Gp.exports=typeof Reflect=="object"&&Reflect.apply||(zE?Hp.bind(jp):function(){return Hp.apply(jp,arguments)})});var he=g((zV,Yp)=>{"use strict";var Wp=zr(),zp=Function.prototype,mu=zp.call,YE=Wp&&zp.bind.bind(mu,mu);Yp.exports=Wp?YE:function(a){return function(){return mu.apply(a,arguments)}}});var hi=g((YV,Xp)=>{"use strict";var Kp=he(),KE=Kp({}.toString),XE=Kp("".slice);Xp.exports=function(a){return XE(KE(a),8,-1)}});var bu=g((KV,Jp)=>{"use strict";var JE=hi(),ZE=he();Jp.exports=function(a){if(JE(a)==="Function")return ZE(a)}});var ue=g((XV,Zp)=>{"use strict";var gu=typeof document=="object"&&document.all;Zp.exports=typeof gu=="undefined"&&gu!==void 0?function(a){return typeof a=="function"||a===gu}:function(a){return typeof a=="function"}});var Ue=g((JV,eh)=>{"use strict";var ex=pe();eh.exports=!ex(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var qe=g((ZV,th)=>{"use strict";var tx=zr(),Xs=Function.prototype.call;th.exports=tx?Xs.bind(Xs):function(){return Xs.apply(Xs,arguments)}});var Su=g(ah=>{"use strict";var ih={}.propertyIsEnumerable,rh=Object.getOwnPropertyDescriptor,ix=rh&&!ih.call({1:2},1);ah.f=ix?function(e){var t=rh(this,e);return!!t&&t.enumerable}:ih});var Yr=g((t_,sh)=>{"use strict";sh.exports=function(a,e){return{enumerable:!(a&1),configurable:!(a&2),writable:!(a&4),value:e}}});var oh=g((i_,nh)=>{"use strict";var rx=he(),ax=pe(),sx=hi(),vu=Object,nx=rx("".split);nh.exports=ax(function(){return!vu("z").propertyIsEnumerable(0)})?function(a){return sx(a)==="String"?nx(a,""):vu(a)}:vu});var Kr=g((r_,uh)=>{"use strict";uh.exports=function(a){return a==null}});var Qt=g((a_,lh)=>{"use strict";var ox=Kr(),ux=TypeError;lh.exports=function(a){if(ox(a))throw new ux("Can't call method on "+a);return a}});var fi=g((s_,ch)=>{"use strict";var lx=oh(),cx=Qt();ch.exports=function(a){return lx(cx(a))}});var $e=g((n_,dh)=>{"use strict";var dx=ue();dh.exports=function(a){return typeof a=="object"?a!==null:dx(a)}});var mi=g((o_,ph)=>{"use strict";ph.exports={}});var Pt=g((u_,fh)=>{"use strict";var yu=mi(),Tu=oe(),px=ue(),hh=function(a){return px(a)?a:void 0};fh.exports=function(a,e){return arguments.length<2?hh(yu[a])||hh(Tu[a]):yu[a]&&yu[a][e]||Tu[a]&&Tu[a][e]}});var Xr=g((l_,mh)=>{"use strict";var hx=he();mh.exports=hx({}.isPrototypeOf)});var bi=g((c_,Sh)=>{"use strict";var fx=oe(),bh=fx.navigator,gh=bh&&bh.userAgent;Sh.exports=gh?String(gh):""});var Eu=g((d_,xh)=>{"use strict";var Eh=oe(),Iu=bi(),vh=Eh.process,yh=Eh.Deno,Th=vh&&vh.versions||yh&&yh.version,Ih=Th&&Th.v8,rt,Js;Ih&&(rt=Ih.split("."),Js=rt[0]>0&&rt[0]<4?1:+(rt[0]+rt[1]));!Js&&Iu&&(rt=Iu.match(/Edge\/(\d+)/),(!rt||rt[1]>=74)&&(rt=Iu.match(/Chrome\/(\d+)/),rt&&(Js=+rt[1])));xh.exports=Js});var xu=g((p_,Ah)=>{"use strict";var wh=Eu(),mx=pe(),bx=oe(),gx=bx.String;Ah.exports=!!Object.getOwnPropertySymbols&&!mx(function(){var a=Symbol("symbol detection");return!gx(a)||!(Object(a)instanceof Symbol)||!Symbol.sham&&wh&&wh<41})});var wu=g((h_,Ph)=>{"use strict";var Sx=xu();Ph.exports=Sx&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var Au=g((f_,kh)=>{"use strict";var vx=Pt(),yx=ue(),Tx=Xr(),Ix=wu(),Ex=Object;kh.exports=Ix?function(a){return typeof a=="symbol"}:function(a){var e=vx("Symbol");return yx(e)&&Tx(e.prototype,Ex(a))}});var Jr=g((m_,Rh)=>{"use strict";var xx=String;Rh.exports=function(a){try{return xx(a)}catch(e){return"Object"}}});var ft=g((b_,Lh)=>{"use strict";var wx=ue(),Ax=Jr(),Px=TypeError;Lh.exports=function(a){if(wx(a))return a;throw new Px(Ax(a)+" is not a function")}});var Zr=g((g_,$h)=>{"use strict";var kx=ft(),Rx=Kr();$h.exports=function(a,e){var t=a[e];return Rx(t)?void 0:kx(t)}});var Dh=g((S_,Mh)=>{"use strict";var Pu=qe(),ku=ue(),Ru=$e(),Lx=TypeError;Mh.exports=function(a,e){var t,i;if(e==="string"&&ku(t=a.toString)&&!Ru(i=Pu(t,a))||ku(t=a.valueOf)&&!Ru(i=Pu(t,a))||e!=="string"&&ku(t=a.toString)&&!Ru(i=Pu(t,a)))return i;throw new Lx("Can't convert object to primitive value")}});var at=g((v_,Ch)=>{"use strict";Ch.exports=!0});var _h=g((y_,Vh)=>{"use strict";var Bh=oe(),$x=Object.defineProperty;Vh.exports=function(a,e){try{$x(Bh,a,{value:e,configurable:!0,writable:!0})}catch(t){Bh[a]=e}return e}});var ea=g((T_,Nh)=>{"use strict";var Mx=at(),Dx=oe(),Cx=_h(),Oh="__core-js_shared__",Fh=Nh.exports=Dx[Oh]||Cx(Oh,{});(Fh.versions||(Fh.versions=[])).push({version:"3.43.0",mode:Mx?"pure":"global",copyright:"\xA9 2014-2025 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.43.0/LICENSE",source:"https://github.com/zloirock/core-js"})});var Lu=g((I_,qh)=>{"use strict";var Uh=ea();qh.exports=function(a,e){return Uh[a]||(Uh[a]=e||{})}});var Wi=g((E_,jh)=>{"use strict";var Bx=Qt(),Vx=Object;jh.exports=function(a){return Vx(Bx(a))}});var st=g((x_,Hh)=>{"use strict";var _x=he(),Ox=Wi(),Fx=_x({}.hasOwnProperty);Hh.exports=Object.hasOwn||function(e,t){return Fx(Ox(e),t)}});var $u=g((w_,Qh)=>{"use strict";var Nx=he(),Ux=0,qx=Math.random(),jx=Nx(1.1.toString);Qh.exports=function(a){return"Symbol("+(a===void 0?"":a)+")_"+jx(++Ux+qx,36)}});var ye=g((A_,Wh)=>{"use strict";var Hx=oe(),Qx=Lu(),Gh=st(),Gx=$u(),Wx=xu(),zx=wu(),zi=Hx.Symbol,Mu=Qx("wks"),Yx=zx?zi.for||zi:zi&&zi.withoutSetter||Gx;Wh.exports=function(a){return Gh(Mu,a)||(Mu[a]=Wx&&Gh(zi,a)?zi[a]:Yx("Symbol."+a)),Mu[a]}});var Xh=g((P_,Kh)=>{"use strict";var Kx=qe(),zh=$e(),Yh=Au(),Xx=Zr(),Jx=Dh(),Zx=ye(),ew=TypeError,tw=Zx("toPrimitive");Kh.exports=function(a,e){if(!zh(a)||Yh(a))return a;var t=Xx(a,tw),i;if(t){if(e===void 0&&(e="default"),i=Kx(t,a,e),!zh(i)||Yh(i))return i;throw new ew("Can't convert object to primitive value")}return e===void 0&&(e="number"),Jx(a,e)}});var Du=g((k_,Jh)=>{"use strict";var iw=Xh(),rw=Au();Jh.exports=function(a){var e=iw(a,"string");return rw(e)?e:e+""}});var Zs=g((R_,ef)=>{"use strict";var aw=oe(),Zh=$e(),Cu=aw.document,sw=Zh(Cu)&&Zh(Cu.createElement);ef.exports=function(a){return sw?Cu.createElement(a):{}}});var Bu=g((L_,tf)=>{"use strict";var nw=Ue(),ow=pe(),uw=Zs();tf.exports=!nw&&!ow(function(){return Object.defineProperty(uw("div"),"a",{get:function(){return 7}}).a!==7})});var sf=g(af=>{"use strict";var lw=Ue(),cw=qe(),dw=Su(),pw=Yr(),hw=fi(),fw=Du(),mw=st(),bw=Bu(),rf=Object.getOwnPropertyDescriptor;af.f=lw?rf:function(e,t){if(e=hw(e),t=fw(t),bw)try{return rf(e,t)}catch(i){}if(mw(e,t))return pw(!cw(dw.f,e,t),e[t])}});var Vu=g((M_,nf)=>{"use strict";var gw=pe(),Sw=ue(),vw=/#|\.prototype\./,ta=function(a,e){var t=Tw[yw(a)];return t===Ew?!0:t===Iw?!1:Sw(e)?gw(e):!!e},yw=ta.normalize=function(a){return String(a).replace(vw,".").toLowerCase()},Tw=ta.data={},Iw=ta.NATIVE="N",Ew=ta.POLYFILL="P";nf.exports=ta});var Yi=g((D_,uf)=>{"use strict";var of=bu(),xw=ft(),ww=zr(),Aw=of(of.bind);uf.exports=function(a,e){return xw(a),e===void 0?a:ww?Aw(a,e):function(){return a.apply(e,arguments)}}});var _u=g((C_,lf)=>{"use strict";var Pw=Ue(),kw=pe();lf.exports=Pw&&kw(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var mt=g((B_,cf)=>{"use strict";var Rw=$e(),Lw=String,$w=TypeError;cf.exports=function(a){if(Rw(a))return a;throw new $w(Lw(a)+" is not an object")}});var gi=g(pf=>{"use strict";var Mw=Ue(),Dw=Bu(),Cw=_u(),en=mt(),df=Du(),Bw=TypeError,Ou=Object.defineProperty,Vw=Object.getOwnPropertyDescriptor,Fu="enumerable",Nu="configurable",Uu="writable";pf.f=Mw?Cw?function(e,t,i){if(en(e),t=df(t),en(i),typeof e=="function"&&t==="prototype"&&"value"in i&&Uu in i&&!i[Uu]){var r=Vw(e,t);r&&r[Uu]&&(e[t]=i.value,i={configurable:Nu in i?i[Nu]:r[Nu],enumerable:Fu in i?i[Fu]:r[Fu],writable:!1})}return Ou(e,t,i)}:Ou:function(e,t,i){if(en(e),t=df(t),en(i),Dw)try{return Ou(e,t,i)}catch(r){}if("get"in i||"set"in i)throw new Bw("Accessors not supported");return"value"in i&&(e[t]=i.value),e}});var Ki=g((__,hf)=>{"use strict";var _w=Ue(),Ow=gi(),Fw=Yr();hf.exports=_w?function(a,e,t){return Ow.f(a,e,Fw(1,t))}:function(a,e,t){return a[e]=t,a}});var de=g((O_,mf)=>{"use strict";var ia=oe(),Nw=fu(),Uw=bu(),qw=ue(),jw=sf().f,Hw=Vu(),Xi=mi(),Qw=Yi(),Ji=Ki(),ff=st();ea();var Gw=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 Nw(a,this,arguments)};return e.prototype=a.prototype,e};mf.exports=function(a,e){var t=a.target,i=a.global,r=a.stat,s=a.proto,n=i?ia:r?ia[t]:ia[t]&&ia[t].prototype,o=i?Xi:Xi[t]||Ji(Xi,t,{})[t],u=o.prototype,l,c,d,f,p,h,m,b,S;for(f in e)l=Hw(i?f:t+(r?".":"#")+f,a.forced),c=!l&&n&&ff(n,f),h=o[f],c&&(a.dontCallGetSet?(S=jw(n,f),m=S&&S.value):m=n[f]),p=c&&m?m:e[f],!(!l&&!s&&typeof h==typeof p)&&(a.bind&&c?b=Qw(p,ia):a.wrap&&c?b=Gw(p):s&&qw(p)?b=Uw(p):b=p,(a.sham||p&&p.sham||h&&h.sham)&&Ji(b,"sham",!0),Ji(o,f,b),s&&(d=t+"Prototype",ff(Xi,d)||Ji(Xi,d,{}),Ji(Xi[d],f,p),a.real&&u&&(l||!u[f])&&Ji(u,f,p)))}});var gf=g((F_,bf)=>{"use strict";var Ww=Math.ceil,zw=Math.floor;bf.exports=Math.trunc||function(e){var t=+e;return(t>0?zw:Ww)(t)}});var ra=g((N_,Sf)=>{"use strict";var Yw=gf();Sf.exports=function(a){var e=+a;return e!==e||e===0?0:Yw(e)}});var yf=g((U_,vf)=>{"use strict";var Kw=ra(),Xw=Math.max,Jw=Math.min;vf.exports=function(a,e){var t=Kw(a);return t<0?Xw(t+e,0):Jw(t,e)}});var qu=g((q_,Tf)=>{"use strict";var Zw=ra(),eA=Math.min;Tf.exports=function(a){var e=Zw(a);return e>0?eA(e,9007199254740991):0}});var Zi=g((j_,If)=>{"use strict";var tA=qu();If.exports=function(a){return tA(a.length)}});var ju=g((H_,xf)=>{"use strict";var iA=fi(),rA=yf(),aA=Zi(),Ef=function(a){return function(e,t,i){var r=iA(e),s=aA(r);if(s===0)return!a&&-1;var n=rA(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}};xf.exports={includes:Ef(!0),indexOf:Ef(!1)}});var aa=g((Q_,wf)=>{"use strict";wf.exports=function(){}});var Af=g(()=>{"use strict";var sA=de(),nA=ju().includes,oA=pe(),uA=aa(),lA=oA(function(){return!Array(1).includes()});sA({target:"Array",proto:!0,forced:lA},{includes:function(e){return nA(this,e,arguments.length>1?arguments[1]:void 0)}});uA("includes")});var Gt=g((z_,Pf)=>{"use strict";var cA=Pt();Pf.exports=cA});var Rf=g((Y_,kf)=>{"use strict";Af();var dA=Gt();kf.exports=dA("Array","includes")});var $f=g((K_,Lf)=>{"use strict";var pA=Rf();Lf.exports=pA});var Ye=g((X_,Mf)=>{"use strict";var hA=$f();Mf.exports=hA});var an=g((lO,Nf)=>{"use strict";var TA=Lu(),IA=$u(),Ff=TA("keys");Nf.exports=function(a){return Ff[a]||(Ff[a]=IA(a))}});var qf=g((cO,Uf)=>{"use strict";var EA=pe();Uf.exports=!EA(function(){function a(){}return a.prototype.constructor=null,Object.getPrototypeOf(new a)!==a.prototype})});var sn=g((dO,Hf)=>{"use strict";var xA=st(),wA=ue(),AA=Wi(),PA=an(),kA=qf(),jf=PA("IE_PROTO"),Gu=Object,RA=Gu.prototype;Hf.exports=kA?Gu.getPrototypeOf:function(a){var e=AA(a);if(xA(e,jf))return e[jf];var t=e.constructor;return wA(t)&&e instanceof t?t.prototype:e instanceof Gu?RA:null}});var nn=g((pO,Qf)=>{"use strict";Qf.exports={}});var zf=g((hO,Wf)=>{"use strict";var LA=he(),Wu=st(),$A=fi(),MA=ju().indexOf,DA=nn(),Gf=LA([].push);Wf.exports=function(a,e){var t=$A(a),i=0,r=[],s;for(s in t)!Wu(DA,s)&&Wu(t,s)&&Gf(r,s);for(;e.length>i;)Wu(t,s=e[i++])&&(~MA(r,s)||Gf(r,s));return r}});var zu=g((fO,Yf)=>{"use strict";Yf.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var Yu=g((mO,Kf)=>{"use strict";var CA=zf(),BA=zu();Kf.exports=Object.keys||function(e){return CA(e,BA)}});var Ku=g((bO,tm)=>{"use strict";var Jf=Ue(),VA=pe(),Zf=he(),_A=sn(),OA=Yu(),FA=fi(),NA=Su().f,em=Zf(NA),UA=Zf([].push),qA=Jf&&VA(function(){var a=Object.create(null);return a[2]=2,!em(a,2)}),Xf=function(a){return function(e){for(var t=FA(e),i=OA(t),r=qA&&_A(t)===null,s=i.length,n=0,o=[],u;s>n;)u=i[n++],(!Jf||(r?u in t:em(t,u)))&&UA(o,a?[u,t[u]]:t[u]);return o}};tm.exports={entries:Xf(!0),values:Xf(!1)}});var im=g(()=>{"use strict";var jA=de(),HA=Ku().entries;jA({target:"Object",stat:!0},{entries:function(e){return HA(e)}})});var am=g((vO,rm)=>{"use strict";im();var QA=mi();rm.exports=QA.Object.entries});var nm=g((yO,sm)=>{"use strict";var GA=am();sm.exports=GA});var er=g((TO,om)=>{"use strict";var WA=nm();om.exports=WA});var Si=g((IO,um)=>{"use strict";um.exports={}});var dm=g((EO,cm)=>{"use strict";var zA=oe(),YA=ue(),lm=zA.WeakMap;cm.exports=YA(lm)&&/native code/.test(String(lm))});var el=g((xO,fm)=>{"use strict";var KA=dm(),hm=oe(),XA=$e(),JA=Ki(),Xu=st(),Ju=ea(),ZA=an(),eP=nn(),pm="Object already initialized",Zu=hm.TypeError,tP=hm.WeakMap,on,sa,un,iP=function(a){return un(a)?sa(a):on(a,{})},rP=function(a){return function(e){var t;if(!XA(e)||(t=sa(e)).type!==a)throw new Zu("Incompatible receiver, "+a+" required");return t}};KA||Ju.state?(nt=Ju.state||(Ju.state=new tP),nt.get=nt.get,nt.has=nt.has,nt.set=nt.set,on=function(a,e){if(nt.has(a))throw new Zu(pm);return e.facade=a,nt.set(a,e),e},sa=function(a){return nt.get(a)||{}},un=function(a){return nt.has(a)}):(vi=ZA("state"),eP[vi]=!0,on=function(a,e){if(Xu(a,vi))throw new Zu(pm);return e.facade=a,JA(a,vi,e),e},sa=function(a){return Xu(a,vi)?a[vi]:{}},un=function(a){return Xu(a,vi)});var nt,vi;fm.exports={set:on,get:sa,has:un,enforce:iP,getterFor:rP}});var rl=g((wO,bm)=>{"use strict";var tl=Ue(),aP=st(),mm=Function.prototype,sP=tl&&Object.getOwnPropertyDescriptor,il=aP(mm,"name"),nP=il&&function(){}.name==="something",oP=il&&(!tl||tl&&sP(mm,"name").configurable);bm.exports={EXISTS:il,PROPER:nP,CONFIGURABLE:oP}});var Sm=g(gm=>{"use strict";var uP=Ue(),lP=_u(),cP=gi(),dP=mt(),pP=fi(),hP=Yu();gm.f=uP&&!lP?Object.defineProperties:function(e,t){dP(e);for(var i=pP(t),r=hP(t),s=r.length,n=0,o;s>n;)cP.f(e,o=r[n++],i[o]);return e}});var al=g((PO,vm)=>{"use strict";var fP=Pt();vm.exports=fP("document","documentElement")});var ul=g((kO,Am)=>{"use strict";var mP=mt(),bP=Sm(),ym=zu(),gP=nn(),SP=al(),vP=Zs(),yP=an(),Tm=">",Im="<",nl="prototype",ol="script",xm=yP("IE_PROTO"),sl=function(){},wm=function(a){return Im+ol+Tm+a+Im+"/"+ol+Tm},Em=function(a){a.write(wm("")),a.close();var e=a.parentWindow.Object;return a=null,e},TP=function(){var a=vP("iframe"),e="java"+ol+":",t;return a.style.display="none",SP.appendChild(a),a.src=String(e),t=a.contentWindow.document,t.open(),t.write(wm("document.F=Object")),t.close(),t.F},ln,cn=function(){try{ln=new ActiveXObject("htmlfile")}catch(e){}cn=typeof document!="undefined"?document.domain&&ln?Em(ln):TP():Em(ln);for(var a=ym.length;a--;)delete cn[nl][ym[a]];return cn()};gP[xm]=!0;Am.exports=Object.create||function(e,t){var i;return e!==null?(sl[nl]=mP(e),i=new sl,sl[nl]=null,i[xm]=e):i=cn(),t===void 0?i:bP.f(i,t)}});var tr=g((RO,Pm)=>{"use strict";var IP=Ki();Pm.exports=function(a,e,t,i){return i&&i.enumerable?a[e]=t:IP(a,e,t),a}});var pl=g((LO,Lm)=>{"use strict";var EP=pe(),xP=ue(),wP=$e(),AP=ul(),km=sn(),PP=tr(),kP=ye(),RP=at(),dl=kP("iterator"),Rm=!1,kt,ll,cl;[].keys&&(cl=[].keys(),"next"in cl?(ll=km(km(cl)),ll!==Object.prototype&&(kt=ll)):Rm=!0);var LP=!wP(kt)||EP(function(){var a={};return kt[dl].call(a)!==a});LP?kt={}:RP&&(kt=AP(kt));xP(kt[dl])||PP(kt,dl,function(){return this});Lm.exports={IteratorPrototype:kt,BUGGY_SAFARI_ITERATORS:Rm}});var dn=g(($O,Mm)=>{"use strict";var $P=ye(),MP=$P("toStringTag"),$m={};$m[MP]="z";Mm.exports=String($m)==="[object z]"});var na=g((MO,Dm)=>{"use strict";var DP=dn(),CP=ue(),pn=hi(),BP=ye(),VP=BP("toStringTag"),_P=Object,OP=pn(function(){return arguments}())==="Arguments",FP=function(a,e){try{return a[e]}catch(t){}};Dm.exports=DP?pn:function(a){var e,t,i;return a===void 0?"Undefined":a===null?"Null":typeof(t=FP(e=_P(a),VP))=="string"?t:OP?pn(e):(i=pn(e))==="Object"&&CP(e.callee)?"Arguments":i}});var Bm=g((DO,Cm)=>{"use strict";var NP=dn(),UP=na();Cm.exports=NP?{}.toString:function(){return"[object "+UP(this)+"]"}});var oa=g((CO,_m)=>{"use strict";var qP=dn(),jP=gi().f,HP=Ki(),QP=st(),GP=Bm(),WP=ye(),Vm=WP("toStringTag");_m.exports=function(a,e,t,i){var r=t?a:a&&a.prototype;r&&(QP(r,Vm)||jP(r,Vm,{configurable:!0,value:e}),i&&!qP&&HP(r,"toString",GP))}});var Fm=g((BO,Om)=>{"use strict";var zP=pl().IteratorPrototype,YP=ul(),KP=Yr(),XP=oa(),JP=Si(),ZP=function(){return this};Om.exports=function(a,e,t,i){var r=e+" Iterator";return a.prototype=YP(zP,{next:KP(+!i,t)}),XP(a,r,!1,!0),JP[r]=ZP,a}});var Um=g((VO,Nm)=>{"use strict";var ek=he(),tk=ft();Nm.exports=function(a,e,t){try{return ek(tk(Object.getOwnPropertyDescriptor(a,e)[t]))}catch(i){}}});var jm=g((_O,qm)=>{"use strict";var ik=$e();qm.exports=function(a){return ik(a)||a===null}});var Qm=g((OO,Hm)=>{"use strict";var rk=jm(),ak=String,sk=TypeError;Hm.exports=function(a){if(rk(a))return a;throw new sk("Can't set "+ak(a)+" as a prototype")}});var hl=g((FO,Gm)=>{"use strict";var nk=Um(),ok=$e(),uk=Qt(),lk=Qm();Gm.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var a=!1,e={},t;try{t=nk(Object.prototype,"__proto__","set"),t(e,[]),a=e instanceof Array}catch(i){}return function(r,s){return uk(r),lk(s),ok(r)&&(a?t(r,s):r.__proto__=s),r}}():void 0)});var rb=g((NO,ib)=>{"use strict";var ck=de(),dk=qe(),hn=at(),eb=rl(),pk=ue(),hk=Fm(),Wm=sn(),zm=hl(),fk=oa(),mk=Ki(),fl=tr(),bk=ye(),Ym=Si(),tb=pl(),gk=eb.PROPER,Sk=eb.CONFIGURABLE,Km=tb.IteratorPrototype,fn=tb.BUGGY_SAFARI_ITERATORS,ua=bk("iterator"),Xm="keys",la="values",Jm="entries",Zm=function(){return this};ib.exports=function(a,e,t,i,r,s,n){hk(t,e,i);var o=function(S){if(S===r&&f)return f;if(!fn&&S&&S in c)return c[S];switch(S){case Xm:return function(){return new t(this,S)};case la:return function(){return new t(this,S)};case Jm:return function(){return new t(this,S)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,c=a.prototype,d=c[ua]||c["@@iterator"]||r&&c[r],f=!fn&&d||o(r),p=e==="Array"&&c.entries||d,h,m,b;if(p&&(h=Wm(p.call(new a)),h!==Object.prototype&&h.next&&(!hn&&Wm(h)!==Km&&(zm?zm(h,Km):pk(h[ua])||fl(h,ua,Zm)),fk(h,u,!0,!0),hn&&(Ym[u]=Zm))),gk&&r===la&&d&&d.name!==la&&(!hn&&Sk?mk(c,"name",la):(l=!0,f=function(){return dk(d,this)})),r)if(m={values:o(la),keys:s?f:o(Xm),entries:o(Jm)},n)for(b in m)(fn||l||!(b in c))&&fl(c,b,m[b]);else ck({target:e,proto:!0,forced:fn||l},m);return(!hn||n)&&c[ua]!==f&&fl(c,ua,f,{name:r}),Ym[e]=f,m}});var sb=g((UO,ab)=>{"use strict";ab.exports=function(a,e){return{value:a,done:e}}});var bl=g((qO,cb)=>{"use strict";var vk=fi(),ml=aa(),nb=Si(),ub=el(),yk=gi().f,Tk=rb(),mn=sb(),Ik=at(),Ek=Ue(),lb="Array Iterator",xk=ub.set,wk=ub.getterFor(lb);cb.exports=Tk(Array,"Array",function(a,e){xk(this,{type:lb,target:vk(a),index:0,kind:e})},function(){var a=wk(this),e=a.target,t=a.index++;if(!e||t>=e.length)return a.target=null,mn(void 0,!0);switch(a.kind){case"keys":return mn(t,!1);case"values":return mn(e[t],!1)}return mn([t,e[t]],!1)},"values");var ob=nb.Arguments=nb.Array;ml("keys");ml("values");ml("entries");if(!Ik&&Ek&&ob.name!=="values")try{yk(ob,"name",{value:"values"})}catch(a){}});var pb=g((jO,db)=>{"use strict";var Ak=ye(),Pk=Si(),kk=Ak("iterator"),Rk=Array.prototype;db.exports=function(a){return a!==void 0&&(Pk.Array===a||Rk[kk]===a)}});var gl=g((HO,fb)=>{"use strict";var Lk=na(),hb=Zr(),$k=Kr(),Mk=Si(),Dk=ye(),Ck=Dk("iterator");fb.exports=function(a){if(!$k(a))return hb(a,Ck)||hb(a,"@@iterator")||Mk[Lk(a)]}});var bb=g((QO,mb)=>{"use strict";var Bk=qe(),Vk=ft(),_k=mt(),Ok=Jr(),Fk=gl(),Nk=TypeError;mb.exports=function(a,e){var t=arguments.length<2?Fk(a):e;if(Vk(t))return _k(Bk(t,a));throw new Nk(Ok(a)+" is not iterable")}});var vb=g((GO,Sb)=>{"use strict";var Uk=qe(),gb=mt(),qk=Zr();Sb.exports=function(a,e,t){var i,r;gb(a);try{if(i=qk(a,"return"),!i){if(e==="throw")throw t;return t}i=Uk(i,a)}catch(s){r=!0,i=s}if(e==="throw")throw t;if(r)throw i;return gb(i),t}});var gn=g((WO,Eb)=>{"use strict";var jk=Yi(),Hk=qe(),Qk=mt(),Gk=Jr(),Wk=pb(),zk=Zi(),yb=Xr(),Yk=bb(),Kk=gl(),Tb=vb(),Xk=TypeError,bn=function(a,e){this.stopped=a,this.result=e},Ib=bn.prototype;Eb.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=jk(e,i),l,c,d,f,p,h,m,b=function(y){return l&&Tb(l,"normal"),new bn(!0,y)},S=function(y){return r?(Qk(y),o?u(y[0],y[1],b):u(y[0],y[1])):o?u(y,b):u(y)};if(s)l=a.iterator;else if(n)l=a;else{if(c=Kk(a),!c)throw new Xk(Gk(a)+" is not iterable");if(Wk(c)){for(d=0,f=zk(a);f>d;d++)if(p=S(a[d]),p&&yb(Ib,p))return p;return new bn(!1)}l=Yk(a,c)}for(h=s?a.next:l.next;!(m=Hk(h,l)).done;){try{p=S(m.value)}catch(y){Tb(l,"throw",y)}if(typeof p=="object"&&p&&yb(Ib,p))return p}return new bn(!1)}});var wb=g((zO,xb)=>{"use strict";var Jk=Ue(),Zk=gi(),eR=Yr();xb.exports=function(a,e,t){Jk?Zk.f(a,e,eR(0,t)):a[e]=t}});var Ab=g(()=>{"use strict";var tR=de(),iR=gn(),rR=wb();tR({target:"Object",stat:!0},{fromEntries:function(e){var t={};return iR(e,function(i,r){rR(t,i,r)},{AS_ENTRIES:!0}),t}})});var kb=g((XO,Pb)=>{"use strict";bl();Ab();var aR=mi();Pb.exports=aR.Object.fromEntries});var Lb=g((JO,Rb)=>{"use strict";Rb.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 Mb=g(()=>{"use strict";bl();var sR=Lb(),nR=oe(),oR=oa(),$b=Si();for(Sn in sR)oR(nR[Sn],Sn),$b[Sn]=$b.Array;var Sn});var Cb=g((tF,Db)=>{"use strict";var uR=kb();Mb();Db.exports=uR});var Sl=g((iF,Bb)=>{"use strict";var lR=Cb();Bb.exports=lR});var Vb=g(()=>{"use strict"});var vl=g((sF,_b)=>{"use strict";var ca=oe(),cR=bi(),dR=hi(),vn=function(a){return cR.slice(0,a.length)===a};_b.exports=function(){return vn("Bun/")?"BUN":vn("Cloudflare-Workers")?"CLOUDFLARE":vn("Deno/")?"DENO":vn("Node.js/")?"NODE":ca.Bun&&typeof Bun.version=="string"?"BUN":ca.Deno&&typeof Deno.version=="object"?"DENO":dR(ca.process)==="process"?"NODE":ca.window&&ca.document?"BROWSER":"REST"}()});var yn=g((nF,Ob)=>{"use strict";var pR=vl();Ob.exports=pR==="NODE"});var Nb=g((oF,Fb)=>{"use strict";var hR=gi();Fb.exports=function(a,e,t){return hR.f(a,e,t)}});var jb=g((uF,qb)=>{"use strict";var fR=Pt(),mR=Nb(),bR=ye(),gR=Ue(),Ub=bR("species");qb.exports=function(a){var e=fR(a);gR&&e&&!e[Ub]&&mR(e,Ub,{configurable:!0,get:function(){return this}})}});var Qb=g((lF,Hb)=>{"use strict";var SR=Xr(),vR=TypeError;Hb.exports=function(a,e){if(SR(e,a))return a;throw new vR("Incorrect invocation")}});var Tl=g((cF,Gb)=>{"use strict";var yR=he(),TR=ue(),yl=ea(),IR=yR(Function.toString);TR(yl.inspectSource)||(yl.inspectSource=function(a){return IR(a)});Gb.exports=yl.inspectSource});var El=g((dF,Xb)=>{"use strict";var ER=he(),xR=pe(),Wb=ue(),wR=na(),AR=Pt(),PR=Tl(),zb=function(){},Yb=AR("Reflect","construct"),Il=/^\s*(?:class|function)\b/,kR=ER(Il.exec),RR=!Il.test(zb),da=function(e){if(!Wb(e))return!1;try{return Yb(zb,[],e),!0}catch(t){return!1}},Kb=function(e){if(!Wb(e))return!1;switch(wR(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return RR||!!kR(Il,PR(e))}catch(t){return!0}};Kb.sham=!0;Xb.exports=!Yb||xR(function(){var a;return da(da.call)||!da(Object)||!da(function(){a=!0})||a})?Kb:da});var Zb=g((pF,Jb)=>{"use strict";var LR=El(),$R=Jr(),MR=TypeError;Jb.exports=function(a){if(LR(a))return a;throw new MR($R(a)+" is not a constructor")}});var xl=g((hF,tg)=>{"use strict";var eg=mt(),DR=Zb(),CR=Kr(),BR=ye(),VR=BR("species");tg.exports=function(a,e){var t=eg(a).constructor,i;return t===void 0||CR(i=eg(t)[VR])?e:DR(i)}});var rg=g((fF,ig)=>{"use strict";var _R=he();ig.exports=_R([].slice)});var sg=g((mF,ag)=>{"use strict";var OR=TypeError;ag.exports=function(a,e){if(a<e)throw new OR("Not enough arguments");return a}});var wl=g((bF,ng)=>{"use strict";var FR=bi();ng.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(FR)});var Cl=g((gF,mg)=>{"use strict";var je=oe(),NR=fu(),UR=Yi(),og=ue(),qR=st(),fg=pe(),ug=al(),jR=rg(),lg=Zs(),HR=sg(),QR=wl(),GR=yn(),$l=je.setImmediate,Ml=je.clearImmediate,WR=je.process,Al=je.Dispatch,zR=je.Function,cg=je.MessageChannel,YR=je.String,Pl=0,pa={},dg="onreadystatechange",ha,yi,kl,Rl;fg(function(){ha=je.location});var Dl=function(a){if(qR(pa,a)){var e=pa[a];delete pa[a],e()}},Ll=function(a){return function(){Dl(a)}},pg=function(a){Dl(a.data)},hg=function(a){je.postMessage(YR(a),ha.protocol+"//"+ha.host)};(!$l||!Ml)&&($l=function(e){HR(arguments.length,1);var t=og(e)?e:zR(e),i=jR(arguments,1);return pa[++Pl]=function(){NR(t,void 0,i)},yi(Pl),Pl},Ml=function(e){delete pa[e]},GR?yi=function(a){WR.nextTick(Ll(a))}:Al&&Al.now?yi=function(a){Al.now(Ll(a))}:cg&&!QR?(kl=new cg,Rl=kl.port2,kl.port1.onmessage=pg,yi=UR(Rl.postMessage,Rl)):je.addEventListener&&og(je.postMessage)&&!je.importScripts&&ha&&ha.protocol!=="file:"&&!fg(hg)?(yi=hg,je.addEventListener("message",pg,!1)):dg in lg("script")?yi=function(a){ug.appendChild(lg("script"))[dg]=function(){ug.removeChild(this),Dl(a)}}:yi=function(a){setTimeout(Ll(a),0)});mg.exports={set:$l,clear:Ml}});var Sg=g((SF,gg)=>{"use strict";var bg=oe(),KR=Ue(),XR=Object.getOwnPropertyDescriptor;gg.exports=function(a){if(!KR)return bg[a];var e=XR(bg,a);return e&&e.value}});var Bl=g((vF,yg)=>{"use strict";var vg=function(){this.head=null,this.tail=null};vg.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}}};yg.exports=vg});var Ig=g((yF,Tg)=>{"use strict";var JR=bi();Tg.exports=/ipad|iphone|ipod/i.test(JR)&&typeof Pebble!="undefined"});var xg=g((TF,Eg)=>{"use strict";var ZR=bi();Eg.exports=/web0s(?!.*chrome)/i.test(ZR)});var $g=g((IF,Lg)=>{"use strict";var rr=oe(),eL=Sg(),wg=Yi(),Vl=Cl().set,tL=Bl(),iL=wl(),rL=Ig(),aL=xg(),_l=yn(),Ag=rr.MutationObserver||rr.WebKitMutationObserver,Pg=rr.document,kg=rr.process,Tn=rr.Promise,Nl=eL("queueMicrotask"),ir,Ol,Fl,In,Rg;Nl||(fa=new tL,ma=function(){var a,e;for(_l&&(a=kg.domain)&&a.exit();e=fa.get();)try{e()}catch(t){throw fa.head&&ir(),t}a&&a.enter()},!iL&&!_l&&!aL&&Ag&&Pg?(Ol=!0,Fl=Pg.createTextNode(""),new Ag(ma).observe(Fl,{characterData:!0}),ir=function(){Fl.data=Ol=!Ol}):!rL&&Tn&&Tn.resolve?(In=Tn.resolve(void 0),In.constructor=Tn,Rg=wg(In.then,In),ir=function(){Rg(ma)}):_l?ir=function(){kg.nextTick(ma)}:(Vl=wg(Vl,rr),ir=function(){Vl(ma)}),Nl=function(a){fa.head||ir(),fa.add(a)});var fa,ma;Lg.exports=Nl});var Dg=g((EF,Mg)=>{"use strict";Mg.exports=function(a,e){try{arguments.length===1?console.error(a):console.error(a,e)}catch(t){}}});var En=g((xF,Cg)=>{"use strict";Cg.exports=function(a){try{return{error:!1,value:a()}}catch(e){return{error:!0,value:e}}}});var Ti=g((wF,Bg)=>{"use strict";var sL=oe();Bg.exports=sL.Promise});var ar=g((AF,Fg)=>{"use strict";var nL=oe(),ba=Ti(),oL=ue(),uL=Vu(),lL=Tl(),cL=ye(),Vg=vl(),dL=at(),Ul=Eu(),_g=ba&&ba.prototype,pL=cL("species"),ql=!1,Og=oL(nL.PromiseRejectionEvent),hL=uL("Promise",function(){var a=lL(ba),e=a!==String(ba);if(!e&&Ul===66||dL&&!(_g.catch&&_g.finally))return!0;if(!Ul||Ul<51||!/native code/.test(a)){var t=new ba(function(s){s(1)}),i=function(s){s(function(){},function(){})},r=t.constructor={};if(r[pL]=i,ql=t.then(function(){})instanceof i,!ql)return!0}return!e&&(Vg==="BROWSER"||Vg==="DENO")&&!Og});Fg.exports={CONSTRUCTOR:hL,REJECTION_EVENT:Og,SUBCLASSING:ql}});var sr=g((PF,Ug)=>{"use strict";var Ng=ft(),fL=TypeError,mL=function(a){var e,t;this.promise=new a(function(i,r){if(e!==void 0||t!==void 0)throw new fL("Bad Promise constructor");e=i,t=r}),this.resolve=Ng(e),this.reject=Ng(t)};Ug.exports.f=function(a){return new mL(a)}});var oS=g(()=>{"use strict";var bL=de(),gL=at(),Pn=yn(),Wt=oe(),SL=mi(),lr=qe(),qg=tr(),jg=hl(),vL=oa(),yL=jb(),TL=ft(),An=ue(),IL=$e(),EL=Qb(),xL=xl(),zg=Cl().set,Wl=$g(),wL=Dg(),AL=En(),PL=Bl(),Yg=el(),kn=Ti(),zl=ar(),Kg=sr(),Rn="Promise",Xg=zl.CONSTRUCTOR,kL=zl.REJECTION_EVENT,RL=zl.SUBCLASSING,jl=Yg.getterFor(Rn),LL=Yg.set,nr=kn&&kn.prototype,Ii=kn,xn=nr,Jg=Wt.TypeError,Hl=Wt.document,Yl=Wt.process,Ql=Kg.f,$L=Ql,ML=!!(Hl&&Hl.createEvent&&Wt.dispatchEvent),Zg="unhandledrejection",DL="rejectionhandled",Hg=0,eS=1,CL=2,Kl=1,tS=2,wn,Qg,iS,Gg,rS=function(a){var e;return IL(a)&&An(e=a.then)?e:!1},aS=function(a,e){var t=e.value,i=e.state===eS,r=i?a.ok:a.fail,s=a.resolve,n=a.reject,o=a.domain,u,l,c;try{r?(i||(e.rejection===tS&&VL(e),e.rejection=Kl),r===!0?u=t:(o&&o.enter(),u=r(t),o&&(o.exit(),c=!0)),u===a.promise?n(new Jg("Promise-chain cycle")):(l=rS(u))?lr(l,u,s,n):s(u)):n(t)}catch(d){o&&!c&&o.exit(),n(d)}},sS=function(a,e){a.notified||(a.notified=!0,Wl(function(){for(var t=a.reactions,i;i=t.get();)aS(i,a);a.notified=!1,e&&!a.rejection&&BL(a)}))},nS=function(a,e,t){var i,r;ML?(i=Hl.createEvent("Event"),i.promise=e,i.reason=t,i.initEvent(a,!1,!0),Wt.dispatchEvent(i)):i={promise:e,reason:t},!kL&&(r=Wt["on"+a])?r(i):a===Zg&&wL("Unhandled promise rejection",t)},BL=function(a){lr(zg,Wt,function(){var e=a.facade,t=a.value,i=Wg(a),r;if(i&&(r=AL(function(){Pn?Yl.emit("unhandledRejection",t,e):nS(Zg,e,t)}),a.rejection=Pn||Wg(a)?tS:Kl,r.error))throw r.value})},Wg=function(a){return a.rejection!==Kl&&!a.parent},VL=function(a){lr(zg,Wt,function(){var e=a.facade;Pn?Yl.emit("rejectionHandled",e):nS(DL,e,a.value)})},or=function(a,e,t){return function(i){a(e,i,t)}},ur=function(a,e,t){a.done||(a.done=!0,t&&(a=t),a.value=e,a.state=CL,sS(a,!0))},Gl=function(a,e,t){if(!a.done){a.done=!0,t&&(a=t);try{if(a.facade===e)throw new Jg("Promise can't be resolved itself");var i=rS(e);i?Wl(function(){var r={done:!1};try{lr(i,e,or(Gl,r,a),or(ur,r,a))}catch(s){ur(r,s,a)}}):(a.value=e,a.state=eS,sS(a,!1))}catch(r){ur({done:!1},r,a)}}};if(Xg&&(Ii=function(e){EL(this,xn),TL(e),lr(wn,this);var t=jl(this);try{e(or(Gl,t),or(ur,t))}catch(i){ur(t,i)}},xn=Ii.prototype,wn=function(e){LL(this,{type:Rn,done:!1,notified:!1,parent:!1,reactions:new PL,rejection:!1,state:Hg,value:null})},wn.prototype=qg(xn,"then",function(e,t){var i=jl(this),r=Ql(xL(this,Ii));return i.parent=!0,r.ok=An(e)?e:!0,r.fail=An(t)&&t,r.domain=Pn?Yl.domain:void 0,i.state===Hg?i.reactions.add(r):Wl(function(){aS(r,i)}),r.promise}),Qg=function(){var a=new wn,e=jl(a);this.promise=a,this.resolve=or(Gl,e),this.reject=or(ur,e)},Kg.f=Ql=function(a){return a===Ii||a===iS?new Qg(a):$L(a)},!gL&&An(kn)&&nr!==Object.prototype)){Gg=nr.then,RL||qg(nr,"then",function(e,t){var i=this;return new Ii(function(r,s){lr(Gg,i,r,s)}).then(e,t)},{unsafe:!0});try{delete nr.constructor}catch(a){}jg&&jg(nr,xn)}bL({global:!0,constructor:!0,wrap:!0,forced:Xg},{Promise:Ii});iS=SL.Promise;vL(Ii,Rn,!1,!0);yL(Rn)});var pS=g((LF,dS)=>{"use strict";var _L=ye(),lS=_L("iterator"),cS=!1;try{uS=0,Xl={next:function(){return{done:!!uS++}},return:function(){cS=!0}},Xl[lS]=function(){return this},Array.from(Xl,function(){throw 2})}catch(a){}var uS,Xl;dS.exports=function(a,e){try{if(!e&&!cS)return!1}catch(r){return!1}var t=!1;try{var i={};i[lS]=function(){return{next:function(){return{done:t=!0}}}},a(i)}catch(r){}return t}});var Jl=g(($F,hS)=>{"use strict";var OL=Ti(),FL=pS(),NL=ar().CONSTRUCTOR;hS.exports=NL||!FL(function(a){OL.all(a).then(void 0,function(){})})});var fS=g(()=>{"use strict";var UL=de(),qL=qe(),jL=ft(),HL=sr(),QL=En(),GL=gn(),WL=Jl();UL({target:"Promise",stat:!0,forced:WL},{all:function(e){var t=this,i=HL.f(t),r=i.resolve,s=i.reject,n=QL(function(){var o=jL(t.resolve),u=[],l=0,c=1;GL(e,function(d){var f=l++,p=!1;c++,qL(o,t,d).then(function(h){p||(p=!0,u[f]=h,--c||r(u))},s)}),--c||r(u)});return n.error&&s(n.value),i.promise}})});var bS=g(()=>{"use strict";var zL=de(),YL=at(),KL=ar().CONSTRUCTOR,ec=Ti(),XL=Pt(),JL=ue(),ZL=tr(),mS=ec&&ec.prototype;zL({target:"Promise",proto:!0,forced:KL,real:!0},{catch:function(a){return this.then(void 0,a)}});!YL&&JL(ec)&&(Zl=XL("Promise").prototype.catch,mS.catch!==Zl&&ZL(mS,"catch",Zl,{unsafe:!0}));var Zl});var gS=g(()=>{"use strict";var e$=de(),t$=qe(),i$=ft(),r$=sr(),a$=En(),s$=gn(),n$=Jl();e$({target:"Promise",stat:!0,forced:n$},{race:function(e){var t=this,i=r$.f(t),r=i.reject,s=a$(function(){var n=i$(t.resolve);s$(e,function(o){t$(n,t,o).then(i.resolve,r)})});return s.error&&r(s.value),i.promise}})});var SS=g(()=>{"use strict";var o$=de(),u$=sr(),l$=ar().CONSTRUCTOR;o$({target:"Promise",stat:!0,forced:l$},{reject:function(e){var t=u$.f(this),i=t.reject;return i(e),t.promise}})});var tc=g((NF,vS)=>{"use strict";var c$=mt(),d$=$e(),p$=sr();vS.exports=function(a,e){if(c$(a),d$(e)&&e.constructor===a)return e;var t=p$.f(a),i=t.resolve;return i(e),t.promise}});var IS=g(()=>{"use strict";var h$=de(),f$=Pt(),yS=at(),m$=Ti(),TS=ar().CONSTRUCTOR,b$=tc(),g$=f$("Promise"),S$=yS&&!TS;h$({target:"Promise",stat:!0,forced:yS||TS},{resolve:function(e){return b$(S$&&this===g$?m$:this,e)}})});var ES=g(()=>{"use strict";oS();fS();bS();gS();SS();IS()});var PS=g(()=>{"use strict";var v$=de(),y$=at(),Ln=Ti(),T$=pe(),wS=Pt(),AS=ue(),I$=xl(),xS=tc(),E$=tr(),rc=Ln&&Ln.prototype,x$=!!Ln&&T$(function(){rc.finally.call({then:function(){}},function(){})});v$({target:"Promise",proto:!0,real:!0,forced:x$},{finally:function(a){var e=I$(this,wS("Promise")),t=AS(a);return this.then(t?function(i){return xS(e,a()).then(function(){return i})}:a,t?function(i){return xS(e,a()).then(function(){throw i})}:a)}});!y$&&AS(Ln)&&(ic=wS("Promise").prototype.finally,rc.finally!==ic&&E$(rc,"finally",ic,{unsafe:!0}));var ic});var RS=g((WF,kS)=>{"use strict";Vb();ES();PS();var w$=Gt();kS.exports=w$("Promise","finally")});var $S=g((zF,LS)=>{"use strict";var A$=RS();LS.exports=A$});var $n=g((YF,MS)=>{"use strict";var P$=$S();MS.exports=P$});var XS=g(()=>{"use strict";var z$=de(),Y$=Ku().values;z$({target:"Object",stat:!0},{values:function(e){return Y$(e)}})});var ZS=g((hU,JS)=>{"use strict";XS();var K$=mi();JS.exports=K$.Object.values});var tv=g((fU,ev)=>{"use strict";var X$=ZS();ev.exports=X$});var pr=g((mU,iv)=>{"use strict";var J$=tv();iv.exports=J$});var hv=g(()=>{"use strict";var fM=de(),mM=Wi(),bM=Zi(),gM=ra(),SM=aa();fM({target:"Array",proto:!0},{at:function(e){var t=mM(this),i=bM(t),r=gM(e),s=r>=0?r:i+r;return s<0||s>=i?void 0:t[s]}});SM("at")});var mv=g((QU,fv)=>{"use strict";hv();var vM=Gt();fv.exports=vM("Array","at")});var gv=g((GU,bv)=>{"use strict";var yM=mv();bv.exports=yM});var ot=g((WU,Sv)=>{"use strict";var TM=gv();Sv.exports=TM});var kc=g((O1,Zv)=>{"use strict";var tD=hi();Zv.exports=Array.isArray||function(e){return tD(e)==="Array"}});var ty=g((F1,ey)=>{"use strict";var iD=TypeError,rD=9007199254740991;ey.exports=function(a){if(a>rD)throw iD("Maximum allowed index exceeded");return a}});var ay=g((N1,ry)=>{"use strict";var aD=kc(),sD=Zi(),nD=ty(),oD=Yi(),iy=function(a,e,t,i,r,s,n,o){for(var u=r,l=0,c=n?oD(n,o):!1,d,f;l<i;)l in t&&(d=c?c(t[l],l,e):t[l],s>0&&aD(d)?(f=sD(d),u=iy(a,e,d,f,u,s-1)-1):(nD(u+1),a[u]=d),u++),l++;return u};ry.exports=iy});var uy=g((U1,oy)=>{"use strict";var sy=kc(),uD=El(),lD=$e(),cD=ye(),dD=cD("species"),ny=Array;oy.exports=function(a){var e;return sy(a)&&(e=a.constructor,uD(e)&&(e===ny||sy(e.prototype))?e=void 0:lD(e)&&(e=e[dD],e===null&&(e=void 0))),e===void 0?ny:e}});var cy=g((q1,ly)=>{"use strict";var pD=uy();ly.exports=function(a,e){return new(pD(a))(e===0?0:e)}});var dy=g(()=>{"use strict";var hD=de(),fD=ay(),mD=ft(),bD=Wi(),gD=Zi(),SD=cy();hD({target:"Array",proto:!0},{flatMap:function(e){var t=bD(this),i=gD(t),r;return mD(e),r=SD(t,0),r.length=fD(r,t,t,i,0,1,e,arguments.length>1?arguments[1]:void 0),r}})});var py=g(()=>{"use strict";var vD=aa();vD("flatMap")});var fy=g((W1,hy)=>{"use strict";dy();py();var yD=Gt();hy.exports=yD("Array","flatMap")});var by=g((z1,my)=>{"use strict";var TD=fy();my.exports=TD});var Ma=g((Y1,gy)=>{"use strict";var ID=by();gy.exports=ID});var Da=g((K1,Sy)=>{"use strict";var ED=na(),xD=String;Sy.exports=function(a){if(ED(a)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return xD(a)}});var Rc=g((X1,vy)=>{"use strict";vy.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 Iy=g((J1,Ty)=>{"use strict";var wD=he(),AD=Qt(),PD=Da(),$c=Rc(),yy=wD("".replace),kD=RegExp("^["+$c+"]+"),RD=RegExp("(^|[^"+$c+"])["+$c+"]+$"),Lc=function(a){return function(e){var t=PD(AD(e));return a&1&&(t=yy(t,kD,"")),a&2&&(t=yy(t,RD,"$1")),t}};Ty.exports={start:Lc(1),end:Lc(2),trim:Lc(3)}});var Ay=g((Z1,wy)=>{"use strict";var LD=rl().PROPER,$D=pe(),Ey=Rc(),xy="\u200B\x85\u180E";wy.exports=function(a){return $D(function(){return!!Ey[a]()||xy[a]()!==xy||LD&&Ey[a].name!==a})}});var Mc=g((ej,Py)=>{"use strict";var MD=Iy().start,DD=Ay();Py.exports=DD("trimStart")?function(){return MD(this)}:"".trimStart});var Ry=g(()=>{"use strict";var CD=de(),ky=Mc();CD({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==ky},{trimLeft:ky})});var $y=g(()=>{"use strict";Ry();var BD=de(),Ly=Mc();BD({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==Ly},{trimStart:Ly})});var Dy=g((sj,My)=>{"use strict";$y();var VD=Gt();My.exports=VD("String","trimLeft")});var By=g((nj,Cy)=>{"use strict";var _D=Dy();Cy.exports=_D});var _y=g((oj,Vy)=>{"use strict";var OD=By();Vy.exports=OD});var Zy=g(()=>{"use strict"});var eT=g(()=>{"use strict"});var iT=g((WQ,tT)=>{"use strict";var uC=$e(),lC=hi(),cC=ye(),dC=cC("match");tT.exports=function(a){var e;return uC(a)&&((e=a[dC])!==void 0?!!e:lC(a)==="RegExp")}});var sT=g((zQ,aT)=>{"use strict";var pC=oe(),hC=pe(),rT=pC.RegExp,fC=!hC(function(){var a=!0;try{rT(".","d")}catch(u){a=!1}var e={},t="",i=a?"dgimsy":"gimsy",r=function(u,l){Object.defineProperty(e,u,{get:function(){return t+=l,!0}})},s={dotAll:"s",global:"g",ignoreCase:"i",multiline:"m",sticky:"y"};a&&(s.hasIndices="d");for(var n in s)r(n,s[n]);var o=Object.getOwnPropertyDescriptor(rT.prototype,"flags").get.call(e);return o!==i||t!==i});aT.exports={correct:fC}});var oT=g((YQ,nT)=>{"use strict";var mC=mt();nT.exports=function(){var a=mC(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 cT=g((KQ,lT)=>{"use strict";var bC=qe(),gC=st(),SC=Xr(),uT=sT(),vC=oT(),yC=RegExp.prototype;lT.exports=uT.correct?function(a){return a.flags}:function(a){return!uT.correct&&SC(yC,a)&&!gC(a,"flags")?bC(vC,a):a.flags}});var pT=g((XQ,dT)=>{"use strict";var _c=he(),TC=Wi(),IC=Math.floor,Bc=_c("".charAt),EC=_c("".replace),Vc=_c("".slice),xC=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,wC=/\$([$&'`]|\d{1,2})/g;dT.exports=function(a,e,t,i,r,s){var n=t+a.length,o=i.length,u=wC;return r!==void 0&&(r=TC(r),u=xC),EC(s,u,function(l,c){var d;switch(Bc(c,0)){case"$":return"$";case"&":return a;case"`":return Vc(e,0,t);case"'":return Vc(e,n);case"<":d=r[Vc(c,1,-1)];break;default:var f=+c;if(f===0)return l;if(f>o){var p=IC(f/10);return p===0?l:p<=o?i[p-1]===void 0?Bc(c,1):i[p-1]+Bc(c,1):l}d=i[f-1]}return d===void 0?"":d})}});var mT=g(()=>{"use strict";var AC=de(),PC=qe(),Fc=he(),hT=Qt(),kC=ue(),RC=$e(),LC=iT(),xr=Da(),$C=Zr(),MC=cT(),DC=pT(),CC=ye(),BC=at(),VC=CC("replace"),_C=TypeError,Oc=Fc("".indexOf),OC=Fc("".replace),fT=Fc("".slice),FC=Math.max;AC({target:"String",proto:!0},{replaceAll:function(e,t){var i=hT(this),r,s,n,o,u,l,c,d,f,p,h=0,m="";if(RC(e)){if(r=LC(e),r&&(s=xr(hT(MC(e))),!~Oc(s,"g")))throw new _C("`.replaceAll` does not allow non-global regexes");if(n=$C(e,VC),n)return PC(n,e,i,t);if(BC&&r)return OC(xr(i),e,t)}for(o=xr(i),u=xr(e),l=kC(t),l||(t=xr(t)),c=u.length,d=FC(1,c),f=Oc(o,u);f!==-1;)p=l?xr(t(u,f,o)):DC(u,o,f,[],void 0,t),m+=fT(o,h,f)+p,h=f+c,f=f+d>o.length?-1:Oc(o,u,f+d);return h<o.length&&(m+=fT(o,h)),m}})});var gT=g((eG,bT)=>{"use strict";Zy();eT();mT();var NC=Gt();bT.exports=NC("String","replaceAll")});var vT=g((tG,ST)=>{"use strict";var UC=gT();ST.exports=UC});var TT=g((iG,yT)=>{"use strict";var qC=vT();yT.exports=qC});var ET=g((rG,IT)=>{"use strict";var jC=ra(),HC=Da(),QC=Qt(),GC=RangeError;IT.exports=function(e){var t=HC(QC(this)),i="",r=jC(e);if(r<0||r===1/0)throw new GC("Wrong number of repetitions");for(;r>0;(r>>>=1)&&(t+=t))r&1&&(i+=t);return i}});var kT=g((aG,PT)=>{"use strict";var AT=he(),WC=qu(),xT=Da(),zC=ET(),YC=Qt(),KC=AT(zC),XC=AT("".slice),JC=Math.ceil,wT=function(a){return function(e,t,i){var r=xT(YC(e)),s=WC(t),n=r.length,o=i===void 0?" ":xT(i),u,l;return s<=n||o===""?r:(u=s-n,l=KC(o,JC(u/o.length)),l.length>u&&(l=XC(l,0,u)),a?r+l:l+r)}};PT.exports={start:wT(!1),end:wT(!0)}});var LT=g((sG,RT)=>{"use strict";var ZC=bi();RT.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(ZC)});var $T=g(()=>{"use strict";var eB=de(),tB=kT().start,iB=LT();eB({target:"String",proto:!0,forced:iB},{padStart:function(e){return tB(this,e,arguments.length>1?arguments[1]:void 0)}})});var DT=g((uG,MT)=>{"use strict";$T();var rB=Gt();MT.exports=rB("String","padStart")});var BT=g((lG,CT)=>{"use strict";var aB=DT();CT.exports=aB});var _T=g((cG,VT)=>{"use strict";var sB=BT();VT.exports=sB});var Fp="2.0.136-dev.b7a1035a.0";var Le=(r=>(r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused",r))(Le||{}),At=(v=>(v.MPEG="MPEG",v.DASH="DASH",v.DASH_SEP="DASH_SEP",v.DASH_SEP_VK="DASH_SEP",v.DASH_WEBM="DASH_WEBM",v.DASH_WEBM_AV1="DASH_WEBM_AV1",v.DASH_STREAMS="DASH_STREAMS",v.DASH_WEBM_VK="DASH_WEBM",v.DASH_ONDEMAND="DASH_ONDEMAND",v.DASH_ONDEMAND_VK="DASH_ONDEMAND",v.DASH_LIVE="DASH_LIVE",v.DASH_LIVE_CMAF="DASH_LIVE_CMAF",v.DASH_LIVE_WEBM="DASH_LIVE_WEBM",v.HLS="HLS",v.HLS_ONDEMAND="HLS_ONDEMAND",v.HLS_JS="HLS",v.HLS_LIVE="HLS_LIVE",v.HLS_LIVE_CMAF="HLS_LIVE_CMAF",v.WEB_RTC_LIVE="WEB_RTC_LIVE",v))(At||{});var Ys=(r=>(r.NOT_AVAILABLE="NOT_AVAILABLE",r.AVAILABLE="AVAILABLE",r.CONNECTING="CONNECTING",r.CONNECTED="CONNECTED",r))(Ys||{}),du=(i=>(i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic",i))(du||{});var pu=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(pu||{}),Ks=(i=>(i.TRAFFIC_SAVING="traffic_saving",i.HIGH_QUALITY="high_quality",i.UNKNOWN="unknown",i))(Ks||{});var DE=O(Ye(),1);import{assertNever as Of,assertNonNullable as fA,isNonNullable as tn,ValueSubject as Hu,Subject as mA,Subscription as bA,merge as gA,observableFrom as SA,fromEvent as Cf,map as Bf,tap as Vf,filterChanged as vA,isNullable as Qu,ErrorCategory as _f}from"@vkontakte/videoplayer-shared/es2018";var Df=a=>new Promise((e,t)=>{let i=document.createElement("script");i.setAttribute("src",a),i.onload=()=>e(),i.onerror=r=>t(r),document.body.appendChild(i)});var rn=class{constructor(e){this.connection$=new Hu(void 0);this.castState$=new Hu("NOT_AVAILABLE");this.errorEvent$=new mA;this.realCastState$=new Hu("NOT_AVAILABLE");this.subscription=new bA;this.isDestroyed=!1;var s;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");let t="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${t}`}),e.isDisabled||!t)return;let i=tn((s=window.chrome)==null?void 0:s.cast),r=!!window.__onGCastApiAvailable;i?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&!this.isDestroyed&&this.initializeCastApi()},r||Df("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:_f.NETWORK,message:"Script loading failed!"})))}connect(){var e;(e=cast.framework.CastContext.getInstance())==null||e.requestSession()}disconnect(){var e,t;(t=(e=cast.framework.CastContext.getInstance())==null?void 0:e.getCurrentSession())==null||t.endSession(!0)}stopMedia(){return new Promise((e,t)=>{var i,r,s;(s=(r=(i=cast.framework.CastContext.getInstance())==null?void 0:i.getCurrentSession())==null?void 0:r.getMediaSession())==null||s.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){tn(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();Qu(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();Qu(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(Cf(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 Of(r.sessionState)}})).add(gA(Cf(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(Vf(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),Bf(r=>r.castState)),SA([i.getCastState()])).pipe(vA(),Bf(yA),Vf(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{var o,u;let s=r==="CONNECTED",n=tn(this.connection$.getValue());if(s&&!n){let l=i.getCurrentSession();fA(l);let c=l.getCastDevice(),d=(u=(o=l.getMediaSession())==null?void 0:o.media)==null?void 0:u.contentId;(Qu(d)||d===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:l,castDevice:c}))}else!s&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(r==="CONNECTED"?tn(this.connection$.getValue())?"CONNECTED":"AVAILABLE":r)}))}initializeCastApi(){var r;let e,t,i;try{e=cast.framework.CastContext.getInstance(),t=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,i=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(s){return}try{e.setOptions({receiverApplicationId:(r=this.params.receiverApplicationId)!=null?r:t,autoJoinPolicy:i}),this.initListeners()}catch(s){this.errorEvent$.next({id:"ChromecastInitializer",category:_f.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:s})}}},yA=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 Of(a)}};var Gd=O(Ye(),1),fE=O(er(),1),mE=O(Sl(),1);var zS=O($n(),1);import{assertNever as DS}from"@vkontakte/videoplayer-shared/es2018";var le=(a,e=0,t=0)=>{switch(t){case 0:return a.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case 1:{if(e===0)return a;let i=new URL(a);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}case 2:{let i=new URL(a);return!i.searchParams.get("offset_p")&&e===0?a:(i.searchParams.set("offset_p",e.toFixed(0)),i.toString())}default:DS(t)}return a},zt=(a,e)=>{var t;switch(e){case 0:return NaN;case 1:{let i=new URL(a);return Number(i.searchParams.get("playback_shift"))}case 2:{let i=new URL(a);return Number((t=i.searchParams.get("offset_p"))!=null?t:0)}default:DS(e)}};var $=(a,e,t=!1)=>{let i=a.getTransition();(t||!i||i.to===e)&&a.setState(e)};import{isNonNullable as k$,Subject as Mn,merge as CS}from"@vkontakte/videoplayer-shared/es2018";var q=class{constructor(e){this.transitionStarted$=new Mn;this.transitionEnded$=new Mn;this.transitionUpdated$=new Mn;this.forceChanged$=new Mn;this.stateChangeStarted$=CS(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=CS(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||k$(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 US}from"@vkontakte/videoplayer-shared/es2018";var Dn=class{constructor(){this._isMiuiBrowser=!1}get current(){return this._current}get isChrome(){return this.current==="Chrome"}get isFirefox(){return this.current==="Firefox"}get isSafari(){return this.current==="Safari"}get isOpera(){return this.current==="Opera"}get isEdge(){return this.current==="Edge"}get isYandex(){return this.current==="Yandex"}get isSamsungBrowser(){return this.current==="SamsungBrowser"}get currentVersion(){return this._current_version}get chromeVersion(){return this._chromeVersion}get firefoxVersion(){return this._firefoxVersion}get safariVersion(){return this._safariVersion}get operaVersion(){return this._operaVersion}get edgeVersion(){return this._edgeVersion}get yandexVersion(){return this._yandexVersion}get isMiuiBrowser(){return this._isMiuiBrowser}detect(){let{userAgent:e}=navigator;try{let t=/yabrowser/i.test(e)?"Yandex":void 0,i=/samsungbrowser/i.test(e)?"SamsungBrowser":void 0,r=/chrome|crios/i.test(e)?"Chrome":void 0,s=/chromium/i.test(e)?"Chromium":void 0,n=/firefox|fxios/i.test(e)?"Firefox":void 0,o=/webkit|safari|khtml/i.test(e)?"Safari":void 0,u=/opr\//i.test(e)?"Opera":void 0,l=/edg/i.test(e)?"Edge":void 0;this._isMiuiBrowser=/(XiaoMi)|(MiuiBrowser)/i.test(e),this._current=t||i||n||u||l||r||s||o||"Rest"}catch(t){console.error(t)}this.isChrome&&this.detectChromeVersion(),this.isFirefox&&this.detectFirefoxVersion(),this.isSafari&&this.detectSafariVersion(),this.isOpera&&this.detectOperaVersion(),this.isEdge&&this.detectEdgeVersion(),this.isYandex&&this.detectYandexVersion()}detectVersion(e){try{let{userAgent:t}=window.navigator,i=t.match(e);if(!i)return;let r=i[1],s=parseInt(r,10);if(!isNaN(s))return this._current_version=s,s}catch(t){console.error(t)}}detectChromeVersion(){this._chromeVersion=this.detectVersion(/Chrome\/(\d+\.\d+)/)}detectFirefoxVersion(){this._firefoxVersion=this.detectVersion(/Firefox\/(\d+\.\d+)/)}detectSafariVersion(){this._safariVersion=this.detectVersion(/Version\/(\d+)/)}detectOperaVersion(){this._operaVersion=this.detectVersion(/OPR\/(\d+\.\d+)/)}detectEdgeVersion(){this._edgeVersion=this.detectVersion(/Edg\/(\d+\.\d+)/)}detectYandexVersion(){this._yandexVersion=this.detectVersion(/YaBrowser\/(\d+\.\d+\.\d+)/)}};var BS=O(Ye(),1);var ga=()=>{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 Cn=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,BS.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=ga()}catch(t){console.error(t)}this.detectDevice(e),this.detectHighEntropyValues(),this.isIOS&&this.detectIOSVersion()}async detectHighEntropyValues(){let{userAgentData:e}=navigator;if(e!=null&&e.getHighEntropyValues){let t=await e.getHighEntropyValues(["architecture","bitness","brands","mobile","platform","formFactor","model","platformVersion","wow64"]);this._highEntropyValues=t}}detectDevice(e){try{let t=/android/i.test(e)?"Android":void 0,i=/iphone/i.test(e)?"iPhone":void 0,r=/ipad/i.test(e)?"iPad":void 0,s=/ipod/i.test(e)?"iPod":void 0,n=/mac/i.test(e)?"Mac":void 0,o=/webOS|BlackBerry|IEMobile|Opera Mini/i.test(e)?"RestMobile":void 0;this._current=t||i||r||s||o||n||"Desktop"}catch(t){console.error(t)}}detectIOSVersion(){try{if(this._highEntropyValues.platformVersion){let s=this._highEntropyValues.platformVersion.split(".").slice(0,2).join("."),n=parseFloat(s);this._iosVersion=n;return}let{userAgent:e}=window.navigator,t=e.match(/OS (\d+(_\d+)?)/i);if(!t)return;let i=t[1].replace(/_/g,".");if(!i)return;let r=parseFloat(i);if(isNaN(r))return;this._iosVersion=r}catch(e){console.error(e)}}};var Bn=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 He=()=>window.ManagedMediaSource||window.MediaSource,cr=()=>{var a,e;return!!(window.ManagedMediaSource&&((e=(a=window.ManagedSourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},VS=()=>{var a,e;return!!(window.MediaSource&&((e=(a=window.SourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},Vn=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var R$=document.createElement("video"),L$='video/mp4; codecs="avc1.42000a,mp4a.40.2"',$$='video/mp4; codecs="hev1.1.6.L93.B0"',_S='video/webm; codecs="vp09.00.10.08"',OS='video/webm; codecs="av01.0.00M.08"',M$='audio/mp4; codecs="mp4a.40.2"',D$='audio/webm; codecs="opus"',FS,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:OS}}),window.navigator.mediaCapabilities.decodingInfo({...a,video:{...a.video,contentType:_S}})]);FS={DASH_WEBM_AV1:e,DASH_WEBM:t}};C$().catch(a=>{console.log(R$),console.error(a)});var _n=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 FS}get supportedCodecs(){return Object.keys(this._codecs).filter(e=>this._codecs[e])}get nativeHlsSupported(){return this._nativeHlsSupported}detect(){var e,t,i,r,s,n,o,u,l,c,d,f,p,h,m,b,S,y,v,I;this._video=document.createElement("video");try{this._protocols={mms:cr(),mse:VS(),hls:!!((t=(e=this._video).canPlayType)!=null&&t.call(e,"application/x-mpegurl")||(r=(i=this._video).canPlayType)!=null&&r.call(i,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},this._containers={mp4:!!((n=(s=this._video).canPlayType)!=null&&n.call(s,"video/mp4")),webm:!!((u=(o=this._video).canPlayType)!=null&&u.call(o,"video/webm")),cmaf:!0};let E=!!((c=(l=He())==null?void 0:l.isTypeSupported)!=null&&c.call(l,L$)),A=!!((f=(d=He())==null?void 0:d.isTypeSupported)!=null&&f.call(d,$$)),M=!!((h=(p=He())==null?void 0:p.isTypeSupported)!=null&&h.call(p,M$));this._codecs={h264:E,h265:A,vp9:!!((b=(m=He())==null?void 0:m.isTypeSupported)!=null&&b.call(m,_S)),av1:!!((y=(S=He())==null?void 0:S.isTypeSupported)!=null&&y.call(S,OS)),aac:M,opus:!!((I=(v=He())==null?void 0:v.isTypeSupported)!=null&&I.call(v,D$)),mpeg:(E||A)&&M},this._nativeHlsSupported=this._protocols.hls&&this._containers.mp4}catch(E){console.error(E)}try{this.destroyVideoElement()}catch(E){console.error("Error destroying video element:",E)}}destroyVideoElement(){var t;if(!this._video)return;if(this._video.pause(),this._video.currentTime=0,this._video.removeAttribute("src"),this._video.src="",this._video.load(),this._video.remove){this._video.remove(),this._video=null;return}this._video.parentNode&&this._video.parentNode.removeChild(this._video);let e=this._video.cloneNode(!1);(t=this._video.parentNode)==null||t.replaceChild(e,this._video),this._video=null}};var NS="audio/mpeg",On=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,NS))},this._codecs={mp3:!!((r=(i=He())==null?void 0:i.isTypeSupported)!=null&&r.call(i,NS))}}catch(s){console.error(s)}try{this.destroyAudioElement()}catch(s){console.error("Error destroying audio element:",s)}}destroyAudioElement(){var t;if(!this._audio)return;if(this._audio.pause(),this._audio.currentTime=0,this._audio.removeAttribute("src"),this._audio.src="",this._audio.load(),this._audio.remove){this._audio.remove(),this._audio=null;return}this._audio.parentNode&&this._audio.parentNode.removeChild(this._audio);let e=this._audio.cloneNode(!1);(t=this._audio.parentNode)==null||t.replaceChild(e,this._audio),this._audio=null}};import{ValueSubject as B$}from"@vkontakte/videoplayer-shared/es2018";var ac=class{constructor(){this.isInited$=new B$(!1);this._displayChecker=new Bn,this._deviceChecker=new Cn(this._displayChecker),this._browserChecker=new Dn,this._videoChecker=new _n(this._deviceChecker,this._browserChecker),this._audioChecker=new On,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)}},F=new ac;var sc=(a,{useManagedMediaSource:e,useOldMSEDetection:t})=>{let{containers:i,protocols:r,codecs:s,nativeHlsSupported:n}=F.video,o=(s.h264||s.h265)&&s.aac,u=r.mse&&(!t||!!window.MediaStreamTrack)||r.mms&&e;return a.filter(l=>{switch(l){case"DASH_SEP":return u&&i.mp4&&o;case"DASH_WEBM":return u&&i.webm&&s.vp9&&s.opus;case"DASH_WEBM_AV1":return u&&i.webm&&s.av1&&s.opus;case"DASH_STREAMS":return u&&(i.mp4&&o||i.webm&&(s.vp9||s.av1)&&(s.opus||s.aac));case"DASH_LIVE":return u&&i.mp4&&o;case"DASH_LIVE_CMAF":return u&&i.mp4&&o&&i.cmaf;case"DASH_ONDEMAND":return u&&i.mp4&&o;case"HLS":case"HLS_ONDEMAND":case"HLS_LIVE":case"HLS_LIVE_CMAF":return n;case"MPEG":return i.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return r.webrtc&&r.ws&&s.h264&&(i.mp4||i.webm);default:return US(l)}})},nc=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 US(a)}},V$=(a,e)=>{let i=Object.keys(a).filter(r=>!nc(r));return sc(i,e).length>0};import{assertNever as dr,assertNonNullable as Ei,debounce as qS,ErrorCategory as jS,fromEvent as xi,isNonNullable as HS,map as QS,merge as GS,observableFrom as _$,Subject as O$,Subscription as oc,timeout as F$,getHighestQuality as N$}from"@vkontakte/videoplayer-shared/es2018";var U$=5,q$=5,j$=500,WS=7e3,Sa=class{constructor(e){this.subscription=new oc;this.loadMediaTimeoutSubscription=new oc;this.videoState=new q("stopped");this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(s)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.stop());return}if(!t){if((r==null?void 0:r.to)!=="paused"&&s.state==="requested"&&e!=="stopped"){this.seek(s.position/1e3);return}switch(i){case"ready":{switch(e){case"playing":case"paused":case"ready":break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:dr(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:dr(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:dr(e)}break}default:dr(i)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(nc(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 oc;this.subscription.add(e),this.subscription.add(GS(this.videoState.stateChangeStarted$.pipe(QS(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe(QS(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 O$;e.add(r.pipe(qS(j$)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add(xi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(n=>{this.logRemoteEvent(n);let o=n.value;this.params.output.position$.next(o),(this.params.desiredState.seekState.getState().state==="applying"||Math.abs(o-s)>U$)&&r.next(o),s=o})),e.add(xi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(xi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(xi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t(xi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),r=>{this.logRemoteEvent(r);let{remotePlayer:s}=this.params.connection,n=r.value,o=this.params.output.isBuffering$.getValue(),u=n===chrome.cast.media.PlayerState.BUFFERING;switch(o!==u&&this.params.output.isBuffering$.next(u),n){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&s.duration-s.currentTime<q$&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),$(this.params.desiredState.playbackState,"stopped");break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:dr(n)}}),t(xi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t(xi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});let i=GS(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,_$(["init"])).pipe(qS(0));t(i,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});let{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState("paused"),$(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),$(this.params.desiredState.playbackState,"playing"));let i=this.params.output.isLive$.getValue();this.params.output.duration$.next(i?0:t.duration),this.params.output.position$.next(i?0:t.currentTime),this.params.desiredState.seekState.setState({state:"none"})}}prepare(){let e=this.params.format;this.log({message:`[prepare] format: ${e}`});let t=this.createMediaInfo(e),i=this.createLoadRequest(t);this.loadMedia(i)}handleRemotePause(){let e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="paused"||e==="playing")&&(this.videoState.setState("paused"),$(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="playing"||e==="paused")&&(this.videoState.setState("playing"),$(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){var t;let e=this.videoState.getTransition();(e==null?void 0:e.to)==="ready"&&this.videoState.setState("ready"),((t=this.params.desiredState.playbackState.getTransition())==null?void 0:t.to)==="ready"&&$(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){var r,s;let t=this.params.output.volume$.getValue(),i={volume:(r=e.volume)!=null?r:t.volume,muted:(s=e.muted)!=null?s:t.muted};(i.volume!==t.volume||i.muted!==i.muted)&&this.params.output.volume$.next(i)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:i}=this.params.connection;t.currentTime=e,i.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){var l;let t=this.params.source,i,r,s;switch(e){case"MPEG":{let c=t[e];Ei(c);let d=N$(Object.keys(c));Ei(d);let f=c[d];Ei(f),i=f,r="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let c=t[e];Ei(c),i=c.url,r="application/x-mpegurl",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":{let c=t[e];Ei(c),i=c.url,r="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let c=t[e];Ei(c),i=c.url,r="application/dash+xml",s=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let c=t[e];Ei(c),i=le(c.url),r="application/x-mpegurl",s=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let c="Unsupported format for Chromecast",d=new Error(c);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:jS.VIDEO_PIPELINE,message:c,thrown:d}),d}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return dr(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 HS(o)&&(n.metadata.title=o),HS(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(F$(WS).subscribe(()=>s(`timeout(${WS})`)))});(0,zS.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:jS.VIDEO_PIPELINE,message:s,thrown:r})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var Ac=O(Ye(),1);import{clearVideoElement as KS}from"@vkontakte/videoplayer-shared/es2018";import{clearVideoElement as H$}from"@vkontakte/videoplayer-shared/es2018";var YS=a=>{try{a.pause(),a.playbackRate=0,H$(a),a.remove()}catch(e){console.error(e)}};import{fromEvent as Q$,Subscription as G$}from"@vkontakte/videoplayer-shared/es2018";var uc=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)}},lc=window.WeakMap?new WeakMap:new uc,cc=window.WeakMap?new WeakMap:new Map,W$=(a,e=20)=>{let t=0;return Q$(a,"ratechange").subscribe(i=>{t++,t>=e&&(a.currentTime=a.currentTime,t=0)})},Me=(a,{audioVideoSyncRate:e,disableYandexPiP:t})=>{let i=a.querySelector("video"),r=!!i;i?KS(i):(i=document.createElement("video"),a.appendChild(i)),lc.set(i,r);let s=new G$;return s.add(W$(i,e)),cc.set(i,s),i.setAttribute("crossorigin","anonymous"),i.setAttribute("playsinline","playsinline"),t&&i.setAttribute("x-yandex-pip","false"),i.controls=!1,i.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),i},De=a=>{let e=cc.get(a);e==null||e.unsubscribe(),cc.delete(a);let t=lc.get(a);lc.delete(a),t?KS(a):YS(a)};var pc=O(pr(),1);import{assertNonNullable as ya,isNonNullable as gt,isNullable as tM,fromEvent as hr,merge as rv,observableFrom as av,filterChanged as sv,map as Ta,Subject as nv,Subscription as iM,ValueSubject as rM,ErrorCategory as aM}from"@vkontakte/videoplayer-shared/es2018";import{isNonNullable as dc,isNullable as Z$,Subscription as eM}from"@vkontakte/videoplayer-shared/es2018";var Fn=(a,e,t,{equal:i=(n,o)=>n===o,changed$:r,onError:s}={})=>{let n=a.getState(),o=e(),u=Z$(r),l=new eM;return r&&l.add(r.subscribe(c=>{let d=a.getState();i(c,d)&&a.setState(c)},s)),i(o,n)||(t(n),u&&a.setState(n)),l.add(a.stateChangeStarted$.subscribe(c=>{t(c.to),u&&a.setState(c.to)},s)),l},bt=(a,e,t)=>Fn(e,()=>a.loop,i=>{dc(i)&&(a.loop=i)},{onError:t}),Ce=(a,e,t,i)=>Fn(e,()=>({muted:a.muted,volume:a.volume}),r=>{dc(r)&&(a.muted=r.muted,a.volume=r.volume)},{equal:(r,s)=>r===s||(r==null?void 0:r.muted)===(s==null?void 0:s.muted)&&(r==null?void 0:r.volume)===(s==null?void 0:s.volume),changed$:t,onError:i}),Ke=(a,e,t,i)=>Fn(e,()=>a.playbackRate,r=>{dc(r)&&(a.playbackRate=r)},{changed$:t,onError:i}),va=Fn;var sM=a=>["__",a.language,a.label].join("|"),nM=(a,e)=>{if(a.id===e)return!0;let[t,i,r]=e.split("|");return a.language===i&&a.label===r},hc=class a{constructor(e){this.available$=new nv;this.current$=new rM(void 0);this.error$=new nv;this.subscription=new iM;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:aM.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(va(t.internalTextTracks,()=>(0,pc.default)(this.internalTracks),s=>{gt(s)&&this.setInternal(s)},{equal:(s,n)=>gt(s)&>(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(Ta(s=>s.filter(({type:n})=>n==="internal"))),onError:r})),this.subscription.add(va(t.externalTextTracks,()=>(0,pc.default)(this.externalTracks),s=>{gt(s)&&this.setExternal(s)},{equal:(s,n)=>gt(s)&>(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(Ta(s=>s.filter(({type:n})=>n==="external"))),onError:r})),this.subscription.add(va(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(va(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){ya(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(rv(hr(e,"addtrack"),hr(e,"removetrack"),av(["init"])).pipe(Ta(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),sv((i,r)=>i.length===r.length&&i.every(({id:s},n)=>s===r[n].id))).subscribe(this.available$)),this.subscription.add(rv(hr(e,"change"),av(["init"])).pipe(Ta(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),Ta(i=>i&&this.htmlTextTrackToITextTrack(i).id),sv()).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(hr(e,"addtrack").subscribe(i=>{var s,n;(s=i.track)==null||s.addEventListener("cuechange",t);let r=o=>{var l,c,d,f,p;let u=(c=(l=o.target)==null?void 0:l.cues)!=null?c:null;u&&u.length&&(this.applyCueSettings((f=(d=o.target)==null?void 0:d.cues)!=null?f:null),(p=o.target)==null||p.removeEventListener("cuechange",r))};(n=i.track)==null||n.addEventListener("cuechange",r)})),this.subscription.add(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;gt(t.align)&&(r.align=t.align),gt(t.position)&&(r.position=t.position),gt(t.size)&&(r.size=t.size),gt(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){ya(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:sM(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){ya(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(tM(e)||!nM(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){ya(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){ya(this.video);let t=Array.prototype.find.call(this.video.getElementsByTagName("track"),i=>i.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}},Xe=hc;var wi=class{constructor(){this.pausedTime=0;this.streamOffset=0;this.pauseTimestamp=0}getTotalPausedTime(){return this.pausedTime+this.getCurrentPausedTime()}getCurrentPausedTime(){return this.pauseTimestamp>0?Date.now()-this.pauseTimestamp:0}getStreamOffset(){return this.streamOffset}getTotalOffset(){return this.getTotalPausedTime()+this.streamOffset}pause(){this.pauseTimestamp===0&&(this.pauseTimestamp=Date.now())}resume(){this.pauseTimestamp>0&&(this.pausedTime+=this.getCurrentPausedTime(),this.pauseTimestamp=0)}resetTo(e,t=!1){this.streamOffset=e,this.pauseTimestamp=0,this.pausedTime=0,t&&this.pause()}};var ov=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},fc=a=>{let e=ov(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},uv=a=>{let e=ov(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)};import{fromEvent as Ae,map as St,merge as Nn,filterChanged as cv,isNonNullable as dv,Subject as uM,filter as mc,mapTo as bc,combine as lM,once as cM,shareReplay as Pe,throttle as dM,ErrorCategory as pM,ValueSubject as pv,Subscription as hM}from"@vkontakte/videoplayer-shared/es2018";var oM=3,lv=(a,e,t=oM)=>{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 Be=a=>{let e=k=>Ae(a,k).pipe(bc(void 0),Pe(1)),t=new hM,i=()=>t.unsubscribe(),r=Nn(Ae(a,"progress"),Ae(a,"timeupdate")).pipe(St(()=>lv(a.buffered,a.currentTime)),Pe(1)),s=F.browser.isSafari?lM({play:e("play").pipe(cM()),playing:e("playing")}).pipe(bc(void 0),Pe(1)):e("playing"),n=Ae(a,"volumechange").pipe(St(()=>({muted:a.muted,volume:a.volume})),Pe(1)),o=Ae(a,"ratechange").pipe(St(()=>a.playbackRate),Pe(1)),u=Ae(a,"error").pipe(mc(()=>!!(a.error||a.played.length)),St(()=>{var V;let k=a.error;return{id:k?`MediaError#${k.code}`:"HtmlVideoError",category:pM.VIDEO_PIPELINE,message:k?k.message:"Error event from HTML video element",thrown:(V=a.error)!=null?V:void 0}}),Pe(1)),l=Ae(a,"timeupdate").pipe(St(()=>a.currentTime),Pe(1)),c=["waiting","seeking","seeked","timeupdate"],d=new uM,f=.3,p;t.add(Nn(...c.map(k=>Ae(a,k))).subscribe(k=>{let V=a.currentTime;a.loop&&dv(p)&&dv(V)&&p>=a.duration-f&&V<=f&&d.next(p),p=V}));let h=e("pause").pipe(mc(()=>!a.error&&p!==a.duration),Pe(1)),m=Ae(a,"enterpictureinpicture").pipe(Pe(1)),b=Ae(a,"leavepictureinpicture").pipe(Pe(1)),S=new pv(uv(a));t.add(m.subscribe(()=>S.next(!0))),t.add(b.subscribe(()=>S.next(!1)));let y=new pv(fc(a)),v=Ae(a,"fullscreenchange").pipe(Pe(1));t.add(v.pipe(St(()=>fc(a))).subscribe(y));let I=.1,E=1e3,A=Ae(a,"timeupdate").pipe(St(k=>a.duration-a.currentTime<I),cv(),Pe(1)),M=Nn(A.pipe(mc(k=>!a.loop&&k)),Ae(a,"ended")).pipe(dM(E),bc(void 0),Pe(1)),P=Nn(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(k=>Ae(a,k)),A.pipe(St(k=>({type:k?"ended":"unknown"})))).pipe(St(k=>F.browser.isFirefox&&k.type==="ended"?a.readyState<2:a.readyState<3),cv(),Pe(1));return{playing$:s,pause$:h,canplay$:e("canplay"),ended$:M,looped$:d,error$:u,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:l,durationChange$:Ae(a,"durationchange").pipe(St(()=>a.duration),Pe(1)),isBuffering$:P,currentBuffer$:r,volumeState$:n,playbackRateState$:o,inPiP$:S,inFullscreen$:y,enterPip$:m,leavePip$:b,destroy:i}};import{VideoQuality as Yt}from"@vkontakte/videoplayer-shared/es2018";var Kt=a=>{switch(a){case"mobile":return Yt.Q_144P;case"lowest":return Yt.Q_240P;case"low":return Yt.Q_360P;case"sd":case"medium":return Yt.Q_480P;case"hd":case"high":return Yt.Q_720P;case"fullhd":case"full":return Yt.Q_1080P;case"quadhd":case"quad":return Yt.Q_1440P;case"ultrahd":case"ultra":return Yt.Q_2160P}};var Re=O(ot(),1),vc=O(Ye(),1),Ai=O(er(),1);import{isNonNullable as X,isNullable as Qn,now as kv,isHigher as Gn,isHigherOrEqual as mr,isInvariantQuality as Wn,isLowerOrEqual as br,videoSizeToQuality as Rv,assertNotEmptyArray as zn,assertNonNullable as Lv}from"@vkontakte/videoplayer-shared/es2018";var gc=!1,Lt={},vv=a=>{gc=a},yv=()=>{Lt={}},Tv=a=>{a(Lt)},Ia=(a,e)=>{var t;gc&&(Lt.meta=(t=Lt.meta)!=null?t:{},Lt.meta[a]=e)},ke=class{constructor(e){this.name=e}next(e){var i,r;if(!gc)return;Lt.series=(i=Lt.series)!=null?i:{};let t=(r=Lt.series[this.name])!=null?r:[];t.push([Date.now(),e]),Lt.series[this.name]=t}};import{isHigher as IM,isHigherOrEqual as ZU,isLower as Iv,isLowerOrEqual as eq,isNonNullable as Un,isNullable as EM,videoHeightToQuality as qn}from"@vkontakte/videoplayer-shared/es2018";function Sc(a,e,t){return!a.max&&a.min===e?"high_quality":!a.min&&a.max===t?"traffic_saving":"unknown"}function jn(a,e,t){return!!a&&Sc(a,e,t)==="high_quality"}function fr(a,e,t){return EM(a)||Un(a.min)&&Un(a.max)&&Iv(a.max,a.min)||Un(a.min)&&e&&IM(a.min,e)||Un(a.max)&&t&&Iv(a.max,t)}function Ev({limits:a,highestAvailableHeight:e,lowestAvailableHeight:t}){return fr({max:a!=null&&a.max?qn(a.max):void 0,min:a!=null&&a.min?qn(a.min):void 0},e?qn(e):void 0,t?qn(t):void 0)}var $v=new ke("best_bitrate"),Yn=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t;var gr=a=>(e,t)=>a*(Number(e.bitrate)-Number(t.bitrate)),Xt=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=kv()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},Kn='Assertion "ABR Tracks is empty array" failed',Hn=new WeakMap,xv=new WeakMap,wv=new WeakMap,Ea=(a,e,t,i)=>{var u;let r=[...e].sort(gr(1)),s=[...t].sort(gr(1)),n=s.filter(l=>X(l.bitrate)&&X(a.bitrate)?a.bitrate/l.bitrate>i:!0),o=(u=(0,Re.default)(s,Math.round(s.length*r.indexOf(a)/(r.length+1))))!=null?u:(0,Re.default)(s,-1);return o&&(0,vc.default)(n,o)?o:n.length?(0,Re.default)(n,-1):(0,Re.default)(s,0)},xa=(a,e,t,i)=>{var u;let r=Hn.get(e);r||(r=[...e].sort(gr(1)),Hn.set(e,r));let s=Hn.get(t);s||(s=[...t].sort(gr(1)),Hn.set(t,s));let n=wv.get(a);n||(n=s.filter(l=>X(l.bitrate)&&X(a.bitrate)?a.bitrate/l.bitrate>i:!0),wv.set(a,n));let o=(u=(0,Re.default)(s,Math.round(s.length*r.indexOf(a)/(r.length+1))))!=null?u:(0,Re.default)(s,-1);return o&&(0,vc.default)(n,o)?o:n.length?(0,Re.default)(n,-1):(0,Re.default)(s,0)},Av=a=>"quality"in a,Xn=(a,e,t,i)=>{var n;let r=X((n=i==null?void 0:i.last)==null?void 0:n.bitrate)&&X(t==null?void 0:t.bitrate)&&i.last.bitrate<t.bitrate?a.trackCooldownIncreaseQuality:a.trackCooldownDecreaseQuality,s=t&&i&&i.history[t.id]&&kv()-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=Av(o)?"video":"audio",l=Av(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},xM=(a,e)=>Math.log(e)/Math.log(a),Mv=({tuning:a,container:e,limits:t,panelSize:i})=>{let r=a.containerSizeFactor;if(i)return{containerSizeLimit:i,containerSizeFactor:r};if(a.usePixelRatio&&F.display.pixelRatio){let s=F.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=xM(n,o*s+u)+l;Number.isFinite(c)&&(r*=c)}}return jn(t,a.highQualityLimit,a.trafficSavingLimit)&&(r*=2),{containerSizeLimit:a.limitByContainer&&e&&e.width>0&&e.height>0?{width:e.width*r,height:e.height*r}:void 0,containerSizeFactor:r}},Pv=new WeakMap,vt=(a,{container:e,estimatedThroughput:t,tuning:i,limits:r,reserve:s=0,forwardBufferHealth:n,playbackRate:o,current:u,history:l,visible:c,droppedVideoMaxQualityLimit:d,stallsVideoMaxQualityLimit:f,stallsPredictedThroughput:p,abrLogger:h,panelSize:m})=>{var _,Y,J,T,R;zn(a,Kn);let{containerSizeFactor:b,containerSizeLimit:S}=Mv({container:e,tuning:i,limits:r,panelSize:m}),y=i.considerPlaybackRate&&X(o)?o:1,v=Pv.get(a);v||(v=a.filter(x=>!Wn(x.quality)).sort((x,w)=>Gn(x.quality,w.quality)?-1:1),Pv.set(a,v));let I=(_=(0,Re.default)(v,-1))==null?void 0:_.quality,E=(Y=(0,Re.default)(v,0))==null?void 0:Y.quality,A=fr(r,E,I),M=y*Yn(n!=null?n:.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),L={},P=null;for(let x of v){let w=!0;if(S)if(x.size)w=x.size.width<=S.width&&x.size.height<=S.height;else{let Ne=S&&Rv(S);w=Ne?br(x.quality,Ne):!0}if(!w){L[x.quality]="FitsContainer";continue}let B=p||t,ne=X(B)&&isFinite(B)&&X(x.bitrate)?B-s>=x.bitrate*M:!0,Fe=jn(r,i.highQualityLimit,i.trafficSavingLimit)&&(r==null?void 0:r.min)===x.quality;if(!ne&&!Fe){L[x.quality]="FitsThroughput";continue}if(i.lazyQualitySwitch&&X(i.minBufferToSwitchUp)&&u&&!Wn(u.quality)&&(n!=null?n:0)<i.minBufferToSwitchUp&&Gn(x.quality,u.quality)){L[x.quality]="Buffer";continue}if(!!d&&mr(x.quality,d)&&!Fe){L[x.quality]="DroppedFramesLimit";continue}if(!!f&&mr(x.quality,f)&&!Fe){L[x.quality]="StallsLimit";continue}let Se=A||(Qn(r==null?void 0:r.max)||br(x.quality,r.max))&&(Qn(r==null?void 0:r.min)||mr(x.quality,r.min)),ve=X(c)&&!c?br(x.quality,i.backgroundVideoQualityLimit):!0;if(!Se||!ve){L[x.quality]="FitsQualityLimits";continue}P||(P=x)}P&&P.bitrate&&$v.next(P.bitrate);let k=(J=P!=null?P:(0,Re.default)(v,-1))!=null?J:a[0],V=l==null?void 0:l.last,D=Xn(i,h,k,l);return X(l)&&D.quality!==(V==null?void 0:V.quality)&&h({message:`
|
|
10
10
|
[VIDEO TRACKS ABR]
|
|
11
11
|
[available video tracks]
|
|
12
|
-
${a.map(
|
|
12
|
+
${a.map(x=>{var w,B;return`{ id: ${x.id}, quality: ${x.quality}, bitrate: ${x.bitrate}, size: ${(w=x.size)==null?void 0:w.width}:${(B=x.size)==null?void 0:B.height} }`}).join(`
|
|
13
13
|
`)}
|
|
14
14
|
|
|
15
15
|
[tuning]
|
|
16
|
-
${(0,
|
|
16
|
+
${(0,Ai.default)(i!=null?i:{}).map(([x,w])=>`${x}: ${w}`).join(`
|
|
17
17
|
`)}
|
|
18
18
|
|
|
19
19
|
[limit params]
|
|
20
|
-
containerSizeFactor: ${
|
|
21
|
-
containerSizeLimit: ${(
|
|
20
|
+
containerSizeFactor: ${b},
|
|
21
|
+
containerSizeLimit: ${(T=S==null?void 0:S.width)!=null?T:0} x ${(R=S==null?void 0:S.height)!=null?R:0},
|
|
22
22
|
estimatedThroughput: ${t},
|
|
23
23
|
stallsPredictedThroughput: ${p},
|
|
24
24
|
reserve: ${s},
|
|
25
25
|
playbackRate: ${o},
|
|
26
|
-
playbackRateFactor: ${
|
|
26
|
+
playbackRateFactor: ${y},
|
|
27
27
|
forwardBufferHealth: ${n},
|
|
28
|
-
bitrateFactor: ${
|
|
28
|
+
bitrateFactor: ${M},
|
|
29
29
|
minBufferToSwitchUp: ${i.minBufferToSwitchUp},
|
|
30
|
-
droppedVideoMaxQualityLimit: ${
|
|
30
|
+
droppedVideoMaxQualityLimit: ${d},
|
|
31
31
|
stallsVideoMaxQualityLimit: ${f},
|
|
32
|
-
limitsAreInvalid: ${
|
|
32
|
+
limitsAreInvalid: ${A},
|
|
33
33
|
maxQualityLimit: ${r==null?void 0:r.max},
|
|
34
34
|
minQualityLimit: ${r==null?void 0:r.min},
|
|
35
35
|
|
|
36
36
|
[limited video tracks]
|
|
37
|
-
${(0,
|
|
37
|
+
${(0,Ai.default)(L).map(([x,w])=>`${x}: ${w}`).join(`
|
|
38
38
|
`)||"All tracks are available"}
|
|
39
39
|
|
|
40
|
-
[best video track] ${
|
|
41
|
-
[selected video track] ${
|
|
42
|
-
`}),
|
|
40
|
+
[best video track] ${P==null?void 0:P.quality}
|
|
41
|
+
[selected video track] ${D==null?void 0:D.quality}
|
|
42
|
+
`}),D},Jn=(a,{container:e,estimatedThroughput:t,tuning:i,limits:r,reserve:s=0,forwardBufferHealth:n,playbackRate:o,current:u,history:l,visible:c,droppedVideoMaxQualityLimit:d,stallsVideoMaxQualityLimit:f,stallsPredictedThroughput:p,abrLogger:h,panelSize:m})=>{var Y,J,T,R,x;zn(a,Kn);let{containerSizeFactor:b,containerSizeLimit:S}=Mv({container:e,tuning:i,limits:r,panelSize:m}),y=i.considerPlaybackRate&&X(o)?o:1,v=a.filter(w=>!Wn(w.quality)).sort((w,B)=>Gn(w.quality,B.quality)?-1:1),I=(Y=(0,Re.default)(v,-1))==null?void 0:Y.quality,E=(J=(0,Re.default)(v,0))==null?void 0:J.quality,A=fr(r,E,I),M=y*Yn(n!=null?n:.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),L={},k=v.filter(w=>{let B=!0;if(S)if(w.size)B=w.size.width<=S.width&&w.size.height<=S.height;else{let xt=S&&Rv(S);B=xt?br(w.quality,xt):!0}if(!B)return L[w.quality]="FitsContainer",!1;let ne=p||t,Fe=X(ne)&&isFinite(ne)&&X(w.bitrate)?ne-s>=w.bitrate*M:!0,ie=jn(r,i.highQualityLimit,i.trafficSavingLimit)&&(r==null?void 0:r.min)===w.quality;if(!Fe&&!ie)return L[w.quality]="FitsThroughput",!1;if(i.lazyQualitySwitch&&X(i.minBufferToSwitchUp)&&u&&!Wn(u.quality)&&(n!=null?n:0)<i.minBufferToSwitchUp&&Gn(w.quality,u.quality))return L[w.quality]="Buffer",!1;if(!!d&&mr(w.quality,d)&&!ie)return L[w.quality]="DroppedFramesLimit",!1;if(!!f&&mr(w.quality,f)&&!ie)return L[w.quality]="StallsLimit",!1;let ve=A||(Qn(r==null?void 0:r.max)||br(w.quality,r.max))&&(Qn(r==null?void 0:r.min)||mr(w.quality,r.min)),Ne=X(c)&&!c?br(w.quality,i.backgroundVideoQualityLimit):!0;return!ve||!Ne?(L[w.quality]="FitsQualityLimits",!1):!0})[0];k&&k.bitrate&&$v.next(k.bitrate);let V=(T=k!=null?k:(0,Re.default)(v,-1))!=null?T:a[0],D=l==null?void 0:l.last,_=Xn(i,h,V,l);return X(l)&&_.quality!==(D==null?void 0:D.quality)&&h({message:`
|
|
43
43
|
[VIDEO TRACKS ABR]
|
|
44
44
|
[available video tracks]
|
|
45
|
-
${a.map(
|
|
45
|
+
${a.map(w=>{var B,ne;return`{ id: ${w.id}, quality: ${w.quality}, bitrate: ${w.bitrate}, size: ${(B=w.size)==null?void 0:B.width}:${(ne=w.size)==null?void 0:ne.height} }`}).join(`
|
|
46
46
|
`)}
|
|
47
47
|
|
|
48
48
|
[tuning]
|
|
49
|
-
${(0,
|
|
49
|
+
${(0,Ai.default)(i!=null?i:{}).map(([w,B])=>`${w}: ${B}`).join(`
|
|
50
50
|
`)}
|
|
51
51
|
|
|
52
52
|
[limit params]
|
|
53
|
-
containerSizeFactor: ${
|
|
54
|
-
containerSizeLimit: ${(
|
|
53
|
+
containerSizeFactor: ${b},
|
|
54
|
+
containerSizeLimit: ${(R=S==null?void 0:S.width)!=null?R:0} x ${(x=S==null?void 0:S.height)!=null?x:0},
|
|
55
55
|
estimatedThroughput: ${t},
|
|
56
56
|
stallsPredictedThroughput: ${p},
|
|
57
57
|
reserve: ${s},
|
|
58
58
|
playbackRate: ${o},
|
|
59
|
-
playbackRateFactor: ${
|
|
59
|
+
playbackRateFactor: ${y},
|
|
60
60
|
forwardBufferHealth: ${n},
|
|
61
|
-
bitrateFactor: ${
|
|
61
|
+
bitrateFactor: ${M},
|
|
62
62
|
minBufferToSwitchUp: ${i.minBufferToSwitchUp},
|
|
63
|
-
droppedVideoMaxQualityLimit: ${
|
|
63
|
+
droppedVideoMaxQualityLimit: ${d},
|
|
64
64
|
stallsVideoMaxQualityLimit: ${f},
|
|
65
|
-
limitsAreInvalid: ${
|
|
65
|
+
limitsAreInvalid: ${A},
|
|
66
66
|
maxQualityLimit: ${r==null?void 0:r.max},
|
|
67
67
|
minQualityLimit: ${r==null?void 0:r.min},
|
|
68
68
|
|
|
69
69
|
[limited video tracks]
|
|
70
|
-
${(0,
|
|
70
|
+
${(0,Ai.default)(L).map(([w,B])=>`${w}: ${B}`).join(`
|
|
71
71
|
`)||"All tracks are available"}
|
|
72
72
|
|
|
73
|
-
[best video track] ${
|
|
74
|
-
[selected video track] ${
|
|
75
|
-
`}),
|
|
73
|
+
[best video track] ${k==null?void 0:k.quality}
|
|
74
|
+
[selected video track] ${_==null?void 0:_.quality}
|
|
75
|
+
`}),_},Zn=(a,e,t,{estimatedThroughput:i,tuning:r,playbackRate:s,forwardBufferHealth:n,history:o,abrLogger:u,stallsPredictedThroughput:l})=>{zn(t,Kn);let c=r.considerPlaybackRate&&X(s)?s:1,d=[...t].sort(gr(-1)),f=a.bitrate;Lv(f);let p=c*Yn(n!=null?n:.5,r.bitrateAudioFactorAtEmptyBuffer,r.bitrateAudioFactorAtFullBuffer),h,m=Ea(a,e,t,r.minVideoAudioRatio),b=l||i;X(b)&&isFinite(b)&&(h=d.find(v=>X(v.bitrate)&&X(m==null?void 0:m.bitrate)?b-f>=v.bitrate*p&&v.bitrate>=m.bitrate:!1)),h||(h=m);let S=o==null?void 0:o.last,y=h&&Xn(r,u,h,o);return X(o)&&(y==null?void 0:y.bitrate)!==(S==null?void 0:S.bitrate)&&u({message:`
|
|
76
76
|
[AUDIO TRACKS ABR]
|
|
77
77
|
[available audio tracks]
|
|
78
|
-
${t.map(
|
|
78
|
+
${t.map(v=>`{ id: ${v.id}, bitrate: ${v.bitrate} }`).join(`
|
|
79
79
|
`)}
|
|
80
80
|
|
|
81
81
|
[tuning]
|
|
82
|
-
${(0,
|
|
82
|
+
${(0,Ai.default)(r!=null?r:{}).map(([v,I])=>`${v}: ${I}`).join(`
|
|
83
83
|
`)}
|
|
84
84
|
|
|
85
85
|
[limit params]
|
|
@@ -87,20 +87,20 @@ var BE=Object.create;var Cp=Object.defineProperty;var VE=Object.getOwnPropertyDe
|
|
|
87
87
|
stallsPredictedThroughput: ${l},
|
|
88
88
|
reserve: ${f},
|
|
89
89
|
playbackRate: ${s},
|
|
90
|
-
playbackRateFactor: ${
|
|
90
|
+
playbackRateFactor: ${c},
|
|
91
91
|
forwardBufferHealth: ${n},
|
|
92
92
|
bitrateFactor: ${p},
|
|
93
93
|
minBufferToSwitchUp: ${r.minBufferToSwitchUp},
|
|
94
94
|
|
|
95
|
-
[selected audio track] ${
|
|
96
|
-
`}),
|
|
95
|
+
[selected audio track] ${y==null?void 0:y.id}
|
|
96
|
+
`}),y},eo=(a,e,t,{estimatedThroughput:i,tuning:r,playbackRate:s,forwardBufferHealth:n,history:o,abrLogger:u,stallsPredictedThroughput:l})=>{zn(t,Kn);let c=r.considerPlaybackRate&&X(s)?s:1,d=xv.get(t);d||(d=[...t].sort(gr(-1)),xv.set(t,d));let f=a.bitrate;Lv(f);let p=c*Yn(n!=null?n:.5,r.bitrateAudioFactorAtEmptyBuffer,r.bitrateAudioFactorAtFullBuffer),h,m=xa(a,e,t,r.minVideoAudioRatio),b=l||i;X(b)&&isFinite(b)&&(h=d.find(v=>X(v.bitrate)&&X(m==null?void 0:m.bitrate)?b-f>=v.bitrate*p&&v.bitrate>=m.bitrate:!1)),h||(h=m);let S=o==null?void 0:o.last,y=h&&Xn(r,u,h,o);return X(o)&&(y==null?void 0:y.bitrate)!==(S==null?void 0:S.bitrate)&&u({message:`
|
|
97
97
|
[AUDIO TRACKS ABR]
|
|
98
98
|
[available audio tracks]
|
|
99
|
-
${t.map(
|
|
99
|
+
${t.map(v=>`{ id: ${v.id}, bitrate: ${v.bitrate} }`).join(`
|
|
100
100
|
`)}
|
|
101
101
|
|
|
102
102
|
[tuning]
|
|
103
|
-
${(0,
|
|
103
|
+
${(0,Ai.default)(r!=null?r:{}).map(([v,I])=>`${v}: ${I}`).join(`
|
|
104
104
|
`)}
|
|
105
105
|
|
|
106
106
|
[limit params]
|
|
@@ -108,20 +108,20 @@ var BE=Object.create;var Cp=Object.defineProperty;var VE=Object.getOwnPropertyDe
|
|
|
108
108
|
stallsPredictedThroughput: ${l},
|
|
109
109
|
reserve: ${f},
|
|
110
110
|
playbackRate: ${s},
|
|
111
|
-
playbackRateFactor: ${
|
|
111
|
+
playbackRateFactor: ${c},
|
|
112
112
|
forwardBufferHealth: ${n},
|
|
113
113
|
bitrateFactor: ${p},
|
|
114
114
|
minBufferToSwitchUp: ${r.minBufferToSwitchUp},
|
|
115
115
|
|
|
116
|
-
[selected audio track] ${
|
|
117
|
-
`}),v};var Te=a=>new URL(a).hostname;import{assertNever as Fv,assertNonNullable as Nv,combine as FM,debounce as NM,ErrorCategory as Uv,filter as qv,filterChanged as UM,isNonNullable as Tc,map as ro,merge as Hv,observableFrom as qM,once as HM,Subscription as jM,ValueSubject as Ic,videoQualityToHeight as jv,videoSizeToQuality as QM}from"@vkontakte/videoplayer-shared/es2018";var Bv=N(gt(),1);var Lv=N(ze(),1),kv=a=>{if(a instanceof DOMException&&(0,Lv.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"))},Be=async(a,e)=>{let t=a.muted;try{await a.play()}catch(i){if(!kv(i))return!1;if(e&&e(),t)return console.warn(i),!1;a.muted=!0;try{await a.play()}catch(r){return kv(r)&&(a.muted=!1,console.warn(r)),!1}}return!0};import{isNonNullable as to,isNullable as TM,assertNonNullable as Aa}from"@vkontakte/videoplayer-shared/es2018";var Mv=N(ur(),1);import{isNonNullable as $v,assertNonNullable as eo,now as vM}from"@vkontakte/videoplayer-shared/es2018";function fe(){return vM()}function gc(a){return fe()-a}function Sc(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 Dv(a,e,t){let i=(...r)=>{t.apply(null,r),a.removeEventListener(e,i)};a.addEventListener(e,i)}function mr(a,e,t,i){let r=window.XMLHttpRequest,s,n,o,u=!1,l=0,d,c,f=!1,p="arraybuffer",h=7e3,m=2e3,g=()=>{if(u)return;eo(d);let M=gc(d),k;if(M<m){k=m-M,setTimeout(g,k);return}m*=2,m>h&&(m=h),n&&n.abort(),n=new r,x()},S=M=>(s=M,B),v=M=>(c=M,B),y=()=>(p="json",B),I=()=>{if(!u){if(--l>=0){g(),i&&i();return}u=!0,c&&c(),t&&t()}},T=M=>(f=M,B),x=()=>{d=fe(),n=new r,n.open("get",a);let M=0,k,Q=0,O=()=>(eo(d),Math.max(d,Math.max(k||0,Q||0)));if(s&&n.addEventListener("progress",A=>{let _=fe();s.updateChunk&&A.loaded>M&&(s.updateChunk(O(),A.loaded-M),M=A.loaded,k=_)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>I())),n.addEventListener("load",()=>{if(u)return;eo(n);let A=n.status;if(A>=200&&A<300){let{response:_,responseType:R}=n,E=_==null?void 0:_.byteLength;if(typeof E=="number"&&s){let C=E-M;C&&s.updateChunk&&s.updateChunk(O(),C)}R==="json"&&(!_||!(0,Mv.default)(_).length)?I():(c&&c(),e(_))}else I()}),n.addEventListener("error",()=>{I()}),f){let A=()=>{eo(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(Q=fe(),n.removeEventListener("readystatechange",A))};n.addEventListener("readystatechange",A)}return n.responseType=p,n.send(),B},B={withBitrateReporting:S,withParallel:T,withJSONResponse:y,withRetryCount:M=>(l=M,B),withRetryInterval:(M,k)=>($v(M)&&(m=M),$v(k)&&(h=k),B),withTimeout:M=>(o=M,B),withFinally:v,send:x,abort:()=>{n&&(n.abort(),n=void 0),u=!0,c&&c()}};return B}var xa=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 Cv=N(ur(),1);var wa=class{constructor(e,t,i,r,s){this.pendingQueue=[];this.activeRequests={};this.completeRequests={};this.averageSegmentDuration=2e3;this.lastPrefetchStart=0;this.throttleTimeout=null;this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=i,this.MAX_PARALLEL_REQUESTS=r,this.logger=s}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){let t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){let i=fe(),r=u=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=u,e._errorCB?e._errorCB(u):(this.limitCompleteCount(),this.completeRequests[t]=e)},s=u=>{e._complete=1,e._responseData=u,e._downloadTime=fe()-i,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(u,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=mr(t,s,()=>r("error"),o),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(n),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=fe()}_getParallelRequestCount(){return Math.min(this.MAX_PARALLEL_REQUESTS,this.averageSegmentDuration<3e3?3:2)}_getPrefetchDelay(){return Math.max(100,Math.min(5e3,this.averageSegmentDuration/3))}_canSendPending(){let e=this._getParallelRequestCount(),t=fe();if(Object.keys(this.activeRequests).length>=e)return!1;let i=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),i>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),i),!1):!0}_sendPending(){for(;this._canSendPending();){let e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){(0,Cv.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 IM}from"@vkontakte/videoplayer-shared/es2018";var io=1e4,vc=3;var EM=6e4,xM=10,wM=1,AM=500,Pa=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 IM,this.chunkRateEstimator=new xa(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=Sc(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setAutoQualityLimits(e){this.autoQualityLimits=e}switchByName(e){let t;for(let i=0;i<this.manifest.length;++i)if(t=this.manifest[i],t.name===e){this._switchToQuality(t);return}}catchUp(){if(this.rep&&this.rep.stop(),this.currentManifestEntry){let e=this.params.playbackState.getState();this.paused=e==="paused",this._initPlayerWith(this.currentManifestEntry),this._notifyBuffering(!0)}}stop(){this.params.videoElement.pause(),this.rep&&(this.rep.stop(),this.rep=null)}pause(){this.paused=!0,this.params.videoElement.pause(),this.videoPlayStarted=!1,this._notifyBuffering(!1)}play(){this.paused=!1;let e=this.lowLatency&&this._getBufferSizeSec()>this.sourceJitter+5;this.rep&&!e?(this.bufferStates=[],this.videoPlayStarted=!1,this.shouldPlay()?this._playVideoElement():this._notifyBuffering(!0)):this.catchUp()}startPlay(e,t){this.autoQuality=t,this._initPlayerWith(e)}destroy(){this.destroyed=!0,this.rep&&(this.rep.stop(),this.rep=null),this.manifestRequest&&this.manifestRequest.abort(),this.manifestRefetchTimer&&(clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=void 0)}reinit(e){this.manifestUrl=e,this.urlResolver=Sc(e),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){let e=this.params.videoElement,t=0,i=e.buffered.length;return i!==0&&(t=e.buffered.end(i-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){let{videoElement:e,logger:t}=this.params;e.addEventListener("error",()=>{var r,s;!!e.error&&!this.destroyed&&(t(`Video element error: ${(r=e.error)==null?void 0:r.code}, details: ${(s=e.error)==null?void 0:s.message}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{let i=this._getBufferSizeSec();!this.paused&&i<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(i+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){let{logger:e,videoElement:t}=this.params,i=t.buffered.length,r;i!==0&&!this.waitingForFirstBufferAfterSrcChange&&(r=t.buffered.start(i-1),t.currentTime<r&&(e("Fixup stall"),t.currentTime=r))}_selectQuality(e){let{videoElement:t}=this.params,i,r,s,n=t&&1.62*(U.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||{};!vv({limits:this.autoQualityLimits,highestAvailableHeight:this.manifest[0].video.height,lowestAvailableHeight:(0,Bv.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||to(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=()=>{Dv(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 wa(vc,io,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,d=!1,c=()=>{let I=s&&(!d||d===this.rep);return I||t("Not running!"),I},f=(I,T,x)=>{u&&u.abort(),u=mr(this.urlResolver.resolve(I,!1),T,x,()=>this._retryCallback()).withTimeout(io).withBitrateReporting(this.bitrateSwitcher).withRetryCount(vc).withFinally(()=>{u=null}).send()},p=(I,T,x)=>{Aa(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(I,!1),T,x,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},h=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)h(1);else{let I=this._getBufferSizeSec();if(this.bufferStates.length<5){h(1);return}let x=fe()-1e4,V=0;for(let w=0;w<this.bufferStates.length;w++){let P=this.bufferStates[w];I=Math.min(I,P.buf),P.ts<x&&V++}this.bufferStates.splice(0,V),t(`update playback rate; minBuffer=${I} drop=${V} jitter=${this.sourceJitter}`);let $=I-wM;this.sourceJitter>=0?$-=this.sourceJitter/2:this.sourceJitter-=1,$>3?h(1.15):$>1?h(1.1):$>.3?h(1.05):h(1)}},S=I=>{let T,x=()=>T&&T.start?T.start.length:0,V=A=>T.start[A]/1e3,$=A=>T.dur[A]/1e3,w=A=>T.fragIndex+A,P=(A,_)=>({chunkIdx:w(A),startTS:V(A),dur:$(A),discontinuity:_}),B=()=>{let A=0;if(T&&T.dur){let _=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,R=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,E=_;this.sourceJitter>1&&(E+=this.sourceJitter-1);let C=T.dur.length-1;for(;C>=0&&(E-=T.dur[C],!(E<=0));--C);A=Math.min(C,T.dur.length-1-R),A=Math.max(A,0)}return P(A,!0)},M=A=>{let _=x();if(!(_<=0)){if(to(A)){for(let R=0;R<_;R++)if(V(R)>A)return P(R)}return B()}},k=A=>{let _=x(),R=A?A.chunkIdx+1:0,E=R-T.fragIndex;if(!(_<=0)){if(!A||E<0||E-_>xM)return t(`Resync: offset=${E} bChunks=${_} chunk=`+JSON.stringify(A)),B();if(!(E>=_))return P(R-T.fragIndex,!1)}},Q=(A,_,R)=>{l&&l.abort(),l=mr(this.urlResolver.resolve(A,!0,this.lowLatency),_,R,()=>this._retryCallback()).withTimeout(io).withRetryCount(vc).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(A,_)=>{Q(I,R=>{if(!c())return;T=R;let E=!!T.lowLatency;E!==this.lowLatency&&m(E);let C=0;for(let ne=0;ne<T.dur.length;++ne)C+=T.dur[ne];C>0&&(Aa(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(C/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(M(_))},()=>this._handleNetworkError())},nextChunk:k}},v=()=>{s=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),Aa(this.filesFetcher),this.filesFetcher.abortAll()};return d={start:I=>{let{videoElement:T,logger:x}=this.params,V=S(e.jidxUrl),$,w,P,B,M=0,k,Q,O,A=()=>{k&&(clearTimeout(k),k=void 0);let Y=Math.max(AM,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),ge=M+Y,Se=fe(),ve=Math.min(1e4,ge-Se);M=Se;let Fe=()=>{l||c()&&V.seek(()=>{c()&&(M=fe(),_(),A())})};ve>0?k=window.setTimeout(()=>{this.paused?A():Fe()},ve):Fe()},_=()=>{let Y;for(;Y=V.nextChunk(B);)B=Y,Oe(Y);let ge=V.nextChunk(P);if(ge){if(P&&ge.discontinuity){x("Detected discontinuity; restarting playback"),this.paused?A():(v(),this._initPlayerWith(e));return}ne(ge)}else A()},R=(Y,ge)=>{if(!c()||!this.sourceBuffer)return;let Se,ve,Fe,Et=_t=>{window.setTimeout(()=>{c()&&R(Y,ge)},_t)};if(this.sourceBuffer.updating)x("Source buffer is updating; delaying appendBuffer"),Et(100);else{let _t=fe(),si=T.currentTime;!this.paused&&T.buffered.length>1&&Q===si&&_t-O>500&&(x("Stall suspected; trying to fix"),this._fixupStall()),Q!==si&&(Q=si,O=_t);let _i=this._getBufferSizeSec();if(_i>30)x(`Buffered ${_i} seconds; delaying appendBuffer`),Et(2e3);else try{this.sourceBuffer.appendBuffer(Y),this.videoPlayStarted?(this.bufferStates.push({ts:_t,buf:_i}),g(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),ge&&ge()}catch(Fr){if(Fr.name==="QuotaExceededError")x("QuotaExceededError; delaying appendBuffer"),Fe=this.sourceBuffer.buffered.length,Fe!==0&&(Se=this.sourceBuffer.buffered.start(0),ve=si,ve-Se>4&&this.sourceBuffer.remove(Se,ve-3)),Et(1e3);else throw Fr}}},E=()=>{w&&$&&(x([`Appending chunk, sz=${w.byteLength}:`,JSON.stringify(P)]),R(w,function(){w=null,_()}))},C=Y=>e.fragUrlTemplate.replace("%%id%%",Y.chunkIdx),ne=Y=>{c()&&p(C(Y),(ge,Se)=>{if(c()){if(Se/=1e3,w=ge,P=Y,n=Y.startTS,Se){let ve=Math.min(10,Y.dur/Se);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*ve:ve}E()}},()=>this._handleNetworkError())},Oe=Y=>{c()&&(Aa(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(C(Y),!1)))},ie=Y=>{c()&&(e.cachedHeader=Y,R(Y,()=>{$=!0,E()}))};s=!0,V.seek(Y=>{if(c()){if(M=fe(),!Y){A();return}B=Y,!TM(I)||Y.startTS>I?ne(Y):(P=Y,_())}},I),e.cachedHeader?ie(e.cachedHeader):f(e.headerUrl,ie,()=>this._handleNetworkError())},stop:v,getTimestampSec:()=>n},d}_switchToQuality(e){let{logger:t,playerCallback:i}=this.params,r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),to(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,Aa(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return to(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,i=c=>{if(!this.autoQuality)return;let f,p,h;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&c<this.bitrate&&(p=this._getBufferSizeSec(),h=c/this.bitrate,p>10&&h>.8||p>15&&h>.5||p>20&&h>.3)){e(`Not switching: buffer=${Math.floor(p)}; bitrate=${this.bitrate}; newRate=${Math.floor(c)}`);return}f=this._selectQuality(c),f?this._switchToQuality(f):e(`Could not find quality by bitrate ${c}`)},s={updateChunk:(f,p)=>{let h=fe();if(this.chunkRateEstimator.addInterval(f,h,p)){let g=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:p,duration:h-f,speed:g}),!0}},get:()=>{let f=this.chunkRateEstimator.getBitRate();return f?f*.85:0}},n=-1/0,o,u=!0,l=()=>{let c=s.get();if(c&&o&&this.autoQuality){if(u&&c>o&&gc(n)<3e4)return;i(c)}u=this.autoQuality};return{updateChunk:(c,f)=>{let p=s.updateChunk(c,f);return p&&l(),p},notifySwitch:c=>{let f=fe();c<o&&(n=f),o=c}}}_fetchManifest(e,t,i){this.manifestRequest=mr(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(io).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;Be(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 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=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))},EM))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var Ov=N(Xi(),1);import{debounce as PM,filter as Vv,fromEvent as RM,interval as kM,isHigher as LM,isInvariantQuality as $M,isLower as MM,merge as DM,Subject as _v,Subscription as CM}from"@vkontakte/videoplayer-shared/es2018";var yc=class{constructor(){this.onDroopedVideoFramesLimit$=new _v;this.subscription=new CM;this.playing=!1;this.tracks=[];this.forceChecker$=new _v;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&&!$M(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&&LM(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(RM(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=kM(this.droppedFramesChecker.checkTime).pipe(Vv(()=>this.playing),Vv(()=>{let r=!!this.isForceCheckCounter;return r&&(this.isForceCheckCounter-=1),!r})),t=this.forceChecker$.pipe(PM(this.droppedFramesChecker.checkTime)),i=DM(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,Ov.default)(this.limitCounts).filter(([,s])=>s>=this.droppedFramesChecker.countLimit).sort(([s],[n])=>MM(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}},br=yc;import{map as BM,Observable as VM}from"@vkontakte/videoplayer-shared/es2018";import{fromEvent as _M}from"@vkontakte/videoplayer-shared/es2018";var Ra=()=>{var a;return!!((a=window.documentPictureInPicture)!=null&&a.window)||!!document.pictureInPictureElement};var OM=(a,e)=>new VM(t=>{if(!window.IntersectionObserver)return;let i={root:null},r=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||Ra()))},{...i,...e});r.observe(a);let s=_M(document,"visibilitychange").pipe(BM(n=>!document.hidden||Ra())).subscribe(n=>t.next(n));return()=>{r.unobserve(a),s.unsubscribe()}}),Xe=OM;var GM=["paused","playing","ready"],WM=["paused","playing","ready"],ka=class{constructor(e){this.subscription=new jM;this.videoState=new H("stopped");this.representations$=new Ic([]);this.droppedFramesManager=new br;this.maxSeekBackTime$=new Ic(1/0);this.zeroTime$=new Ic(void 0);this.liveOffset=new xi;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:Uv.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:QM(u.video),c=u.bitrate/1e3,f={...u.video};if(!d)continue;let p={id:l,quality:d,bitrate:c,size:f};o.push({track:p,representation:u})}this.representations$.next(o),this.params.output.availableVideoTracks$.next(o.map(({track:u})=>u)),((r=this.videoState.getTransition())==null?void 0:r.to)==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let n=e.quality,o=(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),Tc(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,Ec.default)(WM,e)&&(n||o)){this.prepare();return}if((r==null?void 0:r.to)!=="paused"&&s.state==="requested"&&(0,Ec.default)(GM,e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(le(this.params.source.url));return;case"manifest_ready":this.videoState.startTransitionTo("ready"),this.prepare();break;case"ready":if(i==="paused")this.videoState.setState("paused");else if(i==="playing"){this.videoState.startTransitionTo("playing");let u=r==null?void 0:r.from;u&&u==="ready"&&this.dash.catchUp(),this.dash.play()}return;case"playing":i==="paused"&&(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.dash.pause());return;case"paused":if(i==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.dash.play(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let u=this.liveOffset.getTotalOffset();u>=this.maxSeekBackTime$.getValue()&&(u=0,this.liveOffset.resetTo(u)),this.liveOffset.resume(),this.params.output.position$.next(-u/1e3),this.dash.reinit(le(this.params.source.url,u))}return;default:return Fv(e)}};this.textTracksManager=new Ke(e.source.url),this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=r=>{e.output.error$.next({id:"DashLiveProvider",category:Uv.WTF,message:"DashLiveProvider internal logic error",thrown:r})};this.subscription.add(Hv(this.videoState.stateChangeStarted$.pipe(ro(r=>({transition:r,type:"start"}))),this.videoState.stateChangeEnded$.pipe(ro(r=>({transition:r,type:"end"})))).subscribe(({transition:r,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(r)}`})})),this.video=$e(e.container,e.tuning),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.subscription.add(this.dash.soundProhibitedEvent$.subscribe(this.params.output.soundProhibitedEvent$)),this.params.output.duration$.next(1/0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(Te(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);let i=Ce(this.video);this.subscription.add(()=>i.destroy()),this.subscription.add(this.representations$.pipe(ro(r=>r.map(({track:s})=>s)),qv(r=>!!r.length),HM()).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(UM(),ro(r=>-r/1e3)).subscribe(this.params.output.duration$)).add(FM({zeroTime:this.zeroTime$.pipe(qv(Tc)),position:i.timeUpdate$}).subscribe(({zeroTime:r,position:s})=>this.params.output.liveTime$.next(r+s*1e3),t)).add(ft(this.video,this.params.desiredState.isLooped,t)).add(De(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(Ye(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(Xe(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:r,min:s}})=>{this.dash.setAutoQualityLimits({max:r&&jv(r),min:s&&jv(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 Fv(r.to)}},t)).add(Hv(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,qM(["init"])).pipe(NM(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),Me(this.video)}createLiveDashPlayer(){let e=new Pa({videoElement:this.video,videoState:this.videoState,playbackState:this.params.desiredState.playbackState,liveOffset:this.liveOffset,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode,manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){var l,d,c,f,p,h;let e=this.representations$.getValue(),t=(d=(l=this.params.desiredState.videoTrack.getTransition())==null?void 0:l.to)!=null?d:this.params.desiredState.videoTrack.getState(),i=(f=(c=this.params.desiredState.autoVideoTrackSwitching.getTransition())==null?void 0:c.to)!=null?f:this.params.desiredState.autoVideoTrackSwitching.getState(),r=!i&&Tc(t)?t:St(e.map(({track:m})=>m),{container:this.video.getBoundingClientRect(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),s=r==null?void 0:r.id,n=this.params.desiredState.videoTrack.getTransition(),o=(p=this.params.desiredState.videoTrack.getState())==null?void 0:p.id,u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(r&&(n||s!==o)&&this.setVideoTrack(r),u&&this.setAutoQuality(i),n||u||s!==o){let m=(h=e.find(({track:g})=>g.id===s))==null?void 0:h.representation;Nv(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;Nv(t,`No such representation ${e.id}`),this.dash.switchByName(t.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),r=t==="paused"&&i==="paused",s=-e,n=s<=this.maxSeekBackTime$.getValue()?s:0;this.params.output.position$.next(e/1e3),this.dash.reinit(le(this.params.source.url,n)),r&&this.dash.pause(),this.liveOffset.resetTo(n,r)}};var Qv=ka;var dI=N(ze(),1);var me=(a,e)=>{let t=0;for(let i=0;i<a.length;i++){let r=a.start(i)*1e3,s=a.end(i)*1e3;r<=e&&e<=s&&(t=s)}return Math.max(t-e,0)};import{assertNever as DB,assertNonNullable as CB,debounce as BB,ErrorCategory as uI,filter as sd,filterChanged as $o,fromEvent as VB,isNonNullable as lI,isNullable as _B,map as nd,merge as Mo,observableFrom as od,once as cI,Subscription as OB}from"@vkontakte/videoplayer-shared/es2018";var{NativeAbortSignal:S1,NativeAbortController:v1}=function(a){return{NativeAbortSignal:a.AbortSignal,NativeAbortController:a.AbortController}}(typeof self!="undefined"?self:global);function Gv(a){let e;try{e=new Event("abort")}catch(t){typeof document!="undefined"?document.createEvent?(e=document.createEvent("Event"),e.initEvent("abort",!1,!1)):(e=document.createEventObject(),e.type="abort"):e={type:"abort",bubbles:!1,cancelable:!1}}return e.reason=a,e}function Wv(a){if(a===void 0)if(typeof document=="undefined")a=new Error("This operation was aborted"),a.name="AbortError";else try{a=new DOMException("signal is aborted without reason"),Object.defineProperty(a,"name",{value:"AbortError"})}catch(e){a=new Error("This operation was aborted"),a.name="AbortError"}return a}var ao=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}},gr=class extends ao{constructor(){super(),this.listeners||ao.call(this),Object.defineProperty(this,"aborted",{value:!1,writable:!0,configurable:!0}),Object.defineProperty(this,"onabort",{value:null,writable:!0,configurable:!0}),Object.defineProperty(this,"reason",{value:void 0,writable:!0,configurable:!0})}toString(){return"[object AbortSignal]"}dispatchEvent(e){e.type==="abort"&&(this.aborted=!0,typeof this.onabort=="function"&&this.onabort.call(this,e)),super.dispatchEvent(e)}throwIfAborted(){let{aborted:e,reason:t="Aborted"}=this;if(e)throw t}static timeout(e){let t=new Ai;return setTimeout(()=>t.abort(new DOMException(`This signal is timeout in ${e}ms`,"TimeoutError")),e),t.signal}static any(e){let t=new Ai;function i(){t.abort(this.reason),r()}function r(){for(let s of e)s.removeEventListener("abort",i)}for(let s of e)if(s.aborted){t.abort(s.reason);break}else s.addEventListener("abort",i);return t.signal}},Ai=class{constructor(){Object.defineProperty(this,"signal",{value:new gr,writable:!0,configurable:!0})}abort(e){let t=Wv(e),i=Gv(t);this.signal.reason=t,this.signal.dispatchEvent(i)}toString(){return"[object AbortController]"}};typeof Symbol!="undefined"&&Symbol.toStringTag&&(Ai.prototype[Symbol.toStringTag]="AbortController",gr.prototype[Symbol.toStringTag]="AbortSignal");function so(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 xc(a){typeof a=="function"&&(a={fetch:a});let{fetch:e,Request:t=e.Request,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r=!1}=a;if(!so({fetch:e,Request:t,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r}))return{fetch:e,Request:s};let s=t;(s&&!s.prototype.hasOwnProperty("signal")||r)&&(s=function(l,d){let c;d&&d.signal&&(c=d.signal,delete d.signal);let f=new t(l,d);return c&&Object.defineProperty(f,"signal",{writable:!1,enumerable:!1,configurable:!0,value:c}),f},s.prototype=t.prototype);let n=e;return{fetch:(u,l)=>{let d=s&&s.prototype.isPrototypeOf(u)?u.signal:l?l.signal:void 0;if(d){let c;try{c=new DOMException("Aborted","AbortError")}catch(p){c=new Error("Aborted"),c.name="AbortError"}if(d.aborted)return Promise.reject(c);let f=new Promise((p,h)=>{d.addEventListener("abort",()=>h(c),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([f,n(u,l)])}return n(u,l)},Request:s}}var zM=()=>"fetch"in window,La=zM()&&so({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),zv=La?xc({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,Je=La?zv.fetch:window.fetch,k1=La?zv.Request:window.Request,Z=La?Ai:window.AbortController,L1=La?gr:window.AbortSignal;var Zc=N($a(),1);var Cy=N(Dy(),1);import{ErrorCategory as Da}from"@vkontakte/videoplayer-shared/es2018";var no=a=>{if(!a)return{id:"EmptyResponse",category:Da.PARSER,message:"Empty response"};if(a.length<=2&&a.match(/^\d+$/))return{id:`UVError#${a}`,category:Da.NETWORK,message:`UV Error ${a}`};let e=(0,Cy.default)(a).substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:Da.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:Da.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:Da.PARSER,message:"Response is valid XML, but parser failed"}};var Ie=(a,e,t=0)=>{for(let i=0;i<a.length;i++)if(a.start(i)*1e3-t<=e&&a.end(i)*1e3+t>e)return!0;return!1};import{abortable as Kc,assertNonNullable as Rr,combine as kr,ErrorCategory as ut,filter as Eo,filterChanged as ds,flattenObject as ps,fromEvent as Ct,getTraceSubscriptionMethod as mB,interval as Xc,isNonNullable as hs,isNullable as iI,map as Lr,merge as Li,now as Jc,Subject as xo,Subscription as rI,tap as bB,throttle as gB,ValueSubject as ae}from"@vkontakte/videoplayer-shared/es2018";var lo=N(ze(),1),wr=N(gt(),1),co=N($a(),1);var DD=(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)},CD=a=>window.clearTimeout(a),By=a=>typeof a=="function"&&(a==null?void 0:a.toString().endsWith("{ [native code] }")),Vy=!By(window.requestIdleCallback)||!By(window.cancelIdleCallback),Sr=Vy?DD:window.requestIdleCallback,vt=Vy?CD:window.cancelIdleCallback;var GT=N(Ln(),1);import{assertNever as BD,ErrorCategory as _y,Subject as Oy}from"@vkontakte/videoplayer-shared/es2018";var VD=18,Fy=!1;try{Fy=U.browser.isSafari&&!!U.browser.safariVersion&&U.browser.safariVersion<=VD}catch(a){console.error(a)}var Lc=class{constructor(e){this.bufferFull$=new Oy;this.error$=new Oy;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:_y.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)};Fy&&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:_y.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:BD(t)}}},Ny=Lc;var vr=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 Jt,assertNonNullable as Ve,ErrorCategory as $t,fromEvent as jc,getExponentialDelay as Qc,isNonNullable as xr,isNullable as Ee,now as uo,once as rB,Subject as aB,Subscription as sB,ValueSubject as ki}from"@vkontakte/videoplayer-shared/es2018";var W=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let i=this.readUint32();this.type=this.readString(4),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 yr=class extends W{};var Ca=class extends W{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 Ba=class extends W{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 Va=class extends W{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var re=class extends W{constructor(e,t){super(e,t);let i=this.readUint32();this.version=i>>>24,this.flags=i&16777215}};var _a=class extends re{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 Oa=class extends W{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Fa=class extends W{constructor(e,t){super(e,t),this.data=this.content}};var Pi=class extends re{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 W{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ua=class extends W{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var qa=class extends re{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 Ha=class extends re{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var ja=class extends re{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var Qa=class extends W{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ga=class extends re{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.trackId=this.readUint32(),this.cursor+=4,this.duration=this.readUint32(),this.cursor+=8,this.layer=this.readUint16(),this.alternateGroup=this.readUint16(),this.cursor+=2,this.cursor+=2,this.matrix=[[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()]],this.width=this.readUint32(),this.height=this.readUint32()}};var Wa=class extends W{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var za=class extends W{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ya=class extends re{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var Ka=class extends W{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Xa=class extends re{constructor(e,t){super(e,t),this.trackId=this.readUint32(),this.flags&1&&(this.baseDataOffset=this.readUint64()),this.flags&2&&(this.sampleDescriptionIndex=this.readUint32()),this.flags&8&&(this.defaultSampleDuration=this.readUint32()),this.flags&16&&(this.defaultSampleSize=this.readUint32()),this.flags&32&&(this.defaultSampleFlags=this.readUint32())}};var Ja=class extends re{constructor(t,i){super(t,i);this.baseMediaDecodeTime32=0;this.baseMediaDecodeTime64=BigInt(0);this.version===1?this.baseMediaDecodeTime64=this.readUint64():this.baseMediaDecodeTime32=this.readUint32()}get baseMediaDecodeTime(){return this.version===1?this.baseMediaDecodeTime64:this.baseMediaDecodeTime32}};var Za=class extends re{constructor(t,i){super(t,i);this.sampleDuration=[];this.sampleSize=[];this.sampleFlags=[];this.sampleCompositionTimeOffset=[];this.optionalFields=0;this.sampleCount=this.readUint32(),this.flags&1&&(this.dataOffset=this.readUint32()),this.flags&4&&(this.firstSampleFlags=this.readUint32());for(let r=0;r<this.sampleCount;r++)this.flags&256&&this.sampleDuration.push(this.readUint32()),this.flags&512&&this.sampleSize.push(this.readUint32()),this.flags&1024&&this.sampleFlags.push(this.readUint32()),this.flags&2048&&this.sampleCompositionTimeOffset.push(this.readUint32())}};var es=class extends W{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ts=class extends re{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 is=class extends W{constructor(e,t){super(e,t),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+78,this.content.byteLength-78))}};var OD={ftyp:Ba,moov:Va,mvhd:_a,moof:Oa,mdat:Fa,sidx:Pi,trak:Na,mdia:Qa,mfhd:Ya,tkhd:Ga,traf:Ka,tfhd:Xa,tfdt:Ja,trun:Za,minf:Wa,sv3d:Ua,st3d:qa,prhd:Ha,proj:za,equi:ja,uuid:Ca,stbl:es,stsd:ts,avc1:is,unknown:yr},Lt=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=OD[e];return i?new i(t,new a):new yr(t,new a)}};var Xt=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 ND=new TextDecoder("ascii"),UD=a=>ND.decode(new DataView(a.buffer,a.byteOffset+4,4))==="ftyp",qD=a=>{let e=new Pi(a,new Lt),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})},HD=(a,e)=>{let i=new Lt().parse(a),r=new Xt(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,c=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(a.buffer,l,c)},jD=a=>{let t=new Lt().parse(a),i=new Xt(t),r={},s=i.findAll("uuid");return s.length?s[s.length-1]:r},QD=a=>{var r;let t=new Lt().parse(a);return(r=new Xt(t).find("sidx"))==null?void 0:r.timescale},GD=(a,e)=>{let i=new Lt().parse(a),s=new Xt(i).findAll("traf"),n=s[s.length-1].children.find(c=>c.type==="tfhd"),o=s[s.length-1].children.find(c=>c.type==="tfdt"),u=s[s.length-1].children.find(c=>c.type==="trun"),l=0;return u.sampleDuration.length?l=u.sampleDuration.reduce((c,f)=>c+f,0):l=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+l)/e*1e3},WD=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 Lt().parse(a),r=new Xt(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},Uy={validateData:UD,parseInit:WD,getIndexRange:()=>{},parseSegments:qD,parseFeedableSegmentChunk:HD,getChunkEndTime:GD,getServerLatencyTimestamps:jD,getTimescaleFromIndex:QD};var ss=N(ze(),1);import{assertNonNullable as $c,isNonNullable as Qy,isNullable as YD}from"@vkontakte/videoplayer-shared/es2018";import{assertNever as zD}from"@vkontakte/videoplayer-shared/es2018";var qy={440786851:{type:"master"},17030:{type:"uint"},17143:{type:"uint"},17138:{type:"uint"},17139:{type:"uint"},17026:{type:"string"},17031:{type:"uint"},17029:{type:"uint"},236:{type:"binary"},408125543:{type:"master"},290298740:{type:"master"},19899:{type:"master"},21419:{type:"binary"},21420:{type:"uint"},357149030:{type:"master"},2807729:{type:"uint"},17545:{type:"float"},374648427:{type:"master"},174:{type:"master"},224:{type:"master"},30320:{type:"master"},30321:{type:"uint"},30322:{type:"master"},272869232:{type:"master"},524531317:{type:"master"},231:{type:"uint"},22612:{type:"master"},22743:{type:"uint"},167:{type:"uint"},171:{type:"uint"},163:{type:"binary"},160:{type:"master"},175:{type:"binary"},423732329:{type:"master"},307544935:{type:"master"},475249515:{type:"master"},187:{type:"master"},179:{type:"uint"},183:{type:"master"},247:{type:"uint"},241:{type:"uint"},240:{type:"uint"},178:{type:"uint"},21368:{type:"uint"},234:{type:"uint"},219:{type:"master"},150:{type:"uint"}},Hy=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=as(a,t),r=i in qy,s=r?qy[i].type:"binary",n=a.getUint8(t),o=0;n&128?o=1:n&64?o=2:n&32?o=3:n&16?o=4:n&8?o=5:n&4?o=6:n&2?o=7:n&1&&(o=8);let u=new DataView(a.buffer,a.byteOffset+t+1,o-1),l=n&255>>o,d=as(u),c=l*2**((o-1)*8)+d,f=t+o,p;return f+c>a.byteLength?p=new DataView(a.buffer,a.byteOffset+f):p=new DataView(a.buffer,a.byteOffset+f,c),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:s,tagHeaderSize:f,tagSize:f+c,value:p,valueSize:c}},as=(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},nt=(a,e)=>{switch(e){case"int":return a.getInt8(0);case"uint":return as(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:zD(e)}},Ri=(a,e)=>{let t=0;for(;t<a.byteLength;){let i=new DataView(a.buffer,a.byteOffset+t),r=Hy(i);if(!e(r))return;r.type==="master"&&Ri(r.value,e),t=r.value.byteOffset-a.byteOffset+r.valueSize}},jy=a=>{if(a.getUint32(0)!==440786851)return!1;let e,t,i,r=Hy(a);return Ri(r.value,({tag:s,type:n,value:o})=>(s===17143?e=nt(o,n):s===17026?t=nt(o,n):s===17029&&(i=nt(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)};var Gy=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],KD=[231,22612,22743,167,171,163,160,175],XD=a=>{let e,t,i,r,s=!1,n=!1,o=!1,u,l,d=!1,c=0;return Ri(a,({tag:f,type:p,value:h,valueSize:m})=>{if(f===21419){let g=nt(h,p);l=as(g)}else f!==21420&&(l=void 0);return f===408125543?(e=h.byteOffset,t=h.byteOffset+m):f===357149030?s=!0:f===290298740?n=!0:f===2807729?i=nt(h,p):f===17545?r=nt(h,p):f===21420&&l===475249515?u=nt(h,p):f===374648427?Ri(h,({tag:g,type:S,value:v})=>g===30321?(d=nt(v,S)===1,!1):!0):s&&n&&(0,ss.default)(Gy,f)&&(o=!0),!o}),$c(e,"Failed to parse webm Segment start"),$c(t,"Failed to parse webm Segment end"),$c(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}}}},JD=a=>{if(YD(a.cuesSeekPosition))return;let e=a.segmentStart+a.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},ZD=(a,e)=>{let t=!1,i=!1,r=o=>Qy(o.time)&&Qy(o.position),s=[],n;return Ri(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=nt(l,u));break;case 183:break;case 241:n&&(n.position=nt(l,u));break;default:t&&(0,ss.default)(Gy,o)&&(i=!0)}return!(t&&i)}),n&&r(n)&&s.push(n),s.map((o,u)=>{let{time:l,position:d}=o,c=s[u+1];return{status:"none",time:{from:l,to:c?c.time:e.segmentDuration},byte:{from:e.segmentStart+d,to:c?e.segmentStart+c.position-1:e.segmentEnd-1}}})},eC=a=>{let e=0,t=!1;try{Ri(a,i=>i.tag===524531317?i.tagSize<=a.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):(0,ss.default)(KD,i.tag)?(e+i.tagSize<=a.byteLength&&(e+=i.tagSize,t||(t=(0,ss.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},Wy={validateData:jy,parseInit:XD,getIndexRange:JD,parseSegments:ZD,parseFeedableSegmentChunk:eC};var yt=a=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(a);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return Wy;case"mp4":return Uy}}throw new ReferenceError(`Unsupported mime type ${a}`)};var Tt=a=>a instanceof DOMException&&(a.name==="AbortError"||a.code===20);var Oc=N(bT(),1),OT=N(Xi(),1),FT=N(MT(),1),NT=N(gt(),1),Fc=N(ur(),1);var DT=N(ze(),1),_c=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,DT.default)(["6E","7A","F4"],o)}}return!1};import{isNonNullable as eB,isNullable as VT}from"@vkontakte/videoplayer-shared/es2018";var CT=a=>{if(a.includes("/")){let e=a.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(a)};var BT=a=>{var e;try{let t=ZC(),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 ZC(){let a="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",d=`^(?:(?<langtag>${`
|
|
116
|
+
[selected audio track] ${y==null?void 0:y.id}
|
|
117
|
+
`}),y};var Te=a=>new URL(a).hostname;import{assertNever as jv,assertNonNullable as Hv,combine as QM,debounce as GM,ErrorCategory as Qv,filter as Gv,filterChanged as WM,isNonNullable as xc,map as ao,merge as Wv,observableFrom as zM,once as YM,Subscription as KM,ValueSubject as wc,videoQualityToHeight as zv,videoSizeToQuality as XM}from"@vkontakte/videoplayer-shared/es2018";var Fv=O(ot(),1);var Cv=O(Ye(),1),Dv=a=>{if(a instanceof DOMException&&(0,Cv.default)(["Failed to load because no supported source was found.","The element has no supported sources."],a.message))throw a;return!(a instanceof DOMException&&(a.code===20||a.name==="AbortError"))},Ve=async(a,e)=>{let t=a.muted;try{await a.play()}catch(i){if(!Dv(i))return!1;if(e&&e(),t)return console.warn(i),!1;a.muted=!0;try{await a.play()}catch(r){return Dv(r)&&(a.muted=!1,console.warn(r)),!1}}return!0};import{isNonNullable as io,isNullable as PM,assertNonNullable as Pa}from"@vkontakte/videoplayer-shared/es2018";var Vv=O(pr(),1);import{isNonNullable as Bv,assertNonNullable as to,now as wM}from"@vkontakte/videoplayer-shared/es2018";function fe(){return wM()}function yc(a){return fe()-a}function Tc(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 _v(a,e,t){let i=(...r)=>{t.apply(null,r),a.removeEventListener(e,i)};a.addEventListener(e,i)}function Sr(a,e,t,i){let r=window.XMLHttpRequest,s,n,o,u=!1,l=0,c,d,f=!1,p="arraybuffer",h=7e3,m=2e3,b=()=>{if(u)return;to(c);let D=yc(c),_;if(D<m){_=m-D,setTimeout(b,_);return}m*=2,m>h&&(m=h),n&&n.abort(),n=new r,A()},S=D=>(s=D,V),y=D=>(d=D,V),v=()=>(p="json",V),I=()=>{if(!u){if(--l>=0){b(),i&&i();return}u=!0,d&&d(),t&&t()}},E=D=>(f=D,V),A=()=>{c=fe(),n=new r,n.open("get",a);let D=0,_,Y=0,J=()=>(to(c),Math.max(c,Math.max(_||0,Y||0)));if(s&&n.addEventListener("progress",T=>{let R=fe();s.updateChunk&&T.loaded>D&&(s.updateChunk(J(),T.loaded-D),D=T.loaded,_=R)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>I())),n.addEventListener("load",()=>{if(u)return;to(n);let T=n.status;if(T>=200&&T<300){let{response:R,responseType:x}=n,w=R==null?void 0:R.byteLength;if(typeof w=="number"&&s){let B=w-D;B&&s.updateChunk&&s.updateChunk(J(),B)}x==="json"&&(!R||!(0,Vv.default)(R).length)?I():(d&&d(),e(R))}else I()}),n.addEventListener("error",()=>{I()}),f){let T=()=>{to(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(Y=fe(),n.removeEventListener("readystatechange",T))};n.addEventListener("readystatechange",T)}return n.responseType=p,n.send(),V},V={withBitrateReporting:S,withParallel:E,withJSONResponse:v,withRetryCount:D=>(l=D,V),withRetryInterval:(D,_)=>(Bv(D)&&(m=D),Bv(_)&&(h=_),V),withTimeout:D=>(o=D,V),withFinally:y,send:A,abort:()=>{n&&(n.abort(),n=void 0),u=!0,d&&d()}};return V}var wa=class{constructor(e){this.intervals=[];this.currentRate=0;this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,i){return{start:e,end:t,bytes:i}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;let e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-500;if(t-e>2e3){let i=0,r=0;for(;this.intervals.length>0;){let s=this.intervals[0];if(s.end<=t)i+=s.end-s.start,r+=s.bytes,this.intervals.splice(0,1);else{if(s.start>=t)break;{let n=t-s.start,o=s.end-s.start;i+=n;let u=s.bytes*n/o;r+=u,s.start=t,s.bytes-=u}}}if(r>0&&i>0){let s=r*8/(i/1e3);return this._updateRate(s),this.logger(`rate updated, new=${Math.round(s/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(r)}/${Math.round(i)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,i){return this.intervals.push(this._createInterval(e,t,i)),this._joinIntervals(),this.intervals.length>100&&(this.logger(`too many intervals (${this.intervals.length}); will merge`,{type:"warn"}),this._doMergeIntervals(this.intervals[1],this.intervals[0]),this.intervals.splice(0,1)),this._flushIntervals()}getBitRate(){return this.currentRate}};var Ov=O(pr(),1);var Aa=class{constructor(e,t,i,r,s){this.pendingQueue=[];this.activeRequests={};this.completeRequests={};this.averageSegmentDuration=2e3;this.lastPrefetchStart=0;this.throttleTimeout=null;this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=i,this.MAX_PARALLEL_REQUESTS=r,this.logger=s}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){let t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){let i=fe(),r=u=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=u,e._errorCB?e._errorCB(u):(this.limitCompleteCount(),this.completeRequests[t]=e)},s=u=>{e._complete=1,e._responseData=u,e._downloadTime=fe()-i,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(u,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=Sr(t,s,()=>r("error"),o),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(n),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=fe()}_getParallelRequestCount(){return Math.min(this.MAX_PARALLEL_REQUESTS,this.averageSegmentDuration<3e3?3:2)}_getPrefetchDelay(){return Math.max(100,Math.min(5e3,this.averageSegmentDuration/3))}_canSendPending(){let e=this._getParallelRequestCount(),t=fe();if(Object.keys(this.activeRequests).length>=e)return!1;let i=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),i>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),i),!1):!0}_sendPending(){for(;this._canSendPending();){let e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){(0,Ov.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 kM}from"@vkontakte/videoplayer-shared/es2018";var ro=1e4,Ic=3;var RM=6e4,LM=10,$M=1,MM=500,ka=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 kM,this.chunkRateEstimator=new wa(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=Tc(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setAutoQualityLimits(e){this.autoQualityLimits=e}switchByName(e){let t;for(let i=0;i<this.manifest.length;++i)if(t=this.manifest[i],t.name===e){this._switchToQuality(t);return}}catchUp(){if(this.rep&&this.rep.stop(),this.currentManifestEntry){let e=this.params.playbackState.getState();this.paused=e==="paused",this._initPlayerWith(this.currentManifestEntry),this._notifyBuffering(!0)}}stop(){this.params.videoElement.pause(),this.rep&&(this.rep.stop(),this.rep=null)}pause(){this.paused=!0,this.params.videoElement.pause(),this.videoPlayStarted=!1,this._notifyBuffering(!1)}play(){this.paused=!1;let e=this.lowLatency&&this._getBufferSizeSec()>this.sourceJitter+5;this.rep&&!e?(this.bufferStates=[],this.videoPlayStarted=!1,this.shouldPlay()?this._playVideoElement():this._notifyBuffering(!0)):this.catchUp()}startPlay(e,t){this.autoQuality=t,this._initPlayerWith(e)}destroy(){this.destroyed=!0,this.rep&&(this.rep.stop(),this.rep=null),this.manifestRequest&&this.manifestRequest.abort(),this.manifestRefetchTimer&&(clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=void 0)}reinit(e){this.manifestUrl=e,this.urlResolver=Tc(e),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){let e=this.params.videoElement,t=0,i=e.buffered.length;return i!==0&&(t=e.buffered.end(i-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){let{videoElement:e,logger:t}=this.params;e.addEventListener("error",()=>{var r,s;!!e.error&&!this.destroyed&&(t(`Video element error: ${(r=e.error)==null?void 0:r.code}, details: ${(s=e.error)==null?void 0:s.message}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{let i=this._getBufferSizeSec();!this.paused&&i<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(i+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){let{logger:e,videoElement:t}=this.params,i=t.buffered.length,r;i!==0&&!this.waitingForFirstBufferAfterSrcChange&&(r=t.buffered.start(i-1),t.currentTime<r&&(e("Fixup stall"),t.currentTime=r))}_selectQuality(e){let{videoElement:t}=this.params,i,r,s,n=t&&1.62*(F.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||{};!Ev({limits:this.autoQualityLimits,highestAvailableHeight:this.manifest[0].video.height,lowestAvailableHeight:(0,Fv.default)(this.manifest,-1).video.height})&&(u&&s.video.height>u||l&&s.video.height<l)||(s.bitrate<e&&n>Math.min(s.video.height,s.video.width)?(!r||s.bitrate>r.bitrate)&&(r=s):(!i||i.bitrate>s.bitrate)&&(i=s))}return r||i}shouldPlay(){if(this.paused)return!1;let t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||io(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){let{logger:i,videoElement:r,playerCallback:s}=this.params;this.mediaSource=new window.MediaSource,i("setting video src"),r.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,r.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});let n=()=>{_v(r,"progress",()=>{r.buffered.length?(r.currentTime=r.buffered.start(0),this.waitingForFirstBufferAfterSrcChange=!1,s({name:"playing"})):n()})};this.waitingForFirstBufferAfterSrcChange=!0,n()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new Aa(Ic,ro,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:i,playerCallback:r}=this.params,s=!1,n=null,o=null,u=null,l=null,c=!1,d=()=>{let I=s&&(!c||c===this.rep);return I||t("Not running!"),I},f=(I,E,A)=>{u&&u.abort(),u=Sr(this.urlResolver.resolve(I,!1),E,A,()=>this._retryCallback()).withTimeout(ro).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Ic).withFinally(()=>{u=null}).send()},p=(I,E,A)=>{Pa(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(I,!1),E,A,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},h=I=>{let E=i.playbackRate;i.playbackRate!==I&&(t(`Playback rate switch: ${E}=>${I}`),i.playbackRate=I)},m=I=>{this.lowLatency=I,t(`lowLatency changed to ${I}`),b()},b=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)h(1);else{let I=this._getBufferSizeSec();if(this.bufferStates.length<5){h(1);return}let A=fe()-1e4,M=0;for(let P=0;P<this.bufferStates.length;P++){let k=this.bufferStates[P];I=Math.min(I,k.buf),k.ts<A&&M++}this.bufferStates.splice(0,M),t(`update playback rate; minBuffer=${I} drop=${M} jitter=${this.sourceJitter}`);let L=I-$M;this.sourceJitter>=0?L-=this.sourceJitter/2:this.sourceJitter-=1,L>3?h(1.15):L>1?h(1.1):L>.3?h(1.05):h(1)}},S=I=>{let E,A=()=>E&&E.start?E.start.length:0,M=T=>E.start[T]/1e3,L=T=>E.dur[T]/1e3,P=T=>E.fragIndex+T,k=(T,R)=>({chunkIdx:P(T),startTS:M(T),dur:L(T),discontinuity:R}),V=()=>{let T=0;if(E&&E.dur){let R=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,x=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,w=R;this.sourceJitter>1&&(w+=this.sourceJitter-1);let B=E.dur.length-1;for(;B>=0&&(w-=E.dur[B],!(w<=0));--B);T=Math.min(B,E.dur.length-1-x),T=Math.max(T,0)}return k(T,!0)},D=T=>{let R=A();if(!(R<=0)){if(io(T)){for(let x=0;x<R;x++)if(M(x)>T)return k(x)}return V()}},_=T=>{let R=A(),x=T?T.chunkIdx+1:0,w=x-E.fragIndex;if(!(R<=0)){if(!T||w<0||w-R>LM)return t(`Resync: offset=${w} bChunks=${R} chunk=`+JSON.stringify(T)),V();if(!(w>=R))return k(x-E.fragIndex,!1)}},Y=(T,R,x)=>{l&&l.abort(),l=Sr(this.urlResolver.resolve(T,!0,this.lowLatency),R,x,()=>this._retryCallback()).withTimeout(ro).withRetryCount(Ic).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(T,R)=>{Y(I,x=>{if(!d())return;E=x;let w=!!E.lowLatency;w!==this.lowLatency&&m(w);let B=0;for(let ne=0;ne<E.dur.length;++ne)B+=E.dur[ne];B>0&&(Pa(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(B/E.dur.length)),r({name:"index",zeroTime:E.zeroTime,shiftDuration:E.shiftDuration}),this.sourceJitter=E.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,E.jitter/1e3)):1,T(D(R))},()=>this._handleNetworkError())},nextChunk:_}},y=()=>{s=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),Pa(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:I=>{let{videoElement:E,logger:A}=this.params,M=S(e.jidxUrl),L,P,k,V,D=0,_,Y,J,T=()=>{_&&(clearTimeout(_),_=void 0);let W=Math.max(MM,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),ge=D+W,Se=fe(),ve=Math.min(1e4,ge-Se);D=Se;let Ne=()=>{l||d()&&M.seek(()=>{d()&&(D=fe(),R(),T())})};ve>0?_=window.setTimeout(()=>{this.paused?T():Ne()},ve):Ne()},R=()=>{let W;for(;W=M.nextChunk(V);)V=W,Fe(W);let ge=M.nextChunk(k);if(ge){if(k&&ge.discontinuity){A("Detected discontinuity; restarting playback"),this.paused?T():(y(),this._initPlayerWith(e));return}ne(ge)}else T()},x=(W,ge)=>{if(!d()||!this.sourceBuffer)return;let Se,ve,Ne,xt=Ot=>{window.setTimeout(()=>{d()&&x(W,ge)},Ot)};if(this.sourceBuffer.updating)A("Source buffer is updating; delaying appendBuffer"),xt(100);else{let Ot=fe(),ni=E.currentTime;!this.paused&&E.buffered.length>1&&Y===ni&&Ot-J>500&&(A("Stall suspected; trying to fix"),this._fixupStall()),Y!==ni&&(Y=ni,J=Ot);let Ni=this._getBufferSizeSec();if(Ni>30)A(`Buffered ${Ni} seconds; delaying appendBuffer`),xt(2e3);else try{this.sourceBuffer.appendBuffer(W),this.videoPlayStarted?(this.bufferStates.push({ts:Ot,buf:Ni}),b(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),ge&&ge()}catch(Nr){if(Nr.name==="QuotaExceededError")A("QuotaExceededError; delaying appendBuffer"),Ne=this.sourceBuffer.buffered.length,Ne!==0&&(Se=this.sourceBuffer.buffered.start(0),ve=ni,ve-Se>4&&this.sourceBuffer.remove(Se,ve-3)),xt(1e3);else throw Nr}}},w=()=>{P&&L&&(A([`Appending chunk, sz=${P.byteLength}:`,JSON.stringify(k)]),x(P,function(){P=null,R()}))},B=W=>e.fragUrlTemplate.replace("%%id%%",W.chunkIdx),ne=W=>{d()&&p(B(W),(ge,Se)=>{if(d()){if(Se/=1e3,P=ge,k=W,n=W.startTS,Se){let ve=Math.min(10,W.dur/Se);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*ve:ve}w()}},()=>this._handleNetworkError())},Fe=W=>{d()&&(Pa(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(B(W),!1)))},ie=W=>{d()&&(e.cachedHeader=W,x(W,()=>{L=!0,w()}))};s=!0,M.seek(W=>{if(d()){if(D=fe(),!W){T();return}V=W,!PM(I)||W.startTS>I?ne(W):(k=W,R())}},I),e.cachedHeader?ie(e.cachedHeader):f(e.headerUrl,ie,()=>this._handleNetworkError())},stop:y,getTimestampSec:()=>n},c}_switchToQuality(e){let{logger:t,playerCallback:i}=this.params,r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),io(r)&&(r+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,Pa(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return io(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,i=d=>{if(!this.autoQuality)return;let f,p,h;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&d<this.bitrate&&(p=this._getBufferSizeSec(),h=d/this.bitrate,p>10&&h>.8||p>15&&h>.5||p>20&&h>.3)){e(`Not switching: buffer=${Math.floor(p)}; bitrate=${this.bitrate}; newRate=${Math.floor(d)}`);return}f=this._selectQuality(d),f?this._switchToQuality(f):e(`Could not find quality by bitrate ${d}`)},s={updateChunk:(f,p)=>{let h=fe();if(this.chunkRateEstimator.addInterval(f,h,p)){let b=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:p,duration:h-f,speed:b}),!0}},get:()=>{let f=this.chunkRateEstimator.getBitRate();return f?f*.85:0}},n=-1/0,o,u=!0,l=()=>{let d=s.get();if(d&&o&&this.autoQuality){if(u&&d>o&&yc(n)<3e4)return;i(d)}u=this.autoQuality};return{updateChunk:(d,f)=>{let p=s.updateChunk(d,f);return p&&l(),p},notifySwitch:d=>{let f=fe();d<o&&(n=f),o=d}}}_fetchManifest(e,t,i){this.manifestRequest=Sr(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(ro).withRetryCount(this.params.config.manifestRetryMaxCount).withRetryInterval(this.params.config.manifestRetryInterval,this.params.config.manifestRetryMaxInterval).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(){let{videoElement:e}=this.params;Ve(e,()=>{this.soundProhibitedEvent$.next()}).then(t=>{t||(this.params.liveOffset.pause(),this.params.videoState.setState("paused"))})}_handleManifestUpdate(e){let{logger:t,playerCallback:i,videoElement:r}=this.params,s=n=>{let o=[];return n!=null&&n.length?(n.forEach((u,l)=>{var c,d;u.video&&r.canPlayType(u.codecs).replace(/no/,"")&&((d=(c=window.MediaSource)==null?void 0:c.isTypeSupported)!=null&&d.call(c,u.codecs))&&(u.index=l,o.push(u))}),o.sort(function(u,l){return u.video&&l.video?l.video.height-u.video.height:l.bitrate-u.bitrate}),o):(i({name:"error",type:"empty_manifest"}),[])};this.manifest=s(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),i({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},RM))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var qv=O(er(),1);import{debounce as DM,filter as Nv,fromEvent as CM,interval as BM,isHigher as VM,isInvariantQuality as _M,isLower as OM,merge as FM,Subject as Uv,Subscription as NM}from"@vkontakte/videoplayer-shared/es2018";var Ec=class{constructor(){this.onDroopedVideoFramesLimit$=new Uv;this.subscription=new NM;this.playing=!1;this.tracks=[];this.forceChecker$=new Uv;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&&!_M(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&&VM(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(CM(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=BM(this.droppedFramesChecker.checkTime).pipe(Nv(()=>this.playing),Nv(()=>{let r=!!this.isForceCheckCounter;return r&&(this.isForceCheckCounter-=1),!r})),t=this.forceChecker$.pipe(DM(this.droppedFramesChecker.checkTime)),i=FM(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,qv.default)(this.limitCounts).filter(([,s])=>s>=this.droppedFramesChecker.countLimit).sort(([s],[n])=>OM(s,n)?-1:1))==null?void 0:i[0])==null?void 0:r[0];return e!=null?e:t}get isEnabled(){return this.droppedFramesChecker.enabled&&this.isDroppedFramesCheckerSupport}get isDroppedFramesCheckerSupport(){return!!this.video&&typeof this.video.getVideoPlaybackQuality=="function"}savePrevFrameCounts(e,t){this.prevTotalVideoFrames=e,this.prevDroppedVideoFrames=t}},vr=Ec;import{map as UM,Observable as qM}from"@vkontakte/videoplayer-shared/es2018";import{fromEvent as jM}from"@vkontakte/videoplayer-shared/es2018";var Ra=()=>{var a;return!!((a=window.documentPictureInPicture)!=null&&a.window)||!!document.pictureInPictureElement};var HM=(a,e)=>new qM(t=>{if(!window.IntersectionObserver)return;let i={root:null},r=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||Ra()))},{...i,...e});r.observe(a);let s=jM(document,"visibilitychange").pipe(UM(n=>!document.hidden||Ra())).subscribe(n=>t.next(n));return()=>{r.unobserve(a),s.unsubscribe()}}),Je=HM;var JM=["paused","playing","ready"],ZM=["paused","playing","ready"],La=class{constructor(e){this.subscription=new KM;this.videoState=new q("stopped");this.representations$=new wc([]);this.droppedFramesManager=new vr;this.maxSeekBackTime$=new wc(1/0);this.zeroTime$=new wc(void 0);this.liveOffset=new wi;this._dashCb=e=>{var t,i,r,s;switch(e.name){case"buffering":{let n=e.isBuffering;this.params.output.isBuffering$.next(n);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,category:Qv.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{let n=e.manifest,o=[];for(let u of n){let l=(t=u.name)!=null?t:u.index.toString(10),c=(i=Kt(u.name))!=null?i:XM(u.video),d=u.bitrate/1e3,f={...u.video};if(!c)continue;let p={id:l,quality:c,bitrate:d,size:f};o.push({track:p,representation:u})}this.representations$.next(o),this.params.output.availableVideoTracks$.next(o.map(({track:u})=>u)),((r=this.videoState.getTransition())==null?void 0:r.to)==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let n=e.quality,o=(s=this.representations$.getValue().find(({representation:u})=>u===n))==null?void 0:s.track;this.params.output.hostname$.next(new URL(n.headerUrl,this.params.source.url).hostname),xc(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,Ac.default)(ZM,e)&&(n||o)){this.prepare();return}if((r==null?void 0:r.to)!=="paused"&&s.state==="requested"&&(0,Ac.default)(JM,e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(le(this.params.source.url));return;case"manifest_ready":this.videoState.startTransitionTo("ready"),this.prepare();break;case"ready":if(i==="paused")this.videoState.setState("paused");else if(i==="playing"){this.videoState.startTransitionTo("playing");let u=r==null?void 0:r.from;u&&u==="ready"&&this.dash.catchUp(),this.dash.play()}return;case"playing":i==="paused"&&(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.dash.pause());return;case"paused":if(i==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.dash.play(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let u=this.liveOffset.getTotalOffset();u>=this.maxSeekBackTime$.getValue()&&(u=0,this.liveOffset.resetTo(u)),this.liveOffset.resume(),this.params.output.position$.next(-u/1e3),this.dash.reinit(le(this.params.source.url,u))}return;default:return jv(e)}};this.textTracksManager=new Xe(e.source.url),this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=r=>{e.output.error$.next({id:"DashLiveProvider",category:Qv.WTF,message:"DashLiveProvider internal logic error",thrown:r})};this.subscription.add(Wv(this.videoState.stateChangeStarted$.pipe(ao(r=>({transition:r,type:"start"}))),this.videoState.stateChangeEnded$.pipe(ao(r=>({transition:r,type:"end"})))).subscribe(({transition:r,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(r)}`})})),this.video=Me(e.container,e.tuning),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.subscription.add(this.dash.soundProhibitedEvent$.subscribe(this.params.output.soundProhibitedEvent$)),this.params.output.duration$.next(1/0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(Te(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);let i=Be(this.video);this.subscription.add(()=>i.destroy()),this.subscription.add(this.representations$.pipe(ao(r=>r.map(({track:s})=>s)),Gv(r=>!!r.length),YM()).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(WM(),ao(r=>-r/1e3)).subscribe(this.params.output.duration$)).add(QM({zeroTime:this.zeroTime$.pipe(Gv(xc)),position:i.timeUpdate$}).subscribe(({zeroTime:r,position:s})=>this.params.output.liveTime$.next(r+s*1e3),t)).add(bt(this.video,this.params.desiredState.isLooped,t)).add(Ce(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(Ke(this.video,this.params.desiredState.playbackRate,i.playbackRateState$,t)).add(i.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(i.loadedMetadata$.subscribe(this.params.output.loadedMetadataEvent$)).add(i.playing$.subscribe(this.params.output.firstFrameEvent$)).add(i.canplay$.subscribe(this.params.output.canplay$)).add(i.inPiP$.subscribe(this.params.output.inPiP$)).add(i.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(Je(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:r,min:s}})=>{this.dash.setAutoQualityLimits({max:r&&zv(r),min:s&&zv(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 jv(r.to)}},t)).add(Wv(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,zM(["init"])).pipe(GM(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),De(this.video)}createLiveDashPlayer(){let e=new ka({videoElement:this.video,videoState:this.videoState,playbackState:this.params.desiredState.playbackState,liveOffset:this.liveOffset,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode,manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){var l,c,d,f,p,h;let e=this.representations$.getValue(),t=(c=(l=this.params.desiredState.videoTrack.getTransition())==null?void 0:l.to)!=null?c:this.params.desiredState.videoTrack.getState(),i=(f=(d=this.params.desiredState.autoVideoTrackSwitching.getTransition())==null?void 0:d.to)!=null?f:this.params.desiredState.autoVideoTrackSwitching.getState(),r=!i&&xc(t)?t:vt(e.map(({track:m})=>m),{container:this.video.getBoundingClientRect(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),s=r==null?void 0:r.id,n=this.params.desiredState.videoTrack.getTransition(),o=(p=this.params.desiredState.videoTrack.getState())==null?void 0:p.id,u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(r&&(n||s!==o)&&this.setVideoTrack(r),u&&this.setAutoQuality(i),n||u||s!==o){let m=(h=e.find(({track:b})=>b.id===s))==null?void 0:h.representation;Hv(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;Hv(t,`No such representation ${e.id}`),this.dash.switchByName(t.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),r=t==="paused"&&i==="paused",s=-e,n=s<=this.maxSeekBackTime$.getValue()?s:0;this.params.output.position$.next(e/1e3),this.dash.reinit(le(this.params.source.url,n)),r&&this.dash.pause(),this.liveOffset.resetTo(n,r)}};var Yv=La;var mI=O(Ye(),1);var me=(a,e)=>{let t=0;for(let i=0;i<a.length;i++){let r=a.start(i)*1e3,s=a.end(i)*1e3;r<=e&&e<=s&&(t=s)}return Math.max(t-e,0)};import{assertNever as NB,assertNonNullable as UB,debounce as qB,ErrorCategory as pI,filter as ld,filterChanged as Mo,fromEvent as jB,isNonNullable as hI,isNullable as HB,map as cd,merge as Do,observableFrom as dd,once as fI,Subscription as QB}from"@vkontakte/videoplayer-shared/es2018";var{NativeAbortSignal:x1,NativeAbortController:w1}=function(a){return{NativeAbortSignal:a.AbortSignal,NativeAbortController:a.AbortController}}(typeof self!="undefined"?self:global);function Kv(a){let e;try{e=new Event("abort")}catch(t){typeof document!="undefined"?document.createEvent?(e=document.createEvent("Event"),e.initEvent("abort",!1,!1)):(e=document.createEventObject(),e.type="abort"):e={type:"abort",bubbles:!1,cancelable:!1}}return e.reason=a,e}function Xv(a){if(a===void 0)if(typeof document=="undefined")a=new Error("This operation was aborted"),a.name="AbortError";else try{a=new DOMException("signal is aborted without reason"),Object.defineProperty(a,"name",{value:"AbortError"})}catch(e){a=new Error("This operation was aborted"),a.name="AbortError"}return a}var so=class{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,i){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:i})}removeEventListener(e,t){if(!(e in this.listeners))return;let i=this.listeners[e];for(let r=0,s=i.length;r<s;r++)if(i[r].callback===t){i.splice(r,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;let i=this.listeners[e.type].slice();for(let r=0,s=i.length;r<s;r++){let n=i[r];try{n.callback.call(this,e)}catch(o){Promise.resolve().then(()=>{throw o})}n.options&&n.options.once&&this.removeEventListener(e.type,n.callback)}return!e.defaultPrevented}},yr=class extends so{constructor(){super(),this.listeners||so.call(this),Object.defineProperty(this,"aborted",{value:!1,writable:!0,configurable:!0}),Object.defineProperty(this,"onabort",{value:null,writable:!0,configurable:!0}),Object.defineProperty(this,"reason",{value:void 0,writable:!0,configurable:!0})}toString(){return"[object AbortSignal]"}dispatchEvent(e){e.type==="abort"&&(this.aborted=!0,typeof this.onabort=="function"&&this.onabort.call(this,e)),super.dispatchEvent(e)}throwIfAborted(){let{aborted:e,reason:t="Aborted"}=this;if(e)throw t}static timeout(e){let t=new Pi;return setTimeout(()=>t.abort(new DOMException(`This signal is timeout in ${e}ms`,"TimeoutError")),e),t.signal}static any(e){let t=new Pi;function i(){t.abort(this.reason),r()}function r(){for(let s of e)s.removeEventListener("abort",i)}for(let s of e)if(s.aborted){t.abort(s.reason);break}else s.addEventListener("abort",i);return t.signal}},Pi=class{constructor(){Object.defineProperty(this,"signal",{value:new yr,writable:!0,configurable:!0})}abort(e){let t=Xv(e),i=Kv(t);this.signal.reason=t,this.signal.dispatchEvent(i)}toString(){return"[object AbortController]"}};typeof Symbol!="undefined"&&Symbol.toStringTag&&(Pi.prototype[Symbol.toStringTag]="AbortController",yr.prototype[Symbol.toStringTag]="AbortSignal");function no(a){return a.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof a.Request=="function"&&!a.Request.prototype.hasOwnProperty("signal")||!a.AbortController}function Pc(a){typeof a=="function"&&(a={fetch:a});let{fetch:e,Request:t=e.Request,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r=!1}=a;if(!no({fetch:e,Request:t,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r}))return{fetch:e,Request:s};let s=t;(s&&!s.prototype.hasOwnProperty("signal")||r)&&(s=function(l,c){let d;c&&c.signal&&(d=c.signal,delete c.signal);let f=new t(l,c);return d&&Object.defineProperty(f,"signal",{writable:!1,enumerable:!1,configurable:!0,value:d}),f},s.prototype=t.prototype);let n=e;return{fetch:(u,l)=>{let c=s&&s.prototype.isPrototypeOf(u)?u.signal:l?l.signal:void 0;if(c){let d;try{d=new DOMException("Aborted","AbortError")}catch(p){d=new Error("Aborted"),d.name="AbortError"}if(c.aborted)return Promise.reject(d);let f=new Promise((p,h)=>{c.addEventListener("abort",()=>h(d),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([f,n(u,l)])}return n(u,l)},Request:s}}var eD=()=>"fetch"in window,$a=eD()&&no({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),Jv=$a?Pc({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,Ze=$a?Jv.fetch:window.fetch,B1=$a?Jv.Request:window.Request,Z=$a?Pi:window.AbortController,V1=$a?yr:window.AbortSignal;var rd=O(Ma(),1);var Oy=O(_y(),1);import{ErrorCategory as Ca}from"@vkontakte/videoplayer-shared/es2018";var oo=a=>{if(!a)return{id:"EmptyResponse",category:Ca.PARSER,message:"Empty response"};if(a.length<=2&&a.match(/^\d+$/))return{id:`UVError#${a}`,category:Ca.NETWORK,message:`UV Error ${a}`};let e=(0,Oy.default)(a).substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:Ca.NETWORK,message:"Received unexpected HTML, possibly a ISP block"};if(e.startsWith("<?xml"))return new DOMParser().parseFromString(a,"text/xml").querySelector("parsererror")?{id:"InvalidXML",category:Ca.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:Ca.PARSER,message:"Response is valid XML, but parser failed"}};var Ie=(a,e,t=0)=>{for(let i=0;i<a.length;i++)if(a.start(i)*1e3-t<=e&&a.end(i)*1e3+t>e)return!0;return!1};import{abortable as ed,assertNonNullable as Lr,combine as $r,ErrorCategory as ct,filter as xo,filterChanged as ps,flattenObject as hs,fromEvent as Bt,getTraceSubscriptionMethod as IB,interval as td,isNonNullable as fs,isNullable as nI,map as Mr,merge as Mi,now as id,Subject as wo,Subscription as oI,tap as EB,throttle as xB,ValueSubject as ae}from"@vkontakte/videoplayer-shared/es2018";var po=O(Ye(),1),$i=O(ot(),1),ho=O(Ma(),1);var FD=(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)},ND=a=>window.clearTimeout(a),Fy=a=>typeof a=="function"&&(a==null?void 0:a.toString().endsWith("{ [native code] }")),Ny=!Fy(window.requestIdleCallback)||!Fy(window.cancelIdleCallback),Tr=Ny?FD:window.requestIdleCallback,yt=Ny?ND:window.cancelIdleCallback;var XT=O($n(),1);import{assertNever as UD,ErrorCategory as Uy,Subject as qy}from"@vkontakte/videoplayer-shared/es2018";var qD=18,jy=!1;try{jy=F.browser.isSafari&&!!F.browser.safariVersion&&F.browser.safariVersion<=qD}catch(a){console.error(a)}var Dc=class{constructor(e){this.bufferFull$=new qy;this.error$=new qy;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:Uy.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)};jy&&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:Uy.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:UD(t)}}},Hy=Dc;var Ir=a=>{let e=0;for(let t=0;t<a.length;t++)e+=a.end(t)-a.start(t);return e*1e3};import{abortable as Zt,assertNonNullable as _e,ErrorCategory as Mt,fromEvent as Wc,getExponentialDelay as zc,isNonNullable as Pr,isNullable as Ee,now as co,once as cB,Subject as dB,Subscription as pB,ValueSubject as Li}from"@vkontakte/videoplayer-shared/es2018";var Qy=O(ot(),1);var uo=a=>a.valid,Q=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let i=this.readUint32();this.type=this.readString(4),i===1&&(this.cursor+=8);let r=e.byteOffset+this.cursor,s;i===0?(this.size=void 0,this.valid=!1,s=void 0):i===1?(this.size=void 0,this.valid=!1,s=void 0):i>e.byteLength?(this.size=i,this.valid=!1,s=Math.min(i-this.cursor,e.byteLength-this.cursor)):(this.size=i,this.valid=!0,s=i-this.cursor),this.content=new DataView(e.buffer,r,s)}get id(){return this.type}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t="ascii"){let r=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,r}readUint8(){let e=this.source.getUint8(this.cursor);return this.cursor+=1,e}readUint16(){let e=this.source.getUint16(this.cursor);return this.cursor+=2,e}readUint32(){let e=this.source.getUint32(this.cursor);return this.cursor+=4,e}readUint64(){let e=this.source.getBigInt64(this.cursor);return this.cursor+=8,e}};var Er=class extends Q{};import{assertNever as jD}from"@vkontakte/videoplayer-shared/es2018";var Ba=class extends Q{constructor(e,t){if(super(e,t),!this.valid)return;let i=this.readString(16),r=new DataView(this.content.buffer,this.content.byteOffset+16,this.content.byteLength-16);this.userData=this.parseData(i,r)}parseData(e,t){switch(e){case"ondemandlivejson":{let i=new TextDecoder("ascii").decode(t),r=JSON.parse(i);return{received:r["t-in"],prepared:r["t-out"]}}default:jD(e)}}};var Va=class extends Q{constructor(e,t){if(super(e,t),!this.valid)return;this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let i=new DataView(this.content.buffer,this.content.byteOffset+8,this.content.byteLength-8);for(let r=0;r<i.byteLength;r+=4){let s=this.readString(4);this.compatibleBrands.push(s)}}};var _a=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var re=class extends Q{constructor(e,t){if(super(e,t),!this.valid)return;let i=this.readUint32();this.version=i>>>24,this.flags=i&16777215,this.content=new DataView(this.content.buffer,this.content.byteOffset+4,this.content.byteLength-4)}};var Oa=class extends re{constructor(e,t){super(e,t),this.valid&&(this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.timescale=this.readUint32(),this.duration=this.readUint32(),this.rate=this.readUint32(),this.volume=this.readUint16())}};var Fa=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Na=class extends Q{constructor(e,t){super(e,t),this.data=this.content}};var ki=class extends re{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e,t){if(super(e,t),!!this.valid){this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let i=0;i<this.referenceCount;i++){let r=this.readUint32(),s=r>>>31,n=r<<1>>>1,o=this.readUint32();r=this.readUint32();let u=r>>>28,l=r<<3>>>3;this.segments.push({referenceType:s,referencedSize:n,subsegmentDuration:o,SAPType:u,SAPDeltaTime:l})}}}};var Ua=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var qa=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ja=class extends re{constructor(e,t){if(super(e,t),!this.valid)return;switch(this.readUint8()){case 0:this.stereoMode=0;break;case 1:this.stereoMode=1;break;case 2:this.stereoMode=2;break;case 3:this.stereoMode=3;break;case 4:this.stereoMode=4;break}this.cursor+=1}};var Ha=class extends re{constructor(e,t){super(e,t),this.valid&&(this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32())}};var Qa=class extends re{constructor(e,t){super(e,t),this.valid&&(this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32())}};var Ga=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Wa=class extends re{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.trackId=this.readUint32(),this.cursor+=4,this.duration=this.readUint32(),this.cursor+=8,this.layer=this.readUint16(),this.alternateGroup=this.readUint16(),this.cursor+=2,this.cursor+=2,this.matrix=[[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()]],this.width=this.readUint32(),this.height=this.readUint32()}};var za=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ya=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ka=class extends re{constructor(e,t){super(e,t),this.valid&&(this.sequenceNumber=this.readUint32())}};var Xa=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ja=class extends re{constructor(e,t){super(e,t),this.trackId=this.readUint32(),this.flags&1&&(this.baseDataOffset=this.readUint64()),this.flags&2&&(this.sampleDescriptionIndex=this.readUint32()),this.flags&8&&(this.defaultSampleDuration=this.readUint32()),this.flags&16&&(this.defaultSampleSize=this.readUint32()),this.flags&32&&(this.defaultSampleFlags=this.readUint32())}};var Za=class extends re{constructor(t,i){super(t,i);this.baseMediaDecodeTime32=0;this.baseMediaDecodeTime64=BigInt(0);this.version===1?this.baseMediaDecodeTime64=this.readUint64():this.baseMediaDecodeTime32=this.readUint32()}get baseMediaDecodeTime(){return this.version===1?this.baseMediaDecodeTime64:this.baseMediaDecodeTime32}};var es=class extends re{constructor(t,i){super(t,i);this.sampleDuration=[];this.sampleSize=[];this.sampleFlags=[];this.sampleCompositionTimeOffset=[];this.optionalFields=0;this.sampleCount=this.readUint32(),this.flags&1&&(this.dataOffset=this.readUint32()),this.flags&4&&(this.firstSampleFlags=this.readUint32());for(let r=0;r<this.sampleCount;r++)this.flags&256&&this.sampleDuration.push(this.readUint32()),this.flags&512&&this.sampleSize.push(this.readUint32()),this.flags&1024&&this.sampleFlags.push(this.readUint32()),this.flags&2048&&this.sampleCompositionTimeOffset.push(this.readUint32())}};var ts=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var is=class extends re{constructor(e,t){super(e,t),this.valid&&(this.entryCount=this.readUint32(),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+4,this.content.byteLength-4)))}};var rs=class extends Q{constructor(e,t){super(e,t),this.valid&&(this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+78,this.content.byteLength-78)))}};var QD={ftyp:Va,moov:_a,mvhd:Oa,moof:Fa,mdat:Na,sidx:ki,trak:Ua,mdia:Ga,mfhd:Ka,tkhd:Wa,traf:Xa,tfhd:Ja,tfdt:Za,trun:es,minf:za,sv3d:qa,st3d:ja,prhd:Ha,proj:Ya,equi:Qa,uuid:Ba,stbl:ts,stsd:is,avc1:rs,unknown:Er},$t=class a{constructor(e={}){this.options={offset:0,...e}}parse(e){let t=[],i=this.options.offset;for(;i<e.byteLength;){let s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+i+4,4)),n;try{n=this.createBox(s,new DataView(e.buffer,e.byteOffset+i,e.byteLength-i))}catch(o){if(!(o instanceof RangeError))throw o}if(!n||!uo(n))break;t.push(n),i+=n.size}return t}createBox(e,t){let i=QD[e];return i?new i(t,new a):new Er(t,new a)}};var Jt=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{var i,r,s;uo(t)&&((s=(i=this.index)[r=t.type])!=null||(i[r]=[]),this.index[t.type].push(t),t.children.length>0&&this.indexBoxLevel(t.children))})}find(e){return this.index[e]&&this.index[e][0]?this.index[e][0]:null}findAll(e){return this.index[e]||[]}};var WD=new TextDecoder("ascii"),zD=a=>WD.decode(new DataView(a.buffer,a.byteOffset+4,4))==="ftyp",YD=a=>{let e=new ki(a,new $t),t=e.earliestPresentationTime/e.timescale*1e3,i=a.byteOffset+a.byteLength+e.firstOffset;return e.segments.map(s=>{if(s.referenceType!==0)throw new Error("Unsupported multilevel sidx");let n=s.subsegmentDuration/e.timescale*1e3,o={status:"none",time:{from:t,to:t+n},byte:{from:i,to:i+s.referencedSize-1}};return t+=n,i+=s.referencedSize,o})},KD=(a,e)=>{let i=new $t().parse(a),r=new Jt(i),s=r.findAll("moof"),n=e?r.findAll("uuid"):r.findAll("mdat");if(!(n.length&&s.length))return null;let o=s[0],u=n[n.length-1],l=o.source.byteOffset,d=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(a.buffer,l,d)},XD=a=>{let t=new $t().parse(a),i=new Jt(t),r={},s=i.findAll("uuid"),n=(0,Qy.default)(s,-1);return n?{serverDataReceivedTimestamp:n.userData.received,serverDataPreparedTime:n.userData.received}:r},JD=a=>{var r;let t=new $t().parse(a);return(r=new Jt(t).find("sidx"))==null?void 0:r.timescale},ZD=(a,e)=>{let i=new $t().parse(a),s=new Jt(i).findAll("traf"),n=s[s.length-1].children.find(d=>d.type==="tfhd"),o=s[s.length-1].children.find(d=>d.type==="tfdt"),u=s[s.length-1].children.find(d=>d.type==="trun"),l=0;return u.sampleDuration.length?l=u.sampleDuration.reduce((d,f)=>d+f,0):l=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+l)/e*1e3},eC=a=>{let e={is3dVideo:!1,stereoMode:0,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}},i=new $t().parse(a),r=new Jt(i);if(r.find("sv3d")){e.is3dVideo=!0;let n=r.find("st3d");n&&(e.stereoMode=n.stereoMode);let o=r.find("prhd");o&&(e.projectionData.pose.yaw=o.poseYawDegrees,e.projectionData.pose.pitch=o.posePitchDegrees,e.projectionData.pose.roll=o.poseRollDegrees);let u=r.find("equi");u&&(e.projectionData.bounds.top=u.projectionBoundsTop,e.projectionData.bounds.right=u.projectionBoundsRight,e.projectionData.bounds.bottom=u.projectionBoundsBottom,e.projectionData.bounds.left=u.projectionBoundsLeft)}return e},Gy={validateData:zD,parseInit:eC,getIndexRange:()=>{},parseSegments:YD,parseFeedableSegmentChunk:KD,getChunkEndTime:ZD,getServerLatencyTimestamps:XD,getTimescaleFromIndex:JD};var ns=O(Ye(),1);import{assertNonNullable as Cc,isNonNullable as Ky,isNullable as iC}from"@vkontakte/videoplayer-shared/es2018";import{assertNever as tC}from"@vkontakte/videoplayer-shared/es2018";var Wy={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"}},zy=a=>{let e=a.getUint8(0),t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);let i=ss(a,t),r=i in Wy,s=r?Wy[i].type:"binary",n=a.getUint8(t),o=0;n&128?o=1:n&64?o=2:n&32?o=3:n&16?o=4:n&8?o=5:n&4?o=6:n&2?o=7:n&1&&(o=8);let u=new DataView(a.buffer,a.byteOffset+t+1,o-1),l=n&255>>o,c=ss(u),d=l*2**((o-1)*8)+c,f=t+o,p;return f+d>a.byteLength?p=new DataView(a.buffer,a.byteOffset+f):p=new DataView(a.buffer,a.byteOffset+f,d),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:s,tagHeaderSize:f,tagSize:f+d,value:p,valueSize:d}},ss=(a,e=a.byteLength)=>{switch(e){case 1:return a.getUint8(0);case 2:return a.getUint16(0);case 3:return a.getUint8(0)*2**16+a.getUint16(1);case 4:return a.getUint32(0);case 5:return a.getUint8(0)*2**32+a.getUint32(1);case 6:return a.getUint16(0)*2**32+a.getUint32(2);case 7:{let t=a.getUint8(0)*281474976710656+a.getUint16(1)*4294967296+a.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},ut=(a,e)=>{switch(e){case"int":return a.getInt8(0);case"uint":return ss(a);case"float":return a.byteLength===4?a.getFloat32(0):a.getFloat64(0);case"string":return new TextDecoder("ascii").decode(a);case"utf8":return new TextDecoder("utf-8").decode(a);case"date":return new Date(Date.UTC(2001,0)+a.getInt8(0)).getTime();case"master":return a;case"binary":return a;default:tC(e)}},Ri=(a,e)=>{let t=0;for(;t<a.byteLength;){let i=new DataView(a.buffer,a.byteOffset+t),r=zy(i);if(!e(r))return;r.type==="master"&&Ri(r.value,e),t=r.value.byteOffset-a.byteOffset+r.valueSize}},Yy=a=>{if(a.getUint32(0)!==440786851)return!1;let e,t,i,r=zy(a);return Ri(r.value,({tag:s,type:n,value:o})=>(s===17143?e=ut(o,n):s===17026?t=ut(o,n):s===17029&&(i=ut(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)};var Xy=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],rC=[231,22612,22743,167,171,163,160,175],aC=a=>{let e,t,i,r,s=!1,n=!1,o=!1,u,l,c=!1,d=0;return Ri(a,({tag:f,type:p,value:h,valueSize:m})=>{if(f===21419){let b=ut(h,p);l=ss(b)}else f!==21420&&(l=void 0);return f===408125543?(e=h.byteOffset,t=h.byteOffset+m):f===357149030?s=!0:f===290298740?n=!0:f===2807729?i=ut(h,p):f===17545?r=ut(h,p):f===21420&&l===475249515?u=ut(h,p):f===374648427?Ri(h,({tag:b,type:S,value:y})=>b===30321?(c=ut(y,S)===1,!1):!0):s&&n&&(0,ns.default)(Xy,f)&&(o=!0),!o}),Cc(e,"Failed to parse webm Segment start"),Cc(t,"Failed to parse webm Segment end"),Cc(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}}}},sC=a=>{if(iC(a.cuesSeekPosition))return;let e=a.segmentStart+a.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},nC=(a,e)=>{let t=!1,i=!1,r=o=>Ky(o.time)&&Ky(o.position),s=[],n;return Ri(a,({tag:o,type:u,value:l})=>{switch(o){case 475249515:t=!0;break;case 187:n&&r(n)&&s.push(n),n={};break;case 179:n&&(n.time=ut(l,u));break;case 183:break;case 241:n&&(n.position=ut(l,u));break;default:t&&(0,ns.default)(Xy,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}}})},oC=a=>{let e=0,t=!1;try{Ri(a,i=>i.tag===524531317?i.tagSize<=a.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):(0,ns.default)(rC,i.tag)?(e+i.tagSize<=a.byteLength&&(e+=i.tagSize,t||(t=(0,ns.default)([163,160,175],i.tag))),!0):!1)}catch(i){}return e>0&&e<=a.byteLength&&t?new DataView(a.buffer,a.byteOffset,e):null},Jy={validateData:Yy,parseInit:aC,getIndexRange:sC,parseSegments:nC,parseFeedableSegmentChunk:oC};var Tt=a=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(a);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return Jy;case"mp4":return Gy}}throw new ReferenceError(`Unsupported mime type ${a}`)};var It=a=>a instanceof DOMException&&(a.name==="AbortError"||a.code===20);var Uc=O(TT(),1),jT=O(er(),1),HT=O(_T(),1),QT=O(ot(),1),qc=O(pr(),1);var OT=O(Ye(),1),Nc=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,OT.default)(["6E","7A","F4"],o)}}return!1};import{isNonNullable as oB,isNullable as UT}from"@vkontakte/videoplayer-shared/es2018";var FT=a=>{if(a.includes("/")){let e=a.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(a)};var NT=a=>{var e;try{let t=nB(),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 nB(){let a="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",c=`^(?:(?<langtag>${`
|
|
118
118
|
(?<language>${`(?:[a-z]{2,3}(?:-${a})?|[a-z]{4}|[a-z]{5,8})`})
|
|
119
119
|
(-(?<script>[a-z]{4}))?
|
|
120
120
|
(-(?<region>(?:[a-z]{2}|[0-9]{3})))?
|
|
121
121
|
(?<variants>(?:-(?:[a-z0-9]{5,8}|[0-9][a-z0-9]{3}))*)
|
|
122
122
|
(?<extensions>(?:-[0-9a-wy-z](?:-[a-z0-9]{2,8})+)*)
|
|
123
123
|
(?:-(?<privateuse>(?:${e})))?
|
|
124
|
-
`})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(d,"i")}var _T=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},ot=(a,e)=>{let t=a;t=(0,Oc.default)(t,"$$","$");let i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[r,s]of(0,OT.default)(i)){let n=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=(0,Oc.default)(t,n,(o,u)=>VT(s)?o:VT(u)?s:(0,FT.default)(s,parseInt(u,10),"0"))}return t},oo=(a,e)=>{var w,P,B,M,k,Q,O,A,_,R,E,C,ne,Oe,ie,Y,ge,Se,ve,Fe,Et,_t,si,_i,Fr,Kd,Xd,Jd,Zd,ep,tp,ip,rp,ap,sp,np,op,up,lp,cp,dp,pp,hp,fp,mp,bp,gp,Sp,vp,yp,Tp,Ip,Ep,xp,wp,Ap,Pp,Rp,kp,Lp,$p;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(Ze=>{var te,ni;return(ni=(te=Ze.textContent)==null?void 0:te.trim())!=null?ni:""}),o=(w=(0,NT.default)(n,0))!=null?w:"",u=s.getAttribute("type")==="dynamic",l=s.getAttribute("availabilityStartTime"),d=s.getAttribute("publishTime"),c=s.getElementsByTagName("vk:Attrs")[0],f=c==null?void 0:c.getElementsByTagName("vk:XLatestSegmentPublishTime")[0].textContent,p=c==null?void 0:c.getElementsByTagName("vk:XStreamIsLive")[0].textContent,h=c==null?void 0:c.getElementsByTagName("vk:XStreamIsUnpublished")[0].textContent,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:f?new Date(f).getTime():0,streamIsAlive:p==="yes",streamIsUnpublished:h==="yes"});let S,v=s.getAttribute("mediaPresentationDuration"),y=[...s.getElementsByTagName("Period")],I=y.reduce((Ze,te)=>({...Ze,[te.id]:te.children}),{}),T=y.reduce((Ze,te)=>({...Ze,[te.id]:te.getAttribute("duration")}),{});v?S=_T(v):(0,Fc.default)(T).filter(Ze=>Ze).length&&!u?S=(0,Fc.default)(T).reduce((Ze,te)=>{var ni;return Ze+((ni=_T(te))!=null?ni:0)},0):m&&(S=parseInt(m,10));let x=0,V=(B=(P=s.getAttribute("profiles"))==null?void 0:P.split(","))!=null?B:[];for(let Ze of y.map(te=>te.id))for(let te of I[Ze]){let ni=(M=te.getAttribute("id"))!=null?M:"id"+(x++).toString(10),Nr=(k=te.getAttribute("mimeType"))!=null?k:"",su=(Q=te.getAttribute("codecs"))!=null?Q:"",nu=(O=te.getAttribute("contentType"))!=null?O:Nr==null?void 0:Nr.split("/")[0],RE=(_=(A=te.getAttribute("profiles"))==null?void 0:A.split(","))!=null?_:[],Mp=(E=BT((R=te.getAttribute("lang"))!=null?R:""))!=null?E:{},Bs=(Oe=(ne=(C=te.querySelector("Label"))==null?void 0:C.textContent)==null?void 0:ne.trim())!=null?Oe:void 0,kE=te.querySelectorAll("Representation"),LE=te.querySelector("SegmentTemplate"),$E=(Y=(ie=te.querySelector("Role"))==null?void 0:ie.getAttribute("value"))!=null?Y:void 0,Oi=nu,ce={id:ni,language:Mp.language,isDefault:$E==="main",label:Bs,codecs:su,hdr:Oi==="video"&&_c(su),mime:Nr,representations:[]};for(let ee of kE){let Ot=(ge=ee.getAttribute("lang"))!=null?ge:void 0,Ur=(ve=(Se=Bs!=null?Bs:te.getAttribute("label"))!=null?Se:ee.getAttribute("label"))!=null?ve:void 0,Vs=(_t=(Et=(Fe=ee.querySelector("BaseURL"))==null?void 0:Fe.textContent)==null?void 0:Et.trim())!=null?_t:"",oi=new URL(Vs||o,e).toString(),Ft=(si=ee.getAttribute("mimeType"))!=null?si:Nr,_s=(Fr=(_i=ee.getAttribute("codecs"))!=null?_i:su)!=null?Fr:"",Os;if(nu==="text"){let Nt=ee.getAttribute("id")||"",Fs=((Kd=Mp.privateuse)==null?void 0:Kd.includes("x-auto"))||Nt.includes("_auto"),ui=ee.querySelector("SegmentTemplate");if(ui){let qr={representationId:(Xd=ee.getAttribute("id"))!=null?Xd:void 0,bandwidth:(Jd=ee.getAttribute("bandwidth"))!=null?Jd:void 0},Ns=parseInt((Zd=ee.getAttribute("bandwidth"))!=null?Zd:"",10)/1e3,Us=(tp=parseInt((ep=ui.getAttribute("startNumber"))!=null?ep:"",10))!=null?tp:1,Fi=parseInt((ip=ui.getAttribute("timescale"))!=null?ip:"",10),ou=(rp=ui.querySelectorAll("SegmentTimeline S"))!=null?rp:[],Ni=ui.getAttribute("media");if(!Ni)continue;let qs=[],Hs=0,js="",Ui=0,Hr=Us,we=0;for(let et of ou){let li=parseInt((ap=et.getAttribute("d"))!=null?ap:"",10),We=parseInt((sp=et.getAttribute("r"))!=null?sp:"",10)||0,Ut=parseInt((np=et.getAttribute("t"))!=null?np:"",10);we=Number.isFinite(Ut)?Ut:we;let ci=li/Fi*1e3,qt=we/Fi*1e3;for(let ct=0;ct<We+1;ct++){let Ht=ot(Ni,{...qr,segmentNumber:Hr.toString(10),segmentTime:(we+ct*li).toString(10)}),qi=(qt!=null?qt:0)+ct*ci,Qr=qi+ci;Hr++,qs.push({time:{from:qi,to:Qr},url:Ht})}we+=(We+1)*li,Hs+=(We+1)*ci}Ui=we/Fi*1e3,js=ot(Ni,{...qr,segmentNumber:Hr.toString(10),segmentTime:we.toString(10)});let jr={time:{from:Ui,to:1/0},url:js},xt={type:"template",baseUrl:oi,segmentTemplateUrl:Ni,initUrl:"",totalSegmentsDurationMs:Hs,segments:qs,nextSegmentBeyondManifest:jr,timescale:Fi};Os={id:Nt,kind:"text",segmentReference:xt,profiles:[],duration:S,bitrate:Ns,mime:"",codecs:"",width:0,height:0,isAuto:Fs}}else Os={id:Nt,isAuto:Fs,kind:"text",url:oi}}else{let Nt=(up=(op=ee.getAttribute("contentType"))!=null?op:Ft==null?void 0:Ft.split("/")[0])!=null?up:nu,Fs=(cp=(lp=te.getAttribute("profiles"))==null?void 0:lp.split(","))!=null?cp:[],ui=parseInt((dp=ee.getAttribute("width"))!=null?dp:"",10),qr=parseInt((pp=ee.getAttribute("height"))!=null?pp:"",10),Ns=parseInt((hp=ee.getAttribute("bandwidth"))!=null?hp:"",10)/1e3,Us=(fp=ee.getAttribute("frameRate"))!=null?fp:"",Fi=(mp=ee.getAttribute("quality"))!=null?mp:void 0,ou=Us?CT(Us):void 0,Ni=(bp=ee.getAttribute("id"))!=null?bp:"id"+(x++).toString(10),qs=Nt==="video"?`${qr}p`:Nt==="audio"?`${Ns}Kbps`:_s,Hs=`${Ni}@${qs}`,js=[...V,...RE,...Fs],Ui,Hr=ee.querySelector("SegmentBase"),we=(gp=ee.querySelector("SegmentTemplate"))!=null?gp:LE;if(Hr){let xt=(vp=(Sp=ee.querySelector("SegmentBase Initialization"))==null?void 0:Sp.getAttribute("range"))!=null?vp:"",[et,li]=xt.split("-").map(Ht=>parseInt(Ht,10)),We={from:et,to:li},Ut=(yp=ee.querySelector("SegmentBase"))==null?void 0:yp.getAttribute("indexRange"),[ci,qt]=Ut?Ut.split("-").map(Ht=>parseInt(Ht,10)):[],ct=Ut?{from:ci,to:qt}:void 0;Ui={type:"byteRange",url:oi,initRange:We,indexRange:ct}}else if(we){let xt={representationId:(Tp=ee.getAttribute("id"))!=null?Tp:void 0,bandwidth:(Ip=ee.getAttribute("bandwidth"))!=null?Ip:void 0},et=parseInt((Ep=we.getAttribute("timescale"))!=null?Ep:"",10),li=(xp=we.getAttribute("initialization"))!=null?xp:"",We=we.getAttribute("media"),Ut=(Ap=parseInt((wp=we.getAttribute("startNumber"))!=null?wp:"",10))!=null?Ap:1,ci=ot(li,xt);if(!We)throw new ReferenceError("No media attribute in SegmentTemplate");let qt=(Pp=we.querySelectorAll("SegmentTimeline S"))!=null?Pp:[],ct=[],Ht=0,qi="",Qr=0;if(qt.length){let Qs=Ut,tt=0;for(let Hi of qt){let dt=parseInt((Rp=Hi.getAttribute("d"))!=null?Rp:"",10),di=parseInt((kp=Hi.getAttribute("r"))!=null?kp:"",10)||0,Gs=parseInt((Lp=Hi.getAttribute("t"))!=null?Lp:"",10);tt=Number.isFinite(Gs)?Gs:tt;let uu=dt/et*1e3,lu=tt/et*1e3;for(let Ws=0;Ws<di+1;Ws++){let DE=ot(We,{...xt,segmentNumber:Qs.toString(10),segmentTime:(tt+Ws*dt).toString(10)}),Dp=(lu!=null?lu:0)+Ws*uu,CE=Dp+uu;Qs++,ct.push({time:{from:Dp,to:CE},url:DE})}tt+=(di+1)*dt,Ht+=(di+1)*uu}Qr=tt/et*1e3,qi=ot(We,{...xt,segmentNumber:Qs.toString(10),segmentTime:tt.toString(10)})}else if(eB(S)){let tt=parseInt(($p=we.getAttribute("duration"))!=null?$p:"",10)/et*1e3,Hi=Math.ceil(S/tt),dt=0;for(let di=1;di<Hi;di++){let Gs=ot(We,{...xt,segmentNumber:di.toString(10),segmentTime:dt.toString(10)});ct.push({time:{from:dt,to:dt+tt},url:Gs}),dt+=tt}Qr=dt,qi=ot(We,{...xt,segmentNumber:Hi.toString(10),segmentTime:dt.toString(10)})}let ME={time:{from:Qr,to:1/0},url:qi};Ui={type:"template",baseUrl:oi,segmentTemplateUrl:We,initUrl:ci,totalSegmentsDurationMs:Ht,segments:ct,nextSegmentBeyondManifest:ME,timescale:et}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Nt||!Ft)continue;let jr={video:"video",audio:"audio",text:"text"}[Nt];if(!jr)continue;Oi||(Oi=jr),Os={id:Hs,kind:jr,segmentReference:Ui,profiles:js,duration:S,bitrate:Ns,mime:Ft,codecs:_s,width:ui,height:qr,fps:ou,quality:Fi}}ce.language||(ce.language=Ot),ce.label||(ce.label=Ur),ce.mime||(ce.mime=Ft),ce.codecs||(ce.codecs=_s),ce.hdr||(ce.hdr=Oi==="video"&&_c(_s)),ce.representations.push(Os)}if(Oi){let ee=r[Oi].find(Ot=>Ot.id===ce.id);if(ee&&ce.representations.every(Ot=>Ot.segmentReference.type==="template"))for(let Ot of ee.representations){let Ur=ce.representations.find(Ft=>Ft.id===Ot.id),Vs=Ur==null?void 0:Ur.segmentReference,oi=Ot.segmentReference;oi.segments.push(...Vs.segments),oi.nextSegmentBeyondManifest=Vs.nextSegmentBeyondManifest}else r[Oi].push(ce)}}return{duration:S,streams:r,baseUrls:n,live:g}};var Nc=N(gt(),1);import{videoSizeToQuality as tB}from"@vkontakte/videoplayer-shared/es2018";var UT=({id:a,width:e,height:t,bitrate:i,fps:r,quality:s,streamId:n})=>{var u;let o=(u=s?Yt(s):void 0)!=null?u:tB({width:e,height:t});return o&&{id:a,quality:o,bitrate:i,size:{width:e,height:t},fps:r,streamId:n}},qT=({id:a,bitrate:e})=>({id:a,bitrate:e}),HT=({language:a,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),jT=({language:a,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),Uc=({id:a,language:e,label:t,codecs:i,isDefault:r})=>({id:a,language:e,label:t,codec:(0,Nc.default)(i.split("."),0),isDefault:r}),qc=({id:a,language:e,label:t,hdr:i,codecs:r})=>({id:a,language:e,hdr:i,label:t,codec:(0,Nc.default)(r.split("."),0)}),Hc=a=>"url"in a,je=a=>a.type==="template";import{isNonNullable as QT}from"@vkontakte/videoplayer-shared/es2018";var F=(a,e)=>QT(a)&&QT(e)&&a.readyState==="open"&&iB(a,e);function iB(a,e){for(let t=0;t<a.activeSourceBuffers.length;++t)if(a.activeSourceBuffers[t]===e)return!0;return!1}var ns=class{constructor(e,t,i,{fetcher:r,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new ki(0);this.currentLowLatencySegmentLength$=new ki(0);this.currentSegmentLength$=new ki(0);this.onLastSegment$=new ki(!1);this.fullyBuffered$=new ki(!1);this.playingRepresentation$=new ki(void 0);this.playingRepresentationInit$=new ki(void 0);this.error$=new aB;this.gaps=[];this.subscription=new sB;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new Z;this.switchAbortController=new Z;this.destroyAbortController=new Z;this.bufferLimit=1/0;this.failedDownloads=0;this.baseUrls=[];this.baseUrlsIndex=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.lastDataObtainedTimestampMs=0;this.loadByteRangeSegmentsTimeoutId=0;this.startWith=Jt(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);Ve(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new Ny(this.sourceBuffer),this.subscription.add(jc(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:$t.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o!=null||(o={id:"SegmentEjection",category:$t.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),this.error$.next(o)})),this.subscription.add(jc(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:$t.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o||!F(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,vr(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),s=this.parsedInitData.get(t.id);Ve(i,"No init buffer for starting representation"),Ve(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=Jt(this.destroyAbortController.signal,async function*(e,t=!1){if(!F(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);Ve(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if(Ee(s)||Ee(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),Ve(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!F(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer();else{let n=this.getCurrentPosition();xr(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=Jt(this.destroyAbortController.signal,async function*(e,t=!1){if(!F(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);Ve(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if(Ee(s)||Ee(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),Ve(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!F(this.mediaSource,this.sourceBuffer)))if(yield this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let n=this.getCurrentPosition();xr(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=Jt(this.destroyAbortController.signal,async function*(e){var u,l;let t=(u=(0,co.default)(e,d=>d.representations))!=null?u:[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let d of this.representations.keys()){let c=t.find(h=>h.id===d);c&&this.representations.set(d,c);let f=this.representations.get(d);if(!f||!je(f.segmentReference))return;let p=this.getActualLiveStartingSegments(f.segmentReference);this.segments.set(f.id,p)}let i=(l=this.switchingToRepresentationId)!=null?l:this.downloadingRepresentationId,r=this.representations.get(i);Ve(r);let s=this.segments.get(i);Ve(s,"No segments for starting representation");let n=this.initData.get(i);if(Ve(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 d;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=(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){!F(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new Z,Jt(this.switchAbortController.signal,async function*(i,r=!1){this.switchingToRepresentationId=i;let s=this.representations.get(i);Ve(s,`No such representation ${i}`);let n=this.segments.get(i),o=this.initData.get(i);if(Ee(o)||Ee(n)?yield this.loadInit(s,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(i),Ve(n,"No segments for starting representation"),o=this.initData.get(i),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer||!F(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(o,this.downloadAbortController.signal),r)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=i,yield this.dropBuffer();else{let u=this.getCurrentPosition();xr(u)&&!this.isLive&&(this.bufferLimit=this.forwardBufferTarget,yield this.pruneBuffer(u,1/0,!0)),this.downloadingRepresentationId=i,this.switchingToRepresentationId=void 0}this.maintain()}}.bind(this))(e,t))}warmUpMediaSource(){!Ee(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}async abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);return this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new Z,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(Ee(e)||Ee(this.downloadingRepresentationId)||Ee(this.playingRepresentationId)||Ee(this.sourceBuffer)||!F(this.mediaSource,this.sourceBuffer)||xr(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(Ve(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;let r=i.find(d=>e>=d.time.from&&e<d.time.to);xr(r)&&isFinite(r.time.from)&&isFinite(r.time.to)&&this.currentSegmentLength$.next((r==null?void 0:r.time.to)-r.time.from);let s=e,n=100;if(this.playingRepresentationId!==this.downloadingRepresentationId){let d=this.getForwardBufferDuration(e),c=r?r.time.to+n:-1/0;r&&r.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&d>=r.time.to-e+n&&(s=c)}if(isFinite(this.bufferLimit)&&vr(this.sourceBuffer.buffered)>=this.bufferLimit){let d=this.getForwardBufferDuration(e),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,d<c).catch(f=>{this.handleAsyncError(f,"pruneBuffer")});return}let u=[];if(!this.activeSegments.size&&(u=this.selectForwardBufferSegments(i,t.segmentReference.type,s),u.length)){let d="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if((0,lo.default)(u,r))d="high";else{let c=(0,wr.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,wr.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;xr(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,co.default)(e==null?void 0:e.streams[this.kind],r=>r.representations).find(r=>r.id===this.downloadingRepresentationId);if(!t)return;let i=this.segments.get(t.id);if(i!=null&&i.length)return{from:i[0].time.from,to:i[i.length-1].time.to}}updateLive(e){var i,r,s,n;let t=(i=(0,co.default)(e==null?void 0:e.streams[this.kind],o=>o.representations))!=null?i:[];if(![...this.segments.values()].every(o=>!o.length))for(let o of t){if(!o||!je(o.segmentReference))return;let u=o.segmentReference.segments.map(p=>({...p,status:"none",size:void 0})),l=100,d=(r=this.segments.get(o.id))!=null?r:[],c=(n=(s=(0,wr.default)(d,-1))==null?void 0:s.time.to)!=null?n:0,f=u==null?void 0:u.findIndex(p=>c>=p.time.from+l&&c<=p.time.to+l);if(f===-1){this.liveUpdateSegmentIndex=0;let p=this.getActualLiveStartingSegments(o.segmentReference);this.segments.set(o.id,p)}else{let p=u.slice(f+1);this.segments.set(o.id,[...d,...p])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;Ve(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(!je(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),d=ot(s.segmentTemplateUrl,{segmentTime:l});n.push({status:"none",time:{from:e.time.to,to:1/0},url:d})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){var s,n,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&&vt&&vt(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&vt&&vt(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}this.sourceBuffer=null,this.downloadAbortController.abort(),this.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,i){return this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){let i=e.findIndex(r=>t>=r.time.from&&t<r.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=i),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,i){let r=this.getForwardBufferDuration(i),s=e.findIndex(({status:f,time:{from:p,to:h}},m)=>{let g=p<=i&&h>=i,S=p>i||g||m===0&&i===0,v=Math.min(this.forwardBufferTarget,this.bufferLimit),y=this.preloadOnly&&p<=i+v||r<v&&h-p>=v||h<=i+v;return(f==="none"||f==="partially_ejected"&&S&&y&&this.sourceBuffer&&F(this.mediaSource,this.sourceBuffer)&&!(Ie(this.sourceBuffer.buffered,p)&&Ie(this.sourceBuffer.buffered,h)))&&S&&y});if(s===-1)return[];if(t!=="byteRange")return e.slice(s,s+1);let n=e,o=0,u=0,l=[],d=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,c=this.preloadOnly?this.forwardBufferTarget:0;for(let f=s;f<n.length&&(o<=d||u<=c);f++){let p=n[f];if(o+=p.byte.to+1-p.byte.from,u+=p.time.to+1-p.time.from,p.status==="none"||p.status==="partially_ejected")l.push(p);else break}return l}async loadSegments(e,t,i="auto"){je(t.segmentReference)?await this.loadTemplateSegment(e[0],t,i):await this.loadByteRangeSegments(e,t,i)}async loadTemplateSegment(e,t,i="auto"){e.status="downloading";let r={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(r);let{range:s,url:n,signal:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await Jt(o,async function*(){let d=Qc(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,d))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let d=await this.fetcher.fetch(n,{range:s,signal:o,onProgress:u,priority:i,isLowLatency:this.isActiveLowLatency()});if(this.lastDataObtainedTimestampMs=uo(),!d)return;let c=new DataView(d),f=yt(t.mime);if(!isFinite(r.segment.time.to)){let m=t.segmentReference.timescale;r.segment.time.to=f.getChunkEndTime(c,m)}u&&r.feedingBytes&&l?await Promise.all(l):await this.sourceBufferTaskQueue.append(c,o);let{serverDataReceivedTimestamp:p,serverDataPreparedTime:h}=f.getServerLatencyTimestamps(c);p&&h&&this.currentLiveSegmentServerLatency$.next(h-p),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(d){this.abortActiveSegments([e]),Tt(d)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}updateRepresentationsBaseUrlIfNeeded(){if(!this.tuning.dash.enableBaseUrlSupport||!this.baseUrls.length||this.failedDownloads<=this.tuning.dash.maxSegmentRetryCount)return;this.baseUrlsIndex=(this.baseUrlsIndex+1)%this.baseUrls.length;let e=this.baseUrls[this.baseUrlsIndex];for(let t of this.representations.values())je(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}async loadByteRangeSegments(e,t,i="auto"){if(!e.length)return;for(let u of e)u.status="downloading",this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:r,url:s,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(await Jt(n,async function*(){let u=Qc(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),jc(window,"online").pipe(rB()).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=uo(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),Tt(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(je(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:(0,wr.default)(e,0).byte.from,to:(0,wr.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=uo(),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:$t.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!je(t.segmentReference))throw new Error("Representation is not template type");let i=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&i.searchParams.set("low-latency","yes");let r=i.toString(),{signal:s}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,d)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=uo();let c=this.onSomeTemplateDataLoaded({dataView:l,loaded:d,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(c)}catch(c){this.error$.next({id:"SegmentFeeding",category:$t.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}}:void 0;return{url:r,signal:s,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,lo.default)(e,t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:s}){if(!this.activeSegments.size||!F(this.mediaSource,this.sourceBuffer))return;let n=this.representations.get(t);if(n)for(let o of this.activeSegments){let{segment:u}=o;if(o.representationId===t){if(s.aborted){r();continue}if(o.loadedBytes=i,o.loadedBytes>o.feedingBytes){let l=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),d=yt(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:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size||!F(this.mediaSource,this.sourceBuffer))return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){let{segment:l}=u;if(u.representationId!==t)continue;if(s.aborted){await n();continue}let d=l.byte.from-i,c=l.byte.to-i,f=c-d+1,p=d<r,h=c<=r;if(!p)continue;let m=yt(o.mime);if(l.status==="downloading"&&h){l.status="downloaded";let g=new DataView(e.buffer,e.byteOffset+d,f);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(f,r-d),u.loadedBytes>u.feedingBytes)){let g=new DataView(e.buffer,e.byteOffset+d+u.feedingBytes,u.loadedBytes-u.feedingBytes),S=u.loadedBytes===f?g:m.parseFeedableSegmentChunk(g);S!=null&&S.byteLength&&(l.status="partially_fed",u.feedingBytes+=S.byteLength,await this.sourceBufferTaskQueue.append(S,s)&&!s.aborted?(u.fedBytes+=S.byteLength,u.fedBytes===f&&this.onSegmentFullyAppended(u,t)):await n())}}}onSegmentFullyAppended(e,t){var i;if(!(Ee(this.sourceBuffer)||!F(this.mediaSource,this.sourceBuffer))){!this.isLive&&U.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(Ie(this.sourceBuffer.buffered,e.segment.time.from,100)&&Ie(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:$t.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",Hc(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=Sr(()=>(0,GT.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?Jt(this.destroyAbortController.signal,async function*(){let o=Qc(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,yt(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 f=d;this.isLive&&je(e.segmentReference)&&(f=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,f),u&&this.parsedInitData.set(e.id,u)}).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:$t.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n}async dropBuffer(){for(let e of this.segments.values())for(let t of e)t.status="none";await this.pruneBuffer(0,1/0,!0)}async pruneBuffer(e,t,i=!1){if(!this.sourceBuffer||!F(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||Ee(e))return!1;let r=[],s=0,n=u=>{u.sort((d,c)=>d.from-c.from);let l=[u[0]];for(let d=1;d<u.length;d++){let{from:c,to:f}=u[d],p=l[l.length-1];p.to>=c?p.to=Math.max(p.to,f):l.push(u[d])}return l},o=u=>{var d;if(s>=t)return r;r.push({...u.time}),r=n(r);let l=Hc(u)?(d=u.size)!=null?d:0:u.byte.to-u.byte.from;s+=l};for(let u of this.segments.values())for(let l of u){let d=l.time.to<=e-this.tuning.dash.bufferPruningSafeZone,c=l.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(d||c)&&l.status==="fed"&&o(l)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let l=this.sourceBuffer.buffered.start(u)*1e3,d=this.sourceBuffer.buffered.end(u)*1e3,c=0;for(let f of this.segments.values())for(let p of f)(0,lo.default)(["none","partially_ejected"],p.status)&&Math.round(p.time.from)<=Math.round(l)&&Math.round(p.time.to)>=Math.round(d)&&c++;if(c===this.segments.size){let f={time:{from:l,to:d},url:"",status:"none"};o(f)}}if(r.length&&i){let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let l of this.segments.values())for(let d of l)d.time.from>=e+u&&d.status==="fed"&&o(d)}return r.length?(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||!F(this.mediaSource,this.sourceBuffer))return!1;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;return this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!F(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}getForwardBufferDuration(e=this.getCurrentPosition()){return!this.sourceBuffer||!F(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||Ee(e)?0:me(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!(!this.sourceBuffer||!F(this.mediaSource,this.sourceBuffer))){if(this.tuning.useRefactoredSearchGap)for(let i=0;i<this.sourceBuffer.buffered.length;i++)this.gaps=this.gaps.filter(r=>this.sourceBuffer&&(Math.round(r.from)<Math.round(this.sourceBuffer.buffered.start(i)*1e3)||Math.round(r.to)>Math.round(this.sourceBuffer.buffered.end(i)*1e3)));for(let i of t){let r={representation:e,from:i.time.from,to:i.time.to};for(let s=0;s<this.sourceBuffer.buffered.length;s++){let n=this.sourceBuffer.buffered.start(s)*1e3,o=this.sourceBuffer.buffered.end(s)*1e3;if(!(o<=i.time.from||n>=i.time.to)){if(n<=i.time.from&&o>=i.time.to){r=void 0;break}o>i.time.from&&o<i.time.to&&(r.from=o),n<i.time.to&&n>i.time.from&&(r.to=n)}}r&&r.to-r.from>1&&!this.gaps.some(s=>r&&s.from===r.from&&s.to===r.to)&&this.gaps.push(r)}}}detectGapsWhenIdle(e,t){if(!(this.gapDetectionIdleCallback||!this.sourceBuffer||!F(this.mediaSource,this.sourceBuffer))){if(!this.tuning.useRefactoredSearchGap)for(let i=0;i<this.sourceBuffer.buffered.length;i++)this.gaps=this.gaps.filter(r=>this.sourceBuffer&&(Math.round(r.from)<Math.round(this.sourceBuffer.buffered.start(i)*1e3)||Math.round(r.to)>Math.round(this.sourceBuffer.buffered.end(i)*1e3)));this.gapDetectionIdleCallback=Sr(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:$t.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if(Ee(this.sourceBuffer)||!F(this.mediaSource,this.sourceBuffer)||Ee(this.playingRepresentationId))return;let e=[];for(let i=0;i<this.sourceBuffer.buffered.length;i++){let r=Math.floor(this.sourceBuffer.buffered.start(i)*1e3),s=Math.ceil(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:r,to:s})}let t=100;for(let i of this.segments.values())for(let r of i){let{status:s}=r;if(s!=="fed"&&s!=="partially_ejected")continue;let n=Math.floor(r.time.from),o=Math.ceil(r.time.to),u=e.some(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:$t.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}};var Zt=a=>{let e=new URL(a);return e.searchParams.set("quic","1"),e.toString()};var po=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 os,assertNever as WT,fromEvent as zT,merge as nB,now as us,Subscription as oB,Subject as YT,ValueSubject as Gc,flattenObject as Ar,ErrorCategory as ls}from"@vkontakte/videoplayer-shared/es2018";var ho=a=>{let e=new URL(a);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var mo=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:s=!1}){this.lastConnectionType$=new Gc(void 0);this.lastConnectionReused$=new Gc(void 0);this.lastRequestFirstBytes$=new Gc(void 0);this.recoverableError$=new YT;this.error$=new YT;this.abortAllController=new Z;this.subscription=new oB;this.fetchManifest=os(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=Zt(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=ho(i));let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(fo);return r?(t.log("success",Ar({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(r.headers),r.text()):(t.error("error",Ar({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=os(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 B,M;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 k=new URL(l,location.href);k.searchParams.append("bytes",`${i.from}-${i.to}`),l=k.toString();break}default:WT(t)}this.requestQuic&&(l=Zt(l));let f=this.abortAllController.signal,p;if(n){let k=new Z;if(p=nB(zT(this.abortAllController.signal,"abort"),zT(n,"abort")).subscribe(()=>{try{k.abort()}catch(Q){fo(Q)}}),this.subscription.add(p),this.abortAllController.signal.aborted||n.aborted)try{k.abort()}catch(Q){fo(Q)}f=k.signal}let h=us();c.log("startRequest",Ar({url:l,priority:s,rangeMethod:t,range:i,isLowLatency:u,requestStartedAt:h}));let m=yield this.doFetch(l,{priority:s,headers:d,signal:f}),g=us();if(!m)return c.error("error",{message:"No response in request"}),c.end(),p==null||p.unsubscribe(),null;if((B=this.throughputEstimator)==null||B.addRawRtt(g-h),!m.ok||!m.body){p==null||p.unsubscribe();let k=`Fetch error ${m.status}: ${m.statusText}`;return c.error("error",{message:k}),c.end(),Promise.reject(new Error(`Fetch error ${m.status}: ${m.statusText}`))}if(this.onHeadersReceived(m.headers),!r&&!o){p==null||p.unsubscribe();let k=us(),Q={requestStartedAt:h,requestEndedAt:k,duration:k-h};return c.log("endRequest",Ar(Q)),c.end(),m.arrayBuffer()}let[S,v]=m.body.tee(),y=S.getReader();o&&((M=this.throughputEstimator)==null||M.trackStream(v,u));let I=0,T=new Uint8Array(0),x=!1,V=k=>{p==null||p.unsubscribe(),x=!0,fo(k)},$=os(f,async function*({done:k,value:Q}){if(I===0&&this.lastRequestFirstBytes$.next(us()-h),f.aborted){p==null||p.unsubscribe();return}if(!k&&Q){let O=new Uint8Array(T.length+Q.length);O.set(T),O.set(Q,T.length),T=O,I+=Q.byteLength,r==null||r(new DataView(T.buffer),I),yield y==null?void 0:y.read().then($,V)}}.bind(this));yield y==null?void 0:y.read().then($,V),p==null||p.unsubscribe();let w=us(),P={failed:x,requestStartedAt:h,requestEndedAt:w,duration:w-h};return x?(c.error("endRequest",Ar(P)),c.end(),null):(c.log("endRequest",Ar(P)),c.end(),T.buffer)}.bind(this));this.fetchByteRangeRepresentation=os(this.abortAllController.signal,async function*(e,t,i){var S;if(e.type!=="byteRange")return null;let{from:r,to:s}=e.initRange,n=r,o=s,u=!1,l,d;e.indexRange&&(l=e.indexRange.from,d=e.indexRange.to,u=s+1===l,u&&(n=Math.min(l,r),o=Math.max(d,s))),n=Math.min(n,0);let c=yield this.fetch(e.url,{range:{from:n,to:o},priority:i,measureThroughput:!1});if(!c)return null;let f=new DataView(c,r-n,s-n+1);if(!t.validateData(f))throw new Error("Invalid media file");let p=t.parseInit(f),h=(S=e.indexRange)!=null?S:t.getIndexRange(p);if(!h)throw new ReferenceError("No way to load representation index");let m;if(u)m=new DataView(c,h.from-n,h.to-h.from+1);else{let v=yield this.fetch(e.url,{range:h,priority:i,measureThroughput:!1});if(!v)return null;m=new DataView(v)}let g=t.parseSegments(m,p,h);return{init:p,dataView:new DataView(c),segments:g}}.bind(this));this.fetchTemplateRepresentation=os(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}=po(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:WT(r)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}async doFetch(e,t){let i=await Je(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:ls.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:ls.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:ls.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:ls.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${s})`,category:ls.FATAL})}}},fo=a=>{if(!Tt(a))throw a};var Mt=(a,e,t)=>t*e+(1-t)*a,Wc=(a,e)=>a.reduce((t,i)=>t+i,0)/e,KT=(a,e,t,i)=>{let r=0,s=t,n=Wc(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 uB,ValueSubject as XT}from"@vkontakte/videoplayer-shared/es2018";var ei=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 XT(e.initial),this.debounced$=new XT(e.initial);let t=(i=e.label)!=null?i:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new Pe(`raw_${t}`),this.smoothedSeries$=new Pe(`smoothed_${t}`),this.reportedSeries$=new Pe(`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)&&(uB(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 bo=class extends ei{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=Mt(this.slow,e,this.params.emaAlphaSlow),this.fast=Mt(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var go=class extends ei{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=Wc(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Mt(this.emaSmoothed,e,this.params.emaAlpha);let i=KT(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}};var So=class extends ei{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?Mt(this.smoothed,t,this.params.emaAlpha):t}};var Dt=class{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new bo({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new go({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 So({initial:e,label:"liveEdgeDelay",...t})}};var Pr=(a,e)=>{a&&a.playbackRate!==e&&(a.playbackRate=e)};import{isNullable as lB,ValueSubject as cB}from"@vkontakte/videoplayer-shared/es2018";var cs=class a{constructor(e,t){this.currentRepresentation$=new cB(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(!lB(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(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,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&&je(t.segmentReference))}};var yo=N(gt(),1);import{assertNever as To}from"@vkontakte/videoplayer-shared/es2018";var JT=(a,{useManagedMediaSource:e,useOldMSEDetection:t})=>{let{containers:i,protocols:r,codecs:s,nativeHlsSupported:n}=U.video,o=(s.h264||s.h265)&&s.aac,u=r.mse&&(!t||!!window.MediaStreamTrack)||r.mms&&e;return a.filter(l=>{switch(l){case"DASH_SEP":return u&&i.mp4&&o;case"DASH_WEBM":return u&&i.webm&&s.vp9&&s.opus;case"DASH_WEBM_AV1":return u&&i.webm&&s.av1&&s.opus;case"DASH_STREAMS":return u&&(i.mp4&&o||i.webm&&(s.vp9||s.av1)&&(s.opus||s.aac));case"DASH_LIVE":return u&&i.mp4&&o;case"DASH_LIVE_CMAF":return u&&i.mp4&&o&&i.cmaf;case"DASH_ONDEMAND":return u&&i.mp4&&o;case"HLS":case"HLS_ONDEMAND":case"HLS_LIVE":case"HLS_LIVE_CMAF":return n;case"MPEG":return i.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return r.webrtc&&r.ws&&s.h264&&(i.mp4||i.webm);default:return To(l)}})},vo=a=>{let{webmDecodingInfo:e}=U.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:To(a)}return[t,i]},ZT=({webmCodec:a,androidPreferredFormat:e,preferMultiStream:t})=>{let i=[...t?["DASH_STREAMS"]:[],...vo(a),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],r=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(U.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",...vo(a),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...vo(a),"MPEG",...r,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...vo(a),...r,"HLS","HLS_ONDEMAND"];default:To(e)}return U.video.nativeHlsSupported?[...i,"HLS","HLS_ONDEMAND","MPEG"]:[...i,"HLS","HLS_ONDEMAND","MPEG"]},eI=({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=U.device.isMac&&U.browser.isSafari;if(U.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:To(a)}else U.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"]},zc=a=>a?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],Io=a=>{if(a.size===0)return;if(a.size===1){let t=a.values().next();return(0,yo.default)(t.value.split("."),0)}for(let t of a){let i=(0,yo.default)(t.split("."),0);if(i==="opus"||i==="vp09"||i==="av01")return i}let e=a.values().next();return(0,yo.default)(e.value.split("."),0)};var SB=["timeupdate","progress","play","seeked","stalled","waiting"],vB=["timeupdate","progress","loadeddata","playing","seeked"];var wo=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new rI;this.representationSubscription=new rI;this.state$=new H("none");this.currentVideoRepresentation$=new ae(void 0);this.currentVideoRepresentationInit$=new ae(void 0);this.currentAudioRepresentation$=new ae(void 0);this.currentVideoSegmentLength$=new ae(0);this.currentAudioSegmentLength$=new ae(0);this.error$=new xo;this.lastConnectionType$=new ae(void 0);this.lastConnectionReused$=new ae(void 0);this.lastRequestFirstBytes$=new ae(void 0);this.currentLiveTextRepresentation$=new ae(null);this.isLive$=new ae(!1);this.isActiveLive$=new ae(!1);this.isLowLatency$=new ae(!1);this.liveDuration$=new ae(0);this.liveSeekableDuration$=new ae(0);this.liveAvailabilityStartTime$=new ae(0);this.liveStreamStatus$=new ae(void 0);this.bufferLength$=new ae(0);this.liveLatency$=new ae(void 0);this.liveLoadBufferLength$=new ae(0);this.livePositionFromPlayer$=new ae(0);this.currentStallDuration$=new ae(0);this.videoLastDataObtainedTimestamp$=new ae(0);this.fetcherRecoverableError$=new xo;this.fetcherError$=new xo;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new xo;this.gapWatchdogActive=!1;this.destroyController=new Z;this.initManifest=Kc(this.destroyController.signal,async function*(e,t,i){var r;this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=le(t,i,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),(r=this.manifest)!=null&&r.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:ut.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=Kc(this.destroyController.signal,async function*(){var n,o;this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(u=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:ut.NETWORK,message:"Failed to load manifest",thrown:u})});if(!e)return null;let t=null;try{t=oo(e!=null?e:"",this.manifestUrlString)}catch(u){let l=(n=no(e))!=null?n:{id:"ManifestParsing",category:ut.PARSER,message:"Failed to parse MPD manifest",thrown:u};this.error$.next(l)}if(!t)return null;let i=(u,l,d)=>{var c,f,p,h;return!!((f=(c=this.element)==null?void 0:c.canPlayType)!=null&&f.call(c,l)&&((h=(p=He())==null?void 0:p.isTypeSupported)!=null&&h.call(p,`${l}; codecs="${d}"`))||u==="text")};if(t.live){this.isLive$.next(!!t.live);let{availabilityStartTime:u,latestSegmentPublishTime:l,streamIsUnpublished:d,streamIsAlive:c}=t.live,f=((o=t.duration)!=null?o:0)/1e3;this.liveSeekableDuration$.next(-1*f),this.liveDuration$.next((l-u)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let p="active";c||(p=d?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(p)}let r={text:t.streams.text,video:[],audio:[]};for(let u of["video","audio"]){let d=t.streams[u].filter(({mime:p,codecs:h})=>i(u,p,h)),c=new Set(d.map(({codecs:p})=>p)),f=Io(c);if(f&&(r[u]=d.filter(({codecs:p})=>p.startsWith(f))),u==="video"){let p=this.tuning.preferHDR,h=r.video.some(g=>g.hdr),m=r.video.some(g=>!g.hdr);U.display.isHDR&&p&&h?r.video=r.video.filter(g=>g.hdr):m&&(r.video=r.video.filter(g=>!g.hdr))}}let s={...t,streams:r};return this.tracer.log("updateManifestEnd",ps(s)),s}.bind(this));this.initRepresentations=Kc(this.destroyController.signal,async function*(e,t,i){var f;this.tracer.log("initRepresentationsStart",ps({initialVideo:e,initialAudio:t,sourceHls:i})),Rr(this.manifest),Rr(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let r=p=>{this.representationSubscription.add(Ct(p,"error").pipe(Eo(h=>{var m;return!!((m=this.element)!=null&&m.played.length)})).subscribe(h=>{this.error$.next({id:"VideoSource",category:ut.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=this.tuning.useManagedMediaSource?Vn():new MediaSource;let s=document.createElement("source");if(r(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&cr())if(i){let p=document.createElement("source");r(p),p.type="application/x-mpegurl",p.src=i.url,this.element.appendChild(p)}else this.element.disableRemotePlayback=!0;this.isActiveLive$.next(this.isLive$.getValue());let n={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),manifest:this.manifest},o=this.manifest.streams.video.reduce((p,h)=>[...p,...h.representations],[]);if(this.videoBufferManager=new ns("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],hs(t)){let p=this.manifest.streams.audio.reduce((h,m)=>[...h,...m.representations],[]);this.audioBufferManager=new ns("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}cs.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new cs(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(Li(...vB.map(p=>Ct(this.element,p))).pipe(Lr(p=>this.element?me(this.element.buffered,this.element.currentTime*1e3):0),ds(),bB(p=>{p>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add(Li(Ct(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe(ds()).subscribe(h=>this.liveStreamEndTimestamp=Jc())),this.subscription.add(Ct(this.element,"pause").subscribe(()=>{this.livePauseWatchdogSubscription=Xc(1e3).subscribe(h=>{let m=Wt(this.manifestUrlString,2);this.manifestUrlString=le(this.manifestUrlString,m+1e3,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add(Ct(this.element,"play").subscribe(h=>{var m;return(m=this.livePauseWatchdogSubscription)==null?void 0:m.unsubscribe()})),this.representationSubscription.add(kr({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(Lr(({isActiveLive:h,isLowLatency:m})=>h&&m),ds()).subscribe(h=>{this.isManualDecreasePlaybackInLive()||Pr(this.element,1)})),this.representationSubscription.add(kr({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(Eo(({bufferLength:h,isActiveLive:m,isLowLatency:g})=>m&&g&&!!h)).subscribe(({bufferLength:h})=>this.liveBuffer.next(h))),this.representationSubscription.add(this.videoBufferManager.currentLowLatencySegmentLength$.subscribe(h=>{if(!this.isActiveLive$.getValue()&&!this.isLowLatency$.getValue()&&!h)return;let m=this.liveSeekableDuration$.getValue()-h/1e3;this.liveSeekableDuration$.next(Math.max(m,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+h/1e3)})),this.representationSubscription.add(kr({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(Eo(({isLive:h})=>h),ds((h,m)=>m.bufferLength<h.bufferLength),Lr(({rtt:h,bufferLength:m,segmentServerLatency:g})=>{let S=Wt(this.manifestUrlString,2);return(h/2+m+g+S)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(kr({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:h,isActiveLive:m,isLowLatency:g})=>{if(!g||!m)return;let S=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,v=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,y=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,I=h-S;if(this.isManualDecreasePlaybackInLive())return;let T=1;Math.abs(I)>v&&(T=1+Math.sign(I)*y),Pr(this.element,T)})),this.representationSubscription.add(this.bufferLength$.subscribe(h=>{var g,S;let m=0;if(h){let v=((S=(g=this.element)==null?void 0:g.currentTime)!=null?S:0)*1e3;m=Math.min(...this.bufferManagers.map(I=>{var T,x;return(x=(T=I.getLiveSegmentsToLoadState(this.manifest))==null?void 0:T.to)!=null?x:v}))-v}this.liveLoadBufferLength$.getValue()!==m&&this.liveLoadBufferLength$.next(m)}));let p=0;this.representationSubscription.add(kr({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(gB(1e3)).subscribe(async({liveLoadBufferLength:h,bufferLength:m})=>{if(!this.element||this.isUpdatingLive)return;let g=this.element.playbackRate,S=Wt(this.manifestUrlString,2),v=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,y=Math.min(v,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*g),I=this.tuning.dashCmafLive.normalizedActualBufferOffset*g,T=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*g,x=isFinite(h)?h:m,V=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),$=v<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next($);let w="none";if(V?w="active_low_latency":this.isLowLatency$.getValue()&&$?(this.bufferManagers.forEach(P=>P.proceedLowLatencyLive()),w="active_low_latency"):S!==0&&x<y?w="live_forward_buffering":x<y+T&&(w="live_with_target_offset"),isFinite(h)&&(p=h>p?h:p),w==="live_forward_buffering"||w==="live_with_target_offset"){let P=p-(y+I),B=this.normolizeLiveOffset(Math.trunc(S+P/g)),M=Math.abs(B-S),k=0;!h||M<=this.tuning.dashCmafLive.offsetCalculationError?k=S:B>0&&M>this.tuning.dashCmafLive.offsetCalculationError&&(k=B),this.manifestUrlString=le(this.manifestUrlString,k,2)}(w==="live_with_target_offset"||w==="live_forward_buffering")&&(p=0,await this.updateLive())},h=>{this.error$.next({id:"updateLive",category:ut.VIDEO_PIPELINE,thrown:h,message:"Failed to update live with subscription"})}))}let l=Li(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe(Lr(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),d=Li(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe(Lr(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue()))),c=kr({allBuffersFull:l,someBufferEnded:d}).pipe(ds(),Lr(({allBuffersFull:p,someBufferEnded:h})=>p&&h),Eo(p=>p));if(this.representationSubscription.add(Li(this.forceEnded$,c).subscribe(()=>{var p;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(h=>!h.updating))try{(p=this.source)==null||p.endOfStream()}catch(h){this.error$.next({id:"EndOfStream",category:ut.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:h})}})),this.representationSubscription.add(Li(...this.bufferManagers.map(p=>p.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.representationSubscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.representationSubscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.liveTextManager&&this.representationSubscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$)),this.source.readyState!=="open"){let p=this.tuning.dash.sourceOpenTimeout>=0;yield new Promise(h=>{var m;p&&(this.timeoutSourceOpenId=setTimeout(()=>{var g;if(((g=this.source)==null?void 0:g.readyState)==="open"){h();return}this.error$.next({id:"OpenOfStream",category:ut.VIDEO_PIPELINE,message:"Failed to open MediaSource",thrown:new Error("Timeout reject when wait sourceopen event"),traceAsLog:!0})},this.tuning.dash.sourceOpenTimeout)),(m=this.source)==null||m.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),h()},{once:!0})})}if(!this.isLive$.getValue()){let p=[(f=this.manifest.duration)!=null?f:0,...(0,Zc.default)((0,Zc.default)([...this.manifest.streams.audio,...this.manifest.streams.video],h=>h.representations),h=>{let m=[];return h.duration&&m.push(h.duration),je(h.segmentReference)&&h.segmentReference.totalSegmentsDurationMs&&m.push(h.segmentReference.totalSegmentsDurationMs),m})];this.source.duration=Math.max(...p)/1e3}this.audioBufferManager&&hs(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=Xc(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),n=>{this.error$.next({id:"GapWatchdog",category:ut.WTF,message:"Error handling gaps",thrown:n})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.fetcher=new mo({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=Dt.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator}),this.initTracerSubscription()}async seekLive(e){var r,s,n;Rr(this.element);let t=this.liveStreamStatus$.getValue()!=="active"?Jc()-this.liveStreamEndTimestamp:0,i=this.normolizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=le(this.manifestUrlString,i,2),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await((r=this.videoBufferManager)==null?void 0:r.seekLive(this.manifest.streams.video)),await((s=this.audioBufferManager)==null?void 0:s.seekLive(this.manifest.streams.audio)),(n=this.liveTextManager)==null||n.seekLive(this.manifest.streams.text))}initBuffer(){Rr(this.element),this.state$.setState("running"),this.subscription.add(Li(...SB.map(e=>Ct(this.element,e)),Ct(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:ut.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(Ct(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(Ct(this.element,"waiting").subscribe(()=>{var t;this.element&&this.element.readyState===2&&!this.element.seeking&&Ie(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{var p,h,m,g,S,v,y,I,T,x,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},s=Jc(),n=100,o=(m=(h=this.videoBufferManager)==null?void 0:h.lastDataObtainedTimestamp)!=null?m:0;this.videoLastDataObtainedTimestamp$.next(o);let u=(S=(g=this.audioBufferManager)==null?void 0:g.lastDataObtainedTimestamp)!=null?S:0,l=(y=(v=this.videoBufferManager)==null?void 0:v.getForwardBufferDuration())!=null?y:0,d=(T=(I=this.audioBufferManager)==null?void 0:I.getForwardBufferDuration())!=null?T:0,c=l<n&&s-o>this.tuning.dash.crashOnStallTWithoutDataTimeout,f=this.audioBufferManager&&d<n&&s-u>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((c||f)&&i>this.tuning.dash.crashOnStallTWithoutDataTimeout||i>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${i} ms`);if(this.isLive$.getValue()&&i%2e3===0){let $=this.normolizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive($).catch(w=>{this.error$.next({id:"stallIntervalCallback",category:ut.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:w})}),r.liveLastOffset=$}else{let $=this.element.currentTime*1e3;(x=this.videoBufferManager)==null||x.maintain($),(V=this.audioBufferManager)==null||V.maintain($),r.position=$}this.tracer.log("stallIntervalCallback",ps(r))};(t=this.stallWatchdogSubscription)==null||t.unsubscribe(),this.stallWatchdogSubscription=Xc(50).subscribe(e,i=>{this.error$.next({id:"StallWatchdogCallback",category:ut.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;Rr(this.element),Rr(this.videoBufferManager);let i;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?i=e:i=Math.max((r=this.videoBufferManager.findSegmentStartTime(e))!=null?r:e,(n=(s=this.audioBufferManager)==null?void 0:s.findSegmentStartTime(e))!=null?n:e),this.warmUpMediaSourceIfNeeded(i),Ie(this.element.buffered,i)||await Promise.all([this.videoBufferManager.abort(),(o=this.audioBufferManager)==null?void 0:o.abort()]),!(iI(this.element)||iI(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),(u=this.audioBufferManager)==null||u.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",ps({requestedPosition:e,forcePrecise:t,position:i})))}warmUpMediaSourceIfNeeded(e=(t=>(t=this.element)==null?void 0:t.currentTime)()){var i;hs(this.element)&&hs(this.source)&&hs(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=mB(this.tracer.error.bind(this.tracer));this.subscription.add(this.error$.subscribe(e("error")))}isManualDecreasePlaybackInLive(){if(!this.element||!this.isLive$.getValue())return!1;let e=1-this.element.playbackRate;return Number(e.toFixed(2))>Number(this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup.toFixed(2))}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){var e,t;this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&((e=this.bufferManagers)==null||e.forEach(i=>i.updateLive(this.manifest)),(t=this.liveTextManager)==null||t.updateLive(this.manifest)),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getDebugBufferState();if(!e)return;let t=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),i={isJumpGapAfterSeekLive:this.isJumpGapAfterSeekLive,isActiveLowLatency:t,initialCurrentTime:this.element.currentTime};this.isJumpGapAfterSeekLive&&!t&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let r=this.element.currentTime*1e3,s=[],n=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let o of this.bufferManagers)for(let u of o.gaps)o.playingRepresentation$.getValue()===u.representation&&u.from-n<=r&&u.to+n>r&&(this.element.duration*1e3-u.to<this.tuning.endGapTolerance?s.push(1/0):s.push(u.to));if(s.length){let o=Math.max(...s)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,o===1/0?this.forceEnded$.next():(this.element.currentTime=o/1e3,i={...i,gapEnds:s,jumpTo:o,resultCurrentTime:this.element.currentTime},this.tracer.log("jumpGap",ps(i)))}}};var Ao=class{constructor(e,t){this.fov=e,this.orientation=t}};var Po=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 sI=`attribute vec2 a_vertex;
|
|
124
|
+
`})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(c,"i")}var qT=a=>{if(!(a!=null&&a.startsWith("P")))return;let e=(n,o)=>{let u=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(u)?0:u)*o},i=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(a),r=(i==null?void 0:i[1])==="-"?-1:1,s={days:e(i==null?void 0:i[5],r),hours:e(i==null?void 0:i[6],r),minutes:e(i==null?void 0:i[7],r),seconds:e(i==null?void 0:i[8],r)};return s.days*24*60*60*1e3+s.hours*60*60*1e3+s.minutes*60*1e3+s.seconds*1e3},lt=(a,e)=>{let t=a;t=(0,Uc.default)(t,"$$","$");let i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[r,s]of(0,jT.default)(i)){let n=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=(0,Uc.default)(t,n,(o,u)=>UT(s)?o:UT(u)?s:(0,HT.default)(s,parseInt(u,10),"0"))}return t},lo=(a,e)=>{var P,k,V,D,_,Y,J,T,R,x,w,B,ne,Fe,ie,W,ge,Se,ve,Ne,xt,Ot,ni,Ni,Nr,ep,tp,ip,rp,ap,sp,np,op,up,lp,cp,dp,pp,hp,fp,mp,bp,gp,Sp,vp,yp,Tp,Ip,Ep,xp,wp,Ap,Pp,kp,Rp,Lp,$p,Mp,Dp,Cp,Bp;let i=new DOMParser().parseFromString(a,"application/xml"),r={video:[],audio:[],text:[]},s=i.children[0],n=Array.from(s.querySelectorAll("MPD > BaseURL").values()).map(et=>{var te,oi;return(oi=(te=et.textContent)==null?void 0:te.trim())!=null?oi:""}),o=(P=(0,QT.default)(n,0))!=null?P:"",u=s.getAttribute("type")==="dynamic",l=s.getAttribute("availabilityStartTime"),c=s.getAttribute("publishTime"),d=s.getElementsByTagName("vk:Attrs")[0],f=d==null?void 0:d.getElementsByTagName("vk:XLatestSegmentPublishTime")[0].textContent,p=d==null?void 0:d.getElementsByTagName("vk:XStreamIsLive")[0].textContent,h=d==null?void 0:d.getElementsByTagName("vk:XStreamIsUnpublished")[0].textContent,m=d==null?void 0:d.getElementsByTagName("vk:XPlaybackDuration")[0].textContent,b;u&&(b={availabilityStartTime:l?new Date(l).getTime():0,publishTime:c?new Date(c).getTime():0,latestSegmentPublishTime:f?new Date(f).getTime():0,streamIsAlive:p==="yes",streamIsUnpublished:h==="yes"});let S,y=s.getAttribute("mediaPresentationDuration"),v=[...s.getElementsByTagName("Period")],I=v.reduce((et,te)=>({...et,[te.id]:te.children}),{}),E=v.reduce((et,te)=>({...et,[te.id]:te.getAttribute("duration")}),{});y?S=qT(y):(0,qc.default)(E).filter(et=>et).length&&!u?S=(0,qc.default)(E).reduce((et,te)=>{var oi;return et+((oi=qT(te))!=null?oi:0)},0):m&&(S=parseInt(m,10));let A=0,M=(V=(k=s.getAttribute("profiles"))==null?void 0:k.split(","))!=null?V:[];for(let et of v.map(te=>te.id))for(let te of I[et]){let oi=(D=te.getAttribute("id"))!=null?D:"id"+(A++).toString(10),Ur=(_=te.getAttribute("mimeType"))!=null?_:"",nu=(Y=te.getAttribute("codecs"))!=null?Y:"",ou=(J=te.getAttribute("contentType"))!=null?J:Ur==null?void 0:Ur.split("/")[0],CE=(R=(T=te.getAttribute("profiles"))==null?void 0:T.split(","))!=null?R:[],Vp=(w=NT((x=te.getAttribute("lang"))!=null?x:""))!=null?w:{},Vs=(Fe=(ne=(B=te.querySelector("Label"))==null?void 0:B.textContent)==null?void 0:ne.trim())!=null?Fe:void 0,BE=te.querySelectorAll("Representation"),VE=te.querySelector("SegmentTemplate"),_E=(W=(ie=te.querySelector("Role"))==null?void 0:ie.getAttribute("value"))!=null?W:void 0,Ui=ou,ce={id:oi,language:Vp.language,isDefault:_E==="main",label:Vs,codecs:nu,hdr:Ui==="video"&&Nc(nu),mime:Ur,representations:[]};for(let ee of BE){let Ft=(ge=ee.getAttribute("lang"))!=null?ge:void 0,qr=(ve=(Se=Vs!=null?Vs:te.getAttribute("label"))!=null?Se:ee.getAttribute("label"))!=null?ve:void 0,_s=(Ot=(xt=(Ne=ee.querySelector("BaseURL"))==null?void 0:Ne.textContent)==null?void 0:xt.trim())!=null?Ot:"",ui=new URL(_s||o,e).toString(),Nt=(ni=ee.getAttribute("mimeType"))!=null?ni:Ur,Os=(Nr=(Ni=ee.getAttribute("codecs"))!=null?Ni:nu)!=null?Nr:"",Fs;if(ou==="text"){let Ut=ee.getAttribute("id")||"",Ns=((ep=Vp.privateuse)==null?void 0:ep.includes("x-auto"))||Ut.includes("_auto"),li=ee.querySelector("SegmentTemplate");if(li){let jr={representationId:(tp=ee.getAttribute("id"))!=null?tp:void 0,bandwidth:(ip=ee.getAttribute("bandwidth"))!=null?ip:void 0},Us=parseInt((rp=ee.getAttribute("bandwidth"))!=null?rp:"",10)/1e3,qs=(sp=parseInt((ap=li.getAttribute("startNumber"))!=null?ap:"",10))!=null?sp:1,qi=parseInt((np=li.getAttribute("timescale"))!=null?np:"",10),uu=(op=li.querySelectorAll("SegmentTimeline S"))!=null?op:[],ji=li.getAttribute("media");if(!ji)continue;let js=[],Hs=0,Qs="",Hi=0,Hr=qs,we=0;for(let tt of uu){let ci=parseInt((up=tt.getAttribute("d"))!=null?up:"",10),ze=parseInt((lp=tt.getAttribute("r"))!=null?lp:"",10)||0,qt=parseInt((cp=tt.getAttribute("t"))!=null?cp:"",10);we=Number.isFinite(qt)?qt:we;let di=ci/qi*1e3,jt=we/qi*1e3;for(let pt=0;pt<ze+1;pt++){let Ht=lt(ji,{...jr,segmentNumber:Hr.toString(10),segmentTime:(we+pt*ci).toString(10)}),Qi=(jt!=null?jt:0)+pt*di,Gr=Qi+di;Hr++,js.push({time:{from:Qi,to:Gr},url:Ht})}we+=(ze+1)*ci,Hs+=(ze+1)*di}Hi=we/qi*1e3,Qs=lt(ji,{...jr,segmentNumber:Hr.toString(10),segmentTime:we.toString(10)});let Qr={time:{from:Hi,to:1/0},url:Qs},wt={type:"template",baseUrl:ui,segmentTemplateUrl:ji,initUrl:"",totalSegmentsDurationMs:Hs,segments:js,nextSegmentBeyondManifest:Qr,timescale:qi};Fs={id:Ut,kind:"text",segmentReference:wt,profiles:[],duration:S,bitrate:Us,mime:"",codecs:"",width:0,height:0,isAuto:Ns}}else Fs={id:Ut,isAuto:Ns,kind:"text",url:ui}}else{let Ut=(pp=(dp=ee.getAttribute("contentType"))!=null?dp:Nt==null?void 0:Nt.split("/")[0])!=null?pp:ou,Ns=(fp=(hp=te.getAttribute("profiles"))==null?void 0:hp.split(","))!=null?fp:[],li=parseInt((mp=ee.getAttribute("width"))!=null?mp:"",10),jr=parseInt((bp=ee.getAttribute("height"))!=null?bp:"",10),Us=parseInt((gp=ee.getAttribute("bandwidth"))!=null?gp:"",10)/1e3,qs=(Sp=ee.getAttribute("frameRate"))!=null?Sp:"",qi=(vp=ee.getAttribute("quality"))!=null?vp:void 0,uu=qs?FT(qs):void 0,ji=(yp=ee.getAttribute("id"))!=null?yp:"id"+(A++).toString(10),js=Ut==="video"?`${jr}p`:Ut==="audio"?`${Us}Kbps`:Os,Hs=`${ji}@${js}`,Qs=[...M,...CE,...Ns],Hi,Hr=ee.querySelector("SegmentBase"),we=(Tp=ee.querySelector("SegmentTemplate"))!=null?Tp:VE;if(Hr){let wt=(Ep=(Ip=ee.querySelector("SegmentBase Initialization"))==null?void 0:Ip.getAttribute("range"))!=null?Ep:"",[tt,ci]=wt.split("-").map(Ht=>parseInt(Ht,10)),ze={from:tt,to:ci},qt=(xp=ee.querySelector("SegmentBase"))==null?void 0:xp.getAttribute("indexRange"),[di,jt]=qt?qt.split("-").map(Ht=>parseInt(Ht,10)):[],pt=qt?{from:di,to:jt}:void 0;Hi={type:"byteRange",url:ui,initRange:ze,indexRange:pt}}else if(we){let wt={representationId:(wp=ee.getAttribute("id"))!=null?wp:void 0,bandwidth:(Ap=ee.getAttribute("bandwidth"))!=null?Ap:void 0},tt=parseInt((Pp=we.getAttribute("timescale"))!=null?Pp:"",10),ci=(kp=we.getAttribute("initialization"))!=null?kp:"",ze=we.getAttribute("media"),qt=(Lp=parseInt((Rp=we.getAttribute("startNumber"))!=null?Rp:"",10))!=null?Lp:1,di=lt(ci,wt);if(!ze)throw new ReferenceError("No media attribute in SegmentTemplate");let jt=($p=we.querySelectorAll("SegmentTimeline S"))!=null?$p:[],pt=[],Ht=0,Qi="",Gr=0;if(jt.length){let Gs=qt,it=0;for(let Gi of jt){let ht=parseInt((Mp=Gi.getAttribute("d"))!=null?Mp:"",10),pi=parseInt((Dp=Gi.getAttribute("r"))!=null?Dp:"",10)||0,Ws=parseInt((Cp=Gi.getAttribute("t"))!=null?Cp:"",10);it=Number.isFinite(Ws)?Ws:it;let lu=ht/tt*1e3,cu=it/tt*1e3;for(let zs=0;zs<pi+1;zs++){let FE=lt(ze,{...wt,segmentNumber:Gs.toString(10),segmentTime:(it+zs*ht).toString(10)}),_p=(cu!=null?cu:0)+zs*lu,NE=_p+lu;Gs++,pt.push({time:{from:_p,to:NE},url:FE})}it+=(pi+1)*ht,Ht+=(pi+1)*lu}Gr=it/tt*1e3,Qi=lt(ze,{...wt,segmentNumber:Gs.toString(10),segmentTime:it.toString(10)})}else if(oB(S)){let it=parseInt((Bp=we.getAttribute("duration"))!=null?Bp:"",10)/tt*1e3,Gi=Math.ceil(S/it),ht=0;for(let pi=1;pi<Gi;pi++){let Ws=lt(ze,{...wt,segmentNumber:pi.toString(10),segmentTime:ht.toString(10)});pt.push({time:{from:ht,to:ht+it},url:Ws}),ht+=it}Gr=ht,Qi=lt(ze,{...wt,segmentNumber:Gi.toString(10),segmentTime:ht.toString(10)})}let OE={time:{from:Gr,to:1/0},url:Qi};Hi={type:"template",baseUrl:ui,segmentTemplateUrl:ze,initUrl:di,totalSegmentsDurationMs:Ht,segments:pt,nextSegmentBeyondManifest:OE,timescale:tt}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Ut||!Nt)continue;let Qr={video:"video",audio:"audio",text:"text"}[Ut];if(!Qr)continue;Ui||(Ui=Qr),Fs={id:Hs,kind:Qr,segmentReference:Hi,profiles:Qs,duration:S,bitrate:Us,mime:Nt,codecs:Os,width:li,height:jr,fps:uu,quality:qi}}ce.language||(ce.language=Ft),ce.label||(ce.label=qr),ce.mime||(ce.mime=Nt),ce.codecs||(ce.codecs=Os),ce.hdr||(ce.hdr=Ui==="video"&&Nc(Os)),ce.representations.push(Fs)}if(Ui){let ee=r[Ui].find(Ft=>Ft.id===ce.id);if(ee&&ce.representations.every(Ft=>Ft.segmentReference.type==="template"))for(let Ft of ee.representations){let qr=ce.representations.find(Nt=>Nt.id===Ft.id),_s=qr==null?void 0:qr.segmentReference,ui=Ft.segmentReference;ui.segments.push(..._s.segments),ui.nextSegmentBeyondManifest=_s.nextSegmentBeyondManifest}else r[Ui].push(ce)}}return{duration:S,streams:r,baseUrls:n,live:b}};var jc=O(ot(),1);import{videoSizeToQuality as uB}from"@vkontakte/videoplayer-shared/es2018";var GT=({id:a,width:e,height:t,bitrate:i,fps:r,quality:s,streamId:n})=>{var u;let o=(u=s?Kt(s):void 0)!=null?u:uB({width:e,height:t});return o&&{id:a,quality:o,bitrate:i,size:{width:e,height:t},fps:r,streamId:n}},WT=({id:a,bitrate:e})=>({id:a,bitrate:e}),zT=({language:a,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),YT=({language:a,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),Hc=({id:a,language:e,label:t,codecs:i,isDefault:r})=>({id:a,language:e,label:t,codec:(0,jc.default)(i.split("."),0),isDefault:r}),Qc=({id:a,language:e,label:t,hdr:i,codecs:r})=>({id:a,language:e,hdr:i,label:t,codec:(0,jc.default)(r.split("."),0)}),Gc=a=>"url"in a,Qe=a=>a.type==="template";import{isNonNullable as KT}from"@vkontakte/videoplayer-shared/es2018";var N=(a,e)=>KT(a)&&KT(e)&&a.readyState==="open"&&lB(a,e);function lB(a,e){for(let t=0;t<a.activeSourceBuffers.length;++t)if(a.activeSourceBuffers[t]===e)return!0;return!1}var os=class{constructor(e,t,i,{fetcher:r,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new Li(0);this.currentLowLatencySegmentLength$=new Li(0);this.currentSegmentLength$=new Li(0);this.onLastSegment$=new Li(!1);this.fullyBuffered$=new Li(!1);this.playingRepresentation$=new Li(void 0);this.playingRepresentationInit$=new Li(void 0);this.error$=new dB;this.gaps=[];this.subscription=new pB;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new Z;this.switchAbortController=new Z;this.destroyAbortController=new Z;this.bufferLimit=1/0;this.failedDownloads=0;this.baseUrls=[];this.baseUrlsIndex=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.lastDataObtainedTimestampMs=0;this.loadByteRangeSegmentsTimeoutId=0;this.startWith=Zt(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);_e(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new Hy(this.sourceBuffer),this.subscription.add(Wc(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:Mt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o!=null||(o={id:"SegmentEjection",category:Mt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),this.error$.next(o)})),this.subscription.add(Wc(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:Mt.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o||!N(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,Ir(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=this.getForwardBufferDuration(o),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,n*2,l<c).catch(d=>{this.handleAsyncError(d,"pruneBuffer")})})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);let i=this.initData.get(t.id),r=this.segments.get(t.id),s=this.parsedInitData.get(t.id);_e(i,"No init buffer for starting representation"),_e(r,"No segments for starting representation"),i instanceof ArrayBuffer&&(this.searchGaps(r,t),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s))}.bind(this));this.switchTo=Zt(this.destroyAbortController.signal,async function*(e,t=!1){if(!N(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);_e(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if(Ee(s)||Ee(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),_e(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!N(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer();else{let n=this.getCurrentPosition();Pr(n)&&!this.isLive&&(this.bufferLimit=1/0,await this.pruneBuffer(n,1/0,!0)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}this.maintain()}}.bind(this));this.switchToOld=Zt(this.destroyAbortController.signal,async function*(e,t=!1){if(!N(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);_e(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if(Ee(s)||Ee(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),_e(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!N(this.mediaSource,this.sourceBuffer)))if(yield this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let n=this.getCurrentPosition();Pr(n)&&(this.isLive||(this.bufferLimit=1/0,await this.pruneBuffer(n,1/0,!0)),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}}.bind(this));this.seekLive=Zt(this.destroyAbortController.signal,async function*(e){var u,l;let t=(u=(0,ho.default)(e,c=>c.representations))!=null?u:[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let c of this.representations.keys()){let d=t.find(h=>h.id===c);d&&this.representations.set(c,d);let f=this.representations.get(c);if(!f||!Qe(f.segmentReference))return;let p=this.getActualLiveStartingSegments(f.segmentReference);this.segments.set(f.id,p)}let i=(l=this.switchingToRepresentationId)!=null?l:this.downloadingRepresentationId,r=this.representations.get(i);_e(r);let s=this.segments.get(i);_e(s,"No segments for starting representation");let n=this.initData.get(i);if(_e(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer))return;let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(s,r),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));var c;this.fetcher=r,this.tuning=s,this.compatibilityMode=u,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!(l!=null&&l.live),this.baseUrls=(c=l==null?void 0:l.baseUrls)!=null?c:[],this.initData=new Map(i.map(d=>[d.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(d=>[d.id,d])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchToWithPreviousAbort(e,t=!1){!N(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new Z,Zt(this.switchAbortController.signal,async function*(i,r=!1){this.switchingToRepresentationId=i;let s=this.representations.get(i);_e(s,`No such representation ${i}`);let n=this.segments.get(i),o=this.initData.get(i);if(Ee(o)||Ee(n)?yield this.loadInit(s,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(i),_e(n,"No segments for starting representation"),o=this.initData.get(i),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer||!N(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(o,this.downloadAbortController.signal),r)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=i,yield this.dropBuffer();else{let u=this.getCurrentPosition();Pr(u)&&!this.isLive&&(this.bufferLimit=this.forwardBufferTarget,yield this.pruneBuffer(u,1/0,!0)),this.downloadingRepresentationId=i,this.switchingToRepresentationId=void 0}this.maintain()}}.bind(this))(e,t))}warmUpMediaSource(){!Ee(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}async abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);return this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new Z,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(Ee(e)||Ee(this.downloadingRepresentationId)||Ee(this.playingRepresentationId)||Ee(this.sourceBuffer)||!N(this.mediaSource,this.sourceBuffer)||Pr(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(_e(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;let r=i.find(c=>e>=c.time.from&&e<c.time.to);Pr(r)&&isFinite(r.time.from)&&isFinite(r.time.to)&&this.currentSegmentLength$.next((r==null?void 0:r.time.to)-r.time.from);let s=e,n=100;if(this.playingRepresentationId!==this.downloadingRepresentationId){let c=this.getForwardBufferDuration(e),d=r?r.time.to+n:-1/0;r&&r.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&c>=r.time.to-e+n&&(s=d)}if(isFinite(this.bufferLimit)&&Ir(this.sourceBuffer.buffered)>=this.bufferLimit){let c=this.getForwardBufferDuration(e),d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,c<d).catch(f=>{this.handleAsyncError(f,"pruneBuffer")});return}let u=[];if(!this.activeSegments.size&&(u=this.selectForwardBufferSegments(i,t.segmentReference.type,s),u.length)){let c="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if((0,po.default)(u,r))c="high";else{let d=(0,$i.default)(u,0);d&&d.time.from-r.time.to>=this.forwardBufferTarget/2&&(c="low")}this.loadSegments(u,t,c).catch(d=>{this.handleAsyncError(d,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&r&&r.status==="fed"&&!u.length&&this.getForwardBufferDuration(e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let l=(0,$i.default)(i,-1);!this.isLive&&l&&(this.fullyBuffered$.next(l.time.to-e-this.getForwardBufferDuration(e)<n),this.onLastSegment$.next(e-l.time.from>0))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let i=0,r=this.isLive?this.liveInitialAdditionalOffset:0;for(let s of e)Math.trunc(s.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:s.time.from+r}),i=s.time.to;Pr(t.duration)&&t.duration-i>0&&!this.isLive&&this.gaps.push({representation:t.id,from:i,to:t.duration})}getActualLiveStartingSegments(e){let t=e.segments,i=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,r=[],s=0,n=t.length-1;do r.unshift(t[n]),s+=t[n].time.to-t[n].time.from,n--;while(s<i&&n>=0);return this.liveInitialAdditionalOffset=s-i,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){let t=(0,ho.default)(e==null?void 0:e.streams[this.kind],r=>r.representations).find(r=>r.id===this.downloadingRepresentationId);if(!t)return;let i=this.segments.get(t.id);if(i!=null&&i.length)return{from:i[0].time.from,to:i[i.length-1].time.to}}updateLive(e){var i,r,s,n;let t=(i=(0,ho.default)(e==null?void 0:e.streams[this.kind],o=>o.representations))!=null?i:[];if(![...this.segments.values()].every(o=>!o.length))for(let o of t){if(!o||!Qe(o.segmentReference))return;let u=o.segmentReference.segments.map(p=>({...p,status:"none",size:void 0})),l=100,c=(r=this.segments.get(o.id))!=null?r:[],d=(n=(s=(0,$i.default)(c,-1))==null?void 0:s.time.to)!=null?n:0,f=u==null?void 0:u.findIndex(p=>d>=p.time.from+l&&d<=p.time.to+l);if(f===-1){this.liveUpdateSegmentIndex=0;let p=this.getActualLiveStartingSegments(o.segmentReference);this.segments.set(o.id,p)}else{let p=u.slice(f+1);this.segments.set(o.id,[...c,...p])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;_e(e);let t=this.segments.get(e);if(t!=null&&t.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}calculateDurationFromSegments(){var t;if(!this.playingRepresentationId)return 0;let e=this.segments.get(this.playingRepresentationId);return(e?(t=(0,$i.default)(e,-1))==null?void 0:t.time.to:0)||0}updateLowLatencyLiveIfNeeded(e){var i;let t=0;for(let r of this.representations.values()){let s=r.segmentReference;if(!Qe(s))return;let n=(i=this.segments.get(r.id))!=null?i:[],o=n.find(l=>Math.floor(l.time.from)===Math.floor(e.time.from));if(o&&!isFinite(o.time.to)&&(o.time.to=e.time.to,t=o.time.to-o.time.from),!!!n.find(l=>Math.floor(l.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let l=Math.round(e.time.to*s.timescale/1e3).toString(10),c=lt(s.segmentTemplateUrl,{segmentTime:l});n.push({status:"none",time:{from:e.time.to,to:1/0},url:c})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){var s,n,o;let t=(n=(s=this.switchingToRepresentationId)!=null?s:this.downloadingRepresentationId)!=null?n:this.playingRepresentationId;if(!t)return;let i=this.segments.get(t);if(!i)return;let r=i.find(u=>u.time.from<=e&&u.time.to>=e);return(o=r==null?void 0:r.time.from)!=null?o:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)==null||e.destroy(),this.gapDetectionIdleCallback&&yt&&yt(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&yt&&yt(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}this.sourceBuffer=null,this.downloadAbortController.abort(),this.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,i){return this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){let i=e.findIndex(r=>t>=r.time.from&&t<r.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=i),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,i){let r=this.getForwardBufferDuration(i),s=e.findIndex(({status:f,time:{from:p,to:h}},m)=>{let b=p<=i&&h>=i,S=p>i||b||m===0&&i===0,y=Math.min(this.forwardBufferTarget,this.bufferLimit),v=this.preloadOnly&&p<=i+y||r<y&&h-p>=y||h<=i+y;return(f==="none"||f==="partially_ejected"&&S&&v&&this.sourceBuffer&&N(this.mediaSource,this.sourceBuffer)&&!(Ie(this.sourceBuffer.buffered,p)&&Ie(this.sourceBuffer.buffered,h)))&&S&&v});if(s===-1)return[];if(t!=="byteRange")return e.slice(s,s+1);let n=e,o=0,u=0,l=[],c=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,d=this.preloadOnly?this.forwardBufferTarget:0;for(let f=s;f<n.length&&(o<=c||u<=d);f++){let p=n[f];if(o+=p.byte.to+1-p.byte.from,u+=p.time.to+1-p.time.from,p.status==="none"||p.status==="partially_ejected")l.push(p);else break}return l}async loadSegments(e,t,i="auto"){Qe(t.segmentReference)?await this.loadTemplateSegment(e[0],t,i):await this.loadByteRangeSegments(e,t,i)}async loadTemplateSegment(e,t,i="auto"){e.status="downloading";let r={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(r);let{range:s,url:n,signal:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await Zt(o,async function*(){let c=zc(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,c))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let c=await this.fetcher.fetch(n,{range:s,signal:o,onProgress:u,priority:i,isLowLatency:this.isActiveLowLatency(),bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation});if(this.lastDataObtainedTimestampMs=co(),!c)return;let d=new DataView(c),f=Tt(t.mime);if(!isFinite(r.segment.time.to)){let m=t.segmentReference.timescale;r.segment.time.to=f.getChunkEndTime(d,m)}u&&r.feedingBytes&&l?await Promise.all(l):await this.sourceBufferTaskQueue.append(d,o);let{serverDataReceivedTimestamp:p,serverDataPreparedTime:h}=f.getServerLatencyTimestamps(d);p&&h&&this.currentLiveSegmentServerLatency$.next(h-p),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(c){this.abortActiveSegments([e]),It(c)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}updateRepresentationsBaseUrlIfNeeded(){if(!this.tuning.dash.enableBaseUrlSupport||!this.baseUrls.length||this.failedDownloads<=this.tuning.dash.maxSegmentRetryCount)return;this.baseUrlsIndex=(this.baseUrlsIndex+1)%this.baseUrls.length;let e=this.baseUrls[this.baseUrlsIndex];for(let t of this.representations.values())Qe(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}async loadByteRangeSegments(e,t,i="auto"){if(!e.length)return;for(let u of e)u.status="downloading",this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:r,url:s,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(await Zt(n,async function*(){let u=zc(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),Wc(window,"online").pipe(cB()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(s,{range:r,onProgress:o,signal:n,priority:i,bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation}),this.lastDataObtainedTimestampMs=co(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),It(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(Qe(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:(0,$i.default)(e,0).byte.from,to:(0,$i.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:i,range:r,signal:s,onProgress:async(o,u)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=co(),await this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:Mt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!Qe(t.segmentReference))throw new Error("Representation is not template type");let i=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&i.searchParams.set("low-latency","yes");let r=i.toString(),{signal:s}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,c)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=co();let d=this.onSomeTemplateDataLoaded({dataView:l,loaded:c,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(d)}catch(d){this.error$.next({id:"SegmentFeeding",category:Mt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}:void 0;return{url:r,signal:s,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,po.default)(e,t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:s}){if(!this.activeSegments.size||!N(this.mediaSource,this.sourceBuffer))return;let n=this.representations.get(t);if(n)for(let o of this.activeSegments){let{segment:u}=o;if(o.representationId===t){if(s.aborted){r();continue}if(o.loadedBytes=i,o.loadedBytes>o.feedingBytes){let l=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),c=Tt(n.mime).parseFeedableSegmentChunk(l,this.isLive);c!=null&&c.byteLength&&(u.status="partially_fed",o.feedingBytes+=c.byteLength,await this.sourceBufferTaskQueue.append(c),o.fedBytes+=c.byteLength)}}}}async onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size||!N(this.mediaSource,this.sourceBuffer))return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){let{segment:l}=u;if(u.representationId!==t)continue;if(s.aborted){await n();continue}let c=l.byte.from-i,d=l.byte.to-i,f=d-c+1,p=c<r,h=d<=r;if(!p)continue;let m=Tt(o.mime);if(l.status==="downloading"&&h){l.status="downloaded";let b=new DataView(e.buffer,e.byteOffset+c,f);await this.sourceBufferTaskQueue.append(b,s)&&!s.aborted?this.onSegmentFullyAppended(u,t):await n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(l.status==="downloading"||l.status==="partially_fed")&&(u.loadedBytes=Math.min(f,r-c),u.loadedBytes>u.feedingBytes)){let b=new DataView(e.buffer,e.byteOffset+c+u.feedingBytes,u.loadedBytes-u.feedingBytes),S=u.loadedBytes===f?b:m.parseFeedableSegmentChunk(b);S!=null&&S.byteLength&&(l.status="partially_fed",u.feedingBytes+=S.byteLength,await this.sourceBufferTaskQueue.append(S,s)&&!s.aborted?(u.fedBytes+=S.byteLength,u.fedBytes===f&&this.onSegmentFullyAppended(u,t)):await n())}}}onSegmentFullyAppended(e,t){var i;if(!(Ee(this.sourceBuffer)||!N(this.mediaSource,this.sourceBuffer))){!this.isLive&&F.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(Ie(this.sourceBuffer.buffered,e.segment.time.from,100)&&Ie(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:Mt.VIDEO_PIPELINE,message:"Browser stuck on empty result of adding segment to source buffer"})),this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",Gc(e.segment)&&(e.segment.size=e.fedBytes);for(let r of this.representations.values())if(r.id!==t)for(let s of(i=this.segments.get(r.id))!=null?i:[])s.status==="fed"&&Math.round(s.time.from)===Math.round(e.segment.time.from)&&Math.round(s.time.to)===Math.round(e.segment.time.to)&&(s.status="none");this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}}abortSegment(e){e.status==="partially_fed"?e.status="partially_ejected":e.status!=="partially_ejected"&&(e.status="none");for(let t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[r,s]of this.initData.entries()){let n=s instanceof Promise;t||(t=n),s===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let i=this.representations.get(e);i&&(this.initLoadIdleCallback=Tr(()=>(0,XT.default)(this.loadInit(i,"low",!1),()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",i=!1){let r=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!i&&this.failedDownloads>0?Zt(this.destroyAbortController.signal,async function*(){let o=zc(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,Tt(e.mime),r)).then(async o=>{if(!o)return;let{init:u,dataView:l,segments:c}=o,d=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,d);let f=c;this.isLive&&Qe(e.segmentReference)&&(f=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,f),u&&this.parsedInitData.set(e.id,u)}).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:Mt.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n}async dropBuffer(){for(let e of this.segments.values())for(let t of e)t.status="none";await this.pruneBuffer(0,1/0,!0)}async pruneBuffer(e,t,i=!1){if(!this.sourceBuffer||!N(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||Ee(e))return!1;let r=[],s=0,n=u=>{u.sort((c,d)=>c.from-d.from);let l=[u[0]];for(let c=1;c<u.length;c++){let{from:d,to:f}=u[c],p=l[l.length-1];p.to>=d?p.to=Math.max(p.to,f):l.push(u[c])}return l},o=u=>{var c;if(s>=t)return r;r.push({...u.time}),r=n(r);let l=Gc(u)?(c=u.size)!=null?c:0:u.byte.to-u.byte.from;s+=l};for(let u of this.segments.values())for(let l of u){let c=l.time.to<=e-this.tuning.dash.bufferPruningSafeZone,d=l.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(c||d)&&l.status==="fed"&&o(l)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let l=this.sourceBuffer.buffered.start(u)*1e3,c=this.sourceBuffer.buffered.end(u)*1e3,d=0;for(let f of this.segments.values())for(let p of f)(0,po.default)(["none","partially_ejected"],p.status)&&Math.round(p.time.from)<=Math.round(l)&&Math.round(p.time.to)>=Math.round(c)&&d++;if(d===this.segments.size){let f={time:{from:l,to:c},url:"",status:"none"};o(f)}}if(r.length&&i){let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let l of this.segments.values())for(let c of l)c.time.from>=e+u&&c.status==="fed"&&o(c)}return r.length?(await Promise.all(r.map(l=>this.sourceBufferTaskQueue.remove(l.from,l.to)))).reduce((l,c)=>l||c,!1):!1}async abortBuffer(){if(!this.sourceBuffer||!N(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||!N(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||!N(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||Ee(e)?0:me(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!(!this.sourceBuffer||!N(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||!N(this.mediaSource,this.sourceBuffer))){if(!this.tuning.useRefactoredSearchGap)for(let i=0;i<this.sourceBuffer.buffered.length;i++)this.gaps=this.gaps.filter(r=>this.sourceBuffer&&(Math.round(r.from)<Math.round(this.sourceBuffer.buffered.start(i)*1e3)||Math.round(r.to)>Math.round(this.sourceBuffer.buffered.end(i)*1e3)));this.gapDetectionIdleCallback=Tr(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:Mt.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if(Ee(this.sourceBuffer)||!N(this.mediaSource,this.sourceBuffer)||Ee(this.playingRepresentationId))return;let e=[];for(let i=0;i<this.sourceBuffer.buffered.length;i++){let r=Math.floor(this.sourceBuffer.buffered.start(i)*1e3),s=Math.ceil(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:r,to:s})}let t=100;for(let i of this.segments.values())for(let r of i){let{status:s}=r;if(s!=="fed"&&s!=="partially_ejected")continue;let n=Math.floor(r.time.from),o=Math.ceil(r.time.to),u=e.some(c=>c.from-t<=n&&c.to+t>=o),l=e.filter(c=>n>=c.from&&n<c.to-t||o>c.from+t&&o<=c.to);u||(l.length===1?r.status="partially_ejected":this.gaps.some(c=>c.from===r.time.from||c.to===r.time.to)?r.status="partially_ejected":r.status="none")}}handleAsyncError(e,t){this.error$.next({id:t,category:Mt.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}};var ei=a=>{let e=new URL(a);return e.searchParams.set("quic","1"),e.toString()};var fo=a=>{var s;let e=a.get("X-Delivery-Type"),t=a.get("X-Reused"),i=e===null?"http1":e!=null?e:void 0,r=t===null?void 0:(s={1:!0,0:!1}[t])!=null?s:void 0;return{type:i,reused:r}};import{abortable as us,assertNever as JT,fromEvent as ZT,merge as hB,now as ls,Subscription as fB,Subject as eI,ValueSubject as Yc,flattenObject as kr,ErrorCategory as cs}from"@vkontakte/videoplayer-shared/es2018";var mo=a=>{let e=new URL(a);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var go=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:s=!1}){this.lastConnectionType$=new Yc(void 0);this.lastConnectionReused$=new Yc(void 0);this.lastRequestFirstBytes$=new Yc(void 0);this.recoverableError$=new eI;this.error$=new eI;this.abortAllController=new Z;this.subscription=new fB;this.fetchManifest=us(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=ei(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=mo(i));let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(bo);return r?(t.log("success",kr({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(r.headers),r.text()):(t.error("error",kr({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=us(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:s="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1,bufferOptimisation:l=!1}={}){var _,Y,J;let c=e,d=new Headers,f=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{d.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let T=new URL(c,location.href);T.searchParams.append("bytes",`${i.from}-${i.to}`),c=T.toString();break}default:JT(t)}this.requestQuic&&(c=ei(c));let p=this.abortAllController.signal,h;if(n){let T=new Z;if(h=hB(ZT(this.abortAllController.signal,"abort"),ZT(n,"abort")).subscribe(()=>{try{T.abort()}catch(R){bo(R)}}),this.subscription.add(h),this.abortAllController.signal.aborted||n.aborted)try{T.abort()}catch(R){bo(R)}p=T.signal}let m=ls();f.log("startRequest",kr({url:c,priority:s,rangeMethod:t,range:i,isLowLatency:u,requestStartedAt:m}));let b=yield this.doFetch(c,{priority:s,headers:d,signal:p}),S=ls();if(!b)return f.error("error",{message:"No response in request"}),f.end(),h==null||h.unsubscribe(),null;if((_=this.throughputEstimator)==null||_.addRawRtt(S-m),!b.ok||!b.body){h==null||h.unsubscribe();let T=`Fetch error ${b.status}: ${b.statusText}`;return f.error("error",{message:T}),f.end(),Promise.reject(new Error(`Fetch error ${b.status}: ${b.statusText}`))}if(this.onHeadersReceived(b.headers),!r&&!o){h==null||h.unsubscribe();let T=ls(),R={requestStartedAt:m,requestEndedAt:T,duration:T-m};return f.log("endRequest",kr(R)),f.end(),b.arrayBuffer()}let y=b.body;if(o){let T;[y,T]=b.body.tee(),(Y=this.throughputEstimator)==null||Y.trackStream(T,u)}let v=y.getReader(),I,E=parseInt((J=b.headers.get("content-length"))!=null?J:"",10);Number.isFinite(E)&&(I=E),!I&&i&&(I=i.to-i.from+1);let A=0,M=I?new Uint8Array(I):new Uint8Array(0),L=!1,P=T=>{h==null||h.unsubscribe(),L=!0,bo(T)},k=us(p,async function*({done:T,value:R}){if(A===0&&this.lastRequestFirstBytes$.next(ls()-m),p.aborted){h==null||h.unsubscribe();return}if(!T&&R){if(l&&I)M.set(R,A),A+=R.byteLength;else{let x=new Uint8Array(M.length+R.length);x.set(M),x.set(R,M.length),M=x,A+=R.byteLength}r==null||r(new DataView(M.buffer),A),yield v==null?void 0:v.read().then(k,P)}}.bind(this));yield v==null?void 0:v.read().then(k,P),h==null||h.unsubscribe();let V=ls(),D={failed:L,requestStartedAt:m,requestEndedAt:V,duration:V-m};return L?(f.error("endRequest",kr(D)),f.end(),null):(f.log("endRequest",kr(D)),f.end(),M.buffer)}.bind(this));this.fetchByteRangeRepresentation=us(this.abortAllController.signal,async function*(e,t,i){var S;if(e.type!=="byteRange")return null;let{from:r,to:s}=e.initRange,n=r,o=s,u=!1,l,c;e.indexRange&&(l=e.indexRange.from,c=e.indexRange.to,u=s+1===l,u&&(n=Math.min(l,r),o=Math.max(c,s))),n=Math.min(n,0);let d=yield this.fetch(e.url,{range:{from:n,to:o},priority:i,measureThroughput:!1});if(!d)return null;let f=new DataView(d,r-n,s-n+1);if(!t.validateData(f))throw new Error("Invalid media file");let p=t.parseInit(f),h=(S=e.indexRange)!=null?S:t.getIndexRange(p);if(!h)throw new ReferenceError("No way to load representation index");let m;if(u)m=new DataView(d,h.from-n,h.to-h.from+1);else{let y=yield this.fetch(e.url,{range:h,priority:i,measureThroughput:!1});if(!y)return null;m=new DataView(y)}let b=t.parseSegments(m,p,h);return{init:p,dataView:new DataView(d),segments:b}}.bind(this));this.fetchTemplateRepresentation=us(this.abortAllController.signal,async function*(e,t){if(e.type!=="template")return null;let i=new URL(e.initUrl,e.baseUrl).toString(),r=yield this.fetch(i,{priority:t,measureThroughput:!1});return r?{init:null,segments:e.segments.map(n=>({...n,status:"none",size:void 0})),dataView:new DataView(r)}:null}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=r,this.tracer=i.createComponentTracer("Fetcher"),this.useEnableSubtitlesParam=s}onHeadersReceived(e){let{type:t,reused:i}=fo(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,t,i="auto"){var s,n;let{type:r}=e;switch(r){case"byteRange":return(s=await this.fetchByteRangeRepresentation(e,t,i))!=null?s:null;case"template":return(n=await this.fetchTemplateRepresentation(e,i))!=null?n:null;default:JT(r)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}async doFetch(e,t){let i=await Ze(e,t);if(i.ok)return i;let r=await i.text(),s=parseInt(r);if(!isNaN(s))switch(s){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:cs.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:cs.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:cs.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:cs.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${s})`,category:cs.FATAL})}}},bo=a=>{if(!It(a))throw a};var Dt=(a,e,t)=>t*e+(1-t)*a,Kc=(a,e)=>a.reduce((t,i)=>t+i,0)/e,tI=(a,e,t,i)=>{let r=0,s=t,n=Kc(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 mB,ValueSubject as iI}from"@vkontakte/videoplayer-shared/es2018";var ti=class{constructor(e){this.prevReported=void 0;this.pastMeasures=[];this.takenMeasures=0;this.measuresCursor=0;var i;this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new iI(e.initial),this.debounced$=new iI(e.initial);let t=(i=e.label)!=null?i:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new ke(`raw_${t}`),this.smoothedSeries$=new ke(`smoothed_${t}`),this.reportedSeries$=new ke(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,i=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=(this.pastMeasures[o]-this.smoothed)**2,i++);this.takenMeasures=i,t/=i;let r=Math.sqrt(t),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)&&(mB(this.prevReported)||Math.abs(this.smoothed-this.prevReported)/this.prevReported>=this.params.changeThreshold)&&(this.prevReported=this.smoothed,this.debounced$.next(this.smoothed),this.reportedSeries$.next(this.smoothed))}};var So=class extends ti{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=Dt(this.slow,e,this.params.emaAlphaSlow),this.fast=Dt(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var vo=class extends ti{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=Kc(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Dt(this.emaSmoothed,e,this.params.emaAlpha);let i=tI(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}};var yo=class extends ti{constructor(t){super(t);this.furtherValues=[];this.currentTopExtremumValue=0;this.extremumInterval=t.extremumInterval}next(t){this.currentTopExtremumValue<=t?(this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.length===this.extremumInterval?(super.next(this.currentTopExtremumValue),this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.push(t)}updateSmoothedValue(t){this.smoothed=this.smoothed?Dt(this.smoothed,t,this.params.emaAlpha):t}};var Ct=class{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new So({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new vo({initial:e,emaAlpha:i.emaAlpha,basisTrendChangeCount:i.basisTrendChangeCount,changeThreshold:i.changeThreshold,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"})}static getLiveBufferSmoothedValue(e,t){return new yo({initial:e,label:"liveEdgeDelay",...t})}};var Rr=(a,e)=>{a&&a.playbackRate!==e&&(a.playbackRate=e)};import{isNullable as bB,ValueSubject as gB}from"@vkontakte/videoplayer-shared/es2018";var ds=class a{constructor(e,t){this.currentRepresentation$=new gB(null);this.maxRepresentations=4;this.representationsCursor=0;this.representations=[];this.currentSegment=null;this.getCurrentPosition=t.getCurrentPosition,this.processStreams(e)}updateLive(e){this.processStreams(e==null?void 0:e.streams.text)}seekLive(e){this.processStreams(e)}maintain(e=this.getCurrentPosition()){var t;if(!bB(e))for(let i of this.representations)for(let r of i){let s=r.segmentReference,n=s.segments.length,o=s.segments[0].time.from,u=s.segments[n-1].time.to;if(e<o||e>u)continue;let l=s.segments.find(c=>c.time.from<=e&&c.time.to>=e);!l||((t=this.currentSegment)==null?void 0:t.time.from)===l.time.from&&this.currentSegment.time.to===l.time.to||(this.currentSegment=l,this.currentRepresentation$.next({...r,label:"Live Text",language:"ru",isAuto:!0,url:new URL(l.url,s.baseUrl).toString()}))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e!=null?e:[]){let i=a.filterRepresentations(t.representations);if(i){this.representations[this.representationsCursor]=i,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!(e!=null&&e.some(t=>a.filterRepresentations(t.representations)))}static filterRepresentations(e){return e==null?void 0:e.filter(t=>t.kind==="text"&&"segmentReference"in t&&Qe(t.segmentReference))}};var Io=O(ot(),1);import{assertNever as Xc}from"@vkontakte/videoplayer-shared/es2018";var To=a=>{let{webmDecodingInfo:e}=F.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:Xc(a)}return[t,i]},rI=({webmCodec:a,androidPreferredFormat:e,preferMultiStream:t})=>{let i=[...t?["DASH_STREAMS"]:[],...To(a),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],r=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(F.device.isAndroid)switch(e){case"mpeg":return["MPEG",...i,"HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...i,"MPEG"];case"dash":return[...i,"HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return[...r,"MPEG",...To(a),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...To(a),"MPEG",...r,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...To(a),...r,"HLS","HLS_ONDEMAND"];default:Xc(e)}return F.video.nativeHlsSupported?[...i,"HLS","HLS_ONDEMAND","MPEG"]:[...i,"HLS","HLS_ONDEMAND","MPEG"]},aI=({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=F.device.isMac&&F.browser.isSafari;if(F.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:Xc(a)}else F.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"]},Jc=a=>a?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],Eo=a=>{if(a.size===0)return;if(a.size===1){let t=a.values().next();return(0,Io.default)(t.value.split("."),0)}for(let t of a){let i=(0,Io.default)(t.split("."),0);if(i==="opus"||i==="vp09"||i==="av01")return i}let e=a.values().next();return(0,Io.default)(e.value.split("."),0)};var wB=["timeupdate","progress","play","seeked","stalled","waiting"],AB=["timeupdate","progress","loadeddata","playing","seeked"];var Ao=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new oI;this.representationSubscription=new oI;this.state$=new q("none");this.currentVideoRepresentation$=new ae(void 0);this.currentVideoRepresentationInit$=new ae(void 0);this.currentAudioRepresentation$=new ae(void 0);this.currentVideoSegmentLength$=new ae(0);this.currentAudioSegmentLength$=new ae(0);this.error$=new wo;this.lastConnectionType$=new ae(void 0);this.lastConnectionReused$=new ae(void 0);this.lastRequestFirstBytes$=new ae(void 0);this.currentLiveTextRepresentation$=new ae(null);this.isLive$=new ae(!1);this.isActiveLive$=new ae(!1);this.isLowLatency$=new ae(!1);this.liveDuration$=new ae(0);this.liveSeekableDuration$=new ae(0);this.liveAvailabilityStartTime$=new ae(0);this.liveStreamStatus$=new ae(void 0);this.bufferLength$=new ae(0);this.liveLatency$=new ae(void 0);this.liveLoadBufferLength$=new ae(0);this.livePositionFromPlayer$=new ae(0);this.currentStallDuration$=new ae(0);this.videoLastDataObtainedTimestamp$=new ae(0);this.fetcherRecoverableError$=new wo;this.fetcherError$=new wo;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new wo;this.gapWatchdogActive=!1;this.destroyController=new Z;this.initManifest=ed(this.destroyController.signal,async function*(e,t,i){var r;this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=le(t,i,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),(r=this.manifest)!=null&&r.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:ct.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=ed(this.destroyController.signal,async function*(){var n,o;this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(u=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:ct.NETWORK,message:"Failed to load manifest",thrown:u})});if(!e)return null;let t=null;try{t=lo(e!=null?e:"",this.manifestUrlString)}catch(u){let l=(n=oo(e))!=null?n:{id:"ManifestParsing",category:ct.PARSER,message:"Failed to parse MPD manifest",thrown:u};this.error$.next(l)}if(!t)return null;let i=(u,l,c)=>{var d,f,p,h;return!!((f=(d=this.element)==null?void 0:d.canPlayType)!=null&&f.call(d,l)&&((h=(p=He())==null?void 0:p.isTypeSupported)!=null&&h.call(p,`${l}; codecs="${c}"`))||u==="text")};if(t.live){this.isLive$.next(!!t.live);let{availabilityStartTime:u,latestSegmentPublishTime:l,streamIsUnpublished:c,streamIsAlive:d}=t.live,f=((o=t.duration)!=null?o:0)/1e3;this.liveSeekableDuration$.next(-1*f),this.liveDuration$.next((l-u)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let p="active";d||(p=c?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(p)}let r={text:t.streams.text,video:[],audio:[]};for(let u of["video","audio"]){let c=t.streams[u].filter(({mime:p,codecs:h})=>i(u,p,h)),d=new Set(c.map(({codecs:p})=>p)),f=Eo(d);if(f&&(r[u]=c.filter(({codecs:p})=>p.startsWith(f))),u==="video"){let p=this.tuning.preferHDR,h=r.video.some(b=>b.hdr),m=r.video.some(b=>!b.hdr);F.display.isHDR&&p&&h?r.video=r.video.filter(b=>b.hdr):m&&(r.video=r.video.filter(b=>!b.hdr))}}let s={...t,streams:r};return this.tracer.log("updateManifestEnd",hs(s)),s}.bind(this));this.initRepresentations=ed(this.destroyController.signal,async function*(e,t,i){var f;this.tracer.log("initRepresentationsStart",hs({initialVideo:e,initialAudio:t,sourceHls:i})),Lr(this.manifest),Lr(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let r=p=>{this.representationSubscription.add(Bt(p,"error").pipe(xo(h=>{var m;return!!((m=this.element)!=null&&m.played.length)})).subscribe(h=>{this.error$.next({id:"VideoSource",category:ct.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=this.tuning.useManagedMediaSource?Vn():new MediaSource;let s=document.createElement("source");if(r(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&cr())if(i){let p=document.createElement("source");r(p),p.type="application/x-mpegurl",p.src=i.url,this.element.appendChild(p)}else this.element.disableRemotePlayback=!0;this.isActiveLive$.next(this.isLive$.getValue());let n={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),manifest:this.manifest},o=this.manifest.streams.video.reduce((p,h)=>[...p,...h.representations],[]);if(this.videoBufferManager=new os("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],fs(t)){let p=this.manifest.streams.audio.reduce((h,m)=>[...h,...m.representations],[]);this.audioBufferManager=new os("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}ds.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new ds(this.manifest.streams.text,n)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$));let u=()=>{var p;(p=this.stallWatchdogSubscription)==null||p.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add(Mi(...AB.map(p=>Bt(this.element,p))).pipe(Mr(p=>this.element?me(this.element.buffered,this.element.currentTime*1e3):0),ps(),EB(p=>{p>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add(Mi(Bt(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe(ps()).subscribe(h=>this.liveStreamEndTimestamp=id())),this.subscription.add(Bt(this.element,"pause").subscribe(()=>{this.livePauseWatchdogSubscription=td(1e3).subscribe(h=>{let m=zt(this.manifestUrlString,2);this.manifestUrlString=le(this.manifestUrlString,m+1e3,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add(Bt(this.element,"play").subscribe(h=>{var m;return(m=this.livePauseWatchdogSubscription)==null?void 0:m.unsubscribe()})),this.representationSubscription.add($r({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(Mr(({isActiveLive:h,isLowLatency:m})=>h&&m),ps()).subscribe(h=>{this.isManualDecreasePlaybackInLive()||Rr(this.element,1)})),this.representationSubscription.add($r({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(xo(({bufferLength:h,isActiveLive:m,isLowLatency:b})=>m&&b&&!!h)).subscribe(({bufferLength:h})=>this.liveBuffer.next(h))),this.representationSubscription.add(this.videoBufferManager.currentLowLatencySegmentLength$.subscribe(h=>{if(!this.isActiveLive$.getValue()&&!this.isLowLatency$.getValue()&&!h)return;let m=this.liveSeekableDuration$.getValue()-h/1e3;this.liveSeekableDuration$.next(Math.max(m,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+h/1e3)})),this.representationSubscription.add($r({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(xo(({isLive:h})=>h),ps((h,m)=>m.bufferLength<h.bufferLength),Mr(({rtt:h,bufferLength:m,segmentServerLatency:b})=>{let S=zt(this.manifestUrlString,2);return(h/2+m+b+S)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add($r({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:h,isActiveLive:m,isLowLatency:b})=>{if(!b||!m)return;let S=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,y=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,v=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,I=h-S;if(this.isManualDecreasePlaybackInLive())return;let E=1;Math.abs(I)>y&&(E=1+Math.sign(I)*v),Rr(this.element,E)})),this.representationSubscription.add(this.bufferLength$.subscribe(h=>{var b,S;let m=0;if(h){let y=((S=(b=this.element)==null?void 0:b.currentTime)!=null?S:0)*1e3;m=Math.min(...this.bufferManagers.map(I=>{var E,A;return(A=(E=I.getLiveSegmentsToLoadState(this.manifest))==null?void 0:E.to)!=null?A:y}))-y}this.liveLoadBufferLength$.getValue()!==m&&this.liveLoadBufferLength$.next(m)}));let p=0;this.representationSubscription.add($r({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(xB(1e3)).subscribe(async({liveLoadBufferLength:h,bufferLength:m})=>{if(!this.element||this.isUpdatingLive)return;let b=this.element.playbackRate,S=zt(this.manifestUrlString,2),y=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,v=Math.min(y,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*b),I=this.tuning.dashCmafLive.normalizedActualBufferOffset*b,E=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*b,A=isFinite(h)?h:m,M=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),L=y<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(L);let P="none";if(M?P="active_low_latency":this.isLowLatency$.getValue()&&L?(this.bufferManagers.forEach(k=>k.proceedLowLatencyLive()),P="active_low_latency"):S!==0&&A<v?P="live_forward_buffering":A<v+E&&(P="live_with_target_offset"),isFinite(h)&&(p=h>p?h:p),P==="live_forward_buffering"||P==="live_with_target_offset"){let k=p-(v+I),V=this.normolizeLiveOffset(Math.trunc(S+k/b)),D=Math.abs(V-S),_=0;!h||D<=this.tuning.dashCmafLive.offsetCalculationError?_=S:V>0&&D>this.tuning.dashCmafLive.offsetCalculationError&&(_=V),this.manifestUrlString=le(this.manifestUrlString,_,2)}(P==="live_with_target_offset"||P==="live_forward_buffering")&&(p=0,await this.updateLive())},h=>{this.error$.next({id:"updateLive",category:ct.VIDEO_PIPELINE,thrown:h,message:"Failed to update live with subscription"})}))}let l=Mi(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe(Mr(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),c=Mi(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe(Mr(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue()))),d=$r({allBuffersFull:l,someBufferEnded:c}).pipe(ps(),Mr(({allBuffersFull:p,someBufferEnded:h})=>p&&h),xo(p=>p));if(this.representationSubscription.add(Mi(this.forceEnded$,d).subscribe(()=>{var p;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(h=>!h.updating))try{(p=this.source)==null||p.endOfStream()}catch(h){this.error$.next({id:"EndOfStream",category:ct.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:h})}})),this.representationSubscription.add(Mi(...this.bufferManagers.map(p=>p.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.representationSubscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.representationSubscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.liveTextManager&&this.representationSubscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$)),this.source.readyState!=="open"){let p=this.tuning.dash.sourceOpenTimeout>=0;yield new Promise(h=>{var m;p&&(this.timeoutSourceOpenId=setTimeout(()=>{var b;if(((b=this.source)==null?void 0:b.readyState)==="open"){h();return}this.error$.next({id:"OpenOfStream",category:ct.VIDEO_PIPELINE,message:"Failed to open MediaSource",thrown:new Error("Timeout reject when wait sourceopen event"),traceAsLog:!0})},this.tuning.dash.sourceOpenTimeout)),(m=this.source)==null||m.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),h()},{once:!0})})}if(!this.isLive$.getValue()){let p=[(f=this.manifest.duration)!=null?f:0,...(0,rd.default)((0,rd.default)([...this.manifest.streams.audio,...this.manifest.streams.video],h=>h.representations),h=>{let m=[];return h.duration&&m.push(h.duration),Qe(h.segmentReference)&&h.segmentReference.totalSegmentsDurationMs&&m.push(h.segmentReference.totalSegmentsDurationMs),m})];this.source.duration=Math.max(...p)/1e3}this.audioBufferManager&&fs(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")}.bind(this));this.tick=()=>{var t,i,r,s;if(!this.element||!this.videoBufferManager||((t=this.source)==null?void 0:t.readyState)!=="open")return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),(i=this.audioBufferManager)==null||i.maintain(e),(r=this.liveTextManager)==null||r.maintain(e),(this.videoBufferManager.gaps.length||(s=this.audioBufferManager)!=null&&s.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=td(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),n=>{this.error$.next({id:"GapWatchdog",category:ct.WTF,message:"Error handling gaps",thrown:n})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.fetcher=new go({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.subscription.add(this.fetcher.recoverableError$.subscribe(this.fetcherRecoverableError$)),this.subscription.add(this.fetcher.error$.subscribe(this.fetcherError$)),this.liveBuffer=Ct.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator}),this.initTracerSubscription()}async seekLive(e){var r,s,n;Lr(this.element);let t=this.liveStreamStatus$.getValue()!=="active"?id()-this.liveStreamEndTimestamp:0,i=this.normolizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=le(this.manifestUrlString,i,2),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await((r=this.videoBufferManager)==null?void 0:r.seekLive(this.manifest.streams.video)),await((s=this.audioBufferManager)==null?void 0:s.seekLive(this.manifest.streams.audio)),(n=this.liveTextManager)==null||n.seekLive(this.manifest.streams.text))}initBuffer(){Lr(this.element),this.state$.setState("running"),this.subscription.add(Mi(...wB.map(e=>Bt(this.element,e)),Bt(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:ct.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(Bt(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(Bt(this.element,"waiting").subscribe(()=>{var t;this.element&&this.element.readyState===2&&!this.element.seeking&&Ie(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{var p,h,m,b,S,y,v,I,E,A,M;if(!this.element||((p=this.source)==null?void 0:p.readyState)!=="open")return;let i=this.currentStallDuration$.getValue();i+=50,this.currentStallDuration$.next(i);let r={timeInWaiting:i},s=id(),n=100,o=(m=(h=this.videoBufferManager)==null?void 0:h.lastDataObtainedTimestamp)!=null?m:0;this.videoLastDataObtainedTimestamp$.next(o);let u=(S=(b=this.audioBufferManager)==null?void 0:b.lastDataObtainedTimestamp)!=null?S:0,l=(v=(y=this.videoBufferManager)==null?void 0:y.getForwardBufferDuration())!=null?v:0,c=(E=(I=this.audioBufferManager)==null?void 0:I.getForwardBufferDuration())!=null?E:0,d=l<n&&s-o>this.tuning.dash.crashOnStallTWithoutDataTimeout,f=this.audioBufferManager&&c<n&&s-u>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((d||f)&&i>this.tuning.dash.crashOnStallTWithoutDataTimeout||i>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${i} ms`);if(this.isLive$.getValue()&&i%2e3===0){let L=this.normolizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(L).catch(P=>{this.error$.next({id:"stallIntervalCallback",category:ct.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:P})}),r.liveLastOffset=L}else{let L=this.element.currentTime*1e3;(A=this.videoBufferManager)==null||A.maintain(L),(M=this.audioBufferManager)==null||M.maintain(L),r.position=L}this.tracer.log("stallIntervalCallback",hs(r))};(t=this.stallWatchdogSubscription)==null||t.unsubscribe(),this.stallWatchdogSubscription=td(50).subscribe(e,i=>{this.error$.next({id:"StallWatchdogCallback",category:ct.NETWORK,message:"Can't restore DASH after stall.",thrown:i})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,i=!1){let r={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return this.tuning.useNewSwitchTo?this.currentStallDuration$.getValue()>0?r==null?void 0:r.switchToWithPreviousAbort(t,i):r==null?void 0:r.switchTo(t,i):r==null?void 0:r.switchToOld(t,i)}async seek(e,t){var r,s,n,o,u;Lr(this.element),Lr(this.videoBufferManager);let i;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?i=e:i=Math.max((r=this.videoBufferManager.findSegmentStartTime(e))!=null?r:e,(n=(s=this.audioBufferManager)==null?void 0:s.findSegmentStartTime(e))!=null?n:e),this.warmUpMediaSourceIfNeeded(i),Ie(this.element.buffered,i)||await Promise.all([this.videoBufferManager.abort(),(o=this.audioBufferManager)==null?void 0:o.abort()]),!(nI(this.element)||nI(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),(u=this.audioBufferManager)==null||u.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",hs({requestedPosition:e,forcePrecise:t,position:i})))}warmUpMediaSourceIfNeeded(e=(t=>(t=this.element)==null?void 0:t.currentTime)()){var i;fs(this.element)&&fs(this.source)&&fs(e)&&((i=this.source)==null?void 0:i.readyState)==="ended"&&this.element.duration*1e3-e>this.tuning.dash.seekBiasInTheEnd&&this.bufferManagers.forEach(r=>r.warmUpMediaSource())}get isStreamEnded(){var e;return((e=this.source)==null?void 0:e.readyState)==="ended"}stop(){var e,t,i;this.tracer.log("stop"),(e=this.element)==null||e.querySelectorAll("source").forEach(r=>{URL.revokeObjectURL(r.src),r.remove()}),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(t=this.videoBufferManager)==null||t.destroy(),this.videoBufferManager=null,(i=this.audioBufferManager)==null||i.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){var e;return(e=this.manifest)==null?void 0:e.streams}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){var e;this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),((e=this.source)==null?void 0:e.readyState)==="open"&&Array.from(this.source.sourceBuffers).every(t=>!t.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=IB(this.tracer.error.bind(this.tracer));this.subscription.add(this.error$.subscribe(e("error")))}isManualDecreasePlaybackInLive(){if(!this.element||!this.isLive$.getValue())return!1;let e=1-this.element.playbackRate;return Number(e.toFixed(2))>Number(this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup.toFixed(2))}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){var e,t;this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&((e=this.bufferManagers)==null||e.forEach(i=>i.updateLive(this.manifest)),(t=this.liveTextManager)==null||t.updateLive(this.manifest)),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getDebugBufferState();if(!e)return;let t=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),i={isJumpGapAfterSeekLive:this.isJumpGapAfterSeekLive,isActiveLowLatency:t,initialCurrentTime:this.element.currentTime};this.isJumpGapAfterSeekLive&&!t&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let r=this.element.currentTime*1e3,s=[],n=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let o of this.bufferManagers)for(let u of o.gaps)o.playingRepresentation$.getValue()===u.representation&&u.from-n<=r&&u.to+n>r&&(this.element.duration*1e3-u.to<this.tuning.endGapTolerance?s.push(1/0):s.push(u.to));if(s.length){let o=Math.max(...s)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,o===1/0?this.forceEnded$.next():(this.element.currentTime=o/1e3,i={...i,gapEnds:s,jumpTo:o,resultCurrentTime:this.element.currentTime},this.tracer.log("jumpGap",hs(i)))}}calculateDurationFromSegments(){var e,t;return Math.max(((e=this.videoBufferManager)==null?void 0:e.calculateDurationFromSegments())||0,((t=this.audioBufferManager)==null?void 0:t.calculateDurationFromSegments())||0)}};var Po=class{constructor(e,t){this.fov=e,this.orientation=t}};var ko=class{constructor(e,t){this.rotating=!1;this.fading=!1;this.lastTickTS=0;this.lastCameraTurnTS=0;this.fadeStartSpeed=null;this.fadeTime=0;this.camera=e,this.options=t,this.rotationSpeed={x:0,y:0,z:0},this.fadeCorrection=1/(this.options.speedFadeTime/1e3)**2}turnCamera(e=0,t=0,i=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+i)}pointCameraTo(e=0,t=0,i=0){t=this.limitCameraRotationY(t);let r=e-this.camera.orientation.x,s=t-this.camera.orientation.y,n=i-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=i,this.lastCameraTurn={x:r,y:s,z:n},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,i){this.rotationSpeed.x=e!=null?e:this.rotationSpeed.x,this.rotationSpeed.y=t!=null?t:this.rotationSpeed.y,this.rotationSpeed.z=i!=null?i:this.rotationSpeed.z}startRotation(){this.rotating=!0}stopRotation(e=!1){e?(this.setRotationSpeed(0,0,0),this.fadeStartSpeed=null):this.startFading(this.rotationSpeed.x,this.rotationSpeed.y,this.rotationSpeed.z),this.rotating=!1}onCameraRelease(){if(this.lastCameraTurn&&this.lastCameraTurnTS){let e=Date.now()-this.lastCameraTurnTS;if(e<this.options.speedFadeThreshold){let t=(1-e/this.options.speedFadeThreshold)*this.options.rotationSpeedCorrection;this.startFading(this.lastCameraTurn.x*t,this.lastCameraTurn.y*t,this.lastCameraTurn.z*t)}}}startFading(e,t,i){this.setRotationSpeed(e,t,i),this.fadeStartSpeed={...this.rotationSpeed},this.fading=!0}stopFading(){this.fadeStartSpeed=null,this.fading=!0,this.fadeTime=0}limitCameraRotationY(e){return Math.max(-this.options.maxYawAngle,Math.min(e,this.options.maxYawAngle))}tick(e){if(!this.lastTickTS){this.lastTickTS=e,this.lastCameraTurnTS=Date.now();return}let t=e-this.lastTickTS,i=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i);else if(this.fading&&this.fadeStartSpeed){let r=-this.fadeCorrection*(this.fadeTime/1e3)**2+1;this.setRotationSpeed(this.fadeStartSpeed.x*r,this.fadeStartSpeed.y*r,this.fadeStartSpeed.z*r),r>0?this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}};var lI=`attribute vec2 a_vertex;
|
|
125
125
|
attribute vec2 a_texel;
|
|
126
126
|
|
|
127
127
|
varying vec2 v_texel;
|
|
@@ -132,7 +132,7 @@ void main(void) {
|
|
|
132
132
|
// save texel vector to pass to fragment shader
|
|
133
133
|
v_texel = a_texel;
|
|
134
134
|
}
|
|
135
|
-
`;var
|
|
135
|
+
`;var cI=`#ifdef GL_ES
|
|
136
136
|
precision highp float;
|
|
137
137
|
precision highp int;
|
|
138
138
|
#else
|
|
@@ -175,6 +175,6 @@ void main(void) {
|
|
|
175
175
|
// sample using new coordinates
|
|
176
176
|
gl_FragColor = texture2D(u_texture, tc);
|
|
177
177
|
}
|
|
178
|
-
`;var $r=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 Ao(this.params.fov,this.params.orientation),this.cameraRotationManager=new Po(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(sI,this.gl.VERTEX_SHADER),i=this.createShader(nI,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,d=t+r,c=e-i,f=t+r;return[s,n,o,u,l,d,c,f]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){let e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}};import{isNullable as IB,now as fs,once as EB,Subscription as xB,ValueSubject as ed,isNonNullable as wB,safeStorage as td,filterChanged as AB}from"@vkontakte/videoplayer-shared/es2018";var Ro="stalls_manager_metrics",id="stalls_manager_abr_params",oI="stalls_manager_default_tuning_abr_params",rd=class{constructor(){this.isSeeked$=new ed(!1);this.isBuffering$=new ed(!1);this.maxQualityLimit=void 0;this.currentStallsCount=0;this.sumStallsDuration=0;this.lastStallDuration=0;this.providerStartWatchingTimestamp=0;this.lastUniqueVideoTrackSelectedTimestamp=0;this.predictedThroughputWithoutData=0;this.subscription=new xB;this.severeStallOccurred$=new ed(!1)}init(e){this.currentStallDuration$=e.currentStallDuration$,this.videoLastDataObtainedTimestamp$=e.videoLastDataObtainedTimestamp$,this.throughput$=e.throughput$,this.rtt$=e.rtt$,this.tuning=e.tuning,this.abrParams=e.abrParams,this.resetStoredAbrParamsIfNeeded(),this.subscribe(e)}get videoMaxQualityLimit(){return this.maxQualityLimit}get predictedThroughput(){return this.predictedThroughputWithoutData}get abrTuningParams(){let e=this.tuning.enabled?this.getStoredData(id):{};return{...this.abrParams,...e}}set lastVideoTrackSelected(e){var t;((t=this.lastUniqueVideoTrackSelected)==null?void 0:t.id)!==e.id&&(this.lastUniqueVideoTrackSelected=e,this.lastUniqueVideoTrackSelectedTimestamp=fs(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe(),this.currentStallDuration$.getValue()!==0&&this.updateStallData();let e=(fs()-this.providerStartWatchingTimestamp-this.sumStallsDuration)/1e3,t=this.sumStallsDuration;this.addStallInfoToHistory(e,t),this.updateStoredAbrParams()}resetStoredAbrParamsIfNeeded(){let{bitrateFactorAtEmptyBuffer:e,bitrateFactorAtFullBuffer:t,containerSizeFactor:i}={...this.getStoredData(oI)},{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:s,containerSizeFactor:n}={...this.abrParams};this.tuning.enabled&&e===r&&t===s&&i===n||(this.removeStoredData(id),this.setStoredData(oI,{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:s,containerSizeFactor:n}))}updateStoredAbrParams(){let e=[],t=this.getStoredData(Ro,"[]");if(!this.tuning.enabled||t.length<this.tuning.stallsMetricsHistoryLength)return;let i=t.reduce((s,n)=>s+n.tvt,0);if(this.tuning.useTotalStallsDurationPerTvt){let n=t.reduce((o,u)=>o+u.stallsDuration,0)/i;e.push(this.calculateOptimalAbrParams(n,i))}if(this.tuning.useAverageStallsDurationPerTvt){let s=t.reduce((n,o)=>n+o.stallsDurationPerTvt,0)/t.length;e.push(this.calculateOptimalAbrParams(s,i))}this.tuning.useEmaStallsDurationPerTvt&&e.push(this.calculateOptimalAbrParams(t[t.length-1].stallsDurationPerTvtSmoothed,i));let r={bitrateFactorAtEmptyBuffer:Math.max(...e.map(s=>s.bitrateFactorAtEmptyBuffer)),bitrateFactorAtFullBuffer:Math.max(...e.map(s=>s.bitrateFactorAtFullBuffer)),containerSizeFactor:Math.min(...e.map(s=>s.containerSizeFactor))};this.setStoredData(Ro,[]),this.setStoredData(id,r)}calculateOptimalAbrParams(e,t){let{targetStallsDurationPerTvt:i,deviationStallsDurationPerTvt:r,criticalStallsDurationPerTvt:s,abrAdjustingSpeed:n,significantTvt:o,stallsMetricsHistoryLength:u}=this.tuning,l=n*Math.min(t/(o*u),1),d=this.abrTuningParams;return e<i-r?d={bitrateFactorAtEmptyBuffer:Math.max(d.bitrateFactorAtEmptyBuffer-l,this.abrParams.minBitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.max(d.bitrateFactorAtFullBuffer-l,this.abrParams.minBitrateFactorAtFullBuffer),containerSizeFactor:Math.min(d.containerSizeFactor+l,this.abrParams.maxContainerSizeFactor)}:e>i+r&&(d={bitrateFactorAtEmptyBuffer:Math.min(d.bitrateFactorAtEmptyBuffer+l,this.abrParams.maxBitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.min(d.bitrateFactorAtFullBuffer+l,this.abrParams.maxBitrateFactorAtFullBuffer),containerSizeFactor:Math.max(d.containerSizeFactor-l,this.abrParams.minContainerSizeFactor)}),e>s&&(d={bitrateFactorAtEmptyBuffer:Math.max(d.bitrateFactorAtEmptyBuffer,this.abrParams.bitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.max(d.bitrateFactorAtFullBuffer,this.abrParams.bitrateFactorAtFullBuffer),containerSizeFactor:Math.min(d.containerSizeFactor,this.abrParams.containerSizeFactor)}),d}getStoredData(e,t="{}"){var i;return JSON.parse((i=td.get(e))!=null?i:t)}setStoredData(e,t){td.set(e,JSON.stringify(t))}removeStoredData(e){td.remove(e)}addStallInfoToHistory(e,t){if(e<this.tuning.minTvtToBeCounted||e>this.tuning.maxTvtToBeCounted||e*1e3<t)return;let i=this.getStoredData(Ro,"[]"),r=t/e,s=i.length?Mt(i[i.length-1].stallsDurationPerTvtSmoothed,t/e,this.tuning.emaAlpha):r,n={tvt:e,stallsDuration:t,stallsDurationPerTvt:r,stallsDurationPerTvtSmoothed:s};i.push(n),i.length>this.tuning.stallsMetricsHistoryLength&&i.shift(),this.setStoredData(Ro,i)}updateStallData(){this.providerStartWatchingTimestamp&&!this.isSeeked$.getValue()&&(this.sumStallsDuration+=Math.min(this.lastStallDuration,this.tuning.maxPossibleStallDuration),this.currentStallsCount++)}subscribe(e){this.subscription.add(e.isSeeked$.subscribe(this.isSeeked$)),this.subscription.add(e.isBuffering$.subscribe(this.isBuffering$)),this.subscription.add(e.looped$.subscribe(t=>this.currentStallsCount=0)),this.subscription.add(e.playing$.pipe(EB()).subscribe(t=>this.providerStartWatchingTimestamp=fs())),this.subscription.add(this.currentStallDuration$.pipe(AB()).subscribe(t=>{let{stallDurationNoDataBeforeQualityDecrease:i,stallCountBeforeQualityDecrease:r,resetQualityRestrictionTimeout:s,ignoreStallsOnSeek:n}=this.tuning;if(IB(this.lastUniqueVideoTrackSelected)||n&&this.isSeeked$.getValue())return;let o=this.rtt$.getValue(),u=this.throughput$.getValue(),l=this.videoLastDataObtainedTimestamp$.getValue(),d=fs(),c=r&&this.currentStallsCount>=r,f=i&&d-this.lastUniqueVideoTrackSelectedTimestamp>=i+o&&d-l>=i+o&&t>=i;(c||f)&&(this.severeStallOccurred$.next(!0),window.clearTimeout(this.qualityRestrictionTimer),this.maxQualityLimit=this.lastUniqueVideoTrackSelected.quality,wB(this.lastUniqueVideoTrackSelected.bitrate)&&u>this.lastUniqueVideoTrackSelected.bitrate&&(this.predictedThroughputWithoutData=this.lastUniqueVideoTrackSelected.bitrate)),!t&&fs()-this.providerStartWatchingTimestamp>this.lastStallDuration&&(this.updateStallData(),this.severeStallOccurred$.next(!1),window.clearTimeout(this.qualityRestrictionTimer),this.qualityRestrictionTimer=window.setTimeout(()=>{this.maxQualityLimit=void 0,this.predictedThroughputWithoutData=0},s)),this.lastStallDuration=t}))}},ko=rd;import{combine as PB,map as RB,observeElementSize as kB,Subscription as LB,ValueSubject as ad,noop as $B}from"@vkontakte/videoplayer-shared/es2018";var Lo=class{constructor(){this.subscription=new LB;this.pipSize$=new ad(void 0);this.videoSize$=new ad(void 0);this.elementSize$=new ad(void 0);this.pictureInPictureWindowRemoveEventListener=$B}connect({observableVideo:e,video:t}){let i=r=>{let s=r.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add(kB(t).subscribe(this.videoSize$)).add(e.enterPip$.subscribe(({pictureInPictureWindow:r})=>{this.pipSize$.next({width:r.width,height:r.height}),r.addEventListener("resize",i),this.pictureInPictureWindowRemoveEventListener=()=>{r.removeEventListener("resize",i)}})).add(e.leavePip$.subscribe(()=>{this.pictureInPictureWindowRemoveEventListener()})).add(PB({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(RB(({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 $i=class{constructor(e){this.subscription=new OB;this.videoState=new H("stopped");this.observableVideo=null;this.droppedFramesManager=new br;this.stallsManager=new ko;this.elementSizeManager=new Lo;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Kt;this.audioTrackSwitchHistory=new Kt;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"),L(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"),L(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="ready"&&L(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"&&L(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&L(this.params.desiredState.playbackState,"paused");return;default:return DB(e)}}};this.init3DScene=e=>{var i,r,s;if(this.scene3D)return;this.scene3D=new $r(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 Ke(e.source.url),this.params=e,this.video=$e(e.container,e.tuning),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Te(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.player=new wo({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;_B(this.observableVideo)&&(this.observableVideo=Ce(this.video),this.subscription.add(()=>{var n;return(n=this.observableVideo)==null?void 0:n.destroy()}));let i=this.constructor.name,r=n=>{e.error$.next({id:i,category:uI.WTF,message:`${i} internal logic error`,thrown:n})},s=(n,o)=>this.subscription.add(n.subscribe(o,r));return{output:e,desiredState:t,observableVideo:this.observableVideo,genericErrorListener:r,connect:s}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:s}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(sd(l=>!!l.length),cI()).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(nd(l=>l.to.state!=="none"),$o());this.stallsManager.init({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$,videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,tuning:this.params.tuning.stallsManager,abrParams:this.params.tuning.autoTrackSelection,isBuffering$:i.isBuffering$,looped$:i.looped$,playing$:i.playing$}),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(this.player.error$,e.error$),s(this.player.fetcherRecoverableError$,e.fetcherRecoverableError$),s(this.player.fetcherError$,e.fetcherError$),s(this.player.lastConnectionType$,e.httpConnectionType$),s(this.player.lastConnectionReused$,e.httpConnectionReused$),s(this.player.isLive$,e.isLive$),s(this.player.lastRequestFirstBytes$.pipe(sd(lI),cI()),e.firstBytesEvent$),s(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),s(this.videoState.stateChangeEnded$.pipe(nd(l=>l.to)),this.params.output.playbackState$),this.subscription.add(i.looped$.subscribe(()=>this.player.warmUpMediaSourceIfNeeded(),r)),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(ft(this.video,t.isLooped,r)),this.subscription.add(De(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Ye(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),s(Xe(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),L(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),L(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(CB(d,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let f=[];for(let p of d.audio){f.push(Uc(p));let h=[];for(let m of p.representations){let g=qT(m);h.push(g),this.audioTracksMap.set(g,{stream:p,representation:m})}this.audioStreamsMap.set(p,h)}this.params.output.availableAudioStreams$.next(f)}let c=[];for(let f of d.video){c.push(qc(f));let p=[];for(let h of f.representations){let m=UT({...h,streamId:f.id});m&&(p.push(m),this.videoTracksMap.set(m,{stream:f,representation:h}))}this.videoStreamsMap.set(f,p)}this.params.output.availableVideoStreams$.next(c);for(let f of d.text)for(let p of f.representations){let h=HT(f,p);this.textTracksMap.set(h,{stream:f,representation:p})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else l==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r)),this.subscription.add(Mo(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$,VB(this.video,"progress")).pipe(sd(()=>this.videoTracksMap.size>0)).subscribe(async()=>{let l=this.player.state$.getState(),d=this.player.state$.getTransition();if(!(0,dI.default)(["manifest_ready","running"],l)||d)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let c=this.selectVideoAudioRepresentations();if(!c)return;let[f,p]=c,h=[...this.videoTracksMap.keys()].find(g=>{var S;return((S=this.videoTracksMap.get(g))==null?void 0:S.representation.id)===f.id});lI(h)&&(this.stallsManager.lastVideoTrackSelected=h);let m=this.params.desiredState.autoVideoTrackLimits.getTransition();if(m&&this.params.output.autoVideoTrackLimits$.next(m.to),l==="manifest_ready")await this.player.initRepresentations(f.id,p==null?void 0:p.id,this.params.sourceHls);else if(await this.player.switchRepresentation("video",f.id),p){let 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($o()).subscribe(l=>{let d=[...this.videoTracksMap.entries()].find(([,{representation:h}])=>h.id===l);if(!d){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[c,{stream:f}]=d,p=this.params.desiredState.videoStream.getTransition();p&&p.to&&p.to.id===f.id&&this.params.desiredState.videoStream.setState(p.to),e.currentVideoTrack$.next(c),e.currentVideoStream$.next(qc(f))},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe($o()).subscribe(l=>{let d=[...this.audioTracksMap.entries()].find(([,{representation:h}])=>h.id===l);if(!d){e.currentAudioStream$.next(void 0);return}let[c,{stream:f}]=d,p=this.params.desiredState.audioStream.getTransition();p&&p.to&&p.to.id===f.id&&this.params.desiredState.audioStream.setState(p.to),e.currentAudioStream$.next(Uc(f))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(l=>{var d,c;if(l!=null&&l.is3dVideo&&((d=this.params.tuning.spherical)!=null&&d.enabled))try{this.init3DScene(l),e.is3DVideo$.next(!0)}catch(f){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${f}`})}else this.destroy3DScene(),(c=this.params.tuning.spherical)!=null&&c.enabled&&e.is3DVideo$.next(!1)},r)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,r)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,r)),this.textTracksManager.connect(this.video,t,e);let o=t.playbackState.stateChangeStarted$.pipe(nd(({to:l})=>l==="ready"),$o());this.subscription.add(Mo(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,od(["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(Mo(o,this.player.state$.stateChangeEnded$,od(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let u=Mo(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,od(["init"])).pipe(BB(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){var P,B,M,k,Q,O,A,_,R,E,C,ne,Oe;if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?Ea:Ia,t=this.params.tuning.useNewAutoSelectVideoTrack?Zn:Jn,i=this.params.tuning.useNewAutoSelectVideoTrack?St:Xn,{desiredState:r,output:s}=this.params,n=r.autoVideoTrackSwitching.getState(),o=(P=r.videoTrack.getState())==null?void 0:P.id,l=[...this.videoTracksMap.keys()].find(({id:ie})=>ie===o),d=s.currentVideoTrack$.getValue(),c=((k=(M=r.videoStream.getState())!=null?M:l&&((B=this.videoTracksMap.get(l))==null?void 0:B.stream))!=null?k:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!c)return;let f=[...this.videoStreamsMap.keys()].find(({id:ie})=>ie===c.id),p=f&&this.videoStreamsMap.get(f);if(!p)return;let h=me(this.video.buffered,this.video.currentTime*1e3),m;this.player.isActiveLive$.getValue()?m=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?m=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:m=n?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let g=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,S=Math.min(h/Math.min(m,g||1/0),1),v=(Q=r.audioStream.getState())!=null?Q:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,y=(O=[...this.audioStreamsMap.keys()].find(({id:ie})=>ie===(v==null?void 0:v.id)))!=null?O:this.audioStreamsMap.keys().next().value,I=0;if(y){if(l&&!n){let ie=e(l,p,(A=this.audioStreamsMap.get(y))!=null?A:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);I=Math.max(I,(_=ie==null?void 0:ie.bitrate)!=null?_:-1/0)}if(d){let ie=e(d,p,(R=this.audioStreamsMap.get(y))!=null?R:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);I=Math.max(I,(E=ie==null?void 0:ie.bitrate)!=null?E:-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}),x=n?T!=null?T:l:l!=null?l:T,V=y&&t(x,p,(C=this.audioStreamsMap.get(y))!=null?C:[],{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}),$=(ne=this.videoTracksMap.get(x))==null?void 0:ne.representation,w=V&&((Oe=this.audioTracksMap.get(V))==null?void 0:Oe.representation);if($&&w)return[$,w];if($&&!w&&this.audioTracksMap.size===0)return[$,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Be(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),L(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:uI.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),Me(this.video),this.tracer.end()}};var ms=class extends $i{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 ud,merge as pI,filter as hI,filterChanged as FB,isNullable as ld,map as fI,ValueSubject as cd,isNonNullable as NB}from"@vkontakte/videoplayer-shared/es2018";var bs=class extends $i{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 cd(1);s(i.playbackRateState$,n),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(r.isLowLatency.stateChangeEnded$.pipe(fI(o=>o.to)).subscribe(this.player.isLowLatency$)).add(ud({liveBufferTime:t.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(fI(({liveBufferTime:o,liveAvailabilityStartTime:u})=>o&&u?o+u:void 0)).subscribe(t.liveTime$)).add(this.player.liveStreamStatus$.pipe(hI(o=>NB(o))).subscribe(o=>t.isLiveEnded$.next(o!=="active"&&t.position$.getValue()===0))).add(ud({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:pI(i.playbackRateState$,new cd(1))}).pipe(hI(({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||ld(l)||(e=o-l)})).add(ud({time:t.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:pI(i.playbackRateState$,new cd(1))}).pipe(FB((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||ld(o)||ld(u))return;let f=-1*(u-o-e);t.position$.next(Math.min(f,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(o=>{if(o){let u=jT(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 p0,assertNonNullable as h0,debounce as f0,ErrorCategory as MI,filter as Ad,filterChanged as jo,fromEvent as m0,isNonNullable as DI,isNullable as b0,map as Pd,merge as Qo,observableFrom as Rd,once as CI,Subscription as g0}from"@vkontakte/videoplayer-shared/es2018";var xd=N($a(),1);import{abortable as yd,assertNonNullable as Br,combine as Vr,ErrorCategory as lt,filter as No,filterChanged as Is,flattenObject as Es,fromEvent as It,getTraceSubscriptionMethod as i0,interval as Td,isNonNullable as xs,isNullable as LI,map as _r,merge as Bi,now as Id,Subject as Uo,Subscription as Ed,tap as r0,throttle as $I,ValueSubject as se}from"@vkontakte/videoplayer-shared/es2018";var Vo=N(ze(),1),Dr=N(gt(),1),_o=N($a(),1);var wI=N(Ln(),1);import{assertNever as UB,ErrorCategory as mI,Subject as bI}from"@vkontakte/videoplayer-shared/es2018";var qB=18,gI=!1;try{gI=U.browser.isSafari&&!!U.browser.safariVersion&&U.browser.safariVersion<=qB}catch(a){console.error(a)}var dd=class{constructor(e){this.bufferFull$=new bI;this.error$=new bI;this.queue=[];this.currentTask=null;this.destroyed=!1;this.abortRequested=!1;this.completeTask=()=>{var e;try{if(this.currentTask){let t=(e=this.currentTask.signal)==null?void 0:e.aborted;this.currentTask.callback(!t),this.currentTask=null}this.queue.length&&this.pull()}catch(t){this.error$.next({id:"BufferTaskQueueUnknown",category:mI.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)};gI&&e?i={operation:"safariAbort",init:e,callback:r}:i={operation:"abort",callback:r};for(let{callback:s}of this.queue)s(!1);this.abortRequested=!0,i&&(this.queue=[i]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){var r;if((this.buffer.updating||this.currentTask||this.destroyed)&&!this.abortRequested)return;let e=this.queue.shift();if(!e)return;if((r=e.signal)!=null&&r.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(s){s instanceof DOMException&&s.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):s instanceof DOMException&&s.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:mI.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:UB(t)}}},SI=dd;import{abortable as ti,assertNonNullable as _e,ErrorCategory as Di,fromEvent as bd,getExponentialDelay as gd,isNonNullable as Mr,isNullable as xe,now as Bo,once as WB,Subject as zB,Subscription as YB,ValueSubject as Ci}from"@vkontakte/videoplayer-shared/es2018";var pd=N(gt(),1);import{videoSizeToQuality as HB,throttleFn as jB}from"@vkontakte/videoplayer-shared/es2018";var vI=({id:a,width:e,height:t,bitrate:i,fps:r,quality:s,streamId:n})=>{var u;let o=(u=s?Yt(s):void 0)!=null?u:HB({width:e,height:t});return o&&{id:a,quality:o,bitrate:i,size:{width:e,height:t},fps:r,streamId:n}},yI=({id:a,bitrate:e})=>({id:a,bitrate:e}),TI=({language:a,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),II=({language:a,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),hd=({id:a,language:e,label:t,codecs:i,isDefault:r})=>({id:a,language:e,label:t,codec:(0,pd.default)(i.split("."),0),isDefault:r}),fd=({id:a,language:e,label:t,hdr:i,codecs:r})=>({id:a,language:e,hdr:i,label:t,codec:(0,pd.default)(r.split("."),0)}),md=a=>"url"in a,Qe=a=>a.type==="template";var EI=a=>{a.sort((t,i)=>t.from-i.from);let e=[a[0]];for(let t=1;t<a.length;t++){let{from:i,to:r}=a[t],s=e[e.length-1];s.to>=i?s.to=Math.max(s.to,r):e.push(a[t])}return e},Mi=(a,e)=>{for(let t of a)if(e(t))return t;return null},xI=a=>{let e=!1,t=jB(()=>{e=!0},a);return()=>{try{return t(),e}finally{e=!1}}};import{fromEvent as QB,Subscription as GB}from"@vkontakte/videoplayer-shared/es2018";var Do=a=>{let e=[];for(let t=0;t<a.length;t++){let i=Math.floor(a.start(t)*1e3),r=Math.ceil(a.end(t)*1e3);e.push(i,r)}return e};var Co=class{constructor(e,t){this.lastUpdateTs=0;this.lastCallTs=0;this.prevRanges=[];this.subscription=new GB;this.mediaSource=e,this.sourceBuffer=t,this.subscription.add(QB(this.sourceBuffer,"updateend").subscribe(()=>this.updateend()))}updateend(){if(!F(this.mediaSource,this.sourceBuffer))return;let{prevRanges:e}=this,t=Do(this.sourceBuffer.buffered);this.prevRanges=t,this.isRangesRemoved(e,t)&&(this.lastUpdateTs=Date.now())}isRangesRemoved(e,t){if(e.length!==t.length)return!0;for(let i=0;i<e.length;i+=2){let r=e[i],s=e[i+1],n=t[i],o=t[i+1];if(n>r||o<s)return!0}return!1}wasUpdated(){let{lastCallTs:e,lastUpdateTs:t}=this;return this.lastCallTs=Date.now(),e<=t}destroy(){this.subscription.unsubscribe()}};var gs=class{constructor(e,t,i,{fetcher:r,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new Ci(0);this.currentLowLatencySegmentLength$=new Ci(0);this.currentSegmentLength$=new Ci(0);this.onLastSegment$=new Ci(!1);this.fullyBuffered$=new Ci(!1);this.playingRepresentation$=new Ci(void 0);this.playingRepresentationInit$=new Ci(void 0);this.error$=new zB;this.gaps=[];this.subscription=new YB;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new Z;this.switchAbortController=new Z;this.destroyAbortController=new Z;this.bufferLimit=1/0;this.failedDownloads=0;this.baseUrls=[];this.baseUrlsIndex=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.lastDataObtainedTimestampMs=0;this.loadByteRangeSegmentsTimeoutId=0;this.sourceBufferBufferedDiff=null;this.startWith=ti(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);_e(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new SI(this.sourceBuffer),this.sourceBufferBufferedDiff=new Co(this.mediaSource,this.sourceBuffer),this.subscription.add(bd(this.sourceBuffer,"updateend").subscribe(()=>{this.maintain()})),this.subscription.add(bd(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:Di.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o||!F(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,vr(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=me(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),s=this.parsedInitData.get(t.id);_e(i,"No init buffer for starting representation"),_e(r,"No segments for starting representation"),i instanceof ArrayBuffer&&(this.searchGaps(r,t),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s))}.bind(this));this.switchTo=ti(this.destroyAbortController.signal,async function*(e,t=!1){if(!F(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);_e(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if(xe(s)||xe(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),_e(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!F(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer();else{let n=this.getCurrentPosition();Mr(n)&&!this.isLive&&(this.bufferLimit=1/0,await this.pruneBuffer(n,1/0,!0)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}this.maintain()}}.bind(this));this.switchToOld=ti(this.destroyAbortController.signal,async function*(e,t=!1){if(!F(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);_e(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if(xe(s)||xe(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),_e(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!F(this.mediaSource,this.sourceBuffer)))if(yield this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let n=this.getCurrentPosition();Mr(n)&&(this.isLive||(this.bufferLimit=1/0,await this.pruneBuffer(n,1/0,!0)),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}}.bind(this));this.seekLive=ti(this.destroyAbortController.signal,async function*(e){var u,l;let t=(u=(0,_o.default)(e,d=>d.representations))!=null?u:[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let d of this.representations.keys()){let c=t.find(h=>h.id===d);c&&this.representations.set(d,c);let f=this.representations.get(d);if(!f||!Qe(f.segmentReference))return;let p=this.getActualLiveStartingSegments(f.segmentReference);this.segments.set(f.id,p)}let i=(l=this.switchingToRepresentationId)!=null?l:this.downloadingRepresentationId,r=this.representations.get(i);_e(r);let s=this.segments.get(i);_e(s,"No segments for starting representation");let n=this.initData.get(i);if(_e(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer))return;let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(s,r),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));var d;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=(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){!F(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new Z,ti(this.switchAbortController.signal,async function*(i,r=!1){this.switchingToRepresentationId=i;let s=this.representations.get(i);_e(s,`No such representation ${i}`);let n=this.segments.get(i),o=this.initData.get(i);if(xe(o)||xe(n)?yield this.loadInit(s,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(i),_e(n,"No segments for starting representation"),o=this.initData.get(i),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer||!F(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(o,this.downloadAbortController.signal),r)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=i,yield this.dropBuffer();else{let u=this.getCurrentPosition();Mr(u)&&!this.isLive&&(this.bufferLimit=this.forwardBufferTarget,yield this.pruneBuffer(u,1/0,!0)),this.downloadingRepresentationId=i,this.switchingToRepresentationId=void 0}this.maintain()}}.bind(this))(e,t))}warmUpMediaSource(){!xe(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}async abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);return this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new Z,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(xe(e)||xe(this.downloadingRepresentationId)||xe(this.playingRepresentationId)||xe(this.sourceBuffer)||!F(this.mediaSource,this.sourceBuffer)||Mr(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(_e(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;let r=i.find(d=>e>=d.time.from&&e<d.time.to);Mr(r)&&isFinite(r.time.from)&&isFinite(r.time.to)&&this.currentSegmentLength$.next((r==null?void 0:r.time.to)-r.time.from);let s=e,n=100;if(this.playingRepresentationId!==this.downloadingRepresentationId){let d=me(this.sourceBuffer.buffered,e),c=r?r.time.to+n:-1/0;r&&r.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&d>=r.time.to-e+n&&(s=c)}if(isFinite(this.bufferLimit)&&vr(this.sourceBuffer.buffered)>=this.bufferLimit){let d=me(this.sourceBuffer.buffered,e),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,d<c).catch(f=>{this.handleAsyncError(f,"pruneBuffer")});return}let u=null;if(!this.activeSegments.size&&(u=this.selectForwardBufferSegments(i,t.segmentReference.type,s),u!=null&&u.length)){let d="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if((0,Vo.default)(u,r))d="high";else{let c=(0,Dr.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)&&me(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let l=(0,Dr.default)(i,-1);!this.isLive&&l&&(this.fullyBuffered$.next(l.time.to-e-me(this.sourceBuffer.buffered,e)<n),this.onLastSegment$.next(e-l.time.from>0))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let i=0,r=this.isLive?this.liveInitialAdditionalOffset:0;for(let s of e)Math.trunc(s.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:s.time.from+r,persistent:!0}),i=s.time.to;Mr(t.duration)&&t.duration-i>0&&!this.isLive&&this.gaps.push({representation:t.id,from:i,to:t.duration,persistent:!0})}getActualLiveStartingSegments(e){let t=e.segments,i=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,r=[],s=0,n=t.length-1;do r.unshift(t[n]),s+=t[n].time.to-t[n].time.from,n--;while(s<i&&n>=0);return this.liveInitialAdditionalOffset=s-i,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){let t=(0,_o.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,_o.default)(e==null?void 0:e.streams[this.kind],o=>o.representations))!=null?i:[];if(![...this.segments.values()].every(o=>!o.length))for(let o of t){if(!o||!Qe(o.segmentReference))return;let u=o.segmentReference.segments.map(p=>({...p,status:"none",size:void 0})),l=100,d=(r=this.segments.get(o.id))!=null?r:[],c=(n=(s=(0,Dr.default)(d,-1))==null?void 0:s.time.to)!=null?n:0,f=u==null?void 0:u.findIndex(p=>c>=p.time.from+l&&c<=p.time.to+l);if(f===-1){this.liveUpdateSegmentIndex=0;let p=this.getActualLiveStartingSegments(o.segmentReference);this.segments.set(o.id,p)}else{let p=u.slice(f+1);this.segments.set(o.id,[...d,...p])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;_e(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(!Qe(r))return;let s=this.segments.get(i.id);if(!s)continue;let n=s.find(u=>Math.floor(u.time.from)===Math.floor(e.time.from));if(n&&!isFinite(n.time.to)&&(n.time.to=e.time.to,t=n.time.to-n.time.from),!!!s.find(u=>Math.floor(u.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let u=Math.round(e.time.to*r.timescale/1e3).toString(10),l=ot(r.segmentTemplateUrl,{segmentTime:u});s.push({status:"none",time:{from:e.time.to,to:1/0},url:l})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){var s,n,o;let t=(n=(s=this.switchingToRepresentationId)!=null?s:this.downloadingRepresentationId)!=null?n:this.playingRepresentationId;if(!t)return;let i=this.segments.get(t);if(!i)return;let r=i.find(u=>u.time.from<=e&&u.time.to>=e);return(o=r==null?void 0:r.time.from)!=null?o:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e,t;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)==null||e.destroy(),(t=this.sourceBufferBufferedDiff)==null||t.destroy(),this.gapDetectionIdleCallback&&vt&&vt(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&vt&&vt(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(i){if(!(i instanceof DOMException&&i.name==="NotFoundError"))throw i}this.sourceBuffer=null,this.downloadAbortController.abort(),this.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,i){return this.checkEjectedSegments(),this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){if(this.playingRepresentationId!==this.downloadingRepresentationId){let i=e.findIndex(r=>t>=r.time.from&&t<r.time.to);this.liveUpdateSegmentIndex=i}return this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):null}selectForwardBufferSegmentsRecord(e,t,i){let r=this.getForwardBufferDuration(i),s=e.findIndex(({status:f,time:{from:p,to:h}},m)=>{let g=p<=i&&h>=i,S=p>i||g||m===0&&i===0,v=Math.min(this.forwardBufferTarget,this.bufferLimit),y=this.preloadOnly&&p<=i+v||r<v&&h-p>=v||h<=i+v;return(f==="none"||f==="partially_ejected"&&S&&y&&this.sourceBuffer&&F(this.mediaSource,this.sourceBuffer)&&!(Ie(this.sourceBuffer.buffered,p)&&Ie(this.sourceBuffer.buffered,h)))&&S&&y});if(s===-1)return null;if(t!=="byteRange")return e.slice(s,s+1);let n=e,o=0,u=0,l=[],d=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,c=this.preloadOnly?this.forwardBufferTarget:0;for(let f=s;f<n.length&&(o<=d||u<=c);f++){let p=n[f];if(o+=p.byte.to+1-p.byte.from,u+=p.time.to+1-p.time.from,p.status==="none"||p.status==="partially_ejected")l.push(p);else break}return l}async loadSegments(e,t,i="auto"){Qe(t.segmentReference)?await this.loadTemplateSegment(e[0],t,i):await this.loadByteRangeSegments(e,t,i)}async loadTemplateSegment(e,t,i="auto"){e.status="downloading";let r={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(r);let{range:s,url:n,signal:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await ti(o,async function*(){let d=gd(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,d))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let d=await this.fetcher.fetch(n,{range:s,signal:o,onProgress:u,priority:i,isLowLatency:this.isActiveLowLatency()});if(this.lastDataObtainedTimestampMs=Bo(),!d)return;let c=new DataView(d),f=yt(t.mime);if(!isFinite(r.segment.time.to)){let m=t.segmentReference.timescale;r.segment.time.to=f.getChunkEndTime(c,m)}u&&r.feedingBytes&&l?await Promise.all(l):await this.sourceBufferTaskQueue.append(c,o);let{serverDataReceivedTimestamp:p,serverDataPreparedTime:h}=f.getServerLatencyTimestamps(c);p&&h&&this.currentLiveSegmentServerLatency$.next(h-p),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(d){this.abortActiveSegments([e]),Tt(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())Qe(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}async loadByteRangeSegments(e,t,i="auto"){if(!e.length)return;for(let u of e)u.status="downloading",this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:r,url:s,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(await ti(n,async function*(){let u=gd(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),bd(window,"online").pipe(WB()).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=Bo(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),Tt(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(Qe(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:(0,Dr.default)(e,0).byte.from,to:(0,Dr.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=Bo(),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:Di.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!Qe(t.segmentReference))throw new Error("Representation is not template type");let i=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&i.searchParams.set("low-latency","yes");let r=i.toString(),{signal:s}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,d)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=Bo();let c=this.onSomeTemplateDataLoaded({dataView:l,loaded:d,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(c)}catch(c){this.error$.next({id:"SegmentFeeding",category:Di.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}}:void 0;return{url:r,signal:s,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,Vo.default)(e,t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:s}){if(!this.activeSegments.size||!F(this.mediaSource,this.sourceBuffer))return;let n=this.representations.get(t);if(n)for(let o of this.activeSegments){let{segment:u}=o;if(o.representationId===t){if(s.aborted){r();continue}if(o.loadedBytes=i,o.loadedBytes>o.feedingBytes){let l=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),d=yt(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:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size||!F(this.mediaSource,this.sourceBuffer))return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){if(u.representationId!==t)continue;if(s.aborted){await n();continue}let{segment:l}=u,d=l.byte.from-i,c=l.byte.to-i,f=c-d+1,p=d<r,h=c<=r;if(p){if(l.status==="downloading"&&h){l.status="downloaded";let m=new DataView(e.buffer,e.byteOffset+d,f);await this.sourceBufferTaskQueue.append(m,s)&&!s.aborted?this.onSegmentFullyAppended(u,t):await n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(l.status==="downloading"||l.status==="partially_fed")&&(u.loadedBytes=Math.min(f,r-d),u.loadedBytes>u.feedingBytes)){let m=new DataView(e.buffer,e.byteOffset+d+u.feedingBytes,u.loadedBytes-u.feedingBytes),g=u.loadedBytes===f?m:yt(o.mime).parseFeedableSegmentChunk(m);g!=null&&g.byteLength&&(l.status="partially_fed",u.feedingBytes+=g.byteLength,await this.sourceBufferTaskQueue.append(g,s)&&!s.aborted?(u.fedBytes+=g.byteLength,u.fedBytes===f&&this.onSegmentFullyAppended(u,t)):await n())}}}}onSegmentFullyAppended(e,t){if(!(xe(this.sourceBuffer)||!F(this.mediaSource,this.sourceBuffer))){!this.isLive&&U.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(Ie(this.sourceBuffer.buffered,e.segment.time.from,100)&&Ie(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:Di.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",md(e.segment)&&(e.segment.size=e.fedBytes);for(let i of this.representations.values()){if(i.id===t)continue;let r=this.segments.get(i.id);if(r)for(let s of r)s.status==="fed"&&Math.round(s.time.from)===Math.round(e.segment.time.from)&&Math.round(s.time.to)===Math.round(e.segment.time.to)&&(s.status="none")}this.isActiveLowLatency()&&this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,e.segment)}}abortSegment(e){e.status==="partially_fed"?e.status="partially_ejected":e.status!=="partially_ejected"&&(e.status="none");for(let t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[r,s]of this.initData.entries()){let n=s instanceof Promise;t||(t=n),s===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let i=this.representations.get(e);i&&(this.initLoadIdleCallback=Sr(()=>(0,wI.default)(this.loadInit(i,"low",!1),()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",i=!1){let r=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!i&&this.failedDownloads>0?ti(this.destroyAbortController.signal,async function*(){let o=gd(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,yt(e.mime),r)).then(o=>{if(!o)return;let{init:u,dataView:l,segments:d}=o,c=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,c);let f=d;this.isLive&&Qe(e.segmentReference)&&(f=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,f),u&&this.parsedInitData.set(e.id,u)}).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:Di.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n}async dropBuffer(){for(let e of this.segments.values())for(let t of e)t.status="none";await this.pruneBuffer(0,1/0,!0)}async pruneBuffer(e,t,i=!1){if(!this.sourceBuffer||!F(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||xe(e))return!1;this.checkEjectedSegments();let r=[],s=0,n=o=>{var l;if(s>=t)return;r.push({...o.time});let u=md(o)?(l=o.size)!=null?l:0:o.byte.to-o.byte.from;s+=u};for(let o of this.segments.values())for(let u of o){let l=u.time.to<=e-this.tuning.dash.bufferPruningSafeZone,d=u.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(l||d)&&u.status==="fed"&&n(u)}for(let o=0;o<this.sourceBuffer.buffered.length;o++){let u=this.sourceBuffer.buffered.start(o)*1e3,l=this.sourceBuffer.buffered.end(o)*1e3,d=0;for(let c of this.segments.values())for(let f of c)(0,Vo.default)(["none","partially_ejected"],f.status)&&Math.round(f.time.from)<=Math.round(u)&&Math.round(f.time.to)>=Math.round(l)&&d++;if(d===this.segments.size){let c={time:{from:u,to:l},url:"",status:"none"};n(c)}}if(r.length&&i){let o=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let u of this.segments.values())for(let l of u)l.time.from>=e+o&&l.status==="fed"&&n(l)}return r.length?(r=EI(r),(await Promise.all(r.map(u=>this.sourceBufferTaskQueue.remove(u.from,u.to)))).reduce((u,l)=>u||l,!1)):!1}async abortBuffer(){if(!this.sourceBuffer||!F(this.mediaSource,this.sourceBuffer))return!1;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;return this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!F(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}getBufferedTo(){return!this.sourceBuffer||!F(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length?null:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}getForwardBufferDuration(e=this.getCurrentPosition()){return!this.sourceBuffer||!F(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||xe(e)?0:me(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!this.sourceBuffer||!F(this.mediaSource,this.sourceBuffer))return;let{buffered:i}=this.sourceBuffer;this.tuning.useRefactoredSearchGap&&(this.gaps=this.gaps.filter(s=>{if(s.persistent)return!0;let n=Math.round(s.from),o=Math.round(s.to);for(let u=0;u<i.length;u++)if(n>=Math.round(i.start(u)*1e3)&&o<=Math.round(i.end(u)*1e3))return!1;return!0}));let r={representation:e,from:t.time.from,to:t.time.to,persistent:!1};for(let s=0;s<i.length;s++){let n=i.start(s)*1e3,o=i.end(s)*1e3;if(!(o<=t.time.from||n>=t.time.to)){if(n<=t.time.from&&o>=t.time.to){r=void 0;break}o>t.time.from&&o<t.time.to&&(r.from=o),n<t.time.to&&n>t.time.from&&(r.to=n)}}r&&r.to-r.from>1&&!this.gaps.some(s=>r&&s.from===r.from&&s.to===r.to)&&this.gaps.push(r)}detectGapsWhenIdle(e,t){if(!(this.gapDetectionIdleCallback||!this.sourceBuffer||!F(this.mediaSource,this.sourceBuffer))){if(!this.tuning.useRefactoredSearchGap)for(let i=0;i<this.sourceBuffer.buffered.length;i++)this.gaps=this.gaps.filter(r=>r.persistent||this.sourceBuffer&&(Math.round(r.from)<Math.round(this.sourceBuffer.buffered.start(i)*1e3)||Math.round(r.to)>Math.round(this.sourceBuffer.buffered.end(i)*1e3)));this.gapDetectionIdleCallback=Sr(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:Di.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if(xe(this.sourceBuffer)||!F(this.mediaSource,this.sourceBuffer)||xe(this.playingRepresentationId)||this.sourceBufferBufferedDiff&&!this.sourceBufferBufferedDiff.wasUpdated())return;let e=Do(this.sourceBuffer.buffered),t=100;for(let i of this.segments.values())for(let r of i){let{status:s}=r;if(s!=="fed"&&s!=="partially_ejected")continue;let n=Math.floor(r.time.from),o=Math.ceil(r.time.to),u=!1,l=0;for(let d=0;d<e.length;d+=2){let c=e[d],f=e[d+1];u||(u=c-t<=n&&f+t>=o),(n>=c&&n<f-t||o>c+t&&o<=f)&&(l+=1)}u||(l===1?r.status="partially_ejected":this.gaps.some(d=>d.from===r.time.from||d.to===r.time.to)?r.status="partially_ejected":r.status="none")}}handleAsyncError(e,t){this.error$.next({id:t,category:Di.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}};import{abortable as Ss,assertNever as AI,fromEvent as PI,merge as KB,now as vs,Subject as RI,ValueSubject as Sd,flattenObject as Cr,ErrorCategory as ys,SubscriptionRemovable as XB}from"@vkontakte/videoplayer-shared/es2018";var Fo=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:s=!1}){this.lastConnectionType$=new Sd(void 0);this.lastConnectionReused$=new Sd(void 0);this.lastRequestFirstBytes$=new Sd(void 0);this.recoverableError$=new RI;this.error$=new RI;this.abortAllController=new Z;this.subscription=new XB;this.fetchManifest=Ss(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=Zt(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=ho(i));let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(Oo);return r?(t.log("success",Cr({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(r.headers),r.text()):(t.error("error",Cr({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=Ss(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 M,k,Q;let l=e,d=new Headers,c=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{d.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let O=new URL(l,location.href);O.searchParams.append("bytes",`${i.from}-${i.to}`),l=O.toString();break}default:AI(t)}this.requestQuic&&(l=Zt(l));let f=this.abortAllController.signal,p;if(n){let O=new Z;if(p=KB(PI(this.abortAllController.signal,"abort"),PI(n,"abort")).subscribe(()=>{try{O.abort()}catch(A){Oo(A)}}),this.subscription.add(p),this.abortAllController.signal.aborted||n.aborted)try{O.abort()}catch(A){Oo(A)}f=O.signal}let h=vs();c.log("startRequest",Cr({url:l,priority:s,rangeMethod:t,range:i,isLowLatency:u,requestStartedAt:h}));let m=yield this.doFetch(l,{priority:s,headers:d,signal:f}),g=vs();if(!m)return c.error("error",{message:"No response in request"}),c.end(),this.unsubscribeAbortSubscription(p),null;if((M=this.throughputEstimator)==null||M.addRawRtt(g-h),!m.ok||!m.body){this.unsubscribeAbortSubscription(p);let O=`Fetch error ${m.status}: ${m.statusText}`;return c.error("error",{message:O}),c.end(),Promise.reject(new Error(`Fetch error ${m.status}: ${m.statusText}`))}if(this.onHeadersReceived(m.headers),!r&&!o){this.unsubscribeAbortSubscription(p);let O=vs(),A={requestStartedAt:h,requestEndedAt:O,duration:O-h};return c.log("endRequest",Cr(A)),c.end(),m.arrayBuffer()}let S=m.body;if(o){let O;[S,O]=m.body.tee(),(k=this.throughputEstimator)==null||k.trackStream(O,u)}let v=S.getReader(),y,I=parseInt((Q=m.headers.get("content-length"))!=null?Q:"",10);Number.isFinite(I)&&(y=I),!y&&i&&(y=i.to-i.from+1);let T=0,x=y?new Uint8Array(y):new Uint8Array(0),V=!1,$=O=>{this.unsubscribeAbortSubscription(p),V=!0,Oo(O)},w=Ss(f,async function*({done:O,value:A}){if(T===0&&this.lastRequestFirstBytes$.next(vs()-h),f.aborted){this.unsubscribeAbortSubscription(p);return}if(!O&&A){if(y)x.set(A,T),T+=A.byteLength;else{let _=new Uint8Array(x.length+A.length);_.set(x),_.set(A,x.length),x=_,T+=A.byteLength}r==null||r(new DataView(x.buffer),T),yield v==null?void 0:v.read().then(w,$)}}.bind(this));yield v==null?void 0:v.read().then(w,$),this.unsubscribeAbortSubscription(p);let P=vs(),B={failed:V,requestStartedAt:h,requestEndedAt:P,duration:P-h};return V?(c.error("endRequest",Cr(B)),c.end(),null):(c.log("endRequest",Cr(B)),c.end(),x.buffer)}.bind(this));this.fetchByteRangeRepresentation=Ss(this.abortAllController.signal,async function*(e,t,i){var S;if(e.type!=="byteRange")return null;let{from:r,to:s}=e.initRange,n=r,o=s,u=!1,l,d;e.indexRange&&(l=e.indexRange.from,d=e.indexRange.to,u=s+1===l,u&&(n=Math.min(l,r),o=Math.max(d,s))),n=Math.min(n,0);let c=yield this.fetch(e.url,{range:{from:n,to:o},priority:i,measureThroughput:!1});if(!c)return null;let f=new DataView(c,r-n,s-n+1);if(!t.validateData(f))throw new Error("Invalid media file");let p=t.parseInit(f),h=(S=e.indexRange)!=null?S:t.getIndexRange(p);if(!h)throw new ReferenceError("No way to load representation index");let m;if(u)m=new DataView(c,h.from-n,h.to-h.from+1);else{let v=yield this.fetch(e.url,{range:h,priority:i,measureThroughput:!1});if(!v)return null;m=new DataView(v)}let g=t.parseSegments(m,p,h);return{init:p,dataView:new DataView(c),segments:g}}.bind(this));this.fetchTemplateRepresentation=Ss(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}=po(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:AI(r)}}destroy(){this.abortAllController.abort(),this.tracer.end(),this.subscription.unsubscribe()}async doFetch(e,t){let i=await Je(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:ys.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:ys.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:ys.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:ys.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${s})`,category:ys.FATAL})}}unsubscribeAbortSubscription(e){e&&(e.unsubscribe(),this.subscription.remove(e))}},Oo=a=>{if(!Tt(a))throw a};import{isNullable as JB,ValueSubject as ZB}from"@vkontakte/videoplayer-shared/es2018";var Ts=class a{constructor(e,t){this.currentRepresentation$=new ZB(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(!JB(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(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,s.baseUrl).toString()}))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e!=null?e:[]){let i=a.filterRepresentations(t.representations);if(i){this.representations[this.representationsCursor]=i,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!(e!=null&&e.some(t=>a.filterRepresentations(t.representations)))}static filterRepresentations(e){return e==null?void 0:e.filter(t=>t.kind==="text"&&"segmentReference"in t&&Qe(t.segmentReference))}};var a0=["progress","play","seeked","stalled","waiting"],s0=["timeupdate","progress","loadeddata","playing","seeked"];var qo=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new Ed;this.representationSubscription=new Ed;this.state$=new H("none");this.currentVideoRepresentation$=new se(void 0);this.currentVideoRepresentationInit$=new se(void 0);this.currentAudioRepresentation$=new se(void 0);this.currentVideoSegmentLength$=new se(0);this.currentAudioSegmentLength$=new se(0);this.error$=new Uo;this.lastConnectionType$=new se(void 0);this.lastConnectionReused$=new se(void 0);this.lastRequestFirstBytes$=new se(void 0);this.currentLiveTextRepresentation$=new se(null);this.isLive$=new se(!1);this.isActiveLive$=new se(!1);this.isLowLatency$=new se(!1);this.liveDuration$=new se(0);this.liveSeekableDuration$=new se(0);this.liveAvailabilityStartTime$=new se(0);this.liveStreamStatus$=new se(void 0);this.bufferLength$=new se(0);this.liveLatency$=new se(void 0);this.liveLoadBufferLength$=new se(0);this.livePositionFromPlayer$=new se(0);this.currentStallDuration$=new se(0);this.videoLastDataObtainedTimestamp$=new se(0);this.fetcherRecoverableError$=new Uo;this.fetcherError$=new Uo;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new Uo;this.gapWatchdogActive=!1;this.destroyController=new Z;this.initManifest=yd(this.destroyController.signal,async function*(e,t,i){var r;this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=le(t,i,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),(r=this.manifest)!=null&&r.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:lt.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=yd(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:lt.NETWORK,message:"Failed to load manifest",thrown:u})});if(!e)return null;let t=null;try{t=oo(e!=null?e:"",this.manifestUrlString)}catch(u){let l=(n=no(e))!=null?n:{id:"ManifestParsing",category:lt.PARSER,message:"Failed to parse MPD manifest",thrown:u};this.error$.next(l)}if(!t)return null;let i=(u,l,d)=>{var c,f,p,h;return!!((f=(c=this.element)==null?void 0:c.canPlayType)!=null&&f.call(c,l)&&((h=(p=He())==null?void 0:p.isTypeSupported)!=null&&h.call(p,`${l}; codecs="${d}"`))||u==="text")};if(t.live){this.isLive$.next(!!t.live);let{availabilityStartTime:u,latestSegmentPublishTime:l,streamIsUnpublished:d,streamIsAlive:c}=t.live,f=((o=t.duration)!=null?o:0)/1e3;this.liveSeekableDuration$.next(-1*f),this.liveDuration$.next((l-u)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let p="active";c||(p=d?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(p)}let r={text:t.streams.text,video:[],audio:[]};for(let u of["video","audio"]){let d=t.streams[u].filter(({mime:p,codecs:h})=>i(u,p,h)),c=new Set(d.map(({codecs:p})=>p)),f=Io(c);if(f&&(r[u]=d.filter(({codecs:p})=>p.startsWith(f))),u==="video"){let p=this.tuning.preferHDR,h=r.video.some(g=>g.hdr),m=r.video.some(g=>!g.hdr);U.display.isHDR&&p&&h?r.video=r.video.filter(g=>g.hdr):m&&(r.video=r.video.filter(g=>!g.hdr))}}let s={...t,streams:r};return this.tracer.log("updateManifestEnd",Es(s)),s}.bind(this));this.initRepresentations=yd(this.destroyController.signal,async function*(e,t,i){var f;this.tracer.log("initRepresentationsStart",Es({initialVideo:e,initialAudio:t,sourceHls:i})),Br(this.manifest),Br(this.element),this.representationSubscription.unsubscribe(),this.representationSubscription=new Ed,this.state$.startTransitionTo("representations_ready");let r=p=>{this.representationSubscription.add(It(p,"error").pipe(No(h=>{var m;return!!((m=this.element)!=null&&m.played.length)})).subscribe(h=>{this.error$.next({id:"VideoSource",category:lt.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=this.tuning.useManagedMediaSource?Vn():new MediaSource;let s=document.createElement("source");if(r(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&cr())if(i){let p=document.createElement("source");r(p),p.type="application/x-mpegurl",p.src=i.url,this.element.appendChild(p)}else this.element.disableRemotePlayback=!0;this.isActiveLive$.next(this.isLive$.getValue());let n={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),manifest:this.manifest},o=this.manifest.streams.video.reduce((p,h)=>[...p,...h.representations],[]);if(this.videoBufferManager=new gs("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],xs(t)){let p=this.manifest.streams.audio.reduce((h,m)=>[...h,...m.representations],[]);this.audioBufferManager=new gs("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}Ts.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new Ts(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(Bi(...s0.map(p=>It(this.element,p))).pipe(_r(p=>this.element?me(this.element.buffered,this.element.currentTime*1e3):0),Is(),r0(p=>{p>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add(Bi(It(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe(Is()).subscribe(h=>this.liveStreamEndTimestamp=Id())),this.subscription.add(It(this.element,"pause").subscribe(()=>{this.livePauseWatchdogSubscription=Td(1e3).subscribe(h=>{let m=Wt(this.manifestUrlString,2);this.manifestUrlString=le(this.manifestUrlString,m+1e3,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add(It(this.element,"play").subscribe(h=>{var m;return(m=this.livePauseWatchdogSubscription)==null?void 0:m.unsubscribe()})),this.representationSubscription.add(Vr({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(_r(({isActiveLive:h,isLowLatency:m})=>h&&m),Is()).subscribe(h=>{this.isManualDecreasePlaybackInLive()||Pr(this.element,1)})),this.representationSubscription.add(Vr({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(No(({bufferLength:h,isActiveLive:m,isLowLatency:g})=>m&&g&&!!h)).subscribe(({bufferLength:h})=>this.liveBuffer.next(h))),this.representationSubscription.add(this.videoBufferManager.currentLowLatencySegmentLength$.subscribe(h=>{if(!this.isActiveLive$.getValue()&&!this.isLowLatency$.getValue()&&!h)return;let m=this.liveSeekableDuration$.getValue()-h/1e3;this.liveSeekableDuration$.next(Math.max(m,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+h/1e3)})),this.representationSubscription.add(Vr({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(No(({isLive:h})=>h),Is((h,m)=>m.bufferLength<h.bufferLength),_r(({rtt:h,bufferLength:m,segmentServerLatency:g})=>{let S=Wt(this.manifestUrlString,2);return(h/2+m+g+S)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(Vr({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:h,isActiveLive:m,isLowLatency:g})=>{if(!g||!m)return;let S=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,v=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,y=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,I=h-S;if(this.isManualDecreasePlaybackInLive())return;let T=1;Math.abs(I)>v&&(T=1+Math.sign(I)*y),Pr(this.element,T)})),this.representationSubscription.add(this.bufferLength$.subscribe(h=>{var g,S;let m=0;if(h){let v=((S=(g=this.element)==null?void 0:g.currentTime)!=null?S:0)*1e3;m=Math.min(...this.bufferManagers.map(I=>{var T,x;return(x=(T=I.getLiveSegmentsToLoadState(this.manifest))==null?void 0:T.to)!=null?x:v}))-v}this.liveLoadBufferLength$.getValue()!==m&&this.liveLoadBufferLength$.next(m)}));let p=0;this.representationSubscription.add(Vr({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe($I(1e3)).subscribe(async({liveLoadBufferLength:h,bufferLength:m})=>{if(!this.element||this.isUpdatingLive)return;let g=this.element.playbackRate,S=Wt(this.manifestUrlString,2),v=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,y=Math.min(v,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*g),I=this.tuning.dashCmafLive.normalizedActualBufferOffset*g,T=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*g,x=isFinite(h)?h:m,V=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),$=v<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next($);let w="none";if(V?w="active_low_latency":this.isLowLatency$.getValue()&&$?(this.bufferManagers.forEach(P=>P.proceedLowLatencyLive()),w="active_low_latency"):S!==0&&x<y?w="live_forward_buffering":x<y+T&&(w="live_with_target_offset"),isFinite(h)&&(p=h>p?h:p),w==="live_forward_buffering"||w==="live_with_target_offset"){let P=p-(y+I),B=this.normolizeLiveOffset(Math.trunc(S+P/g)),M=Math.abs(B-S),k=0;!h||M<=this.tuning.dashCmafLive.offsetCalculationError?k=S:B>0&&M>this.tuning.dashCmafLive.offsetCalculationError&&(k=B),this.manifestUrlString=le(this.manifestUrlString,k,2)}(w==="live_with_target_offset"||w==="live_forward_buffering")&&(p=0,await this.updateLive())},h=>{this.error$.next({id:"updateLive",category:lt.VIDEO_PIPELINE,thrown:h,message:"Failed to update live with subscription"})}))}let l=Bi(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe(_r(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),d=Bi(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe(_r(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue()))),c=Vr({allBuffersFull:l,someBufferEnded:d}).pipe(Is(),_r(({allBuffersFull:p,someBufferEnded:h})=>p&&h),No(p=>p));if(this.representationSubscription.add(Bi(this.forceEnded$,c).subscribe(()=>{var p;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(h=>!h.updating))try{(p=this.source)==null||p.endOfStream()}catch(h){this.error$.next({id:"EndOfStream",category:lt.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:h})}})),this.representationSubscription.add(Bi(...this.bufferManagers.map(p=>p.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.representationSubscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.representationSubscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.liveTextManager&&this.representationSubscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$)),this.source.readyState!=="open"){let p=this.tuning.dash.sourceOpenTimeout>=0;yield new Promise(h=>{var m;p&&(this.timeoutSourceOpenId=setTimeout(()=>{var g;if(((g=this.source)==null?void 0:g.readyState)==="open"){h();return}this.error$.next({id:"OpenOfStream",category:lt.VIDEO_PIPELINE,message:"Failed to open MediaSource",thrown:new Error("Timeout reject when wait sourceopen event"),traceAsLog:!0})},this.tuning.dash.sourceOpenTimeout)),(m=this.source)==null||m.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),h()},{once:!0})})}if(!this.isLive$.getValue()){let p=[(f=this.manifest.duration)!=null?f:0,...(0,xd.default)((0,xd.default)([...this.manifest.streams.audio,...this.manifest.streams.video],h=>h.representations),h=>{let m=[];return h.duration&&m.push(h.duration),Qe(h.segmentReference)&&h.segmentReference.totalSegmentsDurationMs&&m.push(h.segmentReference.totalSegmentsDurationMs),m})];this.source.duration=Math.max(...p)/1e3}this.audioBufferManager&&xs(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=Td(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),n=>{this.error$.next({id:"GapWatchdog",category:lt.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 Fo({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=Dt.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator}),this.initTracerSubscription()}async seekLive(e){var r,s,n;Br(this.element);let t=this.liveStreamStatus$.getValue()!=="active"?Id()-this.liveStreamEndTimestamp:0,i=this.normolizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=le(this.manifestUrlString,i,2),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await((r=this.videoBufferManager)==null?void 0:r.seekLive(this.manifest.streams.video)),await((s=this.audioBufferManager)==null?void 0:s.seekLive(this.manifest.streams.audio)),(n=this.liveTextManager)==null||n.seekLive(this.manifest.streams.text))}initBuffer(){Br(this.element),this.state$.setState("running");let e=It(this.element,"timeupdate");this.tuning.dash.timeupdateEventTickThrottle&&(e=e.pipe($I(this.tuning.dash.timeupdateEventTickThrottle))),this.subscription.add(Bi(...a0.map(t=>It(this.element,t)),It(window,"online"),e).subscribe(()=>this.tick(),t=>{this.error$.next({id:"DashVKPlayer",category:lt.WTF,message:"Internal logic error",thrown:t})})),this.subscription.add(It(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===HTMLMediaElement.HAVE_CURRENT_DATA&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(It(this.element,"waiting").subscribe(()=>{var i;this.element&&this.element.readyState===HTMLMediaElement.HAVE_CURRENT_DATA&&!this.element.seeking&&Ie(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let t=()=>{var h,m,g,S,v,y,I,T,x,V,$;if(!this.element||((h=this.source)==null?void 0:h.readyState)!=="open")return;let r=this.currentStallDuration$.getValue();r+=50,this.currentStallDuration$.next(r);let s={timeInWaiting:r},n=Id(),o=100,u=(g=(m=this.videoBufferManager)==null?void 0:m.lastDataObtainedTimestamp)!=null?g:0;this.videoLastDataObtainedTimestamp$.next(u);let l=(v=(S=this.audioBufferManager)==null?void 0:S.lastDataObtainedTimestamp)!=null?v:0,d=(I=(y=this.videoBufferManager)==null?void 0:y.getForwardBufferDuration())!=null?I:0,c=(x=(T=this.audioBufferManager)==null?void 0:T.getForwardBufferDuration())!=null?x:0,f=d<o&&n-u>this.tuning.dash.crashOnStallTWithoutDataTimeout,p=this.audioBufferManager&&c<o&&n-l>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((f||p)&&r>this.tuning.dash.crashOnStallTWithoutDataTimeout||r>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${r} ms`);if(this.isLive$.getValue()&&r%2e3===0){let w=this.normolizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(w).catch(P=>{this.error$.next({id:"stallIntervalCallback",category:lt.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:P})}),s.liveLastOffset=w}else{let w=this.element.currentTime*1e3;(V=this.videoBufferManager)==null||V.maintain(w),($=this.audioBufferManager)==null||$.maintain(w),s.position=w}this.tracer.log("stallIntervalCallback",Es(s))};(i=this.stallWatchdogSubscription)==null||i.unsubscribe(),this.stallWatchdogSubscription=Td(50).subscribe(t,r=>{this.error$.next({id:"StallWatchdogCallback",category:lt.NETWORK,message:"Can't restore DASH after stall.",thrown:r})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,i=!1){let r={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return this.tuning.useNewSwitchTo?this.currentStallDuration$.getValue()>0?r==null?void 0:r.switchToWithPreviousAbort(t,i):r==null?void 0:r.switchTo(t,i):r==null?void 0:r.switchToOld(t,i)}async seek(e,t){var r,s,n,o,u;Br(this.element),Br(this.videoBufferManager);let i;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?i=e:i=Math.max((r=this.videoBufferManager.findSegmentStartTime(e))!=null?r:e,(n=(s=this.audioBufferManager)==null?void 0:s.findSegmentStartTime(e))!=null?n:e),this.warmUpMediaSourceIfNeeded(i),Ie(this.element.buffered,i)||await Promise.all([this.videoBufferManager.abort(),(o=this.audioBufferManager)==null?void 0:o.abort()]),!(LI(this.element)||LI(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),(u=this.audioBufferManager)==null||u.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",Es({requestedPosition:e,forcePrecise:t,position:i})))}warmUpMediaSourceIfNeeded(e=(t=>(t=this.element)==null?void 0:t.currentTime)()){var i;xs(this.element)&&xs(this.source)&&xs(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=i0(this.tracer.error.bind(this.tracer));this.subscription.add(this.error$.subscribe(e("error")))}isManualDecreasePlaybackInLive(){return!this.element||!this.isLive$.getValue()?!1:1-this.element.playbackRate>this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){var e,t;this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&((e=this.bufferManagers)==null||e.forEach(i=>i.updateLive(this.manifest)),(t=this.liveTextManager)==null||t.updateLive(this.manifest)),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getBufferedTo();if(e===null)return;let t=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),i=this.isJumpGapAfterSeekLive,r=this.element.currentTime;this.isJumpGapAfterSeekLive&&!t&&this.element.currentTime>e&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let s=this.element.currentTime*1e3,n=null,o=this.element.readyState===HTMLMediaElement.HAVE_METADATA?this.tuning.endGapTolerance:0;for(let u of this.bufferManagers)for(let l of u.gaps)(l.persistent||u.playingRepresentation$.getValue()===l.representation)&&l.from-o<=s&&l.to+o>s&&(this.element.duration*1e3-l.to<this.tuning.endGapTolerance?n=1/0:(n===null||l.to>n)&&(n=l.to));if(n!==null){let u=n+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,u===1/0?this.forceEnded$.next():(this.element.currentTime=u/1e3,this.tracer.log("jumpGap",Es({isJumpGapAfterSeekLive:i,isActiveLowLatency:t,initialCurrentTime:r,jumpTo:u,resultCurrentTime:this.element.currentTime})))}}};import{combine as n0,map as o0,observeElementSize as u0,Subscription as l0,ValueSubject as wd,noop as c0}from"@vkontakte/videoplayer-shared/es2018";var Ho=class{constructor(){this.subscription=new l0;this.pipSize$=new wd(void 0);this.videoSize$=new wd(void 0);this.elementSize$=new wd(void 0);this.pictureInPictureWindowRemoveEventListener=c0}connect({observableVideo:e,video:t}){let i=r=>{let s=r.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add(u0(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(n0({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(o0(({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 Vi=class{constructor(e){this.subscription=new g0;this.videoState=new H("stopped");this.observableVideo=null;this.droppedFramesManager=new br;this.stallsManager=new ko;this.elementSizeManager=new Ho;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Kt;this.audioTrackSwitchHistory=new Kt;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"),L(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"),L(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="ready"&&L(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"&&L(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&L(this.params.desiredState.playbackState,"paused");return;default:return p0(e)}}};this.init3DScene=e=>{var i,r,s;if(this.scene3D)return;this.scene3D=new $r(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 Ke(e.source.url),this.params=e,this.video=$e(e.container,e.tuning),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Te(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.player=new qo({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;b0(this.observableVideo)&&(this.observableVideo=Ce(this.video),this.subscription.add(()=>{var n;return(n=this.observableVideo)==null?void 0:n.destroy()}));let i=this.constructor.name,r=n=>{e.error$.next({id:i,category:MI.WTF,message:`${i} internal logic error`,thrown:n})},s=(n,o)=>this.subscription.add(n.subscribe(o,r));return{output:e,desiredState:t,observableVideo:this.observableVideo,genericErrorListener:r,connect:s}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:s}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(Ad(c=>!!c.length),CI()).subscribe(c=>{this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:c})}));let n=this.params.desiredState.seekState.stateChangeEnded$.pipe(Pd(c=>c.to.state!=="none"),jo());this.stallsManager.init({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$,videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,tuning:this.params.tuning.stallsManager,abrParams:this.params.tuning.autoTrackSelection,isBuffering$:i.isBuffering$,looped$:i.looped$,playing$:i.playing$}),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(this.player.error$,e.error$),s(this.player.fetcherRecoverableError$,e.fetcherRecoverableError$),s(this.player.fetcherError$,e.fetcherError$),s(this.player.lastConnectionType$,e.httpConnectionType$),s(this.player.lastConnectionReused$,e.httpConnectionReused$),s(this.player.isLive$,e.isLive$),s(this.player.lastRequestFirstBytes$.pipe(Ad(DI),CI()),e.firstBytesEvent$),s(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),s(this.videoState.stateChangeEnded$.pipe(Pd(c=>c.to)),this.params.output.playbackState$),this.subscription.add(i.looped$.subscribe(()=>this.player.warmUpMediaSourceIfNeeded(),r)),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(ft(this.video,t.isLooped,r)),this.subscription.add(De(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Ye(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),s(Xe(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),L(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),L(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:c})=>{if(c==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let f=this.player.getStreams();if(h0(f,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let h=[];for(let m of f.audio){h.push(hd(m));let g=[];for(let S of m.representations){let v=yI(S);g.push(v),this.audioTracksMap.set(v,{stream:m,representation:S})}this.audioStreamsMap.set(m,g)}this.params.output.availableAudioStreams$.next(h)}let p=[];for(let h of f.video){p.push(fd(h));let m=[];for(let g of h.representations){let S=vI({...g,streamId:h.id});S&&(m.push(S),this.videoTracksMap.set(S,{stream:h,representation:g}))}this.videoStreamsMap.set(h,m)}this.params.output.availableVideoStreams$.next(p);for(let h of f.text)for(let m of h.representations){let g=TI(h,m);this.textTracksMap.set(g,{stream:h,representation:m})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else c==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r));let{vktvAbrThrottle:o}=this.params.tuning.dash,u=o&&xI(o)||null;this.subscription.add(Qo(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$,m0(this.video,"progress")).pipe(Ad(()=>this.videoTracksMap.size>0)).subscribe(async()=>{let c=this.player.state$.getState(),f=this.player.state$.getTransition();if(c!=="manifest_ready"&&c!=="running"||f||c==="running"&&u&&!u())return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState()),this.selectVideoAudioRepresentations();let{video:p,audio:h}=this.selectedRepresentations;if(!p)return;let m=Mi(this.videoTracksMap.keys(),S=>{var v;return((v=this.videoTracksMap.get(S))==null?void 0:v.representation.id)===p.id});DI(m)&&(this.stallsManager.lastVideoTrackSelected=m);let g=this.params.desiredState.autoVideoTrackLimits.getTransition();if(g&&this.params.output.autoVideoTrackLimits$.next(g.to),c==="manifest_ready")await this.player.initRepresentations(p.id,h==null?void 0:h.id,this.params.sourceHls);else if(await this.player.switchRepresentation("video",p.id),h){let S=!!t.audioStream.getTransition();await this.player.switchRepresentation("audio",h.id,S)}},r)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:c})=>{this.scene3D&&c&&this.scene3D.pointCameraTo(c.x,c.y)})),this.subscription.add(this.elementSizeManager.subscribe(c=>{this.scene3D&&c&&this.scene3D.setViewportSize(c.width,c.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(jo()).subscribe(c=>{let f=Mi(this.videoTracksMap.entries(),([,{representation:g}])=>g.id===c);if(!f){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[p,{stream:h}]=f,m=this.params.desiredState.videoStream.getTransition();m&&m.to&&m.to.id===h.id&&this.params.desiredState.videoStream.setState(m.to),e.currentVideoTrack$.next(p),e.currentVideoStream$.next(fd(h))},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(jo()).subscribe(c=>{let f=Mi(this.audioTracksMap.entries(),([,{representation:g}])=>g.id===c);if(!f){e.currentAudioStream$.next(void 0);return}let[p,{stream:h}]=f,m=this.params.desiredState.audioStream.getTransition();m&&m.to&&m.to.id===h.id&&this.params.desiredState.audioStream.setState(m.to),e.currentAudioStream$.next(hd(h))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(c=>{var f,p;if(c!=null&&c.is3dVideo&&((f=this.params.tuning.spherical)!=null&&f.enabled))try{this.init3DScene(c),e.is3DVideo$.next(!0)}catch(h){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${h}`})}else this.destroy3DScene(),(p=this.params.tuning.spherical)!=null&&p.enabled&&e.is3DVideo$.next(!1)},r)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,r)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,r)),this.textTracksManager.connect(this.video,t,e);let l=t.playbackState.stateChangeStarted$.pipe(Pd(({to:c})=>c==="ready"),jo());this.subscription.add(Qo(l,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,Rd(["init"])).subscribe(()=>{let c=t.autoVideoTrackSwitching.getState(),p=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:c?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(p)})),this.subscription.add(Qo(l,this.player.state$.stateChangeEnded$,Rd(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let d=Qo(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Rd(["init"])).pipe(f0(0));this.subscription.add(d.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){var $,w,P,B,M,k,Q,O,A,_,R,E;if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?Ea:Ia,t=this.params.tuning.useNewAutoSelectVideoTrack?Zn:Jn,i=this.params.tuning.useNewAutoSelectVideoTrack?St:Xn,{desiredState:r,output:s}=this.params,n=r.autoVideoTrackSwitching.getState(),o=($=r.videoTrack.getState())==null?void 0:$.id,u=Mi(this.videoTracksMap.keys(),C=>C.id===o),l=s.currentVideoTrack$.getValue(),d=((B=(P=r.videoStream.getState())!=null?P:u&&((w=this.videoTracksMap.get(u))==null?void 0:w.stream))!=null?B:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!d)return;let c=Mi(this.videoStreamsMap.keys(),C=>C.id===d.id),f=c&&this.videoStreamsMap.get(c);if(!f)return;let p=me(this.video.buffered,this.video.currentTime*1e3),h;this.player.isActiveLive$.getValue()?h=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?h=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:h=n?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let m=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,g=Math.min(p/Math.min(h,m||1/0),1),S=(M=r.audioStream.getState())!=null?M:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,v=(S==null?void 0:S.id)&&Mi(this.audioStreamsMap.keys(),C=>C.id===S.id)||this.audioStreamsMap.keys().next().value,y=0;if(v){if(u&&!n){let C=e(u,f,(k=this.audioStreamsMap.get(v))!=null?k:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);y=Math.max(y,(Q=C==null?void 0:C.bitrate)!=null?Q:-1/0)}if(l){let C=e(l,f,(O=this.audioStreamsMap.get(v))!=null?O:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);y=Math.max(y,(A=C==null?void 0:C.bitrate)!=null?A:-1/0)}}let I=u;(n||!I)&&(I=i(f,{container:this.elementSizeManager.getValue(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.stallsManager.abrTuningParams,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:y,forwardBufferHealth:g,current:l,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,stallsVideoMaxQualityLimit:this.stallsManager.videoMaxQualityLimit,stallsPredictedThroughput:this.stallsManager.predictedThroughput,abrLogger:this.params.dependencies.abrLogger}));let T=v&&t(I,f,(_=this.audioStreamsMap.get(v))!=null?_:[],{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}),x=(R=this.videoTracksMap.get(I))==null?void 0:R.representation,V=T&&((E=this.audioTracksMap.get(T))==null?void 0:E.representation);x&&V?(this.selectedRepresentations.video=x,this.selectedRepresentations.audio=V):x&&!V&&this.audioTracksMap.size===0&&(this.selectedRepresentations.video=x,this.selectedRepresentations.audio=null)}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Be(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),L(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:MI.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),Me(this.video),this.tracer.end()}};var ws=class extends Vi{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 kd,merge as BI,filter as VI,filterChanged as S0,isNullable as Ld,map as _I,ValueSubject as $d,isNonNullable as v0}from"@vkontakte/videoplayer-shared/es2018";var As=class extends Vi{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 $d(1);s(i.playbackRateState$,n),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(r.isLowLatency.stateChangeEnded$.pipe(_I(o=>o.to)).subscribe(this.player.isLowLatency$)).add(kd({liveBufferTime:t.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(_I(({liveBufferTime:o,liveAvailabilityStartTime:u})=>o&&u?o+u:void 0)).subscribe(t.liveTime$)).add(this.player.liveStreamStatus$.pipe(VI(o=>v0(o))).subscribe(o=>t.isLiveEnded$.next(o!=="active"&&t.position$.getValue()===0))).add(kd({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:BI(i.playbackRateState$,new $d(1))}).pipe(VI(({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||Ld(l)||(e=o-l)})).add(kd({time:t.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:BI(i.playbackRateState$,new $d(1))}).pipe(S0((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||Ld(o)||Ld(u))return;let f=-1*(u-o-e);t.position$.next(Math.min(f,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(o=>{if(o){let u=II(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 OI="X-Playback-Duration",Md=async a=>{var r;let e=await Je(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(OI)?parseInt(e.headers.get(OI),10):void 0};import{assertNever as L0,combine as $0,debounce as M0,ErrorCategory as zo,filter as D0,filterChanged as C0,isNonNullable as UI,isNullable as Yo,map as qI,merge as B0,observableFrom as V0,Subscription as _0,ValueSubject as Bd,VideoQuality as O0}from"@vkontakte/videoplayer-shared/es2018";var Cd=N(gl(),1);import{videoSizeToQuality as y0,getExponentialDelay as T0}from"@vkontakte/videoplayer-shared/es2018";var I0=a=>{let e=null;if(a.QUALITY&&(e=Yt(a.QUALITY)),!e&&a.RESOLUTION){let[t,i]=a.RESOLUTION.split("x").map(r=>parseInt(r,10));e=y0({width:t,height:i})}return e!=null?e:null},E0=(a,e)=>{var s,n;let t=a.split(`
|
|
179
|
-
`),i=[],r=[];for(let o=0;o<t.length;o++){let u=t[o],l=u.match(/^#EXT-X-STREAM-INF:(.+)/),
|
|
180
|
-
`),s=0;for(let n=0;n<r.length;++n){let o=r[n];switch(!0){case o.startsWith("#EXTINF:"):{let u=r[++n],l=new URL(u,t).toString(),d=Number(this.extractPlaylistRowValue("#EXTINF:",o))*1e3;if(i.segments.push({time:{from:s,to:s+d},url:l}),s=s+d,!i.segmentStartTime){let c=new Date(i.vkStartTime).valueOf(),f=new Date(i.programDateTime).valueOf();i.segmentStartTime=f-c}break}case o.startsWith("#EXT-X-TARGETDURATION:"):i.targetDuration=Number(this.extractPlaylistRowValue("#EXT-X-TARGETDURATION:",o));break;case o.startsWith("#EXT-X-MEDIA-SEQUENCE:"):i.mediaSequence=Number(this.extractPlaylistRowValue("#EXT-X-MEDIA-SEQUENCE:",o));break;case o.startsWith("#EXT-X-VK-PLAYBACK-DURATION:"):i.vkPlaybackDuration=Number(this.extractPlaylistRowValue("#EXT-X-VK-PLAYBACK-DURATION:",o));break;case o.startsWith("#EXT-X-PROGRAM-DATE-TIME:"):{let u=this.extractPlaylistRowValue("#EXT-X-PROGRAM-DATE-TIME:",o);i.programDateTime=u;let l=new Date(u);l.setMilliseconds(0),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(w0(e)&&this.currentTextTrackData){let{segments:t}=this.currentTextTrackData.playlist,{from:i}=t[0].time,{to:r}=t[t.length-1].time;if(e<i||e>r)return;r-e<this.params.downloadThreshold&&this.fetchNextManifestData();for(let n of t)if(n.time.from<=e&&n.time.to>=e){this.availableTextTracks$.next([{...this.currentTextTrackData.textTrack,url:n.url,isAuto:!0}]);break}}}async fetchNextManifestData(){try{if(this.abortControllers.nextManifest)return;this.abortControllers.nextManifest=new Z;let{textTracks:e}=await this.fetchManifestData(),t=await this.parseTextTracks(e,this.params.sourceUrl);this.currentTextTrackData&&t&&(this.currentTextTrackData.playlist.segments=t.playlist.segments)}catch(e){this.error("fetchNextManifestData",e)}finally{this.abortControllers.nextManifest=null}}async fetchManifestData(){var t;let e=(t=this.prepareUrl)!=null?t:this.params.sourceUrl;return await this.params.fetchManifestData(e,{signal:this.abortControllers.destroy.signal})}error(e,t){this.error$.next({id:"[LiveTextManager][HLS_LIVE_CMAF]",category:k0.WTF,thrown:t,message:e})}};var Ps=class{constructor(e){this.subscription=new _0;this.videoState=new H("stopped");this.textTracksManager=null;this.liveTextManager=null;this.manifests$=new Bd([]);this.liveOffset=new xi;this.manifestStartTime$=new Bd(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"),L(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let d=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(d),this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((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"?L(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),L(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"&&L(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"&&(L(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return L0(t)}};var i;this.params=e,this.video=$e(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:O0.INVARIANT,url:this.params.source.url};let t=(r,s)=>Go(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 Wo(this.params.output.liveTime$,this.video,t,this.params.source.url,this.params.tuning.hlsLiveNewTextManagerDownloadThreshold):this.textTracksManager=new Ke(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:zo.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:zo.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:r})}),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Te(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new Bd((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(),s=(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":s;return i&&!r&&t.startTransitionTo(this.masterManifest),n.find(f=>f.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsLiveProvider",category:zo.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},r=Ce(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(De(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Ye(this.video,t.playbackRate,r.playbackRateState$,i)),s(Xe(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"),L(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),L(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(C0(),qI(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&&UI(l.to)){let c=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let f=this.manifests$.getValue().find(p=>p.id===c);f&&(this.params.output.currentVideoTrack$.next(f),this.params.output.hostname$.next(Te(f.url)))}d&&this.params.desiredState.autoVideoTrackSwitching.setState(d.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o&&o.state==="requested"&&this.seek(o.position)},i)),this.subscription.add(r.loadedData$.subscribe(()=>{var u,l,d;let o=(d=(l=(u=this.video)==null?void 0:u.getStartDate)==null?void 0:l.call(u))==null?void 0:d.getTime();this.manifestStartTime$.next(o||void 0)},i)),this.subscription.add($0({startTime:this.manifestStartTime$.pipe(D0(UI)),currentTime:r.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),i)),this.subscription.add(this.manifests$.pipe(qI(o=>o.map(({id:u,quality:l,size:d,bandwidth:c,fps:f})=>({id:u,quality:l,size:d,fps:f,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,i));let n=B0(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,V0(["init"])).pipe(M0(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),Me(this.video)}prepare(){var o,u,l;let e=this.selectManifest();if(Yo(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:d,min:c}=(u=(o=t==null?void 0:t.to)!=null?o:i)!=null?u:{};for(let[f,p]of[[d,"mq"],[c,"lq"]]){let h=String(parseFloat(f||""));p&&f&&r.searchParams.set(p,h)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,n=le(r.toString(),this.liveOffset.getTotalOffset(),s);(l=this.liveTextManager)==null||l.prepare(n),this.video.setAttribute("src",n),this.video.load(),Md(n).then(d=>{var c;if(!Yo(d))this.maxSeekBackTime$.next(d);else{let f=(c=this.params.source.maxSeekBackTime)!=null?c:this.maxSeekBackTime$.getValue();(Yo(f)||!isFinite(f))&&Je(n).then(p=>p.text()).then(p=>{var m;let h=(m=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(p))==null?void 0:m[1];if(h){let g=new URL(h,n).toString();Md(g).then(S=>{Yo(S)||this.maxSeekBackTime$.next(S)})}}).catch(()=>{})}})}playIfAllowed(){Be(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),L(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:zo.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3),this.params.output.seekedEvent$.next()}generateLiveUrl(){let e=le(this.params.source.url);if(this.params.tuning.useHlsLiveNewTextManager){let t=new URL(e);t.searchParams.set("enable-subtitles","yes"),e=t.toString()}return e}};import{assertNever as F0,debounce as N0,ErrorCategory as Vd,fromEvent as _d,isNonNullable as U0,isNullable as q0,map as HI,merge as jI,observableFrom as QI,Subscription as H0,ValueSubject as j0,VideoQuality as Q0}from"@vkontakte/videoplayer-shared/es2018";var Rs=class{constructor(e){this.subscription=new H0;this.videoState=new H("stopped");this.manifests$=new j0([]);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"),L(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let d=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(d);let{currentTime:c}=this.video;this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:c*1e3,forcePrecise:!0});return}switch((r==null?void 0:r.to)!=="paused"&&l.state==="requested"&&this.seek(l.position),t){case"ready":i==="ready"?L(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),L(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"&&L(this.params.desiredState.playbackState,"playing");return;case"paused":i==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&L(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return F0(t)}};this.textTracksManager=new Ke(e.source.url),this.params=e,this.video=$e(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:Q0.INVARIANT,url:this.params.source.url},this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Te(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),Go(le(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:t,textTracks:i})=>{this.manifests$.next([this.masterManifest,...t]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(i)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:Vd.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(),s=(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":s;return i&&(!r||!r.from)&&t.startTransitionTo(this.masterManifest),n.find(f=>f.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsProvider",category:Vd.WTF,message:"HlsProvider internal logic error",thrown:o})},r=Ce(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(HI(o=>o.to)),this.params.output.playbackState$),this.subscription.add(ft(this.video,t.isLooped,i)),this.subscription.add(De(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Ye(this.video,t.playbackRate,r.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),L(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),L(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&&U0(l.to)){let h=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let m=this.manifests$.getValue().find(g=>g.id===h);m&&(this.params.output.currentVideoTrack$.next(m),this.params.output.hostname$.next(Te(m.url)))}let c=this.params.desiredState.playbackRate.getState(),f=(p=this.params.output.element$.getValue())==null?void 0:p.playbackRate;if(c!==f){let h=this.params.output.element$.getValue();h&&(this.params.desiredState.playbackRate.setState(c),h.playbackRate=c)}d&&this.params.desiredState.autoVideoTrackSwitching.setState(d.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o.state==="requested"&&this.seek(o.position)},i))),this.subscription.add(this.manifests$.pipe(HI(o=>o.map(({id:u,quality:l,size:d,bandwidth:c,fps:f})=>({id:u,quality:l,size:d,fps:f,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,i)),!U.device.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(jI(_d(o,"addtrack"),_d(o,"removetrack"),_d(o,"change"),QI(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},i))}let n=jI(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,QI(["init"])).pipe(N0(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Me(this.video)}prepare(){var s,n;let e=this.selectManifest();if(q0(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,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(){Be(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),L(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Vd.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var zI=N(Xi(),1),Od=N(ur(),1),YI=N(gt(),1);import{assertNever as G0,assertNonNullable as GI,debounce as W0,ErrorCategory as WI,isHigherOrEqual as z0,isLowerOrEqual as Y0,isNonNullable as K0,merge as X0,observableFrom as J0,Subscription as Z0,map as eV}from"@vkontakte/videoplayer-shared/es2018";var ks=class{constructor(e){this.subscription=new Z0;this.videoState=new H("stopped");this.trackUrls={};this.textTracksManager=new Ke;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"),L(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"?L(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),L(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"&&L(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&L(this.params.desiredState.playbackState,"paused");return;default:return G0(e)}};this.params=e,this.video=$e(e.container,e.tuning),this.params.output.element$.next(this.video),(0,zI.default)(this.params.source).reverse().forEach(([t,i],r)=>{let s=r.toString(10);this.trackUrls[s]={track:{quality:t,id:s},url:i}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next((0,Od.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:WI.WTF,message:"MpegProvider internal logic error",thrown:o})},r=Ce(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(eV(o=>o.to)),this.params.output.playbackState$),this.subscription.add(ft(this.video,t.isLooped,i)),this.subscription.add(De(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Ye(this.video,t.playbackRate,r.playbackRateState$,i)),s(Xe(this.video),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),L(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),L(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&&K0(o.to)){this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to.id].track);let d=this.params.desiredState.playbackRate.getState(),c=(l=this.params.output.element$.getValue())==null?void 0:l.playbackRate;if(d!==c){let f=this.params.output.element$.getValue();f&&(this.params.desiredState.playbackRate.setState(d),f.playbackRate=d)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.textTracksManager.connect(this.video,t,e);let n=X0(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,J0(["init"])).pipe(W0(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),Me(this.video)}prepare(){var i;let e=(i=this.params.desiredState.videoTrack.getState())==null?void 0:i.id;GI(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];GI(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=Zt(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(Te(t))}playIfAllowed(){Be(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),L(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:WI.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){var l,d;this.params.output.autoVideoTrackLimits$.next(e);let t=c=>{this.params.output.currentVideoTrack$.next(c),this.params.desiredState.videoTrack.startTransitionTo(c)},i=c=>{let f=St(n,{container:this.video.getBoundingClientRect(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,limits:c,abrLogger:this.params.dependencies.abrLogger});t(f)},r=(l=this.params.output.currentVideoTrack$.getValue())==null?void 0:l.quality,s=!!(e.max||e.min),n=(0,Od.default)(this.trackUrls).map(c=>c.track);if(!r||!s||dr(e,n[0].quality,(d=(0,YI.default)(n,-1))==null?void 0:d.quality)){i();return}let o=e.max?Y0(r,e.max):!0,u=e.min?z0(r,e.min):!0;o&&u||i(e)}};import{assertNever as XI,debounce as aV,merge as JI,observableFrom as sV,Subscription as nV,map as ZI,ValueSubject as oV,ErrorCategory as Nd,VideoQuality as uV}from"@vkontakte/videoplayer-shared/es2018";import{ErrorCategory as tV}from"@vkontakte/videoplayer-shared/es2018";var KI=["stun:videostun.mycdn.me:80"],iV=1e3,rV=3,Fd=()=>null,Ko=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=Fd;this.externalStopCallback=Fd;this.externalErrorCallback=Fd;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:KI}]};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:tV.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),iV)}normalizeOptions(e={}){let t={stunServerList:KI,maxRetryNumber:rV,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var Ls=class{constructor(e){this.videoState=new H("stopped");this.maxSeekBackTime$=new oV(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"),L(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"),L(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"&&L(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&L(this.params.desiredState.playbackState,"paused");return;default:return XI(e)}};this.subscription=new nV,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=$e(e.container,e.tuning),this.liveStreamClient=new Ko(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),Me(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,i=n=>{e.error$.next({id:"WebRTCLiveProvider",category:Nd.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};this.subscription.add(JI(this.videoState.stateChangeStarted$.pipe(ZI(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(ZI(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})}));let r=Ce(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(Xe(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(De(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 XI(n.to)}},i)).add(JI(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,sV(["init"])).pipe(aV(0)).subscribe(this.syncPlayback.bind(this),i)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),i))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(Te(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.currentVideoTrack$.next({id:"webrtc",quality:uV.INVARIANT}),this.video.srcObject=e,L(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:Nd.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){Be(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),L(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Nd.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var $s=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 Ds,assertNonNullable as ii,ErrorCategory as Xo,filter as sE,isNonNullable as nE,isNullable as mV,map as bV,merge as gV,once as SV,Subject as be,Subscription as oE,ValueSubject as j,flattenObject as Ud}from"@vkontakte/videoplayer-shared/es2018";import{Observable as lV,map as eE,Subscription as cV,Subject as dV}from"@vkontakte/videoplayer-shared/es2018";var tE=a=>new lV(e=>{let t=new cV,i=a.desiredPlaybackState$.stateChangeStarted$.pipe(eE(({from:l,to:d})=>`${l}-${d}`)),r=a.desiredPlaybackState$.stateChangeEnded$,s=a.providerChanged$.pipe(eE(({type:l})=>l!==void 0)),n=new dV,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 pV,Subscription as hV,combine as fV,filter as rE,once as aE}from"@vkontakte/videoplayer-shared/es2018";function iE(){return new(window.AudioContext||window.webkitAudioContext)}var Ms=class Ms{constructor(e,t,i,r){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=i;this.volumeMultiplier=r;this.destroyController=new Z;this.subscriptions=new hV;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe(rE(s=>!!s.type),aE()).subscribe(({type:s})=>this.subscribe(s)))}subscribe(e){U.browser.isSafari&&e!=="MPEG"||this.subscriptions.add(fV({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(rE(({playbackState:t,video:i,volume:{muted:r,volume:s}})=>t==="playing"&&!!i&&!r&&!!s),aE()).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=iE();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:Ms.errorId,category:pV.VIDEO_PIPELINE,message:(t=e==null?void 0:e.message)!=null?t:`${Ms.errorId} exception`,thrown:e})}};Ms.errorId="VolumeMultiplierManager";var Or=Ms;var vV={chunkDuration:5e3,maxParallelRequests:5},Cs=class{constructor(e){this.current$=new j({type:void 0});this.providerError$=new be;this.noAvailableProvidersError$=new be;this.volumeMultiplierError$=new be;this.providerOutput={position$:new j(0),duration$:new j(1/0),volume$:new j({muted:!1,volume:1}),availableVideoStreams$:new j([]),currentVideoStream$:new j(void 0),availableVideoTracks$:new j([]),currentVideoTrack$:new j(void 0),availableAudioStreams$:new j([]),currentAudioStream$:new j(void 0),availableAudioTracks$:new j([]),currentVideoSegmentLength$:new j(0),currentAudioSegmentLength$:new j(0),isAudioAvailable$:new j(!0),autoVideoTrackLimitingAvailable$:new j(!1),autoVideoTrackLimits$:new j(void 0),currentBuffer$:new j(void 0),isBuffering$:new j(!0),error$:new be,fetcherError$:new be,fetcherRecoverableError$:new be,warning$:new be,willSeekEvent$:new be,soundProhibitedEvent$:new be,seekedEvent$:new be,loopedEvent$:new be,endedEvent$:new be,firstBytesEvent$:new be,loadedMetadataEvent$:new be,firstFrameEvent$:new be,canplay$:new be,isLive$:new j(void 0),isLiveEnded$:new j(null),isLowLatency$:new j(!1),canChangePlaybackSpeed$:new j(!0),liveTime$:new j(void 0),liveBufferTime$:new j(void 0),liveLatency$:new j(void 0),severeStallOccurred$:new be,availableTextTracks$:new j([]),currentTextTrack$:new j(void 0),hostname$:new j(void 0),httpConnectionType$:new j(void 0),httpConnectionReused$:new j(void 0),inPiP$:new j(!1),inFullscreen$:new j(!1),element$:new j(void 0),elementVisible$:new j(!0),availableSources$:new j(void 0),is3DVideo$:new j(!1),playbackState$:new j(""),getCurrentTime$:new j(null)};this.subscription=new oE;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=JT([...eI(this.params.tuning),...ZT(this.params.tuning)],this.params.tuning).filter(l=>nE(e.sources[l])),{forceFormat:i,formatsToAvoid:r}=this.params.tuning,s=[];i?s=[i]:r.length?s=[...t.filter(l=>!(0,qd.default)(r,l)),...t.filter(l=>(0,qd.default)(r,l))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",Ud(s)),this.screenFormatsIterator=new $s(s);let n=[...zc(!0),...zc(!1)];this.chromecastFormatsIterator=new $s(n.filter(l=>nE(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:o=1,tuning:{useVolumeMultiplier:u}}=this.params;u&&o!==1&&Or.isSupported()&&(this.volumeMultiplierManager=new Or(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(mV(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:Xo.WTF,message:"Failed to create provider",thrown:r})}i?this.current$.next({type:t,provider:i,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.tracer.log("reinitProvider"),this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.tracer.log("switchToNextProvider",{destination:e}),this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}destroyProvider(){let e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"}),this.tracer.log("destroyProvider"),e.destroy();let t=this.providerOutput.position$.getValue()*1e3,i=this.params.desiredState.seekState.getState(),r=i.state!=="none";if(this.params.desiredState.seekState.setState({state:"requested",position:r?i.position:t,forcePrecise:r?i.forcePrecise:!1}),e.scene3D){let n=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:n.x,y:n.y})}let s=this.providerOutput.isBuffering$;s.getValue()||s.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),this.tracer.log("createProvider",{destination:e,format:t}),e){case"SCREEN":return this.createScreenProvider(t);case"CHROMECAST":return this.createChromecastProvider(t);default:return Ds(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 ii(u),this.params.tuning.useNewDashProvider?new ws({...o,source:u,sourceHls:l}):new ms({...o,source:u,sourceHls:l})}case"DASH_LIVE_CMAF":{let u=this.applyFailoverHost(t[e]);return ii(u),this.params.tuning.useNewDashProvider?new As({...o,source:u}):new bs({...o,source:u})}case"HLS":case"HLS_ONDEMAND":{let u=this.applyFailoverHost(t[e]);return ii(u),new Rs({...o,source:u})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let u=this.applyFailoverHost(t[e]);return ii(u),new Ps({...o,source:u,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let u=this.applyFailoverHost(t[e]);return ii(u),new ks({...o,source:u})}case"DASH_LIVE":{let u=this.applyFailoverHost(t[e]);return ii(u),new Qv({...o,source:u,config:{...vV,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let u=this.applyFailoverHost(t[e]);return ii(u),new Ls({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 Ds(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 ii(o),new ba({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 Ds(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return Ds(e)}}handleNoFormatsError(e){switch(e){case"SCREEN":this.noAvailableProvidersError$.next(this.params.tuning.forceFormat),this.current$.next({type:void 0});return;case"CHROMECAST":this.params.dependencies.chromecastInitializer.disconnect();return;default:return Ds(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;let t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;let i=r=>{let s=new URL(r);return s.host=t,s.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return{...e,url:i(e.url)}}return(0,lE.default)((0,uE.default)(e).map(([r,s])=>[r,i(s)]))}initProviderErrorHandling(){let e=new oE,t=!1,i=0;return e.add(gV(this.providerOutput.error$.pipe(sE(r=>!this.params.tuning.ignoreAudioRendererError||!r.message||!/AUDIO_RENDERER_ERROR/ig.test(r.message))),tE({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(bV(r=>({id:`ProviderHangup:${r}`,category:Xo.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(sE(({to:s})=>s==="playing"),SV()).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===Xo.NETWORK,u=r.category===Xo.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(s!=null?s:"SCREEN"))}r.traceAsLog?this.tracer.log("providerInfo",Ud(n)):this.tracer.error("providerError",Ud(n))})),e}};import{fromEvent as Jo,once as yV,combine as TV,Subscription as cE,ValueSubject as Hd,map as IV,filter as EV,isNonNullable as Zo,now as Ge,safeStorage as jd}from"@vkontakte/videoplayer-shared/es2018";var xV=5e3,dE="one_video_throughput",pE="one_video_rtt",Bt=window.navigator.connection,hE=()=>{let a=Bt==null?void 0:Bt.downlink;if(Zo(a)&&a!==10)return a*1e3},fE=()=>{let a=Bt==null?void 0:Bt.rtt;if(Zo(a)&&a!==3e3)return a},mE=(a,e,t)=>{let i=t*8,r=i/a;return i/(r+e)},Qd=class a{constructor(e){this.subscription=new cE;this.concurrentDownloads=new Set;var r,s;this.tuningConfig=e;let t=a.load(dE)||(e.useBrowserEstimation?hE():void 0)||xV,i=(s=(r=a.load(pE))!=null?r:e.useBrowserEstimation?fE():void 0)!=null?s:0;if(this.throughput$=new Hd(t),this.rtt$=new Hd(i),this.rttAdjustedThroughput$=new Hd(mE(t,i,e.rttPenaltyRequestSize)),this.throughput=Dt.getSmoothedValue(t,-1,e),this.rtt=Dt.getSmoothedValue(i,1,e),e.useBrowserEstimation){let n=()=>{let u=hE();u&&this.throughput.next(u);let l=fE();Zo(l)&&this.rtt.next(l)};Bt&&"onchange"in Bt&&this.subscription.add(Jo(Bt,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{jd.set(dE,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{jd.set(pE,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(TV({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(IV(({throughput:n,rtt:o})=>mE(n,o,e.rttPenaltyRequestSize)),EV(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=Ge(),r=new cE;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add(Jo(e,"progress").pipe(yV()).subscribe(s=>{t=s.loaded,i=Ge()}));break;case 1:case 0:r.add(Jo(e,"loadstart").subscribe(()=>{t=0,i=Ge()}));break}r.add(Jo(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=Ge(),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=Ge(),n=0,o=Ge(),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,Ge()-s,1),this.concurrentDownloads.delete(e);else if(c){if(t){let f=Ge();if(f-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||f-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let h=o-s;h&&this.addRawSpeed(n,h,1,t),n=c.byteLength,s=Ge()}else n+=c.byteLength;o=Ge()}else r+=c.byteLength,n+=c.byteLength,n>=this.tuningConfig.streamMinSampleSize&&Ge()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,Ge()-o,this.concurrentDownloads.size),n=0,o=Ge());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=jd.get(e);if(Zo(t))return(i=parseInt(t,10))!=null?i:void 0}},bE=Qd;import{fillWithDefault as wV,VideoQuality as eu}from"@vkontakte/videoplayer-shared/es2018";var gE={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:eu.Q_4320P,activeVideoAreaThreshold:.1,highQualityLimit:eu.Q_720P,trafficSavingLimit:eu.Q_480P},stallsManager:{enabled:!1,stallDurationNoDataBeforeQualityDecrease:500,stallDurationToBeCount:100,stallCountBeforeQualityDecrease:3,resetQualityRestrictionTimeout:1e4,ignoreStallsOnSeek:!0,stallsMetricsHistoryLength:5,maxPossibleStallDuration:3e4,minTvtToBeCounted:5,maxTvtToBeCounted:10800,significantTvt:600,targetStallsDurationPerTvt:1,deviationStallsDurationPerTvt:.5,criticalStallsDurationPerTvt:6,abrAdjustingSpeed:.1,emaAlpha:.6,useTotalStallsDurationPerTvt:!0,useAverageStallsDurationPerTvt:!0,useEmaStallsDurationPerTvt:!0},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:eu.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,seekBiasInTheEnd:2e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,crashOnStallTimeout:25e3,crashOnStallTWithoutDataTimeout:5e3,enableSubSegmentBufferFeeding:!0,bufferEmptinessTolerance:100,useFetchPriorityHints:!0,enableBaseUrlSupport:!0,maxSegmentRetryCount:5,sourceOpenTimeout:1e3,vktvAbrThrottle:0,timeupdateEventTickThrottle:300},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,maxLiveDuration:7200,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:250,playbackCatchupSpeedup:.05,isActiveOnDefault:!1,bufferEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:"07A4434E",useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"dash",preferCMAF:!1,preferWebRTC:!1,preferMultiStream:!1,preferHDR:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,seekNearDurationBias:1,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useHlsJs:!1,useNativeHLSTextTracks:!1,useManagedMediaSource:!0,useNewSwitchTo:!1,useNewDashProvider:!1,useNewAutoSelectVideoTrack:!1,useSafariEndlessRequestBugfix:!0,useRefactoredSearchGap:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,audioVideoSyncRate:20,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50},useVolumeMultiplier:!1,ignoreAudioRendererError:!1,useEnableSubtitlesParam:!1,useOldMSEDetection:!1,useHlsLiveNewTextManager:!1,exposeInternalsToGlobal:!1,hlsLiveNewTextManagerDownloadThreshold:4e3,disableYandexPiP:!1,asyncResolveClientChecker:!1,autostartOnlyIfVisible:!1},SE=a=>{var e;return{...wV(a,gE),configName:[...(e=a.configName)!=null?e:[],...gE.configName]}};import{assertNonNullable as tu,combine as Vt,ErrorCategory as iu,filter as q,filterChanged as K,fromEvent as Wd,isNonNullable as IE,isNullable as MV,Logger as DV,map as z,mapTo as EE,merge as ri,now as ru,once as G,Subject as X,Subscription as xE,tap as zd,ValueSubject as D,isHigher as CV,isInvariantQuality as wE,flattenObject as ai,throttle as Yd,getTraceSubscriptionMethod as AE,TracerFactory as BV,InternalsExposure as VV}from"@vkontakte/videoplayer-shared/es2018";import{merge as AV,map as PV,filter as vE,isNonNullable as RV}from"@vkontakte/videoplayer-shared/es2018";var Gd=({seekState:a,position$:e})=>AV(a.stateChangeEnded$.pipe(PV(({to:t})=>{var i;return t.state==="none"?void 0:((i=t.position)!=null?i:NaN)/1e3}),vE(RV)),e.pipe(vE(()=>a.getState().state==="none")));import{assertNonNullable as kV}from"@vkontakte/videoplayer-shared/es2018";var yE=a=>{let e=typeof a.container=="string"?document.getElementById(a.container):a.container;return kV(e,`Wrong container or containerId {${a.container}}`),e};import{filter as LV,once as $V}from"@vkontakte/videoplayer-shared/es2018";var TE=(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(LV(r=>r.length>0),$V()).subscribe(r=>{r.find(i)&&e.startTransitionTo(a)}):(a===void 0||t!=null&&t.getValue().find(i))&&e.startTransitionTo(a)};var au=class{constructor(e={configName:[]},t=BV.createRootTracer(!1)){this.subscription=new xE;this.logger=new DV;this.abrLogger=this.logger.createComponentLog("ABR");this.internalsExposure=null;this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new D(!1);this.hasLiveOffsetByPausedTimer=0;this.playerInitRequest=0;this.playerInited=new D(!1);this.wasSetStartedQuality=!1;this.desiredState={playbackState:new 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 D(void 0),position$:new D(0),duration$:new D(1/0),muted$:new D(!1),volume$:new D(1),availableVideoStreams$:new D([]),currentVideoStream$:new D(void 0),availableQualities$:new D([]),availableQualitiesFps$:new D({}),currentQuality$:new D(void 0),isAutoQualityEnabled$:new D(!0),autoQualityLimitingAvailable$:new D(!1),autoQualityLimits$:new D({}),predefinedQualityLimitType$:new D("unknown"),availableAudioStreams$:new D([]),currentAudioStream$:new D(void 0),availableAudioTracks$:new D([]),isAudioAvailable$:new D(!0),currentPlaybackRate$:new D(1),currentBuffer$:new D({start:0,end:0}),isBuffering$:new D(!0),isStalled$:new D(!1),isEnded$:new D(!1),isLooped$:new D(!1),isLive$:new D(void 0),isLiveEnded$:new D(null),canChangePlaybackSpeed$:new D(void 0),atLiveEdge$:new D(void 0),atLiveDurationEdge$:new D(void 0),liveTime$:new D(void 0),liveBufferTime$:new D(void 0),liveLatency$:new D(void 0),currentFormat$:new D(void 0),availableTextTracks$:new D([]),currentTextTrack$:new D(void 0),throughputEstimation$:new D(void 0),rttEstimation$:new D(void 0),videoBitrate$:new D(void 0),hostname$:new D(void 0),httpConnectionType$:new D(void 0),httpConnectionReused$:new D(void 0),surface$:new D("none"),chromecastState$:new D("NOT_AVAILABLE"),chromecastDeviceName$:new D(void 0),intrinsicVideoSize$:new D(void 0),availableSources$:new D(void 0),is3DVideo$:new D(!1),currentVideoSegmentLength$:new D(0),currentAudioSegmentLength$:new D(0)};this.events={inited$:new X,ready$:new X,started$:new X,playing$:new X,paused$:new X,stopped$:new X,willReady$:new X,willStart$:new X,willResume$:new X,willPause$:new X,willStop$:new X,willDestruct$:new X,watchCoverageRecord$:new X,watchCoverageLive$:new X,managedError$:new X,fatalError$:new X,fetcherRecoverableError$:new X,ended$:new X,looped$:new X,seeked$:new X,willSeek$:new X,autoplaySoundProhibited$:new X,firstBytes$:new X,loadedMetadata$:new X,firstFrame$:new X,canplay$:new X,log$:new X,fetcherError$:new X,severeStallOccured$:new X};this.experimental={element$:new D(void 0),tuningConfigName$:new D([]),enableDebugTelemetry$:new D(!1),dumpTelemetry:gv,getCurrentTime$:new D(null)};if(this.initLogs(),this.tuning=SE(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new tn({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new bE(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new VV("CORE"),this.internalsExposure.expose({player:this})),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(i,r,s)=>{let n=Reflect.get(i,r,s);return typeof n!="function"?n:(...o)=>{try{return n.apply(i,o)}catch(u){let l=o.map(f=>JSON.stringify(f,(p,h)=>{let m=typeof h;return(0,PE.default)(["number","string","boolean"],m)?h:h===null?null:`<${m}>`})),d=`Player.${String(r)}`,c=`Exception calling ${d} (${l.join(", ")})`;throw this.events.fatalError$.next({id:d,category:iu.WTF,message:c,thrown:u}),u}}}})}initVideo(e){var s;this.config=e,(s=this.internalsExposure)==null||s.expose({config:e,logger:this.logger,tuning:this.tuning}),this.setMuted(this.tuning.isAudioDisabled);let t=()=>{var u,l,d;let{container:n,...o}=e;this.tracer.log("initVideo",ai(o)),this.domContainer=yE(e),this.chromecastInitializer.contentId=(u=e.meta)==null?void 0:u.videoId,this.providerContainer=new Cs({sources:e.sources,meta:(l=e.meta)!=null?l:{},failoverHosts:(d=e.failoverHosts)!=null?d:[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,tracer:this.tracer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning,volumeMultiplier:e.volumeMultiplier,panelSize:e.panelSize}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.initTracerSubscription(),this.providerContainer.init(),this.setLiveLowLatency(this.tuning.dashCmafLive.lowLatency.isActiveOnDefault),this.initDebugTelemetry(),this.initWakeLock(),this.playerInited.next(!0)},i=()=>{this.tuning.autostartOnlyIfVisible&&window.requestAnimationFrame?this.playerInitRequest=window.requestAnimationFrame(()=>t()):t()},r=()=>{this.tuning.asyncResolveClientChecker?U.isInited$.pipe(q(n=>!!n),G()).subscribe(()=>{console.log("Core SDK async start"),i()}):i()};return this.isNotActiveTabCase()?(this.tracer.log("request play from hidden tab"),Wd(document,"visibilitychange").pipe(G()).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(q(e=>!!e),G()).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(q(e=>!!e),G()).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(q(e=>!!e),G()).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(q(e=>!!e),G()).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(q(i=>!!i),G()).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(q(t=>!!t),G()).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(q(i=>!!i),G()).subscribe(()=>{var o;let i=this.desiredState.volume,r=i.getTransition(),s=(o=r==null?void 0:r.to.muted)!=null?o:this.info.muted$.getValue(),n=t!=null?t:this.tuning.isAudioDisabled||s;this.tracer.log("setVolume",{volume:e,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:n}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setVolume(e):i.startTransitionTo({volume:e,muted:n})})),this}setMuted(e,t=!1){return this.subscription.add(this.playerInited.pipe(q(i=>!!i),G()).subscribe(()=>{var o;let i=this.desiredState.volume,r=this.tuning.isAudioDisabled&&!t||e,s=i.getTransition(),n=(o=s==null?void 0:s.to.volume)!=null?o:this.info.volume$.getValue();this.tracer.log("setMuted",{isMuted:e,nextMuted:r,volume:n,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue()}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setMuted(r):i.startTransitionTo({volume:n,muted:r})})),this}setVideoStream(e){return this.subscription.add(this.playerInited.pipe(q(t=>!!t),G()).subscribe(()=>{this.desiredState.videoStream.startTransitionTo(e)})),this}setAudioStream(e){return this.subscription.add(this.playerInited.pipe(q(t=>!!t),G()).subscribe(()=>{this.desiredState.audioStream.startTransitionTo(e)})),this}setQuality(e){return this.subscription.add(this.playerInited.pipe(q(t=>!!t),G()).subscribe(()=>{tu(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(q(i=>i.length>0),G()).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(q(t=>!!t),G()).subscribe(()=>{this.tracer.log("setAutoQuality",{enable:e}),this.desiredState.autoVideoTrackSwitching.startTransitionTo(e)})),this}setAutoQualityLimits(e){return this.subscription.add(this.playerInited.pipe(q(t=>!!t),G()).subscribe(()=>{this.tracer.log("setAutoQualityLimits",ai(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e)})),this}setPredefinedQualityLimits(e){return this.subscription.add(this.playerInited.pipe(q(t=>!!t),G()).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(q(t=>!!t),G()).subscribe(()=>{var i;tu(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(q(t=>!!t),G()).subscribe(()=>{e.length&&this.tracer.log("setExternalTextTracks",ai(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t})))})),this}selectTextTrack(e){return this.subscription.add(this.playerInited.pipe(q(t=>!!t),G()).subscribe(()=>{var t;TE(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(q(t=>!!t),G()).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(q(t=>!!t),G()).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(q(i=>!!i),G()).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(q(t=>!!t),G()).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(q(i=>!!i),G()).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(q(e=>e),G()).subscribe(()=>{let e=this.getScene3D();e&&e.holdCamera()})),this}releaseCamera(){return this.subscription.add(this.playerInited.pipe(q(e=>!!e),G()).subscribe(()=>{let e=this.getScene3D();e&&e.releaseCamera()})),this}getExactTime(){if(!this.providerContainer)return 0;let e=this.providerContainer.providerOutput.element$.getValue();if(MV(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),i=t.state==="none"?void 0:t.position;return IE(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(ri(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(z(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(z(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(z(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(z(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(z(e=>e.to)).subscribe(e=>{this.info.autoQualityLimits$.next(e);let{highQualityLimit:t,trafficSavingLimit:i}=this.tuning.autoTrackSelection;this.info.predefinedQualityLimitType$.next(mc(e,t,i))})),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(q(({from:e})=>e==="stopped"),G()).subscribe(()=>{this.initedAt=ru(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case"ready":this.events.ready$.next();break;case"playing":this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case"paused":this.events.paused$.next();break;case"stopped":this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case"ready":this.events.willReady$.next();break;case"paused":this.events.willPause$.next();break;case"playing":this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case"stopped":this.events.willStop$.next();break;default:}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("willSeekEvent",ai(n)),n.state==="requested"?this.desiredState.seekState.setState({...n,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:iu.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe(G()).subscribe(this.events.autoplaySoundProhibited$)).add(e.providerOutput.severeStallOccurred$.subscribe(this.events.severeStallOccured$)).add(e.providerOutput.seekedEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("seekedEvent",ai(n)),n.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe(z(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(z(n=>n.destination),K()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(Vt({availableVideoTracks:e.providerOutput.availableVideoTracks$,currentVideoStream:e.providerOutput.currentVideoStream$}).pipe(z(({availableVideoTracks:n,currentVideoStream:o})=>n.filter(u=>o?o.id===u.streamId:!0).map(({quality:u})=>u).sort((u,l)=>wE(u)?1:wE(l)?-1:CV(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(K()).subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.pipe(q(n=>IE(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(K((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe(K((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(K()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(K()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(K()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.autoVideoTrackLimits$.subscribe(n=>{this.desiredState.autoVideoTrackLimits.setState(n!=null?n:{})})).add(e.providerOutput.currentBuffer$.pipe(z(n=>n?{start:n.from,end:n.to}:{start:0,end:0})).subscribe(this.info.currentBuffer$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.isLiveEnded$.pipe(zd(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(Vt({hasLiveOffsetByPaused:ri(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(z(n=>n.to),K(),z(n=>n==="paused")),isLowLatency:e.providerOutput.isLowLatency$}).subscribe(({hasLiveOffsetByPaused:n,isLowLatency:o})=>{if(window.clearTimeout(this.hasLiveOffsetByPausedTimer),n){this.hasLiveOffsetByPausedTimer=window.setTimeout(()=>{this.hasLiveOffsetByPaused.next(!0)},this.getActiveLiveDelay(o));return}this.hasLiveOffsetByPaused.next(!1)})).add(Vt({atLiveEdge:Vt({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Gd({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(z(({isLive:n,position:o,isLowLatency:u})=>{let l=this.getActiveLiveDelay(u);return n&&Math.abs(o)<l/1e3}),K(),zd(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(z(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add(Vt({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(z(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),K(),zd(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(z(n=>n.muted),K()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(z(n=>n.volume),K()).subscribe(this.info.volume$)).add(Gd({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(ri(e.providerOutput.endedEvent$.pipe(EE(!0)),e.providerOutput.seekedEvent$.pipe(EE(!1))).pipe(K()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.providerOutput.fetcherRecoverableError$.subscribe(this.events.fetcherRecoverableError$)).add(e.providerOutput.fetcherError$.subscribe(this.events.fatalError$)).add(e.volumeMultiplierError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe(z(n=>({id:n?`No${n}`:"NoProviders",category:iu.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(G(),z(n=>n!=null?n:ru()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(G(),z(()=>ru()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(G(),z(()=>ru()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$)).add(e.providerOutput.availableSources$.subscribe(this.info.availableSources$));let t=new D(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let i=new D(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(q(({to:n})=>n==="playing"),G()).subscribe(()=>i.next(!1)));let r=0,s=ri(e.providerOutput.isBuffering$,t,i).pipe(z(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||i.getValue();return n&&!o}),K());this.subscription.add(s.subscribe(n=>{n?r=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(r),this.info.isStalled$.next(!1))})),this.subscription.add(ri(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{let n=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n==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(ri(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,e.providerOutput.elementVisible$,this.chromecastInitializer.castState$).subscribe(()=>{let n=e.providerOutput.inPiP$.getValue(),o=e.providerOutput.inFullscreen$.getValue(),u=e.providerOutput.element$.getValue(),l=e.providerOutput.elementVisible$.getValue(),d=this.chromecastInitializer.castState$.getValue(),c;d==="CONNECTED"?c="second_screen":u?l?n?c="pip":o?c="fullscreen":c="inline":c="invisible":c="none",this.info.surface$.getValue()!==c&&this.info.surface$.next(c)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(z(e=>e==null?void 0:e.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new xE;this.subscription.add(t),this.subscription.add(e.current$.pipe(K((i,r)=>i.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(q(i=>i.length>0),G()).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=St(e,{container:this.domContainer.getBoundingClientRect(),panelSize:this.config.panelSize,estimatedThroughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),playbackRate:this.info.currentPlaybackRate$.getValue(),forwardBufferHealth:0,abrLogger:this.abrLogger})),this.desiredState.videoTrack.startTransitionTo(t),this.info.currentQuality$.next(t.quality),this.info.videoBitrate$.next(t.bitrate)}initLogs(){this.subscription.add(ri(this.desiredState.videoTrack.stateChangeStarted$.pipe(z(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(z(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(z(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(z(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(z(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(z(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(z(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(z(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(z(e=>({component:"desiredState",message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`}))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){var t;let e=(t=this.providerContainer)==null?void 0:t.providerOutput;tu(this.providerContainer),tu(e),bv(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(i=>mv(i)),this.providerContainer.current$.subscribe(({type:i})=>Ta("provider",i)),e.duration$.subscribe(i=>Ta("duration",i)),e.availableVideoTracks$.pipe(q(i=>!!i.length),G()).subscribe(i=>Ta("tracks",i)),this.events.fatalError$.subscribe(new Pe("fatalError")),this.events.managedError$.subscribe(new Pe("managedError")),e.position$.subscribe(new Pe("position")),e.currentVideoTrack$.pipe(z(i=>i==null?void 0:i.quality)).subscribe(new Pe("quality")),this.info.currentBuffer$.subscribe(new Pe("buffer")),e.isBuffering$.subscribe(new Pe("isBuffering"))].forEach(i=>this.subscription.add(i)),Ta("codecs",U.video.supportedCodecs)}initTracerSubscription(){let e=AE(this.tracer.log.bind(this.tracer)),t=AE(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(K()).subscribe(e("currentPlaybackRate"))).add(this.info.isAutoQualityEnabled$.subscribe(e("isAutoQualityEnabled"))).add(this.info.autoQualityLimits$.subscribe(e("autoQualityLimits"))).add(this.info.currentFormat$.subscribe(e("currentFormat"))).add(this.info.availableQualities$.subscribe(e("availableQualities"))).add(this.info.availableQualitiesFps$.subscribe(e("availableQualitiesFps"))).add(this.info.availableAudioTracks$.subscribe(e("availableAudioTracks"))).add(this.info.isAudioAvailable$.subscribe(e("isAudioAvailable"))).add(Vt({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe(q(({currentQuality:i,videoBitrate:r})=>!!i&&!!r),K((i,r)=>i.currentQuality===r.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe(q(i=>i>0),K()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe(q(i=>i>0),K()).subscribe(e("currentAudioSegmentLength"))).add(this.info.hostname$.subscribe(e("hostname"))).add(this.info.currentTextTrack$.subscribe(e("currentTextTrack"))).add(this.info.availableTextTracks$.subscribe(e("availableTextTracks"))).add(this.info.autoQualityLimitingAvailable$.subscribe(e("autoQualityLimitingAvailable"))).add(Vt({currentBuffer:this.info.currentBuffer$.pipe(q(i=>i.end>0),K((i,r)=>i.end===r.end&&i.start===r.start)),position:this.info.position$.pipe(K())}).pipe(Yd(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe(K()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe(K()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe(K()).subscribe(e("canChangePlaybackSpeed"))).add(Vt({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(q(({liveTime:i,liveBufferTime:r})=>!!i&&!!r),Yd(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(K(),q(i=>i===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(K(),q(i=>i===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe(K()).subscribe(e("muted"))).add(this.info.volume$.pipe(K()).subscribe(e("volume"))).add(this.info.isEnded$.pipe(K(),q(i=>i===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add(Vt({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(q(({throughputEstimation:i,rtt:r})=>!!i&&!!r),Yd(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(K(),q(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:iu.DOM,message:String(r)})})};this.subscription.add(ri(Wd(document,"visibilitychange"),Wd(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",ai({quality:t,availableTracks:ai(e),track:ai(i),isAutoQuality:!i})),i?this.desiredState.videoTrack.startTransitionTo(i):this.setAutoQuality(!0)}getActiveLiveDelay(e=!1){return e?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay}isNotActiveTabCase(){return document.hidden&&this.tuning.autoplayOnlyInActiveTab&&!Ra()}};import{Subscription as UX,Observable as qX,Subject as HX,ValueSubject as jX,VideoQuality as QX}from"@vkontakte/videoplayer-shared/es2018";var GX=`@vkontakte/videoplayer-core@${Bp}`;export{zs as ChromecastState,cu as HttpConnectionType,qX as Observable,ke as PlaybackState,au as Player,Ys as PredefinedQualityLimits,GX as SDK_VERSION,HX as Subject,UX as Subscription,du as Surface,Bp as VERSION,jX as ValueSubject,wt as VideoFormat,QX as VideoQuality,U as clientChecker,ya as isMobile};
|
|
178
|
+
`;var Dr=class{constructor(e,t,i){this.videoInitialized=!1;this.active=!1;this.container=e,this.sourceVideoElement=t,this.params=i,this.canvas=this.createCanvas();let r=this.canvas.getContext("webgl");if(!r)throw new Error("Could not initialize WebGL context");this.gl=r,this.container.appendChild(this.canvas),this.camera=new Po(this.params.fov,this.params.orientation),this.cameraRotationManager=new ko(this.camera,{rotationSpeed:this.params.rotationSpeed,maxYawAngle:this.params.maxYawAngle,rotationSpeedCorrection:this.params.rotationSpeedCorrection,degreeToPixelCorrection:this.params.degreeToPixelCorrection,speedFadeTime:this.params.speedFadeTime,speedFadeThreshold:this.params.speedFadeThreshold}),this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.textureMappingBuffer=this.createTextureMappingBuffer(),this.updateTextureMappingBuffer(),this.program=this.createProgram(),this.videoTexture=this.createTexture(),this.gl.useProgram(this.program),this.videoElementDataLoadedFn=this.onDataLoadedHandler.bind(this),this.renderFn=this.render.bind(this)}play(){this.active||(this.videoInitialized?this.doPlay():this.sourceVideoElement.readyState>=2?(this.videoInitialized=!0,this.doPlay()):this.sourceVideoElement.addEventListener("loadeddata",this.videoElementDataLoadedFn))}stop(){this.active=!1}startCameraManualRotation(e,t){this.cameraRotationManager.setRotationSpeed(e*this.params.rotationSpeed,t*this.params.rotationSpeed,0),this.cameraRotationManager.startRotation()}stopCameraManualRotation(e=!1){this.cameraRotationManager.stopRotation(e)}turnCamera(e,t){this.cameraRotationManager.turnCamera(e,t)}pointCameraTo(e,t){this.cameraRotationManager.pointCameraTo(e,t)}pixelToDegree(e){return{x:this.params.degreeToPixelCorrection*this.params.fov.x*-e.x/this.viewportWidth,y:this.params.degreeToPixelCorrection*this.params.fov.y*e.y/this.viewportHeight}}getCameraRotation(){return this.camera.orientation}holdCamera(){this.cameraRotationManager.stopRotation(!0)}releaseCamera(){this.cameraRotationManager.onCameraRelease()}destroy(){this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),this.stop(),this.canvas.remove()}setViewportSize(e,t){this.viewportWidth=e,this.viewportHeight=t,this.canvas.width=this.viewportWidth,this.canvas.height=this.viewportHeight,this.gl.viewport(0,0,this.canvas.width,this.canvas.height)}onDataLoadedHandler(){this.videoInitialized=!0,this.doPlay()}doPlay(){this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.active=!0,this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),requestAnimationFrame(this.renderFn)}render(e){this.cameraRotationManager.tick(e),this.updateTexture(),this.updateTextureMappingBuffer();let t=this.gl.getAttribLocation(this.program,"a_vertex"),i=this.gl.getAttribLocation(this.program,"a_texel"),r=this.gl.getUniformLocation(this.program,"u_texture"),s=this.gl.getUniformLocation(this.program,"u_focus");this.gl.enableVertexAttribArray(t),this.gl.enableVertexAttribArray(i),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.vertexBuffer),this.gl.vertexAttribPointer(t,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.vertexAttribPointer(i,2,this.gl.FLOAT,!1,0,0),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.uniform1i(r,0),this.gl.uniform2f(s,-this.camera.orientation.x,-this.camera.orientation.y),this.gl.drawArrays(this.gl.TRIANGLE_FAN,0,4),this.gl.bindTexture(this.gl.TEXTURE_2D,null),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),this.gl.disableVertexAttribArray(t),this.gl.disableVertexAttribArray(i),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){let i=this.gl.createShader(t);if(!i)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(i,e),this.gl.compileShader(i),!this.gl.getShaderParameter(i,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(i));return i}createProgram(){let e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");let t=this.createShader(lI,this.gl.VERTEX_SHADER),i=this.createShader(cI,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,i),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){let e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,i=1,r=this.frameHeight/(this.frameWidth/this.viewportWidth);return r>this.viewportHeight?t=this.viewportHeight/r:i=r/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-i,t,-i,t,i,-t,i]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){let e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,i=this.camera.fov.x/360/2,r=this.camera.fov.y/180/2,s=e-i,n=t-r,o=e+i,u=t-r,l=e+i,c=t+r,d=e-i,f=t+r;return[s,n,o,u,l,c,d,f]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){let e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}};import{isNullable as RB,now as ms,once as LB,Subscription as $B,ValueSubject as ad,isNonNullable as MB,safeStorage as sd,filterChanged as DB}from"@vkontakte/videoplayer-shared/es2018";var Ro="stalls_manager_metrics",nd="stalls_manager_abr_params",dI="stalls_manager_default_tuning_abr_params",od=class{constructor(){this.isSeeked$=new ad(!1);this.isBuffering$=new ad(!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 $B;this.severeStallOccurred$=new ad(!1)}init(e){this.currentStallDuration$=e.currentStallDuration$,this.videoLastDataObtainedTimestamp$=e.videoLastDataObtainedTimestamp$,this.throughput$=e.throughput$,this.rtt$=e.rtt$,this.tuning=e.tuning,this.abrParams=e.abrParams,this.resetStoredAbrParamsIfNeeded(),this.subscribe(e)}get videoMaxQualityLimit(){return this.maxQualityLimit}get predictedThroughput(){return this.predictedThroughputWithoutData}get abrTuningParams(){let e=this.tuning.enabled?this.getStoredData(nd):{};return{...this.abrParams,...e}}set lastVideoTrackSelected(e){var t;((t=this.lastUniqueVideoTrackSelected)==null?void 0:t.id)!==e.id&&(this.lastUniqueVideoTrackSelected=e,this.lastUniqueVideoTrackSelectedTimestamp=ms(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe(),this.currentStallDuration$.getValue()!==0&&this.updateStallData();let e=(ms()-this.providerStartWatchingTimestamp-this.sumStallsDuration)/1e3,t=this.sumStallsDuration;this.addStallInfoToHistory(e,t),this.updateStoredAbrParams()}resetStoredAbrParamsIfNeeded(){let{bitrateFactorAtEmptyBuffer:e,bitrateFactorAtFullBuffer:t,containerSizeFactor:i}={...this.getStoredData(dI)},{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:s,containerSizeFactor:n}={...this.abrParams};this.tuning.enabled&&e===r&&t===s&&i===n||(this.removeStoredData(nd),this.setStoredData(dI,{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:s,containerSizeFactor:n}))}updateStoredAbrParams(){let e=[],t=this.getStoredData(Ro,"[]");if(!this.tuning.enabled||t.length<this.tuning.stallsMetricsHistoryLength)return;let i=t.reduce((s,n)=>s+n.tvt,0);if(this.tuning.useTotalStallsDurationPerTvt){let n=t.reduce((o,u)=>o+u.stallsDuration,0)/i;e.push(this.calculateOptimalAbrParams(n,i))}if(this.tuning.useAverageStallsDurationPerTvt){let s=t.reduce((n,o)=>n+o.stallsDurationPerTvt,0)/t.length;e.push(this.calculateOptimalAbrParams(s,i))}this.tuning.useEmaStallsDurationPerTvt&&e.push(this.calculateOptimalAbrParams(t[t.length-1].stallsDurationPerTvtSmoothed,i));let r={bitrateFactorAtEmptyBuffer:Math.max(...e.map(s=>s.bitrateFactorAtEmptyBuffer)),bitrateFactorAtFullBuffer:Math.max(...e.map(s=>s.bitrateFactorAtFullBuffer)),containerSizeFactor:Math.min(...e.map(s=>s.containerSizeFactor))};this.setStoredData(Ro,[]),this.setStoredData(nd,r)}calculateOptimalAbrParams(e,t){let{targetStallsDurationPerTvt:i,deviationStallsDurationPerTvt:r,criticalStallsDurationPerTvt:s,abrAdjustingSpeed:n,significantTvt:o,stallsMetricsHistoryLength:u}=this.tuning,l=n*Math.min(t/(o*u),1),c=this.abrTuningParams;return e<i-r?c={bitrateFactorAtEmptyBuffer:Math.max(c.bitrateFactorAtEmptyBuffer-l,this.abrParams.minBitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.max(c.bitrateFactorAtFullBuffer-l,this.abrParams.minBitrateFactorAtFullBuffer),containerSizeFactor:Math.min(c.containerSizeFactor+l,this.abrParams.maxContainerSizeFactor)}:e>i+r&&(c={bitrateFactorAtEmptyBuffer:Math.min(c.bitrateFactorAtEmptyBuffer+l,this.abrParams.maxBitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.min(c.bitrateFactorAtFullBuffer+l,this.abrParams.maxBitrateFactorAtFullBuffer),containerSizeFactor:Math.max(c.containerSizeFactor-l,this.abrParams.minContainerSizeFactor)}),e>s&&(c={bitrateFactorAtEmptyBuffer:Math.max(c.bitrateFactorAtEmptyBuffer,this.abrParams.bitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.max(c.bitrateFactorAtFullBuffer,this.abrParams.bitrateFactorAtFullBuffer),containerSizeFactor:Math.min(c.containerSizeFactor,this.abrParams.containerSizeFactor)}),c}getStoredData(e,t="{}"){var i;return JSON.parse((i=sd.get(e))!=null?i:t)}setStoredData(e,t){sd.set(e,JSON.stringify(t))}removeStoredData(e){sd.remove(e)}addStallInfoToHistory(e,t){if(e<this.tuning.minTvtToBeCounted||e>this.tuning.maxTvtToBeCounted||e*1e3<t)return;let i=this.getStoredData(Ro,"[]"),r=t/e,s=i.length?Dt(i[i.length-1].stallsDurationPerTvtSmoothed,t/e,this.tuning.emaAlpha):r,n={tvt:e,stallsDuration:t,stallsDurationPerTvt:r,stallsDurationPerTvtSmoothed:s};i.push(n),i.length>this.tuning.stallsMetricsHistoryLength&&i.shift(),this.setStoredData(Ro,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(LB()).subscribe(t=>this.providerStartWatchingTimestamp=ms())),this.subscription.add(this.currentStallDuration$.pipe(DB()).subscribe(t=>{let{stallDurationNoDataBeforeQualityDecrease:i,stallCountBeforeQualityDecrease:r,resetQualityRestrictionTimeout:s,ignoreStallsOnSeek:n}=this.tuning;if(RB(this.lastUniqueVideoTrackSelected)||n&&this.isSeeked$.getValue())return;let o=this.rtt$.getValue(),u=this.throughput$.getValue(),l=this.videoLastDataObtainedTimestamp$.getValue(),c=ms(),d=r&&this.currentStallsCount>=r,f=i&&c-this.lastUniqueVideoTrackSelectedTimestamp>=i+o&&c-l>=i+o&&t>=i;(d||f)&&(this.severeStallOccurred$.next(!0),window.clearTimeout(this.qualityRestrictionTimer),this.maxQualityLimit=this.lastUniqueVideoTrackSelected.quality,MB(this.lastUniqueVideoTrackSelected.bitrate)&&u>this.lastUniqueVideoTrackSelected.bitrate&&(this.predictedThroughputWithoutData=this.lastUniqueVideoTrackSelected.bitrate)),!t&&ms()-this.providerStartWatchingTimestamp>this.lastStallDuration&&(this.updateStallData(),this.severeStallOccurred$.next(!1),window.clearTimeout(this.qualityRestrictionTimer),this.qualityRestrictionTimer=window.setTimeout(()=>{this.maxQualityLimit=void 0,this.predictedThroughputWithoutData=0},s)),this.lastStallDuration=t}))}},Lo=od;import{combine as CB,map as BB,observeElementSize as VB,Subscription as _B,ValueSubject as ud,noop as OB}from"@vkontakte/videoplayer-shared/es2018";var $o=class{constructor(){this.subscription=new _B;this.pipSize$=new ud(void 0);this.videoSize$=new ud(void 0);this.elementSize$=new ud(void 0);this.pictureInPictureWindowRemoveEventListener=OB}connect({observableVideo:e,video:t}){let i=r=>{let s=r.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add(VB(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(CB({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(BB(({videoSize:r,inPip:s,pipSize:n})=>s?n:r)).subscribe(this.elementSize$))}getValue(){return this.elementSize$.getValue()}subscribe(e,t){return this.elementSize$.subscribe(e,t)}getObservable(){return this.elementSize$}destroy(){this.pictureInPictureWindowRemoveEventListener(),this.subscription.unsubscribe()}};var Di=class{constructor(e){this.subscription=new QB;this.videoState=new q("stopped");this.observableVideo=null;this.droppedFramesManager=new vr;this.stallsManager=new Lo;this.elementSizeManager=new $o;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Xt;this.audioTrackSwitchHistory=new Xt;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(r.state==="requested"&&(i==null?void 0:i.to)!=="paused"&&e!=="stopped"&&t!=="stopped"&&this.seek(r.position,r.forcePrecise),t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),$(this.params.desiredState.playbackState,"stopped",!0));return}switch(e){case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();return;case"ready":t==="paused"?(this.videoState.setState("paused"),$(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="ready"&&$(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):t==="playing"&&this.video.paused?this.playIfAllowed():(i==null?void 0:i.to)==="playing"&&$(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&$(this.params.desiredState.playbackState,"paused");return;default:return NB(e)}}};this.init3DScene=e=>{var i,r,s;if(this.scene3D)return;this.scene3D=new Dr(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((i=e.projectionData)==null?void 0:i.pose.yaw)||0,y:((r=e.projectionData)==null?void 0:r.pose.pitch)||0,z:((s=e.projectionData)==null?void 0:s.pose.roll)||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSizeManager.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.textTracksManager=new Xe(e.source.url),this.params=e,this.video=Me(e.container,e.tuning),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Te(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.player=new Ao({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params;HB(this.observableVideo)&&(this.observableVideo=Be(this.video),this.subscription.add(()=>{var n;return(n=this.observableVideo)==null?void 0:n.destroy()}));let i=this.constructor.name,r=n=>{e.error$.next({id:i,category:pI.WTF,message:`${i} internal logic error`,thrown:n})},s=(n,o)=>this.subscription.add(n.subscribe(o,r));return{output:e,desiredState:t,observableVideo:this.observableVideo,genericErrorListener:r,connect:s}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:s}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(ld(l=>!!l.length),fI()).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(cd(l=>l.to.state!=="none"),Mo());this.stallsManager.init({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$,videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,tuning:this.params.tuning.stallsManager,abrParams:this.params.tuning.autoTrackSelection,isBuffering$:i.isBuffering$,looped$:i.looped$,playing$:i.playing$}),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(this.player.error$,e.error$),s(this.player.fetcherRecoverableError$,e.fetcherRecoverableError$),s(this.player.fetcherError$,e.fetcherError$),s(this.player.lastConnectionType$,e.httpConnectionType$),s(this.player.lastConnectionReused$,e.httpConnectionReused$),s(this.player.isLive$,e.isLive$),s(this.player.lastRequestFirstBytes$.pipe(ld(hI),fI()),e.firstBytesEvent$),s(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),s(this.videoState.stateChangeEnded$.pipe(cd(l=>l.to)),this.params.output.playbackState$),this.subscription.add(i.looped$.subscribe(()=>this.player.warmUpMediaSourceIfNeeded(),r)),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(bt(this.video,t.isLooped,r)),this.subscription.add(Ce(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Ke(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),s(Je(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),$(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),$(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:l})=>{if(l==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let c=this.player.getStreams();if(UB(c,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let f=[];for(let p of c.audio){f.push(Hc(p));let h=[];for(let m of p.representations){let b=WT(m);h.push(b),this.audioTracksMap.set(b,{stream:p,representation:m})}this.audioStreamsMap.set(p,h)}this.params.output.availableAudioStreams$.next(f)}let d=[];for(let f of c.video){d.push(Qc(f));let p=[];for(let h of f.representations){let m=GT({...h,streamId:f.id});m&&(p.push(m),this.videoTracksMap.set(m,{stream:f,representation:h}))}this.videoStreamsMap.set(f,p)}this.params.output.availableVideoStreams$.next(d);for(let f of c.text)for(let p of f.representations){let h=zT(f,p);this.textTracksMap.set(h,{stream:f,representation:p})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else l==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r)),this.subscription.add(Do(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$,jB(this.video,"progress")).pipe(ld(()=>this.videoTracksMap.size>0)).subscribe(async()=>{let l=this.player.state$.getState(),c=this.player.state$.getTransition();if(!(0,mI.default)(["manifest_ready","running"],l)||c)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let d=this.selectVideoAudioRepresentations();if(!d)return;let[f,p]=d,h=[...this.videoTracksMap.keys()].find(b=>{var S;return((S=this.videoTracksMap.get(b))==null?void 0:S.representation.id)===f.id});hI(h)&&(this.stallsManager.lastVideoTrackSelected=h);let m=this.params.desiredState.autoVideoTrackLimits.getTransition();if(m&&this.params.output.autoVideoTrackLimits$.next(m.to),l==="manifest_ready")await this.player.initRepresentations(f.id,p==null?void 0:p.id,this.params.sourceHls);else if(await this.player.switchRepresentation("video",f.id),p){let b=!!t.audioStream.getTransition();await this.player.switchRepresentation("audio",p.id,b)}},r)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:l})=>{this.scene3D&&l&&this.scene3D.pointCameraTo(l.x,l.y)})),this.subscription.add(this.elementSizeManager.subscribe(l=>{this.scene3D&&l&&this.scene3D.setViewportSize(l.width,l.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(Mo()).subscribe(l=>{let c=[...this.videoTracksMap.entries()].find(([,{representation:m}])=>m.id===l);if(!c){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[d,{stream:f}]=c,p=this.params.desiredState.videoStream.getTransition();p&&p.to&&p.to.id===f.id&&this.params.desiredState.videoStream.setState(p.to),e.currentVideoTrack$.next(d),e.currentVideoStream$.next(Qc(f));let h=this.player.calculateDurationFromSegments();h&&this.params.output.duration$.next(h/1e3)},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(Mo()).subscribe(l=>{let c=[...this.audioTracksMap.entries()].find(([,{representation:h}])=>h.id===l);if(!c){e.currentAudioStream$.next(void 0);return}let[d,{stream:f}]=c,p=this.params.desiredState.audioStream.getTransition();p&&p.to&&p.to.id===f.id&&this.params.desiredState.audioStream.setState(p.to),e.currentAudioStream$.next(Hc(f))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(l=>{var c,d;if(l!=null&&l.is3dVideo&&((c=this.params.tuning.spherical)!=null&&c.enabled))try{this.init3DScene(l),e.is3DVideo$.next(!0)}catch(f){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${f}`})}else this.destroy3DScene(),(d=this.params.tuning.spherical)!=null&&d.enabled&&e.is3DVideo$.next(!1)},r)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,r)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,r)),this.textTracksManager.connect(this.video,t,e);let o=t.playbackState.stateChangeStarted$.pipe(cd(({to:l})=>l==="ready"),Mo());this.subscription.add(Do(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,dd(["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(Do(o,this.player.state$.stateChangeEnded$,dd(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let u=Do(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,dd(["init"])).pipe(qB(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){var k,V,D,_,Y,J,T,R,x,w,B,ne,Fe;if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?xa:Ea,t=this.params.tuning.useNewAutoSelectVideoTrack?eo:Zn,i=this.params.tuning.useNewAutoSelectVideoTrack?vt:Jn,{desiredState:r,output:s}=this.params,n=r.autoVideoTrackSwitching.getState(),o=(k=r.videoTrack.getState())==null?void 0:k.id,l=[...this.videoTracksMap.keys()].find(({id:ie})=>ie===o),c=s.currentVideoTrack$.getValue(),d=((_=(D=r.videoStream.getState())!=null?D:l&&((V=this.videoTracksMap.get(l))==null?void 0:V.stream))!=null?_:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!d)return;let f=[...this.videoStreamsMap.keys()].find(({id:ie})=>ie===d.id),p=f&&this.videoStreamsMap.get(f);if(!p)return;let h=me(this.video.buffered,this.video.currentTime*1e3),m;this.player.isActiveLive$.getValue()?m=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?m=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:m=n?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let b=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,S=Math.min(h/Math.min(m,b||1/0),1),y=(Y=r.audioStream.getState())!=null?Y:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,v=(J=[...this.audioStreamsMap.keys()].find(({id:ie})=>ie===(y==null?void 0:y.id)))!=null?J:this.audioStreamsMap.keys().next().value,I=0;if(v){if(l&&!n){let ie=e(l,p,(T=this.audioStreamsMap.get(v))!=null?T:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);I=Math.max(I,(R=ie==null?void 0:ie.bitrate)!=null?R:-1/0)}if(c){let ie=e(c,p,(x=this.audioStreamsMap.get(v))!=null?x:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);I=Math.max(I,(w=ie==null?void 0:ie.bitrate)!=null?w:-1/0)}}let E=i(p,{container:this.elementSizeManager.getValue(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.stallsManager.abrTuningParams,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:I,forwardBufferHealth:S,current:c,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,stallsVideoMaxQualityLimit:this.stallsManager.videoMaxQualityLimit,stallsPredictedThroughput:this.stallsManager.predictedThroughput,abrLogger:this.params.dependencies.abrLogger}),A=n?E!=null?E:l:l!=null?l:E,M=v&&t(A,p,(B=this.audioStreamsMap.get(v))!=null?B:[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.stallsManager.abrTuningParams,forwardBufferHealth:S,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),L=(ne=this.videoTracksMap.get(A))==null?void 0:ne.representation,P=M&&((Fe=this.audioTracksMap.get(M))==null?void 0:Fe.representation);if(L&&P)return[L,P];if(L&&!P&&this.audioTracksMap.size===0)return[L,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Ve(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),$(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:pI.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.stallsManager.destroy(),this.elementSizeManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),this.params.output.currentVideoStream$.next(void 0),De(this.video),this.tracer.end()}};var bs=class extends Di{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};import{combine as pd,merge as bI,filter as gI,filterChanged as SI,isNullable as hd,map as vI,ValueSubject as fd,isNonNullable as GB}from"@vkontakte/videoplayer-shared/es2018";var gs=class extends Di{constructor(e){super(e),this.textTracksManager.destroy()}subscribe(){super.subscribe();let e=!1,t=-1,{output:i,observableVideo:r,desiredState:s,connect:n}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canPlayLiveTailBuffer$.next(!0),n(r.timeUpdate$,i.liveBufferTime$),n(this.player.liveSeekableDuration$,i.duration$),n(this.player.liveLatency$,i.liveLatency$);let o=new fd(1);n(r.playbackRateState$,o),this.params.tuning.dashCmafLive.catchupLiveForMutedInactiveTab&&this.subscription.add(i.elementVisible$.pipe(SI()).subscribe(u=>{let l=i.position$.getValue(),c=i.volume$.getValue(),d=!c.volume||c.muted;!u&&!l&&d?e=!0:u&&e&&(this.seek(0),e=!1)})),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(s.isLowLatency.stateChangeEnded$.pipe(vI(u=>u.to)).subscribe(this.player.isLowLatency$)).add(pd({liveBufferTime:i.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(vI(({liveBufferTime:u,liveAvailabilityStartTime:l})=>u&&l?u+l:void 0)).subscribe(i.liveTime$)).add(this.player.liveStreamStatus$.pipe(gI(u=>GB(u))).subscribe(u=>i.isLiveEnded$.next(u!=="active"&&i.position$.getValue()===0))).add(pd({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:bI(r.playbackRateState$,new fd(1))}).pipe(gI(({liveStreamStatus:u,liveDuration:l})=>u==="active"&&!!l)).subscribe(({liveDuration:u,playbackRate:l})=>{let c=i.liveBufferTime$.getValue(),d=i.position$.getValue(),{playbackCatchupSpeedup:f}=this.params.tuning.dashCmafLive.lowLatency;d||l<1-f||this.video.paused||hd(c)||(t=u-c)})).add(pd({time:i.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:bI(r.playbackRateState$,new fd(1))}).pipe(SI((u,l)=>this.player.liveStreamStatus$.getValue()==="active"?u.liveDuration===l.liveDuration:u.time===l.time)).subscribe(({time:u,liveDuration:l,playbackRate:c})=>{let d=i.position$.getValue(),{playbackCatchupSpeedup:f}=this.params.tuning.dashCmafLive.lowLatency;if(!d&&!this.video.paused&&c>=1-f||hd(u)||hd(l))return;let p=-1*(l-u-t);i.position$.next(Math.min(p,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(u=>{if(u){let l=YT(u);this.params.output.availableTextTracks$.next([l])}}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=Math.trunc(t/1e3<=Math.abs(this.params.output.duration$.getValue())?t:0);this.player.seekLive(i).then(()=>{this.params.output.position$.next(e/1e3)})}};import{assertNever as S0,assertNonNullable as v0,debounce as y0,ErrorCategory as _I,filter as Ld,filterChanged as Qo,fromEvent as T0,isNonNullable as OI,isNullable as I0,map as $d,merge as Go,observableFrom as Md,once as FI,Subscription as E0}from"@vkontakte/videoplayer-shared/es2018";var kd=O(Ma(),1);import{abortable as xd,assertNonNullable as Vr,combine as _r,ErrorCategory as dt,filter as Uo,filterChanged as Es,flattenObject as xs,fromEvent as Et,getTraceSubscriptionMethod as u0,interval as wd,isNonNullable as ws,isNullable as BI,map as Or,merge as Oi,now as Ad,Subject as qo,Subscription as Pd,tap as l0,throttle as VI,ValueSubject as se}from"@vkontakte/videoplayer-shared/es2018";var _o=O(Ye(),1),_i=O(ot(),1),Oo=O(Ma(),1);var LI=O($n(),1);import{assertNever as WB,ErrorCategory as yI,Subject as TI}from"@vkontakte/videoplayer-shared/es2018";var zB=18,II=!1;try{II=F.browser.isSafari&&!!F.browser.safariVersion&&F.browser.safariVersion<=zB}catch(a){console.error(a)}var md=class{constructor(e){this.bufferFull$=new TI;this.error$=new TI;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:yI.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)};II&&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:yI.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:WB(t)}}},EI=md;import{abortable as ii,assertNonNullable as Oe,ErrorCategory as Bi,fromEvent as yd,getExponentialDelay as Td,isNonNullable as Cr,isNullable as xe,now as Vo,once as ZB,Subject as e0,Subscription as t0,ValueSubject as Vi}from"@vkontakte/videoplayer-shared/es2018";var bd=O(ot(),1);import{videoSizeToQuality as YB,throttleFn as KB}from"@vkontakte/videoplayer-shared/es2018";var xI=({id:a,width:e,height:t,bitrate:i,fps:r,quality:s,streamId:n})=>{var u;let o=(u=s?Kt(s):void 0)!=null?u:YB({width:e,height:t});return o&&{id:a,quality:o,bitrate:i,size:{width:e,height:t},fps:r,streamId:n}},wI=({id:a,bitrate:e})=>({id:a,bitrate:e}),AI=({language:a,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),PI=({language:a,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),gd=({id:a,language:e,label:t,codecs:i,isDefault:r})=>({id:a,language:e,label:t,codec:(0,bd.default)(i.split("."),0),isDefault:r}),Sd=({id:a,language:e,label:t,hdr:i,codecs:r})=>({id:a,language:e,hdr:i,label:t,codec:(0,bd.default)(r.split("."),0)}),vd=a=>"url"in a,Ge=a=>a.type==="template";var kI=a=>{a.sort((t,i)=>t.from-i.from);let e=[a[0]];for(let t=1;t<a.length;t++){let{from:i,to:r}=a[t],s=e[e.length-1];s.to>=i?s.to=Math.max(s.to,r):e.push(a[t])}return e},Ci=(a,e)=>{for(let t of a)if(e(t))return t;return null},RI=a=>{let e=!1,t=KB(()=>{e=!0},a);return()=>{try{return t(),e}finally{e=!1}}};import{fromEvent as XB,Subscription as JB}from"@vkontakte/videoplayer-shared/es2018";var Co=a=>{let e=[];for(let t=0;t<a.length;t++){let i=Math.floor(a.start(t)*1e3),r=Math.ceil(a.end(t)*1e3);e.push(i,r)}return e};var Bo=class{constructor(e,t){this.lastUpdateTs=0;this.lastCallTs=0;this.prevRanges=[];this.subscription=new JB;this.mediaSource=e,this.sourceBuffer=t,this.subscription.add(XB(this.sourceBuffer,"updateend").subscribe(()=>this.updateend()))}updateend(){if(!N(this.mediaSource,this.sourceBuffer))return;let{prevRanges:e}=this,t=Co(this.sourceBuffer.buffered);this.prevRanges=t,this.isRangesRemoved(e,t)&&(this.lastUpdateTs=Date.now())}isRangesRemoved(e,t){if(e.length!==t.length)return!0;for(let i=0;i<e.length;i+=2){let r=e[i],s=e[i+1],n=t[i],o=t[i+1];if(n>r||o<s)return!0}return!1}wasUpdated(){let{lastCallTs:e,lastUpdateTs:t}=this;return this.lastCallTs=Date.now(),e<=t}destroy(){this.subscription.unsubscribe()}};var Ss=class{constructor(e,t,i,{fetcher:r,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new Vi(0);this.currentLowLatencySegmentLength$=new Vi(0);this.currentSegmentLength$=new Vi(0);this.onLastSegment$=new Vi(!1);this.fullyBuffered$=new Vi(!1);this.playingRepresentation$=new Vi(void 0);this.playingRepresentationInit$=new Vi(void 0);this.error$=new e0;this.gaps=[];this.subscription=new t0;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new Z;this.switchAbortController=new Z;this.destroyAbortController=new Z;this.bufferLimit=1/0;this.failedDownloads=0;this.baseUrls=[];this.baseUrlsIndex=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.lastDataObtainedTimestampMs=0;this.loadByteRangeSegmentsTimeoutId=0;this.sourceBufferBufferedDiff=null;this.startWith=ii(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);Oe(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new EI(this.sourceBuffer),this.sourceBufferBufferedDiff=new Bo(this.mediaSource,this.sourceBuffer),this.subscription.add(yd(this.sourceBuffer,"updateend").subscribe(()=>{this.maintain()})),this.subscription.add(yd(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:Bi.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o||!N(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,Ir(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=me(this.sourceBuffer.buffered,o),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,n*2,l<c).catch(d=>{this.handleAsyncError(d,"pruneBuffer")})})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);let i=this.initData.get(t.id),r=this.segments.get(t.id),s=this.parsedInitData.get(t.id);Oe(i,"No init buffer for starting representation"),Oe(r,"No segments for starting representation"),i instanceof ArrayBuffer&&(this.searchGaps(r,t),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s))}.bind(this));this.switchTo=ii(this.destroyAbortController.signal,async function*(e,t=!1){if(!N(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);Oe(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if(xe(s)||xe(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),Oe(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!N(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer();else{let n=this.getCurrentPosition();Cr(n)&&!this.isLive&&(this.bufferLimit=1/0,await this.pruneBuffer(n,1/0,!0)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}this.maintain()}}.bind(this));this.switchToOld=ii(this.destroyAbortController.signal,async function*(e,t=!1){if(!N(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);Oe(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if(xe(s)||xe(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),Oe(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!N(this.mediaSource,this.sourceBuffer)))if(yield this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let n=this.getCurrentPosition();Cr(n)&&(this.isLive||(this.bufferLimit=1/0,await this.pruneBuffer(n,1/0,!0)),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}}.bind(this));this.seekLive=ii(this.destroyAbortController.signal,async function*(e){var u,l;let t=(u=(0,Oo.default)(e,c=>c.representations))!=null?u:[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let c of this.representations.keys()){let d=t.find(h=>h.id===c);d&&this.representations.set(c,d);let f=this.representations.get(c);if(!f||!Ge(f.segmentReference))return;let p=this.getActualLiveStartingSegments(f.segmentReference);this.segments.set(f.id,p)}let i=(l=this.switchingToRepresentationId)!=null?l:this.downloadingRepresentationId,r=this.representations.get(i);Oe(r);let s=this.segments.get(i);Oe(s,"No segments for starting representation");let n=this.initData.get(i);if(Oe(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer))return;let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(s,r),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));var c;this.fetcher=r,this.tuning=s,this.compatibilityMode=u,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!(l!=null&&l.live),this.baseUrls=(c=l==null?void 0:l.baseUrls)!=null?c:[],this.initData=new Map(i.map(d=>[d.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(d=>[d.id,d])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchToWithPreviousAbort(e,t=!1){!N(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new Z,ii(this.switchAbortController.signal,async function*(i,r=!1){this.switchingToRepresentationId=i;let s=this.representations.get(i);Oe(s,`No such representation ${i}`);let n=this.segments.get(i),o=this.initData.get(i);if(xe(o)||xe(n)?yield this.loadInit(s,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(i),Oe(n,"No segments for starting representation"),o=this.initData.get(i),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer||!N(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(o,this.downloadAbortController.signal),r)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=i,yield this.dropBuffer();else{let u=this.getCurrentPosition();Cr(u)&&!this.isLive&&(this.bufferLimit=this.forwardBufferTarget,yield this.pruneBuffer(u,1/0,!0)),this.downloadingRepresentationId=i,this.switchingToRepresentationId=void 0}this.maintain()}}.bind(this))(e,t))}warmUpMediaSource(){!xe(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}async abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);return this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new Z,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(xe(e)||xe(this.downloadingRepresentationId)||xe(this.playingRepresentationId)||xe(this.sourceBuffer)||!N(this.mediaSource,this.sourceBuffer)||Cr(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(Oe(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;let r=i.find(c=>e>=c.time.from&&e<c.time.to);Cr(r)&&isFinite(r.time.from)&&isFinite(r.time.to)&&this.currentSegmentLength$.next((r==null?void 0:r.time.to)-r.time.from);let s=e,n=100;if(this.playingRepresentationId!==this.downloadingRepresentationId){let c=me(this.sourceBuffer.buffered,e),d=r?r.time.to+n:-1/0;r&&r.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&c>=r.time.to-e+n&&(s=d)}if(isFinite(this.bufferLimit)&&Ir(this.sourceBuffer.buffered)>=this.bufferLimit){let c=me(this.sourceBuffer.buffered,e),d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,c<d).catch(f=>{this.handleAsyncError(f,"pruneBuffer")});return}let u=null;if(!this.activeSegments.size&&(u=this.selectForwardBufferSegments(i,t.segmentReference.type,s),u!=null&&u.length)){let c="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if((0,_o.default)(u,r))c="high";else{let d=(0,_i.default)(u,0);d&&d.time.from-r.time.to>=this.forwardBufferTarget/2&&(c="low")}this.loadSegments(u,t,c).catch(d=>{this.handleAsyncError(d,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&r&&r.status==="fed"&&!(u!=null&&u.length)&&me(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let l=(0,_i.default)(i,-1);!this.isLive&&l&&(this.fullyBuffered$.next(l.time.to-e-me(this.sourceBuffer.buffered,e)<n),this.onLastSegment$.next(e-l.time.from>0))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let i=0,r=this.isLive?this.liveInitialAdditionalOffset:0;for(let s of e)Math.trunc(s.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:s.time.from+r,persistent:!0}),i=s.time.to;Cr(t.duration)&&t.duration-i>0&&!this.isLive&&this.gaps.push({representation:t.id,from:i,to:t.duration,persistent:!0})}getActualLiveStartingSegments(e){let t=e.segments,i=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,r=[],s=0,n=t.length-1;do r.unshift(t[n]),s+=t[n].time.to-t[n].time.from,n--;while(s<i&&n>=0);return this.liveInitialAdditionalOffset=s-i,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){let t=(0,Oo.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,Oo.default)(e==null?void 0:e.streams[this.kind],o=>o.representations))!=null?i:[];if(![...this.segments.values()].every(o=>!o.length))for(let o of t){if(!o||!Ge(o.segmentReference))return;let u=o.segmentReference.segments.map(p=>({...p,status:"none",size:void 0})),l=100,c=(r=this.segments.get(o.id))!=null?r:[],d=(n=(s=(0,_i.default)(c,-1))==null?void 0:s.time.to)!=null?n:0,f=u==null?void 0:u.findIndex(p=>d>=p.time.from+l&&d<=p.time.to+l);if(f===-1){this.liveUpdateSegmentIndex=0;let p=this.getActualLiveStartingSegments(o.segmentReference);this.segments.set(o.id,p)}else{let p=u.slice(f+1);this.segments.set(o.id,[...c,...p])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;Oe(e);let t=this.segments.get(e);if(t!=null&&t.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}updateLowLatencyLiveIfNeeded(e){let t=0;for(let i of this.representations.values()){let r=i.segmentReference;if(!Ge(r))return;let s=this.segments.get(i.id);if(!s)continue;let n=s.find(u=>Math.floor(u.time.from)===Math.floor(e.time.from));if(n&&!isFinite(n.time.to)&&(n.time.to=e.time.to,t=n.time.to-n.time.from),!!!s.find(u=>Math.floor(u.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let u=Math.round(e.time.to*r.timescale/1e3).toString(10),l=lt(r.segmentTemplateUrl,{segmentTime:u});s.push({status:"none",time:{from:e.time.to,to:1/0},url:l})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){var s,n,o;let t=(n=(s=this.switchingToRepresentationId)!=null?s:this.downloadingRepresentationId)!=null?n:this.playingRepresentationId;if(!t)return;let i=this.segments.get(t);if(!i)return;let r=i.find(u=>u.time.from<=e&&u.time.to>=e);return(o=r==null?void 0:r.time.from)!=null?o:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e,t;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)==null||e.destroy(),(t=this.sourceBufferBufferedDiff)==null||t.destroy(),this.gapDetectionIdleCallback&&yt&&yt(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&yt&&yt(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(i){if(!(i instanceof DOMException&&i.name==="NotFoundError"))throw i}this.sourceBuffer=null,this.downloadAbortController.abort(),this.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,i){return this.checkEjectedSegments(),this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){if(this.playingRepresentationId!==this.downloadingRepresentationId){let i=e.findIndex(r=>t>=r.time.from&&t<r.time.to);this.liveUpdateSegmentIndex=i}return this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):null}selectForwardBufferSegmentsRecord(e,t,i){let r=this.getForwardBufferDuration(i),s=e.findIndex(({status:f,time:{from:p,to:h}},m)=>{let b=p<=i&&h>=i,S=p>i||b||m===0&&i===0,y=Math.min(this.forwardBufferTarget,this.bufferLimit),v=this.preloadOnly&&p<=i+y||r<y&&h-p>=y||h<=i+y;return(f==="none"||f==="partially_ejected"&&S&&v&&this.sourceBuffer&&N(this.mediaSource,this.sourceBuffer)&&!(Ie(this.sourceBuffer.buffered,p)&&Ie(this.sourceBuffer.buffered,h)))&&S&&v});if(s===-1)return null;if(t!=="byteRange")return e.slice(s,s+1);let n=e,o=0,u=0,l=[],c=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,d=this.preloadOnly?this.forwardBufferTarget:0;for(let f=s;f<n.length&&(o<=c||u<=d);f++){let p=n[f];if(o+=p.byte.to+1-p.byte.from,u+=p.time.to+1-p.time.from,p.status==="none"||p.status==="partially_ejected")l.push(p);else break}return l}async loadSegments(e,t,i="auto"){Ge(t.segmentReference)?await this.loadTemplateSegment(e[0],t,i):await this.loadByteRangeSegments(e,t,i)}async loadTemplateSegment(e,t,i="auto"){e.status="downloading";let r={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(r);let{range:s,url:n,signal:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await ii(o,async function*(){let c=Td(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,c))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let c=await this.fetcher.fetch(n,{range:s,signal:o,onProgress:u,priority:i,isLowLatency:this.isActiveLowLatency(),bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation});if(this.lastDataObtainedTimestampMs=Vo(),!c)return;let d=new DataView(c),f=Tt(t.mime);if(!isFinite(r.segment.time.to)){let m=t.segmentReference.timescale;r.segment.time.to=f.getChunkEndTime(d,m)}u&&r.feedingBytes&&l?await Promise.all(l):await this.sourceBufferTaskQueue.append(d,o);let{serverDataReceivedTimestamp:p,serverDataPreparedTime:h}=f.getServerLatencyTimestamps(d);p&&h&&this.currentLiveSegmentServerLatency$.next(h-p),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(c){this.abortActiveSegments([e]),It(c)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}updateRepresentationsBaseUrlIfNeeded(){if(!this.tuning.dash.enableBaseUrlSupport||!this.baseUrls.length||this.failedDownloads<=this.tuning.dash.maxSegmentRetryCount)return;this.baseUrlsIndex=(this.baseUrlsIndex+1)%this.baseUrls.length;let e=this.baseUrls[this.baseUrlsIndex];for(let t of this.representations.values())Ge(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}async loadByteRangeSegments(e,t,i="auto"){if(!e.length)return;for(let u of e)u.status="downloading",this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:r,url:s,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(await ii(n,async function*(){let u=Td(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),yd(window,"online").pipe(ZB()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(s,{range:r,onProgress:o,signal:n,priority:i,bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation}),this.lastDataObtainedTimestampMs=Vo(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),It(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(Ge(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:(0,_i.default)(e,0).byte.from,to:(0,_i.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:i,range:r,signal:s,onProgress:async(o,u)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=Vo(),await this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:Bi.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!Ge(t.segmentReference))throw new Error("Representation is not template type");let i=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&i.searchParams.set("low-latency","yes");let r=i.toString(),{signal:s}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,c)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=Vo();let d=this.onSomeTemplateDataLoaded({dataView:l,loaded:c,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(d)}catch(d){this.error$.next({id:"SegmentFeeding",category:Bi.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}:void 0;return{url:r,signal:s,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,_o.default)(e,t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:s}){if(!this.activeSegments.size||!N(this.mediaSource,this.sourceBuffer))return;let n=this.representations.get(t);if(n)for(let o of this.activeSegments){let{segment:u}=o;if(o.representationId===t){if(s.aborted){r();continue}if(o.loadedBytes=i,o.loadedBytes>o.feedingBytes){let l=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),c=Tt(n.mime).parseFeedableSegmentChunk(l,this.isLive);c!=null&&c.byteLength&&(u.status="partially_fed",o.feedingBytes+=c.byteLength,await this.sourceBufferTaskQueue.append(c),o.fedBytes+=c.byteLength)}}}}async onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size||!N(this.mediaSource,this.sourceBuffer))return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){if(u.representationId!==t)continue;if(s.aborted){await n();continue}let{segment:l}=u,c=l.byte.from-i,d=l.byte.to-i,f=d-c+1,p=c<r,h=d<=r;if(p){if(l.status==="downloading"&&h){l.status="downloaded";let m=new DataView(e.buffer,e.byteOffset+c,f);await this.sourceBufferTaskQueue.append(m,s)&&!s.aborted?this.onSegmentFullyAppended(u,t):await n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(l.status==="downloading"||l.status==="partially_fed")&&(u.loadedBytes=Math.min(f,r-c),u.loadedBytes>u.feedingBytes)){let m=new DataView(e.buffer,e.byteOffset+c+u.feedingBytes,u.loadedBytes-u.feedingBytes),b=u.loadedBytes===f?m:Tt(o.mime).parseFeedableSegmentChunk(m);b!=null&&b.byteLength&&(l.status="partially_fed",u.feedingBytes+=b.byteLength,await this.sourceBufferTaskQueue.append(b,s)&&!s.aborted?(u.fedBytes+=b.byteLength,u.fedBytes===f&&this.onSegmentFullyAppended(u,t)):await n())}}}}onSegmentFullyAppended(e,t){if(!(xe(this.sourceBuffer)||!N(this.mediaSource,this.sourceBuffer))){!this.isLive&&F.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(Ie(this.sourceBuffer.buffered,e.segment.time.from,100)&&Ie(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:Bi.VIDEO_PIPELINE,message:"Browser stuck on empty result of adding segment to source buffer"})),this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",vd(e.segment)&&(e.segment.size=e.fedBytes);for(let i of this.representations.values()){if(i.id===t)continue;let r=this.segments.get(i.id);if(r)for(let s of r)s.status==="fed"&&Math.round(s.time.from)===Math.round(e.segment.time.from)&&Math.round(s.time.to)===Math.round(e.segment.time.to)&&(s.status="none")}this.isActiveLowLatency()&&this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,e.segment)}}abortSegment(e){e.status==="partially_fed"?e.status="partially_ejected":e.status!=="partially_ejected"&&(e.status="none");for(let t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[r,s]of this.initData.entries()){let n=s instanceof Promise;t||(t=n),s===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let i=this.representations.get(e);i&&(this.initLoadIdleCallback=Tr(()=>(0,LI.default)(this.loadInit(i,"low",!1),()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",i=!1){let r=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!i&&this.failedDownloads>0?ii(this.destroyAbortController.signal,async function*(){let o=Td(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,Tt(e.mime),r)).then(o=>{if(!o)return;let{init:u,dataView:l,segments:c}=o,d=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,d);let f=c;this.isLive&&Ge(e.segmentReference)&&(f=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,f),u&&this.parsedInitData.set(e.id,u)}).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:Bi.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n}async dropBuffer(){for(let e of this.segments.values())for(let t of e)t.status="none";await this.pruneBuffer(0,1/0,!0)}async pruneBuffer(e,t,i=!1){if(!this.sourceBuffer||!N(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||xe(e))return!1;this.checkEjectedSegments();let r=[],s=0,n=o=>{var l;if(s>=t)return;r.push({...o.time});let u=vd(o)?(l=o.size)!=null?l:0:o.byte.to-o.byte.from;s+=u};for(let o of this.segments.values())for(let u of o){let l=u.time.to<=e-this.tuning.dash.bufferPruningSafeZone,c=u.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(l||c)&&u.status==="fed"&&n(u)}for(let o=0;o<this.sourceBuffer.buffered.length;o++){let u=this.sourceBuffer.buffered.start(o)*1e3,l=this.sourceBuffer.buffered.end(o)*1e3,c=0;for(let d of this.segments.values())for(let f of d)(0,_o.default)(["none","partially_ejected"],f.status)&&Math.round(f.time.from)<=Math.round(u)&&Math.round(f.time.to)>=Math.round(l)&&c++;if(c===this.segments.size){let d={time:{from:u,to:l},url:"",status:"none"};n(d)}}if(r.length&&i){let o=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let u of this.segments.values())for(let l of u)l.time.from>=e+o&&l.status==="fed"&&n(l)}return r.length?(r=kI(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||!N(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||!N(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||!N(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||!N(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||xe(e)?0:me(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!this.sourceBuffer||!N(this.mediaSource,this.sourceBuffer))return;let{buffered:i}=this.sourceBuffer;this.tuning.useRefactoredSearchGap&&(this.gaps=this.gaps.filter(s=>{if(s.persistent)return!0;let n=Math.round(s.from),o=Math.round(s.to);for(let u=0;u<i.length;u++)if(n>=Math.round(i.start(u)*1e3)&&o<=Math.round(i.end(u)*1e3))return!1;return!0}));let r={representation:e,from:t.time.from,to:t.time.to,persistent:!1};for(let s=0;s<i.length;s++){let n=i.start(s)*1e3,o=i.end(s)*1e3;if(!(o<=t.time.from||n>=t.time.to)){if(n<=t.time.from&&o>=t.time.to){r=void 0;break}o>t.time.from&&o<t.time.to&&(r.from=o),n<t.time.to&&n>t.time.from&&(r.to=n)}}r&&r.to-r.from>1&&!this.gaps.some(s=>r&&s.from===r.from&&s.to===r.to)&&this.gaps.push(r)}detectGapsWhenIdle(e,t){if(!(this.gapDetectionIdleCallback||!this.sourceBuffer||!N(this.mediaSource,this.sourceBuffer))){if(!this.tuning.useRefactoredSearchGap)for(let i=0;i<this.sourceBuffer.buffered.length;i++)this.gaps=this.gaps.filter(r=>r.persistent||this.sourceBuffer&&(Math.round(r.from)<Math.round(this.sourceBuffer.buffered.start(i)*1e3)||Math.round(r.to)>Math.round(this.sourceBuffer.buffered.end(i)*1e3)));this.gapDetectionIdleCallback=Tr(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:Bi.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if(xe(this.sourceBuffer)||!N(this.mediaSource,this.sourceBuffer)||xe(this.playingRepresentationId)||this.sourceBufferBufferedDiff&&!this.sourceBufferBufferedDiff.wasUpdated())return;let e=Co(this.sourceBuffer.buffered),t=100;for(let i of this.segments.values())for(let r of i){let{status:s}=r;if(s!=="fed"&&s!=="partially_ejected")continue;let n=Math.floor(r.time.from),o=Math.ceil(r.time.to),u=!1,l=0;for(let c=0;c<e.length;c+=2){let d=e[c],f=e[c+1];u||(u=d-t<=n&&f+t>=o),(n>=d&&n<f-t||o>d+t&&o<=f)&&(l+=1)}u||(l===1?r.status="partially_ejected":this.gaps.some(c=>c.from===r.time.from||c.to===r.time.to)?r.status="partially_ejected":r.status="none")}}handleAsyncError(e,t){this.error$.next({id:t,category:Bi.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}calculateDurationFromSegments(){var t;if(!this.playingRepresentationId)return 0;let e=this.segments.get(this.playingRepresentationId);return(e?(t=(0,_i.default)(e,-1))==null?void 0:t.time.to:0)||0}};import{abortable as vs,assertNever as $I,fromEvent as MI,merge as i0,now as ys,Subject as DI,ValueSubject as Id,flattenObject as Br,ErrorCategory as Ts,SubscriptionRemovable as r0}from"@vkontakte/videoplayer-shared/es2018";var No=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:s=!1}){this.lastConnectionType$=new Id(void 0);this.lastConnectionReused$=new Id(void 0);this.lastRequestFirstBytes$=new Id(void 0);this.recoverableError$=new DI;this.error$=new DI;this.abortAllController=new Z;this.subscription=new r0;this.fetchManifest=vs(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=ei(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=mo(i));let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(Fo);return r?(t.log("success",Br({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(r.headers),r.text()):(t.error("error",Br({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=vs(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:s="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1,bufferOptimisation:l=!1}={}){var _,Y,J;let c=e,d=new Headers,f=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{d.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let T=new URL(c,location.href);T.searchParams.append("bytes",`${i.from}-${i.to}`),c=T.toString();break}default:$I(t)}this.requestQuic&&(c=ei(c));let p=this.abortAllController.signal,h;if(n){let T=new Z;if(h=i0(MI(this.abortAllController.signal,"abort"),MI(n,"abort")).subscribe(()=>{try{T.abort()}catch(R){Fo(R)}}),this.subscription.add(h),this.abortAllController.signal.aborted||n.aborted)try{T.abort()}catch(R){Fo(R)}p=T.signal}let m=ys();f.log("startRequest",Br({url:c,priority:s,rangeMethod:t,range:i,isLowLatency:u,requestStartedAt:m}));let b=yield this.doFetch(c,{priority:s,headers:d,signal:p}),S=ys();if(!b)return f.error("error",{message:"No response in request"}),f.end(),this.unsubscribeAbortSubscription(h),null;if((_=this.throughputEstimator)==null||_.addRawRtt(S-m),!b.ok||!b.body){this.unsubscribeAbortSubscription(h);let T=`Fetch error ${b.status}: ${b.statusText}`;return f.error("error",{message:T}),f.end(),Promise.reject(new Error(`Fetch error ${b.status}: ${b.statusText}`))}if(this.onHeadersReceived(b.headers),!r&&!o){this.unsubscribeAbortSubscription(h);let T=ys(),R={requestStartedAt:m,requestEndedAt:T,duration:T-m};return f.log("endRequest",Br(R)),f.end(),b.arrayBuffer()}let y=b.body;if(o){let T;[y,T]=b.body.tee(),(Y=this.throughputEstimator)==null||Y.trackStream(T,u)}let v=y.getReader(),I,E=parseInt((J=b.headers.get("content-length"))!=null?J:"",10);Number.isFinite(E)&&(I=E),!I&&i&&(I=i.to-i.from+1);let A=0,M=I?new Uint8Array(I):new Uint8Array(0),L=!1,P=T=>{this.unsubscribeAbortSubscription(h),L=!0,Fo(T)},k=vs(p,async function*({done:T,value:R}){if(A===0&&this.lastRequestFirstBytes$.next(ys()-m),p.aborted){this.unsubscribeAbortSubscription(h);return}if(!T&&R){if(l&&I)M.set(R,A),A+=R.byteLength;else{let x=new Uint8Array(M.length+R.length);x.set(M),x.set(R,M.length),M=x,A+=R.byteLength}r==null||r(new DataView(M.buffer),A),yield v==null?void 0:v.read().then(k,P)}}.bind(this));yield v==null?void 0:v.read().then(k,P),this.unsubscribeAbortSubscription(h);let V=ys(),D={failed:L,requestStartedAt:m,requestEndedAt:V,duration:V-m};return L?(f.error("endRequest",Br(D)),f.end(),null):(f.log("endRequest",Br(D)),f.end(),M.buffer)}.bind(this));this.fetchByteRangeRepresentation=vs(this.abortAllController.signal,async function*(e,t,i){var S;if(e.type!=="byteRange")return null;let{from:r,to:s}=e.initRange,n=r,o=s,u=!1,l,c;e.indexRange&&(l=e.indexRange.from,c=e.indexRange.to,u=s+1===l,u&&(n=Math.min(l,r),o=Math.max(c,s))),n=Math.min(n,0);let d=yield this.fetch(e.url,{range:{from:n,to:o},priority:i,measureThroughput:!1});if(!d)return null;let f=new DataView(d,r-n,s-n+1);if(!t.validateData(f))throw new Error("Invalid media file");let p=t.parseInit(f),h=(S=e.indexRange)!=null?S:t.getIndexRange(p);if(!h)throw new ReferenceError("No way to load representation index");let m;if(u)m=new DataView(d,h.from-n,h.to-h.from+1);else{let y=yield this.fetch(e.url,{range:h,priority:i,measureThroughput:!1});if(!y)return null;m=new DataView(y)}let b=t.parseSegments(m,p,h);return{init:p,dataView:new DataView(d),segments:b}}.bind(this));this.fetchTemplateRepresentation=vs(this.abortAllController.signal,async function*(e,t){if(e.type!=="template")return null;let i=new URL(e.initUrl,e.baseUrl).toString(),r=yield this.fetch(i,{priority:t,measureThroughput:!1});return r?{init:null,segments:e.segments.map(n=>({...n,status:"none",size:void 0})),dataView:new DataView(r)}:null}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=r,this.tracer=i.createComponentTracer("Fetcher"),this.useEnableSubtitlesParam=s}onHeadersReceived(e){let{type:t,reused:i}=fo(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,t,i="auto"){var s,n;let{type:r}=e;switch(r){case"byteRange":return(s=await this.fetchByteRangeRepresentation(e,t,i))!=null?s:null;case"template":return(n=await this.fetchTemplateRepresentation(e,i))!=null?n:null;default:$I(r)}}destroy(){this.abortAllController.abort(),this.tracer.end(),this.subscription.unsubscribe()}async doFetch(e,t){let i=await Ze(e,t);if(i.ok)return i;let r=await i.text(),s=parseInt(r);if(!isNaN(s))switch(s){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:Ts.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:Ts.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:Ts.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:Ts.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${s})`,category:Ts.FATAL})}}unsubscribeAbortSubscription(e){e&&(e.unsubscribe(),this.subscription.remove(e))}},Fo=a=>{if(!It(a))throw a};import{isNullable as a0,ValueSubject as s0}from"@vkontakte/videoplayer-shared/es2018";var Is=class a{constructor(e,t){this.currentRepresentation$=new s0(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(!a0(e))for(let i of this.representations)for(let r of i){let s=r.segmentReference,n=s.segments.length,o=s.segments[0].time.from,u=s.segments[n-1].time.to;if(e<o||e>u)continue;let l=s.segments.find(c=>c.time.from<=e&&c.time.to>=e);!l||((t=this.currentSegment)==null?void 0:t.time.from)===l.time.from&&this.currentSegment.time.to===l.time.to||(this.currentSegment=l,this.currentRepresentation$.next({...r,label:"Live Text",language:"ru",isAuto:!0,url:new URL(l.url,s.baseUrl).toString()}))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e!=null?e:[]){let i=a.filterRepresentations(t.representations);if(i){this.representations[this.representationsCursor]=i,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!(e!=null&&e.some(t=>a.filterRepresentations(t.representations)))}static filterRepresentations(e){return e==null?void 0:e.filter(t=>t.kind==="text"&&"segmentReference"in t&&Ge(t.segmentReference))}};var c0=["progress","play","seeked","stalled","waiting"],d0=["timeupdate","progress","loadeddata","playing","seeked"];var jo=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new Pd;this.representationSubscription=new Pd;this.state$=new q("none");this.currentVideoRepresentation$=new se(void 0);this.currentVideoRepresentationInit$=new se(void 0);this.currentAudioRepresentation$=new se(void 0);this.currentVideoSegmentLength$=new se(0);this.currentAudioSegmentLength$=new se(0);this.error$=new qo;this.lastConnectionType$=new se(void 0);this.lastConnectionReused$=new se(void 0);this.lastRequestFirstBytes$=new se(void 0);this.currentLiveTextRepresentation$=new se(null);this.isLive$=new se(!1);this.isActiveLive$=new se(!1);this.isLowLatency$=new se(!1);this.liveDuration$=new se(0);this.liveSeekableDuration$=new se(0);this.liveAvailabilityStartTime$=new se(0);this.liveStreamStatus$=new se(void 0);this.bufferLength$=new se(0);this.liveLatency$=new se(void 0);this.liveLoadBufferLength$=new se(0);this.livePositionFromPlayer$=new se(0);this.currentStallDuration$=new se(0);this.videoLastDataObtainedTimestamp$=new se(0);this.fetcherRecoverableError$=new qo;this.fetcherError$=new qo;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new qo;this.gapWatchdogActive=!1;this.destroyController=new Z;this.initManifest=xd(this.destroyController.signal,async function*(e,t,i){var r;this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=le(t,i,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),(r=this.manifest)!=null&&r.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:dt.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=xd(this.destroyController.signal,async function*(){var n,o;this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(u=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:dt.NETWORK,message:"Failed to load manifest",thrown:u})});if(!e)return null;let t=null;try{t=lo(e!=null?e:"",this.manifestUrlString)}catch(u){let l=(n=oo(e))!=null?n:{id:"ManifestParsing",category:dt.PARSER,message:"Failed to parse MPD manifest",thrown:u};this.error$.next(l)}if(!t)return null;let i=(u,l,c)=>{var d,f,p,h;return!!((f=(d=this.element)==null?void 0:d.canPlayType)!=null&&f.call(d,l)&&((h=(p=He())==null?void 0:p.isTypeSupported)!=null&&h.call(p,`${l}; codecs="${c}"`))||u==="text")};if(t.live){this.isLive$.next(!!t.live);let{availabilityStartTime:u,latestSegmentPublishTime:l,streamIsUnpublished:c,streamIsAlive:d}=t.live,f=((o=t.duration)!=null?o:0)/1e3;this.liveSeekableDuration$.next(-1*f),this.liveDuration$.next((l-u)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let p="active";d||(p=c?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(p)}let r={text:t.streams.text,video:[],audio:[]};for(let u of["video","audio"]){let c=t.streams[u].filter(({mime:p,codecs:h})=>i(u,p,h)),d=new Set(c.map(({codecs:p})=>p)),f=Eo(d);if(f&&(r[u]=c.filter(({codecs:p})=>p.startsWith(f))),u==="video"){let p=this.tuning.preferHDR,h=r.video.some(b=>b.hdr),m=r.video.some(b=>!b.hdr);F.display.isHDR&&p&&h?r.video=r.video.filter(b=>b.hdr):m&&(r.video=r.video.filter(b=>!b.hdr))}}let s={...t,streams:r};return this.tracer.log("updateManifestEnd",xs(s)),s}.bind(this));this.initRepresentations=xd(this.destroyController.signal,async function*(e,t,i){var f;this.tracer.log("initRepresentationsStart",xs({initialVideo:e,initialAudio:t,sourceHls:i})),Vr(this.manifest),Vr(this.element),this.representationSubscription.unsubscribe(),this.representationSubscription=new Pd,this.state$.startTransitionTo("representations_ready");let r=p=>{this.representationSubscription.add(Et(p,"error").pipe(Uo(h=>{var m;return!!((m=this.element)!=null&&m.played.length)})).subscribe(h=>{this.error$.next({id:"VideoSource",category:dt.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=this.tuning.useManagedMediaSource?Vn():new MediaSource;let s=document.createElement("source");if(r(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&cr())if(i){let p=document.createElement("source");r(p),p.type="application/x-mpegurl",p.src=i.url,this.element.appendChild(p)}else this.element.disableRemotePlayback=!0;this.isActiveLive$.next(this.isLive$.getValue());let n={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),manifest:this.manifest},o=this.manifest.streams.video.reduce((p,h)=>[...p,...h.representations],[]);if(this.videoBufferManager=new Ss("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],ws(t)){let p=this.manifest.streams.audio.reduce((h,m)=>[...h,...m.representations],[]);this.audioBufferManager=new Ss("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}Is.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new Is(this.manifest.streams.text,n)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$));let u=()=>{var p;(p=this.stallWatchdogSubscription)==null||p.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add(Oi(...d0.map(p=>Et(this.element,p))).pipe(Or(p=>this.element?me(this.element.buffered,this.element.currentTime*1e3):0),Es(),l0(p=>{p>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add(Oi(Et(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe(Es()).subscribe(h=>this.liveStreamEndTimestamp=Ad())),this.subscription.add(Et(this.element,"pause").subscribe(()=>{this.livePauseWatchdogSubscription=wd(1e3).subscribe(h=>{let m=zt(this.manifestUrlString,2);this.manifestUrlString=le(this.manifestUrlString,m+1e3,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add(Et(this.element,"play").subscribe(h=>{var m;return(m=this.livePauseWatchdogSubscription)==null?void 0:m.unsubscribe()})),this.representationSubscription.add(_r({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(Or(({isActiveLive:h,isLowLatency:m})=>h&&m),Es()).subscribe(h=>{this.isManualDecreasePlaybackInLive()||Rr(this.element,1)})),this.representationSubscription.add(_r({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(Uo(({bufferLength:h,isActiveLive:m,isLowLatency:b})=>m&&b&&!!h)).subscribe(({bufferLength:h})=>this.liveBuffer.next(h))),this.representationSubscription.add(this.videoBufferManager.currentLowLatencySegmentLength$.subscribe(h=>{if(!this.isActiveLive$.getValue()&&!this.isLowLatency$.getValue()&&!h)return;let m=this.liveSeekableDuration$.getValue()-h/1e3;this.liveSeekableDuration$.next(Math.max(m,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+h/1e3)})),this.representationSubscription.add(_r({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(Uo(({isLive:h})=>h),Es((h,m)=>m.bufferLength<h.bufferLength),Or(({rtt:h,bufferLength:m,segmentServerLatency:b})=>{let S=zt(this.manifestUrlString,2);return(h/2+m+b+S)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(_r({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:h,isActiveLive:m,isLowLatency:b})=>{if(!b||!m)return;let S=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,y=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,v=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,I=h-S;if(this.isManualDecreasePlaybackInLive())return;let E=1;Math.abs(I)>y&&(E=1+Math.sign(I)*v),Rr(this.element,E)})),this.representationSubscription.add(this.bufferLength$.subscribe(h=>{var b,S;let m=0;if(h){let y=((S=(b=this.element)==null?void 0:b.currentTime)!=null?S:0)*1e3;m=Math.min(...this.bufferManagers.map(I=>{var E,A;return(A=(E=I.getLiveSegmentsToLoadState(this.manifest))==null?void 0:E.to)!=null?A:y}))-y}this.liveLoadBufferLength$.getValue()!==m&&this.liveLoadBufferLength$.next(m)}));let p=0;this.representationSubscription.add(_r({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(VI(1e3)).subscribe(async({liveLoadBufferLength:h,bufferLength:m})=>{if(!this.element||this.isUpdatingLive)return;let b=this.element.playbackRate,S=zt(this.manifestUrlString,2),y=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,v=Math.min(y,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*b),I=this.tuning.dashCmafLive.normalizedActualBufferOffset*b,E=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*b,A=isFinite(h)?h:m,M=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),L=y<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(L);let P="none";if(M?P="active_low_latency":this.isLowLatency$.getValue()&&L?(this.bufferManagers.forEach(k=>k.proceedLowLatencyLive()),P="active_low_latency"):S!==0&&A<v?P="live_forward_buffering":A<v+E&&(P="live_with_target_offset"),isFinite(h)&&(p=h>p?h:p),P==="live_forward_buffering"||P==="live_with_target_offset"){let k=p-(v+I),V=this.normolizeLiveOffset(Math.trunc(S+k/b)),D=Math.abs(V-S),_=0;!h||D<=this.tuning.dashCmafLive.offsetCalculationError?_=S:V>0&&D>this.tuning.dashCmafLive.offsetCalculationError&&(_=V),this.manifestUrlString=le(this.manifestUrlString,_,2)}(P==="live_with_target_offset"||P==="live_forward_buffering")&&(p=0,await this.updateLive())},h=>{this.error$.next({id:"updateLive",category:dt.VIDEO_PIPELINE,thrown:h,message:"Failed to update live with subscription"})}))}let l=Oi(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe(Or(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),c=Oi(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe(Or(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue()))),d=_r({allBuffersFull:l,someBufferEnded:c}).pipe(Es(),Or(({allBuffersFull:p,someBufferEnded:h})=>p&&h),Uo(p=>p));if(this.representationSubscription.add(Oi(this.forceEnded$,d).subscribe(()=>{var p;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(h=>!h.updating))try{(p=this.source)==null||p.endOfStream()}catch(h){this.error$.next({id:"EndOfStream",category:dt.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:h})}})),this.representationSubscription.add(Oi(...this.bufferManagers.map(p=>p.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.representationSubscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.representationSubscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.liveTextManager&&this.representationSubscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$)),this.source.readyState!=="open"){let p=this.tuning.dash.sourceOpenTimeout>=0;yield new Promise(h=>{var m;p&&(this.timeoutSourceOpenId=setTimeout(()=>{var b;if(((b=this.source)==null?void 0:b.readyState)==="open"){h();return}this.error$.next({id:"OpenOfStream",category:dt.VIDEO_PIPELINE,message:"Failed to open MediaSource",thrown:new Error("Timeout reject when wait sourceopen event"),traceAsLog:!0})},this.tuning.dash.sourceOpenTimeout)),(m=this.source)==null||m.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),h()},{once:!0})})}if(!this.isLive$.getValue()){let p=[(f=this.manifest.duration)!=null?f:0,...(0,kd.default)((0,kd.default)([...this.manifest.streams.audio,...this.manifest.streams.video],h=>h.representations),h=>{let m=[];return h.duration&&m.push(h.duration),Ge(h.segmentReference)&&h.segmentReference.totalSegmentsDurationMs&&m.push(h.segmentReference.totalSegmentsDurationMs),m})];this.source.duration=Math.max(...p)/1e3}this.audioBufferManager&&ws(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")}.bind(this));this.tick=()=>{var t,i,r,s;if(!this.element||!this.videoBufferManager||((t=this.source)==null?void 0:t.readyState)!=="open")return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),(i=this.audioBufferManager)==null||i.maintain(e),(r=this.liveTextManager)==null||r.maintain(e),(this.videoBufferManager.gaps.length||(s=this.audioBufferManager)!=null&&s.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=wd(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),n=>{this.error$.next({id:"GapWatchdog",category:dt.WTF,message:"Error handling gaps",thrown:n})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.fetcher=new No({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.subscription.add(this.fetcher.recoverableError$.subscribe(this.fetcherRecoverableError$)),this.subscription.add(this.fetcher.error$.subscribe(this.fetcherError$)),this.liveBuffer=Ct.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator}),this.initTracerSubscription()}async seekLive(e){var r,s,n;Vr(this.element);let t=this.liveStreamStatus$.getValue()!=="active"?Ad()-this.liveStreamEndTimestamp:0,i=this.normolizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=le(this.manifestUrlString,i,2),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await((r=this.videoBufferManager)==null?void 0:r.seekLive(this.manifest.streams.video)),await((s=this.audioBufferManager)==null?void 0:s.seekLive(this.manifest.streams.audio)),(n=this.liveTextManager)==null||n.seekLive(this.manifest.streams.text))}initBuffer(){Vr(this.element),this.state$.setState("running");let e=Et(this.element,"timeupdate");this.tuning.dash.timeupdateEventTickThrottle&&(e=e.pipe(VI(this.tuning.dash.timeupdateEventTickThrottle))),this.subscription.add(Oi(...c0.map(t=>Et(this.element,t)),Et(window,"online"),e).subscribe(()=>this.tick(),t=>{this.error$.next({id:"DashVKPlayer",category:dt.WTF,message:"Internal logic error",thrown:t})})),this.subscription.add(Et(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===HTMLMediaElement.HAVE_CURRENT_DATA&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(Et(this.element,"waiting").subscribe(()=>{var i;this.element&&this.element.readyState===HTMLMediaElement.HAVE_CURRENT_DATA&&!this.element.seeking&&Ie(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let t=()=>{var h,m,b,S,y,v,I,E,A,M,L;if(!this.element||((h=this.source)==null?void 0:h.readyState)!=="open")return;let r=this.currentStallDuration$.getValue();r+=50,this.currentStallDuration$.next(r);let s={timeInWaiting:r},n=Ad(),o=100,u=(b=(m=this.videoBufferManager)==null?void 0:m.lastDataObtainedTimestamp)!=null?b:0;this.videoLastDataObtainedTimestamp$.next(u);let l=(y=(S=this.audioBufferManager)==null?void 0:S.lastDataObtainedTimestamp)!=null?y:0,c=(I=(v=this.videoBufferManager)==null?void 0:v.getForwardBufferDuration())!=null?I:0,d=(A=(E=this.audioBufferManager)==null?void 0:E.getForwardBufferDuration())!=null?A:0,f=c<o&&n-u>this.tuning.dash.crashOnStallTWithoutDataTimeout,p=this.audioBufferManager&&d<o&&n-l>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((f||p)&&r>this.tuning.dash.crashOnStallTWithoutDataTimeout||r>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${r} ms`);if(this.isLive$.getValue()&&r%2e3===0){let P=this.normolizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(P).catch(k=>{this.error$.next({id:"stallIntervalCallback",category:dt.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:k})}),s.liveLastOffset=P}else{let P=this.element.currentTime*1e3;(M=this.videoBufferManager)==null||M.maintain(P),(L=this.audioBufferManager)==null||L.maintain(P),s.position=P}this.tracer.log("stallIntervalCallback",xs(s))};(i=this.stallWatchdogSubscription)==null||i.unsubscribe(),this.stallWatchdogSubscription=wd(50).subscribe(t,r=>{this.error$.next({id:"StallWatchdogCallback",category:dt.NETWORK,message:"Can't restore DASH after stall.",thrown:r})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,i=!1){let r={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return this.tuning.useNewSwitchTo?this.currentStallDuration$.getValue()>0?r==null?void 0:r.switchToWithPreviousAbort(t,i):r==null?void 0:r.switchTo(t,i):r==null?void 0:r.switchToOld(t,i)}async seek(e,t){var r,s,n,o,u;Vr(this.element),Vr(this.videoBufferManager);let i;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?i=e:i=Math.max((r=this.videoBufferManager.findSegmentStartTime(e))!=null?r:e,(n=(s=this.audioBufferManager)==null?void 0:s.findSegmentStartTime(e))!=null?n:e),this.warmUpMediaSourceIfNeeded(i),Ie(this.element.buffered,i)||await Promise.all([this.videoBufferManager.abort(),(o=this.audioBufferManager)==null?void 0:o.abort()]),!(BI(this.element)||BI(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),(u=this.audioBufferManager)==null||u.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",xs({requestedPosition:e,forcePrecise:t,position:i})))}warmUpMediaSourceIfNeeded(e=(t=>(t=this.element)==null?void 0:t.currentTime)()){var i;ws(this.element)&&ws(this.source)&&ws(e)&&((i=this.source)==null?void 0:i.readyState)==="ended"&&this.element.duration*1e3-e>this.tuning.dash.seekBiasInTheEnd&&this.bufferManagers.forEach(r=>r.warmUpMediaSource())}get isStreamEnded(){var e;return((e=this.source)==null?void 0:e.readyState)==="ended"}stop(){var e,t,i;this.tracer.log("stop"),(e=this.element)==null||e.querySelectorAll("source").forEach(r=>{URL.revokeObjectURL(r.src),r.remove()}),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(t=this.videoBufferManager)==null||t.destroy(),this.videoBufferManager=null,(i=this.audioBufferManager)==null||i.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){var e;return(e=this.manifest)==null?void 0:e.streams}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){var e;this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),((e=this.source)==null?void 0:e.readyState)==="open"&&Array.from(this.source.sourceBuffers).every(t=>!t.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=u0(this.tracer.error.bind(this.tracer));this.subscription.add(this.error$.subscribe(e("error")))}isManualDecreasePlaybackInLive(){return!this.element||!this.isLive$.getValue()?!1:1-this.element.playbackRate>this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){var e,t;this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&((e=this.bufferManagers)==null||e.forEach(i=>i.updateLive(this.manifest)),(t=this.liveTextManager)==null||t.updateLive(this.manifest)),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getBufferedTo();if(e===null)return;let t=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),i=this.isJumpGapAfterSeekLive,r=this.element.currentTime;this.isJumpGapAfterSeekLive&&!t&&this.element.currentTime>e&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let s=this.element.currentTime*1e3,n=null,o=this.element.readyState===HTMLMediaElement.HAVE_METADATA?this.tuning.endGapTolerance:0;for(let u of this.bufferManagers)for(let l of u.gaps)(l.persistent||u.playingRepresentation$.getValue()===l.representation)&&l.from-o<=s&&l.to+o>s&&(this.element.duration*1e3-l.to<this.tuning.endGapTolerance?n=1/0:(n===null||l.to>n)&&(n=l.to));if(n!==null){let u=n+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,u===1/0?this.forceEnded$.next():(this.element.currentTime=u/1e3,this.tracer.log("jumpGap",xs({isJumpGapAfterSeekLive:i,isActiveLowLatency:t,initialCurrentTime:r,jumpTo:u,resultCurrentTime:this.element.currentTime})))}}calculateDurationFromSegments(){var e,t;return Math.max(((e=this.videoBufferManager)==null?void 0:e.calculateDurationFromSegments())||0,((t=this.audioBufferManager)==null?void 0:t.calculateDurationFromSegments())||0)}};import{combine as p0,map as h0,observeElementSize as f0,Subscription as m0,ValueSubject as Rd,noop as b0}from"@vkontakte/videoplayer-shared/es2018";var Ho=class{constructor(){this.subscription=new m0;this.pipSize$=new Rd(void 0);this.videoSize$=new Rd(void 0);this.elementSize$=new Rd(void 0);this.pictureInPictureWindowRemoveEventListener=b0}connect({observableVideo:e,video:t}){let i=r=>{let s=r.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add(f0(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(p0({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(h0(({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 E0;this.videoState=new q("stopped");this.observableVideo=null;this.droppedFramesManager=new vr;this.stallsManager=new Lo;this.elementSizeManager=new Ho;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Xt;this.audioTrackSwitchHistory=new Xt;this.selectedRepresentations={audio:null,video:null};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(r.state==="requested"&&(i==null?void 0:i.to)!=="paused"&&e!=="stopped"&&t!=="stopped"&&this.seek(r.position,r.forcePrecise),t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),$(this.params.desiredState.playbackState,"stopped",!0));return}switch(e){case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();return;case"ready":t==="paused"?(this.videoState.setState("paused"),$(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="ready"&&$(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):t==="playing"&&this.video.paused?this.playIfAllowed():(i==null?void 0:i.to)==="playing"&&$(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&$(this.params.desiredState.playbackState,"paused");return;default:return S0(e)}}};this.init3DScene=e=>{var i,r,s;if(this.scene3D)return;this.scene3D=new Dr(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((i=e.projectionData)==null?void 0:i.pose.yaw)||0,y:((r=e.projectionData)==null?void 0:r.pose.pitch)||0,z:((s=e.projectionData)==null?void 0:s.pose.roll)||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSizeManager.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.textTracksManager=new Xe(e.source.url),this.params=e,this.video=Me(e.container,e.tuning),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Te(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.player=new jo({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params;I0(this.observableVideo)&&(this.observableVideo=Be(this.video),this.subscription.add(()=>{var n;return(n=this.observableVideo)==null?void 0:n.destroy()}));let i=this.constructor.name,r=n=>{e.error$.next({id:i,category:_I.WTF,message:`${i} internal logic error`,thrown:n})},s=(n,o)=>this.subscription.add(n.subscribe(o,r));return{output:e,desiredState:t,observableVideo:this.observableVideo,genericErrorListener:r,connect:s}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:s}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(Ld(d=>!!d.length),FI()).subscribe(d=>{this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:d})}));let n=this.params.desiredState.seekState.stateChangeEnded$.pipe($d(d=>d.to.state!=="none"),Qo());this.stallsManager.init({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$,videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,tuning:this.params.tuning.stallsManager,abrParams:this.params.tuning.autoTrackSelection,isBuffering$:i.isBuffering$,looped$:i.looped$,playing$:i.playing$}),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(this.player.error$,e.error$),s(this.player.fetcherRecoverableError$,e.fetcherRecoverableError$),s(this.player.fetcherError$,e.fetcherError$),s(this.player.lastConnectionType$,e.httpConnectionType$),s(this.player.lastConnectionReused$,e.httpConnectionReused$),s(this.player.isLive$,e.isLive$),s(this.player.lastRequestFirstBytes$.pipe(Ld(OI),FI()),e.firstBytesEvent$),s(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),s(this.videoState.stateChangeEnded$.pipe($d(d=>d.to)),this.params.output.playbackState$),this.subscription.add(i.looped$.subscribe(()=>this.player.warmUpMediaSourceIfNeeded(),r)),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(bt(this.video,t.isLooped,r)),this.subscription.add(Ce(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Ke(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),s(Je(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),$(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),$(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:d})=>{if(d==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let f=this.player.getStreams();if(v0(f,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let h=[];for(let m of f.audio){h.push(gd(m));let b=[];for(let S of m.representations){let y=wI(S);b.push(y),this.audioTracksMap.set(y,{stream:m,representation:S})}this.audioStreamsMap.set(m,b)}this.params.output.availableAudioStreams$.next(h)}let p=[];for(let h of f.video){p.push(Sd(h));let m=[];for(let b of h.representations){let S=xI({...b,streamId:h.id});S&&(m.push(S),this.videoTracksMap.set(S,{stream:h,representation:b}))}this.videoStreamsMap.set(h,m)}this.params.output.availableVideoStreams$.next(p);for(let h of f.text)for(let m of h.representations){let b=AI(h,m);this.textTracksMap.set(b,{stream:h,representation:m})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else d==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r));let{vktvAbrThrottle:o}=this.params.tuning.dash,u=o&&RI(o)||null;this.subscription.add(Go(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$,T0(this.video,"progress")).pipe(Ld(()=>this.videoTracksMap.size>0)).subscribe(async()=>{let d=this.player.state$.getState(),f=this.player.state$.getTransition();if(d!=="manifest_ready"&&d!=="running"||f||d==="running"&&u&&!u())return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState()),this.selectVideoAudioRepresentations();let{video:p,audio:h}=this.selectedRepresentations;if(!p)return;let m=Ci(this.videoTracksMap.keys(),S=>{var y;return((y=this.videoTracksMap.get(S))==null?void 0:y.representation.id)===p.id});OI(m)&&(this.stallsManager.lastVideoTrackSelected=m);let b=this.params.desiredState.autoVideoTrackLimits.getTransition();if(b&&this.params.output.autoVideoTrackLimits$.next(b.to),d==="manifest_ready")await this.player.initRepresentations(p.id,h==null?void 0:h.id,this.params.sourceHls);else if(await this.player.switchRepresentation("video",p.id),h){let S=!!t.audioStream.getTransition();await this.player.switchRepresentation("audio",h.id,S)}},r)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:d})=>{this.scene3D&&d&&this.scene3D.pointCameraTo(d.x,d.y)})),this.subscription.add(this.elementSizeManager.subscribe(d=>{this.scene3D&&d&&this.scene3D.setViewportSize(d.width,d.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(Qo()).subscribe(d=>{let f=Ci(this.videoTracksMap.entries(),([,{representation:S}])=>S.id===d);if(!f){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[p,{stream:h}]=f,m=this.params.desiredState.videoStream.getTransition();m&&m.to&&m.to.id===h.id&&this.params.desiredState.videoStream.setState(m.to),e.currentVideoTrack$.next(p),e.currentVideoStream$.next(Sd(h));let b=this.player.calculateDurationFromSegments();b&&this.params.output.duration$.next(b/1e3)},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(Qo()).subscribe(d=>{let f=Ci(this.audioTracksMap.entries(),([,{representation:b}])=>b.id===d);if(!f){e.currentAudioStream$.next(void 0);return}let[p,{stream:h}]=f,m=this.params.desiredState.audioStream.getTransition();m&&m.to&&m.to.id===h.id&&this.params.desiredState.audioStream.setState(m.to),e.currentAudioStream$.next(gd(h))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(d=>{var f,p;if(d!=null&&d.is3dVideo&&((f=this.params.tuning.spherical)!=null&&f.enabled))try{this.init3DScene(d),e.is3DVideo$.next(!0)}catch(h){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${h}`})}else this.destroy3DScene(),(p=this.params.tuning.spherical)!=null&&p.enabled&&e.is3DVideo$.next(!1)},r)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,r)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,r)),this.textTracksManager.connect(this.video,t,e);let l=t.playbackState.stateChangeStarted$.pipe($d(({to:d})=>d==="ready"),Qo());this.subscription.add(Go(l,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,Md(["init"])).subscribe(()=>{let d=t.autoVideoTrackSwitching.getState(),p=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:d?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(p)})),this.subscription.add(Go(l,this.player.state$.stateChangeEnded$,Md(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let c=Go(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Md(["init"])).pipe(y0(0));this.subscription.add(c.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){var L,P,k,V,D,_,Y,J,T,R,x,w;if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?xa:Ea,t=this.params.tuning.useNewAutoSelectVideoTrack?eo:Zn,i=this.params.tuning.useNewAutoSelectVideoTrack?vt:Jn,{desiredState:r,output:s}=this.params,n=r.autoVideoTrackSwitching.getState(),o=(L=r.videoTrack.getState())==null?void 0:L.id,u=Ci(this.videoTracksMap.keys(),B=>B.id===o),l=s.currentVideoTrack$.getValue(),c=((V=(k=r.videoStream.getState())!=null?k:u&&((P=this.videoTracksMap.get(u))==null?void 0:P.stream))!=null?V:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!c)return;let d=Ci(this.videoStreamsMap.keys(),B=>B.id===c.id),f=d&&this.videoStreamsMap.get(d);if(!f)return;let p=me(this.video.buffered,this.video.currentTime*1e3),h;this.player.isActiveLive$.getValue()?h=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?h=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:h=n?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let m=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,b=Math.min(p/Math.min(h,m||1/0),1),S=(D=r.audioStream.getState())!=null?D:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,y=(S==null?void 0:S.id)&&Ci(this.audioStreamsMap.keys(),B=>B.id===S.id)||this.audioStreamsMap.keys().next().value,v=0;if(y){if(u&&!n){let B=e(u,f,(_=this.audioStreamsMap.get(y))!=null?_:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);v=Math.max(v,(Y=B==null?void 0:B.bitrate)!=null?Y:-1/0)}if(l){let B=e(l,f,(J=this.audioStreamsMap.get(y))!=null?J:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);v=Math.max(v,(T=B==null?void 0:B.bitrate)!=null?T:-1/0)}}let I=u;(n||!I)&&(I=i(f,{container:this.elementSizeManager.getValue(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.stallsManager.abrTuningParams,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:v,forwardBufferHealth:b,current:l,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,stallsVideoMaxQualityLimit:this.stallsManager.videoMaxQualityLimit,stallsPredictedThroughput:this.stallsManager.predictedThroughput,abrLogger:this.params.dependencies.abrLogger}));let E=y&&t(I,f,(R=this.audioStreamsMap.get(y))!=null?R:[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.stallsManager.abrTuningParams,forwardBufferHealth:b,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),A=(x=this.videoTracksMap.get(I))==null?void 0:x.representation,M=E&&((w=this.audioTracksMap.get(E))==null?void 0:w.representation);A&&M?(this.selectedRepresentations.video=A,this.selectedRepresentations.audio=M):A&&!M&&this.audioTracksMap.size===0&&(this.selectedRepresentations.video=A,this.selectedRepresentations.audio=null)}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Ve(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),$(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:_I.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.stallsManager.destroy(),this.elementSizeManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),this.params.output.currentVideoStream$.next(void 0),De(this.video),this.tracer.end()}};var As=class extends Fi{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};import{combine as Dd,merge as NI,filter as UI,filterChanged as qI,isNullable as Cd,map as jI,ValueSubject as Bd,isNonNullable as x0}from"@vkontakte/videoplayer-shared/es2018";var Ps=class extends Fi{constructor(e){super(e),this.textTracksManager.destroy()}subscribe(){super.subscribe();let e=!1,t=-1,{output:i,observableVideo:r,desiredState:s,connect:n}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canPlayLiveTailBuffer$.next(!0),n(r.timeUpdate$,i.liveBufferTime$),n(this.player.liveSeekableDuration$,i.duration$),n(this.player.liveLatency$,i.liveLatency$);let o=new Bd(1);n(r.playbackRateState$,o),this.params.tuning.dashCmafLive.catchupLiveForMutedInactiveTab&&this.subscription.add(i.elementVisible$.pipe(qI()).subscribe(u=>{let l=i.position$.getValue(),c=i.volume$.getValue(),d=!c.volume||c.muted;!u&&!l&&d?e=!0:u&&e&&(this.seek(0),e=!1)})),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(s.isLowLatency.stateChangeEnded$.pipe(jI(u=>u.to)).subscribe(this.player.isLowLatency$)).add(Dd({liveBufferTime:i.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(jI(({liveBufferTime:u,liveAvailabilityStartTime:l})=>u&&l?u+l:void 0)).subscribe(i.liveTime$)).add(this.player.liveStreamStatus$.pipe(UI(u=>x0(u))).subscribe(u=>i.isLiveEnded$.next(u!=="active"&&i.position$.getValue()===0))).add(Dd({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:NI(r.playbackRateState$,new Bd(1))}).pipe(UI(({liveStreamStatus:u,liveDuration:l})=>u==="active"&&!!l)).subscribe(({liveDuration:u,playbackRate:l})=>{let c=i.liveBufferTime$.getValue(),d=i.position$.getValue(),{playbackCatchupSpeedup:f}=this.params.tuning.dashCmafLive.lowLatency;d||l<1-f||this.video.paused||Cd(c)||(t=u-c)})).add(Dd({time:i.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:NI(r.playbackRateState$,new Bd(1))}).pipe(qI((u,l)=>this.player.liveStreamStatus$.getValue()==="active"?u.liveDuration===l.liveDuration:u.time===l.time)).subscribe(({time:u,liveDuration:l,playbackRate:c})=>{let d=i.position$.getValue(),{playbackCatchupSpeedup:f}=this.params.tuning.dashCmafLive.lowLatency;if(!d&&!this.video.paused&&c>=1-f||Cd(u)||Cd(l))return;let p=-1*(l-u-t);i.position$.next(Math.min(p,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(u=>{if(u){let l=PI(u);this.params.output.availableTextTracks$.next([l])}}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=Math.trunc(t/1e3<=Math.abs(this.params.output.duration$.getValue())?t:0);this.player.seekLive(i).then(()=>{this.params.output.position$.next(e/1e3)})}};var HI="X-Playback-Duration",Vd=async a=>{var r;let e=await Ze(a),t=await e.text(),i=(r=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t))==null?void 0:r[1];return i?parseInt(i,10):e.headers.has(HI)?parseInt(e.headers.get(HI),10):void 0};import{assertNever as B0,combine as V0,debounce as _0,ErrorCategory as Yo,filter as O0,filterChanged as F0,isNonNullable as WI,isNullable as Ko,map as zI,merge as N0,observableFrom as U0,Subscription as q0,ValueSubject as Fd,VideoQuality as j0}from"@vkontakte/videoplayer-shared/es2018";var Od=O(Sl(),1);import{videoSizeToQuality as w0,getExponentialDelay as A0}from"@vkontakte/videoplayer-shared/es2018";var P0=a=>{let e=null;if(a.QUALITY&&(e=Kt(a.QUALITY)),!e&&a.RESOLUTION){let[t,i]=a.RESOLUTION.split("x").map(r=>parseInt(r,10));e=w0({width:t,height:i})}return e!=null?e:null},k0=(a,e)=>{var s,n;let t=a.split(`
|
|
179
|
+
`),i=[],r=[];for(let o=0;o<t.length;o++){let u=t[o],l=u.match(/^#EXT-X-STREAM-INF:(.+)/),c=u.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!l&&!c)){if(l){let d=(0,Od.default)(l[1].split(",").map(y=>y.split("="))),f=(s=d.QUALITY)!=null?s:`stream-${d.BANDWIDTH}`,p=P0(d),h;d.BANDWIDTH&&(h=parseInt(d.BANDWIDTH,10)/1e3||void 0),!h&&d["AVERAGE-BANDWIDTH"]&&(h=parseInt(d["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let m=d["FRAME-RATE"]?parseFloat(d["FRAME-RATE"]):void 0,b;if(d.RESOLUTION){let[y,v]=d.RESOLUTION.split("x").map(I=>parseInt(I,10));y&&v&&(b={width:y,height:v})}let S=new URL(t[++o],e).toString();p&&i.push({id:f,quality:p,url:S,bandwidth:h,size:b,fps:m})}if(c){let d=(0,Od.default)(c[1].split(",").map(m=>{let b=m.indexOf("=");return[m.substring(0,b),m.substring(b+1)]}).map(([m,b])=>[m,b.replace(/^"|"$/g,"")])),f=(n=d.URI)==null?void 0:n.replace(/playlist$/,"subtitles.vtt"),p=d.LANGUAGE,h=d.NAME;f&&p&&r.push({type:"internal",id:p,label:h,language:p,url:f,isAuto:!1})}}}if(!i.length)throw new Error("Empty manifest");return{qualityManifests:i,textTracks:r}},R0=a=>new Promise(e=>{setTimeout(()=>{e()},a)}),_d=0,QI=async(a,e=a,t,i)=>{let s=await(await Ze(a,i)).text();_d+=1;try{let{qualityManifests:n,textTracks:o}=k0(s,e);return{qualityManifests:n,textTracks:o}}catch(n){if(_d<=t.manifestRetryMaxCount)return await R0(A0(_d-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),QI(a,e,t)}return{qualityManifests:[],textTracks:[]}},Wo=QI;import{isNonNullable as L0,Subscription as $0,throttle as M0,ValueSubject as GI,Subject as D0,ErrorCategory as C0}from"@vkontakte/videoplayer-shared/es2018";var zo=class{constructor(e,t,i,r,s){this.subscription=new $0;this.abortControllers={destroy:new Z,nextManifest:null};this.prepareUrl=void 0;this.currentTextTrackData=null;this.availableTextTracks$=new GI(null);this.getCurrentTime$=new GI(null);this.error$=new D0;this.params={fetchManifestData:i,sourceUrl:r,downloadThreshold:s},this.subscription.add(e.pipe(M0(1e3)).subscribe(n=>{this.processLiveTime(n)})),this.getCurrentTime$.next(()=>this.currentTextTrackData?this.currentTextTrackData.playlist.segmentStartTime/1e3+t.currentTime:0)}destroy(){this.subscription.unsubscribe(),this.abortControllers.destroy.abort()}async prepare(e){try{let t=new URL(e);t.searchParams.set("enable-subtitles","yes"),this.prepareUrl=t.toString();let{textTracks:i}=await this.fetchManifestData();await this.processTextTracks(i,this.params.sourceUrl)}catch(t){this.error("prepare",t)}}async processTextTracks(e,t){try{let i=await this.parseTextTracks(e,t);i&&(this.currentTextTrackData=i)}catch(i){this.error("processTextTracks",i)}}async parseTextTracks(e,t){for(let i of e){let r=new URL(i.url,t).toString(),n=await(await Ze(r,{signal:this.abortControllers.destroy.signal})).text(),o=this.parsePlaylist(n,r);return{textTrack:i,playlist:o}}}parsePlaylist(e,t){let i={mediaSequence:0,programDateTime:"",segments:[],targetDuration:0,vkPlaybackDuration:0,segmentStartTime:0,vkStartTime:""},r=e.split(`
|
|
180
|
+
`),s=0;for(let n=0;n<r.length;++n){let o=r[n];switch(!0){case o.startsWith("#EXTINF:"):{let u=r[++n],l=new URL(u,t).toString(),c=Number(this.extractPlaylistRowValue("#EXTINF:",o))*1e3;if(i.segments.push({time:{from:s,to:s+c},url:l}),s=s+c,!i.segmentStartTime){let d=new Date(i.vkStartTime).valueOf(),f=new Date(i.programDateTime).valueOf();i.segmentStartTime=f-d}break}case o.startsWith("#EXT-X-TARGETDURATION:"):i.targetDuration=Number(this.extractPlaylistRowValue("#EXT-X-TARGETDURATION:",o));break;case o.startsWith("#EXT-X-MEDIA-SEQUENCE:"):i.mediaSequence=Number(this.extractPlaylistRowValue("#EXT-X-MEDIA-SEQUENCE:",o));break;case o.startsWith("#EXT-X-VK-PLAYBACK-DURATION:"):i.vkPlaybackDuration=Number(this.extractPlaylistRowValue("#EXT-X-VK-PLAYBACK-DURATION:",o));break;case o.startsWith("#EXT-X-PROGRAM-DATE-TIME:"):{let u=this.extractPlaylistRowValue("#EXT-X-PROGRAM-DATE-TIME:",o);i.programDateTime=u;let l=new Date(u);l.setMilliseconds(0),s=l.valueOf();break}case o.startsWith("#EXT-X-VK-START-TIME:"):i.vkStartTime=this.extractPlaylistRowValue("#EXT-X-VK-START-TIME:",o);break}}return i}extractPlaylistRowValue(e,t){switch(e){case"#EXTINF:":return t.substring(e.length,t.length-1);default:return t.substring(e.length)}}processLiveTime(e){if(L0(e)&&this.currentTextTrackData){let{segments:t}=this.currentTextTrackData.playlist,{from:i}=t[0].time,{to:r}=t[t.length-1].time;if(e<i||e>r)return;r-e<this.params.downloadThreshold&&this.fetchNextManifestData();for(let n of t)if(n.time.from<=e&&n.time.to>=e){this.availableTextTracks$.next([{...this.currentTextTrackData.textTrack,url:n.url,isAuto:!0}]);break}}}async fetchNextManifestData(){try{if(this.abortControllers.nextManifest)return;this.abortControllers.nextManifest=new Z;let{textTracks:e}=await this.fetchManifestData(),t=await this.parseTextTracks(e,this.params.sourceUrl);this.currentTextTrackData&&t&&(this.currentTextTrackData.playlist.segments=t.playlist.segments)}catch(e){this.error("fetchNextManifestData",e)}finally{this.abortControllers.nextManifest=null}}async fetchManifestData(){var t;let e=(t=this.prepareUrl)!=null?t:this.params.sourceUrl;return await this.params.fetchManifestData(e,{signal:this.abortControllers.destroy.signal})}error(e,t){this.error$.next({id:"[LiveTextManager][HLS_LIVE_CMAF]",category:C0.WTF,thrown:t,message:e})}};var ks=class{constructor(e){this.subscription=new q0;this.videoState=new q("stopped");this.textTracksManager=null;this.liveTextManager=null;this.manifests$=new Fd([]);this.liveOffset=new wi;this.manifestStartTime$=new Fd(void 0);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),$(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let c=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(c),this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((r==null?void 0:r.to)!=="paused"&&l.state==="requested"){this.videoState.startTransitionTo("ready"),this.seek(l.position&&l.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":i==="ready"?$(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),$(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&$(this.params.desiredState.playbackState,"playing");return;case"paused":if(i==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let c=this.liveOffset.getTotalOffset();c>=this.maxSeekBackTime$.getValue()&&(c=0,this.liveOffset.resetTo(c)),this.liveOffset.resume(),this.params.output.position$.next(-c/1e3),this.prepare()}else(r==null?void 0:r.to)==="paused"&&($(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return B0(t)}};var i;this.params=e,this.video=Me(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:j0.INVARIANT,url:this.params.source.url};let t=(r,s)=>Wo(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 zo(this.params.output.liveTime$,this.video,t,this.params.source.url,this.params.tuning.hlsLiveNewTextManagerDownloadThreshold):this.textTracksManager=new Xe(e.source.url),t(this.generateLiveUrl()).then(({qualityManifests:r,textTracks:s})=>{var n;r.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:Yo.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:Yo.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:r})}),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Te(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new Fd((i=e.source.maxSeekBackTime)!=null?i:1/0),this.subscribe()}selectManifest(){var u,l,c,d;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),s=(d=(c=(u=r==null?void 0:r.to)==null?void 0:u.id)!=null?c:(l=t.getState())==null?void 0:l.id)!=null?d:"master",n=this.manifests$.getValue();if(!n.length)return;let o=i?"master":s;return i&&!r&&t.startTransitionTo(this.masterManifest),n.find(f=>f.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsLiveProvider",category:Yo.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},r=Be(this.video);this.subscription.add(()=>r.destroy());let s=(o,u)=>this.subscription.add(o.subscribe(u,i));s(r.ended$,e.endedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.loadedMetadata$,e.firstBytesEvent$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(Ce(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Ke(this.video,t.playbackRate,r.playbackRateState$,i)),s(Je(this.video),e.elementVisible$),this.liveTextManager?(s(this.liveTextManager.getCurrentTime$,this.params.output.getCurrentTime$),s(this.liveTextManager.error$,this.params.output.error$)):this.textTracksManager&&this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),$(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),$(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.liveTextManager&&this.subscription.add(this.liveTextManager.availableTextTracks$.subscribe(o=>{o&&this.params.output.availableTextTracks$.next(o)})),this.subscription.add(this.maxSeekBackTime$.pipe(F0(),zI(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&&WI(l.to)){let d=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let f=this.manifests$.getValue().find(p=>p.id===d);f&&(this.params.output.currentVideoTrack$.next(f),this.params.output.hostname$.next(Te(f.url)))}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o&&o.state==="requested"&&this.seek(o.position)},i)),this.subscription.add(r.loadedData$.subscribe(()=>{var u,l,c;let o=(c=(l=(u=this.video)==null?void 0:u.getStartDate)==null?void 0:l.call(u))==null?void 0:c.getTime();this.manifestStartTime$.next(o||void 0)},i)),this.subscription.add(V0({startTime:this.manifestStartTime$.pipe(O0(WI)),currentTime:r.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),i)),this.subscription.add(this.manifests$.pipe(zI(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:f})=>({id:u,quality:l,size:c,fps:f,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,i));let n=N0(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,U0(["init"])).pipe(_0(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){var e,t;this.subscription.unsubscribe(),(e=this.textTracksManager)==null||e.destroy(),(t=this.liveTextManager)==null||t.destroy(),this.params.output.element$.next(void 0),De(this.video)}prepare(){var o,u,l;let e=this.selectManifest();if(Ko(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:c,min:d}=(u=(o=t==null?void 0:t.to)!=null?o:i)!=null?u:{};for(let[f,p]of[[c,"mq"],[d,"lq"]]){let h=String(parseFloat(f||""));p&&f&&r.searchParams.set(p,h)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,n=le(r.toString(),this.liveOffset.getTotalOffset(),s);(l=this.liveTextManager)==null||l.prepare(n),this.video.setAttribute("src",n),this.video.load(),Vd(n).then(c=>{var d;if(!Ko(c))this.maxSeekBackTime$.next(c);else{let f=(d=this.params.source.maxSeekBackTime)!=null?d:this.maxSeekBackTime$.getValue();(Ko(f)||!isFinite(f))&&Ze(n).then(p=>p.text()).then(p=>{var m;let h=(m=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(p))==null?void 0:m[1];if(h){let b=new URL(h,n).toString();Vd(b).then(S=>{Ko(S)||this.maxSeekBackTime$.next(S)})}}).catch(()=>{})}})}playIfAllowed(){Ve(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),$(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Yo.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3),this.params.output.seekedEvent$.next()}generateLiveUrl(){let e=le(this.params.source.url);if(this.params.tuning.useHlsLiveNewTextManager){let t=new URL(e);t.searchParams.set("enable-subtitles","yes"),e=t.toString()}return e}};import{assertNever as H0,debounce as Q0,ErrorCategory as Nd,fromEvent as Ud,isNonNullable as G0,isNullable as W0,map as YI,merge as KI,observableFrom as XI,Subscription as z0,ValueSubject as Y0,VideoQuality as K0}from"@vkontakte/videoplayer-shared/es2018";var Rs=class{constructor(e){this.subscription=new z0;this.videoState=new q("stopped");this.manifests$=new Y0([]);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),$(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let c=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(c);let{currentTime:d}=this.video;this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:d*1e3,forcePrecise:!0});return}switch((r==null?void 0:r.to)!=="paused"&&l.state==="requested"&&this.seek(l.position),t){case"ready":i==="ready"?$(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),$(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&$(this.params.desiredState.playbackState,"playing");return;case"paused":i==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&$(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return H0(t)}};this.textTracksManager=new Xe(e.source.url),this.params=e,this.video=Me(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:K0.INVARIANT,url:this.params.source.url},this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Te(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),Wo(le(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:t,textTracks:i})=>{this.manifests$.next([this.masterManifest,...t]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(i)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:Nd.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){var u,l,c,d;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),s=(d=(c=(u=r==null?void 0:r.to)==null?void 0:u.id)!=null?c:(l=t.getState())==null?void 0:l.id)!=null?d:"master",n=this.manifests$.getValue();if(!n.length)return;let o=i?"master":s;return i&&(!r||!r.from)&&t.startTransitionTo(this.masterManifest),n.find(f=>f.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsProvider",category:Nd.WTF,message:"HlsProvider internal logic error",thrown:o})},r=Be(this.video);this.subscription.add(()=>r.destroy());let s=(o,u)=>this.subscription.add(o.subscribe(u));if(s(r.timeUpdate$,e.position$),s(r.durationChange$,e.duration$),s(r.ended$,e.endedEvent$),s(r.looped$,e.loopedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.loadedMetadata$,e.firstBytesEvent$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.seeked$,e.seekedEvent$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe(YI(o=>o.to)),this.params.output.playbackState$),this.subscription.add(bt(this.video,t.isLooped,i)),this.subscription.add(Ce(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Ke(this.video,t.playbackRate,r.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),$(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),$(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i).add(r.loadedMetadata$.subscribe(()=>{var p;let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&G0(l.to)){let h=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let m=this.manifests$.getValue().find(b=>b.id===h);m&&(this.params.output.currentVideoTrack$.next(m),this.params.output.hostname$.next(Te(m.url)))}let d=this.params.desiredState.playbackRate.getState(),f=(p=this.params.output.element$.getValue())==null?void 0:p.playbackRate;if(d!==f){let h=this.params.output.element$.getValue();h&&(this.params.desiredState.playbackRate.setState(d),h.playbackRate=d)}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o.state==="requested"&&this.seek(o.position)},i))),this.subscription.add(this.manifests$.pipe(YI(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:f})=>({id:u,quality:l,size:c,fps:f,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,i)),!F.device.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(KI(Ud(o,"addtrack"),Ud(o,"removetrack"),Ud(o,"change"),XI(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},i))}let n=KI(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,XI(["init"])).pipe(Q0(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),De(this.video)}prepare(){var s,n;let e=this.selectManifest();if(W0(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:o,min:u}=(n=(s=t==null?void 0:t.to)!=null?s:i)!=null?n:{};for(let[l,c]of[[o,"mq"],[u,"lq"]]){let d=String(parseFloat(l||""));c&&l&&r.searchParams.set(c,d)}}this.video.setAttribute("src",r.toString()),this.video.load()}playIfAllowed(){Ve(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),$(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Nd.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var eE=O(er(),1),qd=O(pr(),1),tE=O(ot(),1);import{assertNever as X0,assertNonNullable as JI,debounce as J0,ErrorCategory as ZI,isHigherOrEqual as Z0,isLowerOrEqual as eV,isNonNullable as tV,merge as iV,observableFrom as rV,Subscription as aV,map as sV}from"@vkontakte/videoplayer-shared/es2018";var Ls=class{constructor(e){this.subscription=new aV;this.videoState=new q("stopped");this.trackUrls={};this.textTracksManager=new Xe;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),$(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.autoVideoTrackLimits.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.seekState.getState();if(s&&e!=="ready"&&!n){this.handleQualityLimitTransition(s.to);return}if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(n){let{currentTime:u}=this.video;this.prepare(),o.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:u*1e3,forcePrecise:!0});return}switch((i==null?void 0:i.to)!=="paused"&&o.state==="requested"&&this.seek(o.position),e){case"ready":t==="ready"?$(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),$(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(i==null?void 0:i.to)==="playing"&&$(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&$(this.params.desiredState.playbackState,"paused");return;default:return X0(e)}};this.params=e,this.video=Me(e.container,e.tuning),this.params.output.element$.next(this.video),(0,eE.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,qd.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:ZI.WTF,message:"MpegProvider internal logic error",thrown:o})},r=Be(this.video);this.subscription.add(()=>r.destroy());let s=(o,u)=>this.subscription.add(o.subscribe(u,i));s(r.timeUpdate$,e.position$),s(r.durationChange$,e.duration$),s(r.ended$,e.endedEvent$),s(r.looped$,e.loopedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.loadedMetadata$,e.firstBytesEvent$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.seeked$,e.seekedEvent$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe(sV(o=>o.to)),this.params.output.playbackState$),this.subscription.add(bt(this.video,t.isLooped,i)),this.subscription.add(Ce(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Ke(this.video,t.playbackRate,r.playbackRateState$,i)),s(Je(this.video),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),$(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),$(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var u,l;((u=this.videoState.getTransition())==null?void 0:u.to)==="ready"&&this.videoState.setState("ready");let o=this.params.desiredState.videoTrack.getTransition();if(o&&tV(o.to)){this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to.id].track);let c=this.params.desiredState.playbackRate.getState(),d=(l=this.params.output.element$.getValue())==null?void 0:l.playbackRate;if(c!==d){let f=this.params.output.element$.getValue();f&&(this.params.desiredState.playbackRate.setState(c),f.playbackRate=c)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.textTracksManager.connect(this.video,t,e);let n=iV(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,rV(["init"])).pipe(J0(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),De(this.video)}prepare(){var i;let e=(i=this.params.desiredState.videoTrack.getState())==null?void 0:i.id;JI(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];JI(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=ei(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(Te(t))}playIfAllowed(){Ve(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),$(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:ZI.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){var l,c;this.params.output.autoVideoTrackLimits$.next(e);let t=d=>{this.params.output.currentVideoTrack$.next(d),this.params.desiredState.videoTrack.startTransitionTo(d)},i=d=>{let f=vt(n,{container:this.video.getBoundingClientRect(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,limits:d,abrLogger:this.params.dependencies.abrLogger});t(f)},r=(l=this.params.output.currentVideoTrack$.getValue())==null?void 0:l.quality,s=!!(e.max||e.min),n=(0,qd.default)(this.trackUrls).map(d=>d.track);if(!r||!s||fr(e,n[0].quality,(c=(0,tE.default)(n,-1))==null?void 0:c.quality)){i();return}let o=e.max?eV(r,e.max):!0,u=e.min?Z0(r,e.min):!0;o&&u||i(e)}};import{assertNever as rE,debounce as lV,merge as aE,observableFrom as cV,Subscription as dV,map as sE,ValueSubject as pV,ErrorCategory as Hd,VideoQuality as hV}from"@vkontakte/videoplayer-shared/es2018";import{ErrorCategory as nV}from"@vkontakte/videoplayer-shared/es2018";var iE=["stun:videostun.mycdn.me:80"],oV=1e3,uV=3,jd=()=>null,Xo=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=jd;this.externalStopCallback=jd;this.externalErrorCallback=jd;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:iE}]};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:nV.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),oV)}normalizeOptions(e={}){let t={stunServerList:iE,maxRetryNumber:uV,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var $s=class{constructor(e){this.videoState=new q("stopped");this.maxSeekBackTime$=new pV(0);this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.pause(),this.video.srcObject=null,this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),$(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.videoTrack.getTransition();if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s){this.prepare();return}switch(e){case"ready":t==="paused"?(this.videoState.setState("paused"),$(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(i==null?void 0:i.to)==="playing"&&$(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&$(this.params.desiredState.playbackState,"paused");return;default:return rE(e)}};this.subscription=new dV,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=Me(e.container,e.tuning),this.liveStreamClient=new Xo(this.params.source.url,{maxRetryNumber:this.params.tuning.webrtc.connectionRetryMaxNumber,errorChanel:this.params.output.error$}),this.liveStreamClient.onStart(this.onLiveStreamStart.bind(this)),this.liveStreamClient.onStop(this.onLiveStreamStop.bind(this)),this.liveStreamClient.onError(this.onLiveStreamError.bind(this)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),De(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,i=n=>{e.error$.next({id:"WebRTCLiveProvider",category:Hd.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};this.subscription.add(aE(this.videoState.stateChangeStarted$.pipe(sE(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(sE(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})}));let r=Be(this.video);this.subscription.add(()=>r.destroy());let s=(n,o)=>this.subscription.add(n.subscribe(o,i));s(r.timeUpdate$,e.liveTime$),s(r.ended$,e.endedEvent$),s(r.looped$,e.loopedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(Je(this.video),this.params.output.elementVisible$),this.subscription.add(r.durationChange$.subscribe(n=>{e.duration$.next(n===1/0?0:n)})).add(r.canplay$.subscribe(()=>{var n;((n=this.videoState.getTransition())==null?void 0:n.to)==="ready"&&this.videoState.setState("ready")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused")},i)).add(r.playing$.subscribe(()=>{this.videoState.setState("playing")},i)).add(r.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(Ce(this.video,t.volume,r.volumeState$,i)).add(r.volumeState$.subscribe(e.volume$,i)).add(this.videoState.stateChangeEnded$.subscribe(n=>{switch(n.to){case"stopped":e.position$.next(0),e.duration$.next(0),t.playbackState.setState("stopped");break;case"ready":break;case"paused":t.playbackState.setState("paused");break;case"playing":t.playbackState.setState("playing");break;default:return rE(n.to)}},i)).add(aE(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,cV(["init"])).pipe(lV(0)).subscribe(this.syncPlayback.bind(this),i)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),i))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(Te(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.currentVideoTrack$.next({id:"webrtc",quality:hV.INVARIANT}),this.video.srcObject=e,$(this.params.desiredState.playbackState,"playing")}onLiveStreamStop(){this.videoState.startTransitionTo("stopped"),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.params.output.endedEvent$.next()}onLiveStreamError(e){this.onLiveStreamStop(),this.params.output.error$.next({id:"WebRTC stream runtime error",category:Hd.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){Ve(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),$(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Hd.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var Ms=class{constructor(e){this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next()}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return!!this.current.done}};import{assertNever as Cs,assertNonNullable as ri,ErrorCategory as Jo,filter as dE,isNonNullable as pE,isNullable as yV,map as TV,merge as IV,once as EV,Subject as be,Subscription as hE,ValueSubject as j,flattenObject as Qd}from"@vkontakte/videoplayer-shared/es2018";import{Observable as fV,map as nE,Subscription as mV,Subject as bV}from"@vkontakte/videoplayer-shared/es2018";var oE=a=>new fV(e=>{let t=new mV,i=a.desiredPlaybackState$.stateChangeStarted$.pipe(nE(({from:l,to:c})=>`${l}-${c}`)),r=a.desiredPlaybackState$.stateChangeEnded$,s=a.providerChanged$.pipe(nE(({type:l})=>l!==void 0)),n=new bV,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 gV,Subscription as SV,combine as vV,filter as lE,once as cE}from"@vkontakte/videoplayer-shared/es2018";function uE(){return new(window.AudioContext||window.webkitAudioContext)}var Ds=class Ds{constructor(e,t,i,r){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=i;this.volumeMultiplier=r;this.destroyController=new Z;this.subscriptions=new SV;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe(lE(s=>!!s.type),cE()).subscribe(({type:s})=>this.subscribe(s)))}subscribe(e){F.browser.isSafari&&e!=="MPEG"||this.subscriptions.add(vV({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(lE(({playbackState:t,video:i,volume:{muted:r,volume:s}})=>t==="playing"&&!!i&&!r&&!!s),cE()).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=uE();this.audioContext=i;let r=i.createGain();if(this.gainNode=r,r.gain.value=t,r.connect(i.destination),i.state==="suspended"&&(await i.resume(),this.destroyController.signal.aborted))return!1;let s=i.createMediaElementSource(e);return this.mediaElementSource=s,s.connect(r),!0}cleanup(){this.mediaElementSource&&(this.mediaElementSource.disconnect(),this.mediaElementSource=null),this.gainNode&&(this.gainNode.disconnect(),this.gainNode=null),this.audioContext&&(this.audioContext.state!=="closed"&&this.audioContext.close(),this.audioContext=null)}destroy(){this.destroyController.abort(),this.subscriptions.unsubscribe(),this.cleanup()}handleError(e){var t;this.volumeMultiplierError$.next({id:Ds.errorId,category:gV.VIDEO_PIPELINE,message:(t=e==null?void 0:e.message)!=null?t:`${Ds.errorId} exception`,thrown:e})}};Ds.errorId="VolumeMultiplierManager";var Fr=Ds;var xV={chunkDuration:5e3,maxParallelRequests:5},Bs=class{constructor(e){this.current$=new j({type:void 0});this.providerError$=new be;this.noAvailableProvidersError$=new be;this.volumeMultiplierError$=new be;this.providerOutput={position$:new j(0),duration$:new j(1/0),volume$:new j({muted:!1,volume:1}),availableVideoStreams$:new j([]),currentVideoStream$:new j(void 0),availableVideoTracks$:new j([]),currentVideoTrack$:new j(void 0),availableAudioStreams$:new j([]),currentAudioStream$:new j(void 0),availableAudioTracks$:new j([]),currentVideoSegmentLength$:new j(0),currentAudioSegmentLength$:new j(0),isAudioAvailable$:new j(!0),autoVideoTrackLimitingAvailable$:new j(!1),autoVideoTrackLimits$:new j(void 0),currentBuffer$:new j(void 0),isBuffering$:new j(!0),error$:new be,fetcherError$:new be,fetcherRecoverableError$:new be,warning$:new be,willSeekEvent$:new be,soundProhibitedEvent$:new be,seekedEvent$:new be,loopedEvent$:new be,endedEvent$:new be,firstBytesEvent$:new be,loadedMetadataEvent$:new be,firstFrameEvent$:new be,canplay$:new be,isLive$:new j(void 0),isLiveEnded$:new j(null),canPlayLiveTailBuffer$:new j(!1),isLowLatency$:new j(!1),canChangePlaybackSpeed$:new j(!0),liveTime$:new j(void 0),liveBufferTime$:new j(void 0),liveLatency$:new j(void 0),severeStallOccurred$:new be,availableTextTracks$:new j([]),currentTextTrack$:new j(void 0),hostname$:new j(void 0),httpConnectionType$:new j(void 0),httpConnectionReused$:new j(void 0),inPiP$:new j(!1),inFullscreen$:new j(!1),element$:new j(void 0),elementVisible$:new j(!0),availableSources$:new j(void 0),is3DVideo$:new j(!1),playbackState$:new j(""),getCurrentTime$:new j(null)};this.subscription=new hE;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=sc([...aI(this.params.tuning),...rI(this.params.tuning)],this.params.tuning).filter(l=>pE(e.sources[l])),{forceFormat:i,formatsToAvoid:r}=this.params.tuning,s=[];i?s=[i]:r.length?s=[...t.filter(l=>!(0,Gd.default)(r,l)),...t.filter(l=>(0,Gd.default)(r,l))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",Qd(s)),this.screenFormatsIterator=new Ms(s);let n=[...Jc(!0),...Jc(!1)];this.chromecastFormatsIterator=new Ms(n.filter(l=>pE(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:o=1,tuning:{useVolumeMultiplier:u}}=this.params;u&&o!==1&&Fr.isSupported()&&(this.volumeMultiplierManager=new Fr(this.providerOutput,this.current$,this.volumeMultiplierError$,o))}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()}))}destroy(){var e;this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe(),(e=this.volumeMultiplierManager)==null||e.destroy(),this.volumeMultiplierManager=null,this.tracer.end()}initProvider(){let e=this.chooseDestination(),t=this.chooseFormat(e);if(yV(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:Jo.WTF,message:"Failed to create provider",thrown:r})}i?this.current$.next({type:t,provider:i,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.tracer.log("reinitProvider"),this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.tracer.log("switchToNextProvider",{destination:e}),this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}destroyProvider(){let e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"}),this.tracer.log("destroyProvider"),e.destroy();let t=this.providerOutput.position$.getValue()*1e3,i=this.params.desiredState.seekState.getState(),r=i.state!=="none";if(this.params.desiredState.seekState.setState({state:"requested",position:r?i.position:t,forcePrecise:r?i.forcePrecise:!1}),e.scene3D){let n=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:n.x,y:n.y})}let s=this.providerOutput.isBuffering$;s.getValue()||s.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),this.tracer.log("createProvider",{destination:e,format:t}),e){case"SCREEN":return this.createScreenProvider(t);case"CHROMECAST":return this.createChromecastProvider(t);default:return Cs(e)}}createScreenProvider(e){let{sources:t,container:i,desiredState:r,panelSize:s}=this.params,n=this.providerOutput,o={container:i,source:null,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning,panelSize:s};switch(e){case"DASH_SEP":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_ONDEMAND":case"DASH_STREAMS":{let u=this.applyFailoverHost(t[e]),l=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return ri(u),this.params.tuning.useNewDashProvider?new As({...o,source:u,sourceHls:l}):new bs({...o,source:u,sourceHls:l})}case"DASH_LIVE_CMAF":{let u=this.applyFailoverHost(t[e]);return ri(u),this.params.tuning.useNewDashProvider?new Ps({...o,source:u}):new gs({...o,source:u})}case"HLS":case"HLS_ONDEMAND":{let u=this.applyFailoverHost(t[e]);return ri(u),new Rs({...o,source:u})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let u=this.applyFailoverHost(t[e]);return ri(u),new ks({...o,source:u,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let u=this.applyFailoverHost(t[e]);return ri(u),new Ls({...o,source:u})}case"DASH_LIVE":{let u=this.applyFailoverHost(t[e]);return ri(u),new Yv({...o,source:u,config:{...xV,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let u=this.applyFailoverHost(t[e]);return ri(u),new $s({container:i,source:u,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return Cs(e)}}createChromecastProvider(e){let{sources:t,container:i,desiredState:r,meta:s}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return ri(o),new Sa({connection:o,meta:s,container:i,source:t,format:e,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?"CHROMECAST":"SCREEN"}chooseFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case"CHROMECAST":return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return Cs(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return Cs(e)}}handleNoFormatsError(e){switch(e){case"SCREEN":this.noAvailableProvidersError$.next(this.params.tuning.forceFormat),this.current$.next({type:void 0});return;case"CHROMECAST":this.params.dependencies.chromecastInitializer.disconnect();return;default:return Cs(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;let t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;let i=r=>{let s=new URL(r);return s.host=t,s.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return{...e,url:i(e.url)}}return(0,mE.default)((0,fE.default)(e).map(([r,s])=>[r,i(s)]))}initProviderErrorHandling(){let e=new hE,t=!1,i=0;return e.add(IV(this.providerOutput.error$.pipe(dE(r=>!this.params.tuning.ignoreAudioRendererError||!r.message||!/AUDIO_RENDERER_ERROR/ig.test(r.message))),oE({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(TV(r=>({id:`ProviderHangup:${r}`,category:Jo.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(dE(({to:s})=>s==="playing"),EV()).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===Jo.NETWORK,u=r.category===Jo.FATAL,l=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),c=i<this.params.tuning.providerErrorLimit&&!u,d=l&&!u&&(o&&t||!c);n={...n,isNetworkError:o,isFatalError:u,haveFailoverHost:l,tryFailover:d,canReinitProvider:c},c?(i++,this.reinitProvider()):d?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):(i=0,this.switchToNextProvider(s!=null?s:"SCREEN"))}r.traceAsLog?this.tracer.log("providerInfo",Qd(n)):this.tracer.error("providerError",Qd(n))})),e}};import{fromEvent as Zo,once as wV,combine as AV,Subscription as bE,ValueSubject as Wd,map as PV,filter as kV,isNonNullable as eu,now as We,safeStorage as zd}from"@vkontakte/videoplayer-shared/es2018";var RV=5e3,gE="one_video_throughput",SE="one_video_rtt",Vt=window.navigator.connection,vE=()=>{let a=Vt==null?void 0:Vt.downlink;if(eu(a)&&a!==10)return a*1e3},yE=()=>{let a=Vt==null?void 0:Vt.rtt;if(eu(a)&&a!==3e3)return a},TE=(a,e,t)=>{let i=t*8,r=i/a;return i/(r+e)},Yd=class a{constructor(e){this.subscription=new bE;this.concurrentDownloads=new Set;var r,s;this.tuningConfig=e;let t=a.load(gE)||(e.useBrowserEstimation?vE():void 0)||RV,i=(s=(r=a.load(SE))!=null?r:e.useBrowserEstimation?yE():void 0)!=null?s:0;if(this.throughput$=new Wd(t),this.rtt$=new Wd(i),this.rttAdjustedThroughput$=new Wd(TE(t,i,e.rttPenaltyRequestSize)),this.throughput=Ct.getSmoothedValue(t,-1,e),this.rtt=Ct.getSmoothedValue(i,1,e),e.useBrowserEstimation){let n=()=>{let u=vE();u&&this.throughput.next(u);let l=yE();eu(l)&&this.rtt.next(l)};Vt&&"onchange"in Vt&&this.subscription.add(Zo(Vt,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{zd.set(gE,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{zd.set(SE,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(AV({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(PV(({throughput:n,rtt:o})=>TE(n,o,e.rttPenaltyRequestSize)),kV(n=>{let o=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(n-o)/o>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,i=We(),r=new bE;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add(Zo(e,"progress").pipe(wV()).subscribe(s=>{t=s.loaded,i=We()}));break;case 1:case 0:r.add(Zo(e,"loadstart").subscribe(()=>{t=0,i=We()}));break}r.add(Zo(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=We(),u=n-t,l=o-i;this.addRawSpeed(u,l,1)}this.concurrentDownloads.delete(e),r.unsubscribe()}))}trackStream(e,t=!1){let i=e.getReader();if(!i){e.cancel("Could not get reader");return}let r=0,s=We(),n=0,o=We(),u=c=>{this.concurrentDownloads.delete(e),i.releaseLock(),e.cancel(`Throughput Estimator error: ${c}`).catch(()=>{})},l=async({done:c,value:d})=>{if(c)!t&&this.addRawSpeed(r,We()-s,1),this.concurrentDownloads.delete(e);else if(d){if(t){let f=We();if(f-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||f-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let h=o-s;h&&this.addRawSpeed(n,h,1,t),n=d.byteLength,s=We()}else n+=d.byteLength;o=We()}else r+=d.byteLength,n+=d.byteLength,n>=this.tuningConfig.streamMinSampleSize&&We()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,We()-o,this.concurrentDownloads.size),n=0,o=We());await(i==null?void 0:i.read().then(l,u))}};this.concurrentDownloads.add(e),i==null||i.read().then(l,u)}addRawSpeed(e,t,i=1,r=!1){if(a.sanityCheck(e,t,r)){let s=e*8/t;this.throughput.next(s*i)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,i=!1){let r=e*8/t;return!(!r||!isFinite(r)||r>1e6||r<30||i&&e<1e4||!i&&e<10*1024||!i&&t<=20)}static load(e){var i;let t=zd.get(e);if(eu(t))return(i=parseInt(t,10))!=null?i:void 0}},IE=Yd;import{fillWithDefault as LV,VideoQuality as tu}from"@vkontakte/videoplayer-shared/es2018";var EE={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:tu.Q_4320P,activeVideoAreaThreshold:.1,highQualityLimit:tu.Q_720P,trafficSavingLimit:tu.Q_480P},stallsManager:{enabled:!1,stallDurationNoDataBeforeQualityDecrease:500,stallDurationToBeCount:100,stallCountBeforeQualityDecrease:3,resetQualityRestrictionTimeout:1e4,ignoreStallsOnSeek:!0,stallsMetricsHistoryLength:5,maxPossibleStallDuration:3e4,minTvtToBeCounted:5,maxTvtToBeCounted:10800,significantTvt:600,targetStallsDurationPerTvt:1,deviationStallsDurationPerTvt:.5,criticalStallsDurationPerTvt:6,abrAdjustingSpeed:.1,emaAlpha:.6,useTotalStallsDurationPerTvt:!0,useAverageStallsDurationPerTvt:!0,useEmaStallsDurationPerTvt:!0},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:tu.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,seekBiasInTheEnd:2e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,crashOnStallTimeout:25e3,crashOnStallTWithoutDataTimeout:5e3,enableSubSegmentBufferFeeding:!0,bufferEmptinessTolerance:100,useFetchPriorityHints:!0,enableBaseUrlSupport:!0,maxSegmentRetryCount:5,sourceOpenTimeout:1e3,vktvAbrThrottle:0,timeupdateEventTickThrottle:300,fetcherBufferOptimisation:!0},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,maxLiveDuration:7200,catchupLiveForMutedInactiveTab:!0,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:250,playbackCatchupSpeedup:.05,isActiveOnDefault:!1,bufferEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:"07A4434E",useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"dash",preferCMAF:!1,preferWebRTC:!1,preferMultiStream:!1,preferHDR:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,seekNearDurationBias:1,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useHlsJs:!1,useNativeHLSTextTracks:!1,useManagedMediaSource:!0,useNewSwitchTo:!1,useNewDashProvider:!1,useNewAutoSelectVideoTrack:!1,useSafariEndlessRequestBugfix:!0,useRefactoredSearchGap:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,audioVideoSyncRate:20,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50},useVolumeMultiplier:!1,ignoreAudioRendererError:!1,useEnableSubtitlesParam:!1,useOldMSEDetection:!1,useHlsLiveNewTextManager:!1,exposeInternalsToGlobal:!1,hlsLiveNewTextManagerDownloadThreshold:4e3,disableYandexPiP:!1,asyncResolveClientChecker:!1,autostartOnlyIfVisible:!1},xE=a=>{var e;return{...LV(a,EE),configName:[...(e=a.configName)!=null?e:[],...EE.configName]}};import{assertNonNullable as iu,combine as _t,ErrorCategory as ru,filter as U,filterChanged as z,fromEvent as Xd,isNonNullable as kE,isNullable as _V,Logger as OV,map as G,mapTo as RE,merge as ai,now as au,once as H,Subject as K,Subscription as LE,tap as Jd,ValueSubject as C,isHigher as FV,isInvariantQuality as $E,flattenObject as si,throttle as Zd,getTraceSubscriptionMethod as ME,TracerFactory as NV,InternalsExposure as UV}from"@vkontakte/videoplayer-shared/es2018";import{merge as $V,map as MV,filter as wE,isNonNullable as DV}from"@vkontakte/videoplayer-shared/es2018";var Kd=({seekState:a,position$:e})=>$V(a.stateChangeEnded$.pipe(MV(({to:t})=>{var i;return t.state==="none"?void 0:((i=t.position)!=null?i:NaN)/1e3}),wE(DV)),e.pipe(wE(()=>a.getState().state==="none")));import{assertNonNullable as CV}from"@vkontakte/videoplayer-shared/es2018";var AE=a=>{let e=typeof a.container=="string"?document.getElementById(a.container):a.container;return CV(e,`Wrong container or containerId {${a.container}}`),e};import{filter as BV,once as VV}from"@vkontakte/videoplayer-shared/es2018";var PE=(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(BV(r=>r.length>0),VV()).subscribe(r=>{r.find(i)&&e.startTransitionTo(a)}):(a===void 0||t!=null&&t.getValue().find(i))&&e.startTransitionTo(a)};var su=class{constructor(e={configName:[]},t=NV.createRootTracer(!1)){this.subscription=new LE;this.logger=new OV;this.abrLogger=this.logger.createComponentLog("ABR");this.internalsExposure=null;this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new C(!1);this.hasLiveOffsetByPausedTimer=0;this.playerInitRequest=0;this.playerInited=new C(!1);this.wasSetStartedQuality=!1;this.desiredState={playbackState:new q("stopped"),seekState:new q({state:"none"}),volume:new q({volume:1,muted:!1}),videoTrack:new q(void 0),videoStream:new q(void 0),audioStream:new q(void 0),autoVideoTrackSwitching:new q(!0),autoVideoTrackLimits:new q({}),isLooped:new q(!1),isLowLatency:new q(!1),playbackRate:new q(1),externalTextTracks:new q([]),internalTextTracks:new q([]),currentTextTrack:new q(void 0),textTrackCuesSettings:new q({}),cameraOrientation:new q({x:0,y:0})};this.info={playbackState$:new C(void 0),position$:new C(0),duration$:new C(1/0),muted$:new C(!1),volume$:new C(1),availableVideoStreams$:new C([]),currentVideoStream$:new C(void 0),availableQualities$:new C([]),availableQualitiesFps$:new C({}),currentQuality$:new C(void 0),isAutoQualityEnabled$:new C(!0),autoQualityLimitingAvailable$:new C(!1),autoQualityLimits$:new C({}),predefinedQualityLimitType$:new C("unknown"),availableAudioStreams$:new C([]),currentAudioStream$:new C(void 0),availableAudioTracks$:new C([]),isAudioAvailable$:new C(!0),currentPlaybackRate$:new C(1),currentBuffer$:new C({start:0,end:0}),isBuffering$:new C(!0),isStalled$:new C(!1),isEnded$:new C(!1),isLooped$:new C(!1),isLive$:new C(void 0),isLiveEnded$:new C(null),canPlayLiveTailBuffer$:new C(!1),canChangePlaybackSpeed$:new C(void 0),atLiveEdge$:new C(void 0),atLiveDurationEdge$:new C(void 0),liveTime$:new C(void 0),liveBufferTime$:new C(void 0),liveLatency$:new C(void 0),currentFormat$:new C(void 0),availableTextTracks$:new C([]),currentTextTrack$:new C(void 0),throughputEstimation$:new C(void 0),rttEstimation$:new C(void 0),videoBitrate$:new C(void 0),hostname$:new C(void 0),httpConnectionType$:new C(void 0),httpConnectionReused$:new C(void 0),surface$:new C("none"),chromecastState$:new C("NOT_AVAILABLE"),chromecastDeviceName$:new C(void 0),intrinsicVideoSize$:new C(void 0),availableSources$:new C(void 0),is3DVideo$:new C(!1),currentVideoSegmentLength$:new C(0),currentAudioSegmentLength$:new C(0)};this.events={inited$:new K,ready$:new K,started$:new K,playing$:new K,paused$:new K,stopped$:new K,willReady$:new K,willStart$:new K,willResume$:new K,willPause$:new K,willStop$:new K,willDestruct$:new K,watchCoverageRecord$:new K,watchCoverageLive$:new K,managedError$:new K,fatalError$:new K,fetcherRecoverableError$:new K,ended$:new K,looped$:new K,seeked$:new K,willSeek$:new K,autoplaySoundProhibited$:new K,firstBytes$:new K,loadedMetadata$:new K,firstFrame$:new K,canplay$:new K,log$:new K,fetcherError$:new K,severeStallOccured$:new K};this.experimental={element$:new C(void 0),tuningConfigName$:new C([]),enableDebugTelemetry$:new C(!1),dumpTelemetry:Tv,getCurrentTime$:new C(null)};if(this.initLogs(),this.tuning=xE(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new rn({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new IE(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new UV("CORE"),this.internalsExposure.expose({player:this})),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(i,r,s)=>{let n=Reflect.get(i,r,s);return typeof n!="function"?n:(...o)=>{try{return n.apply(i,o)}catch(u){let l=o.map(f=>JSON.stringify(f,(p,h)=>{let m=typeof h;return(0,DE.default)(["number","string","boolean"],m)?h:h===null?null:`<${m}>`})),c=`Player.${String(r)}`,d=`Exception calling ${c} (${l.join(", ")})`;throw this.events.fatalError$.next({id:c,category:ru.WTF,message:d,thrown:u}),u}}}})}initVideo(e){var s;this.config=e,(s=this.internalsExposure)==null||s.expose({config:e,logger:this.logger,tuning:this.tuning}),this.setMuted(this.tuning.isAudioDisabled);let t=()=>{var u,l,c;let{container:n,...o}=e;this.tracer.log("initVideo",si(o)),this.domContainer=AE(e),this.chromecastInitializer.contentId=(u=e.meta)==null?void 0:u.videoId,this.providerContainer=new Bs({sources:e.sources,meta:(l=e.meta)!=null?l:{},failoverHosts:(c=e.failoverHosts)!=null?c:[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,tracer:this.tracer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning,volumeMultiplier:e.volumeMultiplier,panelSize:e.panelSize}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.initTracerSubscription(),this.providerContainer.init(),this.setLiveLowLatency(this.tuning.dashCmafLive.lowLatency.isActiveOnDefault),this.initDebugTelemetry(),this.initWakeLock(),this.playerInited.next(!0)},i=()=>{this.tuning.autostartOnlyIfVisible&&window.requestAnimationFrame?this.playerInitRequest=window.requestAnimationFrame(()=>t()):t()},r=()=>{this.tuning.asyncResolveClientChecker?F.isInited$.pipe(U(n=>!!n),H()).subscribe(()=>{console.log("Core SDK async start"),i()}):i()};return this.isNotActiveTabCase()?(this.tracer.log("request play from hidden tab"),Xd(document,"visibilitychange").pipe(H()).subscribe(r)):r(),this}destroy(){var e,t;this.tracer.log("destroy"),window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.playerInitRequest&&window.cancelAnimationFrame(this.playerInitRequest),this.events.willDestruct$.next(),this.stop(),(e=this.providerContainer)==null||e.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe(),this.tracer.end(),(t=this.internalsExposure)==null||t.destroy()}prepare(){return this.subscription.add(this.playerInited.pipe(U(e=>!!e),H()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("prepare",{currentPlayBackState:e.getState()}),e.getState()==="stopped"&&e.startTransitionTo("ready")})),this}play(){return this.subscription.add(this.playerInited.pipe(U(e=>!!e),H()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("play",{currentPlayBackState:e.getState()}),e.getState()!=="playing"&&e.startTransitionTo("playing")})),this}pause(){return this.subscription.add(this.playerInited.pipe(U(e=>!!e),H()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("pause",{currentPlayBackState:e.getState()}),e.getState()!=="paused"&&e.startTransitionTo("paused")})),this}stop(){return this.subscription.add(this.playerInited.pipe(U(e=>!!e),H()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("stop",{currentPlayBackState:e.getState()}),e.getState()!=="stopped"&&e.startTransitionTo("stopped")})),this}seekTime(e,t=!0){return this.subscription.add(this.playerInited.pipe(U(i=>!!i),H()).subscribe(()=>{let i=this.info.duration$.getValue(),r=this.info.isLive$.getValue(),s=e;e>=i&&!r&&(s=i-this.tuning.seekNearDurationBias),this.tracer.log("seekTime",{duration:i,isLive:r,time:e,calculatedTime:s,forcePrecise:t}),Number.isFinite(s)&&(this.events.willSeek$.next({from:this.getExactTime(),to:s}),this.desiredState.seekState.setState({state:"requested",position:s*1e3,forcePrecise:t}))})),this}seekPercent(e){return this.subscription.add(this.playerInited.pipe(U(t=>!!t),H()).subscribe(()=>{let t=this.info.duration$.getValue();this.tracer.log("seekPercent",{percent:e,duration:t}),isFinite(t)&&this.seekTime(Math.abs(t)*e,!1)})),this}setVolume(e,t){return this.subscription.add(this.playerInited.pipe(U(i=>!!i),H()).subscribe(()=>{var o;let i=this.desiredState.volume,r=i.getTransition(),s=(o=r==null?void 0:r.to.muted)!=null?o:this.info.muted$.getValue(),n=t!=null?t:this.tuning.isAudioDisabled||s;this.tracer.log("setVolume",{volume:e,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:n}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setVolume(e):i.startTransitionTo({volume:e,muted:n})})),this}setMuted(e,t=!1){return this.subscription.add(this.playerInited.pipe(U(i=>!!i),H()).subscribe(()=>{var o;let i=this.desiredState.volume,r=this.tuning.isAudioDisabled&&!t||e,s=i.getTransition(),n=(o=s==null?void 0:s.to.volume)!=null?o:this.info.volume$.getValue();this.tracer.log("setMuted",{isMuted:e,nextMuted:r,volume:n,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue()}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setMuted(r):i.startTransitionTo({volume:n,muted:r})})),this}setVideoStream(e){return this.subscription.add(this.playerInited.pipe(U(t=>!!t),H()).subscribe(()=>{this.desiredState.videoStream.startTransitionTo(e)})),this}setAudioStream(e){return this.subscription.add(this.playerInited.pipe(U(t=>!!t),H()).subscribe(()=>{this.desiredState.audioStream.startTransitionTo(e)})),this}setQuality(e){return this.subscription.add(this.playerInited.pipe(U(t=>!!t),H()).subscribe(()=>{iu(this.providerContainer);let t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();this.tracer.log("setQuality",{isDelayed:t.length===0,quality:e}),this.desiredState.videoTrack.getState()===void 0&&this.desiredState.videoTrack.getPrevState()===void 0&&t.length===0?this.wasSetStartedQuality?this.providerContainer.providerOutput.availableVideoTracks$.pipe(U(i=>i.length>0),H()).subscribe(i=>{this.setVideoTrackIdByQuality(i,e)}):this.explicitInitialQuality=e:t.length>0&&this.setVideoTrackIdByQuality(t,e)})),this}setAutoQuality(e){return this.subscription.add(this.playerInited.pipe(U(t=>!!t),H()).subscribe(()=>{this.tracer.log("setAutoQuality",{enable:e}),this.desiredState.autoVideoTrackSwitching.startTransitionTo(e)})),this}setAutoQualityLimits(e){return this.subscription.add(this.playerInited.pipe(U(t=>!!t),H()).subscribe(()=>{this.tracer.log("setAutoQualityLimits",si(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e)})),this}setPredefinedQualityLimits(e){return this.subscription.add(this.playerInited.pipe(U(t=>!!t),H()).subscribe(()=>{if(this.info.predefinedQualityLimitType$.getValue()===e)return this;let{highQualityLimit:t,trafficSavingLimit:i}=this.tuning.autoTrackSelection,r;switch(e){case"high_quality":r={min:t,max:void 0};break;case"traffic_saving":r={max:i,min:void 0};break;default:r={max:void 0,min:void 0}}this.setAutoQualityLimits(r)})),this}setPlaybackRate(e){return this.subscription.add(this.playerInited.pipe(U(t=>!!t),H()).subscribe(()=>{var i;iu(this.providerContainer);let t=(i=this.providerContainer)==null?void 0:i.providerOutput.element$.getValue();this.tracer.log("setPlaybackRate",{playbackRate:e,isVideoElementAvailable:!!t}),t&&(this.desiredState.playbackRate.setState(e),t.playbackRate=e)})),this}setExternalTextTracks(e){return this.subscription.add(this.playerInited.pipe(U(t=>!!t),H()).subscribe(()=>{e.length&&this.tracer.log("setExternalTextTracks",si(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t})))})),this}selectTextTrack(e){return this.subscription.add(this.playerInited.pipe(U(t=>!!t),H()).subscribe(()=>{var t;PE(e,this.desiredState.currentTextTrack,(t=this.providerContainer)==null?void 0:t.providerOutput.availableTextTracks$,i=>i.id===e),this.tracer.log("selectTextTrack",{textTrackId:e})})),this}setTextTrackCueSettings(e){return this.subscription.add(this.playerInited.pipe(U(t=>!!t),H()).subscribe(()=>{this.tracer.log("setTextTrackCueSettings",{...e}),this.desiredState.textTrackCuesSettings.startTransitionTo(e)})),this}setLiveLowLatency(e){let t=this.info.isLive$.getValue(),i=this.desiredState.isLowLatency.getState();return!t||i===e?this:(this.tracer.log("live switch to low latency "+e),this.desiredState.isLowLatency.setState(e),this.seekTime(0))}setLooped(e){return this.subscription.add(this.playerInited.pipe(U(t=>!!t),H()).subscribe(()=>{this.tracer.log("setLooped",{isLooped:e}),this.desiredState.isLooped.startTransitionTo(e)})),this}toggleChromecast(){this.tracer.log("toggleChromecast"),this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){return this.subscription.add(this.playerInited.pipe(U(i=>!!i),H()).subscribe(()=>{let i=this.getScene3D();this.tracer.log("startCameraManualRotation",{isScene3DAvailable:!!i,mx:e,my:t}),i&&i.startCameraManualRotation(e,t)})),this}stopCameraManualRotation(e=!1){return this.subscription.add(this.playerInited.pipe(U(t=>!!t),H()).subscribe(()=>{let t=this.getScene3D();this.tracer.log("stopCameraManualRotation",{isScene3DAvailable:!!t,immediate:e}),t&&t.stopCameraManualRotation(e)})),this}moveCameraFocusPX(e,t){return this.subscription.add(this.playerInited.pipe(U(i=>!!i),H()).subscribe(()=>{let i=this.getScene3D();if(this.tracer.log("moveCameraFocusPX",{isScene3DAvailable:!!i,dxpx:e,dypx:t}),i){let r=i.getCameraRotation(),s=i.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:r.x+s.x,y:r.y+s.y})}})),this}holdCamera(){return this.subscription.add(this.playerInited.pipe(U(e=>e),H()).subscribe(()=>{let e=this.getScene3D();e&&e.holdCamera()})),this}releaseCamera(){return this.subscription.add(this.playerInited.pipe(U(e=>!!e),H()).subscribe(()=>{let e=this.getScene3D();e&&e.releaseCamera()})),this}getExactTime(){if(!this.providerContainer)return 0;let e=this.providerContainer.providerOutput.element$.getValue();if(_V(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),i=t.state==="none"?void 0:t.position;return kE(i)?i/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){var t,i;let e=(t=this.providerContainer)==null?void 0:t.current$.getValue();if((i=e==null?void 0:e.provider)!=null&&i.scene3D)return e.provider.scene3D}setIntrinsicVideoSize(...e){let t={width:e.reduce((i,{width:r})=>i||r||0,0),height:e.reduce((i,{height:r})=>i||r||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(ai(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(G(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(G(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(G(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(G(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(G(e=>e.to)).subscribe(e=>{this.info.autoQualityLimits$.next(e);let{highQualityLimit:t,trafficSavingLimit:i}=this.tuning.autoTrackSelection;this.info.predefinedQualityLimitType$.next(Sc(e,t,i))})),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(U(({from:e})=>e==="stopped"),H()).subscribe(()=>{this.initedAt=au(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case"ready":this.events.ready$.next();break;case"playing":this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case"paused":this.events.paused$.next();break;case"stopped":this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case"ready":this.events.willReady$.next();break;case"paused":this.events.willPause$.next();break;case"playing":this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case"stopped":this.events.willStop$.next();break;default:}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("willSeekEvent",si(n)),n.state==="requested"?this.desiredState.seekState.setState({...n,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:ru.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe(H()).subscribe(this.events.autoplaySoundProhibited$)).add(e.providerOutput.severeStallOccurred$.subscribe(this.events.severeStallOccured$)).add(e.providerOutput.seekedEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("seekedEvent",si(n)),n.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe(G(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(G(n=>n.destination),z()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(_t({availableVideoTracks:e.providerOutput.availableVideoTracks$,currentVideoStream:e.providerOutput.currentVideoStream$}).pipe(G(({availableVideoTracks:n,currentVideoStream:o})=>n.filter(u=>o?o.id===u.streamId:!0).map(({quality:u})=>u).sort((u,l)=>$E(u)?1:$E(l)?-1:FV(l,u)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(n=>{let o={};for(let u of n)u.fps&&(o[u.quality]=u.fps);this.info.availableQualitiesFps$.next(o)})).add(e.providerOutput.availableAudioStreams$.subscribe(this.info.availableAudioStreams$)).add(e.providerOutput.currentVideoStream$.subscribe(this.info.currentVideoStream$)).add(e.providerOutput.currentAudioStream$.subscribe(this.info.currentAudioStream$)).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.pipe(z()).subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.pipe(U(n=>kE(n))).subscribe(n=>{this.info.currentQuality$.next(n==null?void 0:n.quality),this.info.videoBitrate$.next(n==null?void 0:n.bitrate)})).add(e.providerOutput.currentVideoSegmentLength$.pipe(z((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe(z((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(z()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(z()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(z()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.autoVideoTrackLimits$.subscribe(n=>{this.desiredState.autoVideoTrackLimits.setState(n!=null?n:{})})).add(e.providerOutput.currentBuffer$.pipe(G(n=>n?{start:n.from,end:n.to}:{start:0,end:0})).subscribe(this.info.currentBuffer$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.isLiveEnded$.pipe(Jd(n=>n&&this.stop())).subscribe(this.info.isLiveEnded$)).add(e.providerOutput.canPlayLiveTailBuffer$.subscribe(this.info.canPlayLiveTailBuffer$)).add(e.providerOutput.canChangePlaybackSpeed$.subscribe(this.info.canChangePlaybackSpeed$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.liveBufferTime$.subscribe(this.info.liveBufferTime$)).add(e.providerOutput.liveLatency$.subscribe(this.info.liveLatency$)).add(_t({hasLiveOffsetByPaused:ai(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(G(n=>n.to),z(),G(n=>n==="paused")),isLowLatency:e.providerOutput.isLowLatency$}).subscribe(({hasLiveOffsetByPaused:n,isLowLatency:o})=>{if(window.clearTimeout(this.hasLiveOffsetByPausedTimer),n){this.hasLiveOffsetByPausedTimer=window.setTimeout(()=>{this.hasLiveOffsetByPaused.next(!0)},this.getActiveLiveDelay(o));return}this.hasLiveOffsetByPaused.next(!1)})).add(_t({atLiveEdge:_t({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Kd({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(G(({isLive:n,position:o,isLowLatency:u})=>{let l=this.getActiveLiveDelay(u);return n&&Math.abs(o)<l/1e3}),z(),Jd(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(G(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add(_t({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(G(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),z(),Jd(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(G(n=>n.muted),z()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(G(n=>n.volume),z()).subscribe(this.info.volume$)).add(Kd({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(ai(e.providerOutput.endedEvent$.pipe(RE(!0)),e.providerOutput.seekedEvent$.pipe(RE(!1))).pipe(z()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.providerOutput.fetcherRecoverableError$.subscribe(this.events.fetcherRecoverableError$)).add(e.providerOutput.fetcherError$.subscribe(this.events.fatalError$)).add(e.volumeMultiplierError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe(G(n=>({id:n?`No${n}`:"NoProviders",category:ru.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(H(),G(n=>n!=null?n:au()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(H(),G(()=>au()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(H(),G(()=>au()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$)).add(e.providerOutput.availableSources$.subscribe(this.info.availableSources$));let t=new C(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let i=new C(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(U(({to:n})=>n==="playing"),H()).subscribe(()=>i.next(!1)));let r=0,s=ai(e.providerOutput.isBuffering$,t,i).pipe(G(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||i.getValue();return n&&!o}),z());this.subscription.add(s.subscribe(n=>{n?r=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(r),this.info.isStalled$.next(!1))})),this.subscription.add(ai(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{let n=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n==null?void 0:n.videoWidth,height:n==null?void 0:n.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{var u,l;let o=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:(u=n==null?void 0:n.size)==null?void 0:u.width,height:(l=n==null?void 0:n.size)==null?void 0:l.height},{width:o==null?void 0:o.videoWidth,height:o==null?void 0:o.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add(ai(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,e.providerOutput.elementVisible$,this.chromecastInitializer.castState$).subscribe(()=>{let n=e.providerOutput.inPiP$.getValue(),o=e.providerOutput.inFullscreen$.getValue(),u=e.providerOutput.element$.getValue(),l=e.providerOutput.elementVisible$.getValue(),c=this.chromecastInitializer.castState$.getValue(),d;c==="CONNECTED"?d="second_screen":u?l?n?d="pip":o?d="fullscreen":d="inline":d="invisible":d="none",this.info.surface$.getValue()!==d&&this.info.surface$.next(d)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(G(e=>e==null?void 0:e.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new LE;this.subscription.add(t),this.subscription.add(e.current$.pipe(z((i,r)=>i.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(U(i=>i.length>0),H()).subscribe(i=>{this.setStartingVideoTrack(i)}))}))}setStartingVideoTrack(e){var r;let t;this.wasSetStartedQuality=!0;let i=(r=this.explicitInitialQuality)!=null?r:this.info.currentQuality$.getValue();i&&(t=e.find(({quality:s})=>s===i),t||this.setAutoQuality(!0)),t||(t=vt(e,{container:this.domContainer.getBoundingClientRect(),panelSize:this.config.panelSize,estimatedThroughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),playbackRate:this.info.currentPlaybackRate$.getValue(),forwardBufferHealth:0,abrLogger:this.abrLogger})),this.desiredState.videoTrack.startTransitionTo(t),this.info.currentQuality$.next(t.quality),this.info.videoBitrate$.next(t.bitrate)}initLogs(){this.subscription.add(ai(this.desiredState.videoTrack.stateChangeStarted$.pipe(G(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(G(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(G(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(G(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(G(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(G(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(G(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(G(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(G(e=>({component:"desiredState",message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`}))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){var t;let e=(t=this.providerContainer)==null?void 0:t.providerOutput;iu(this.providerContainer),iu(e),yv(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(i=>vv(i)),this.providerContainer.current$.subscribe(({type:i})=>Ia("provider",i)),e.duration$.subscribe(i=>Ia("duration",i)),e.availableVideoTracks$.pipe(U(i=>!!i.length),H()).subscribe(i=>Ia("tracks",i)),this.events.fatalError$.subscribe(new ke("fatalError")),this.events.managedError$.subscribe(new ke("managedError")),e.position$.subscribe(new ke("position")),e.currentVideoTrack$.pipe(G(i=>i==null?void 0:i.quality)).subscribe(new ke("quality")),this.info.currentBuffer$.subscribe(new ke("buffer")),e.isBuffering$.subscribe(new ke("isBuffering"))].forEach(i=>this.subscription.add(i)),Ia("codecs",F.video.supportedCodecs)}initTracerSubscription(){let e=ME(this.tracer.log.bind(this.tracer)),t=ME(this.tracer.error.bind(this.tracer));this.subscription.add(this.info.playbackState$.subscribe(e("playbackState"))).add(this.info.isLooped$.subscribe(e("isLooped"))).add(this.info.currentPlaybackRate$.pipe(z()).subscribe(e("currentPlaybackRate"))).add(this.info.isAutoQualityEnabled$.subscribe(e("isAutoQualityEnabled"))).add(this.info.autoQualityLimits$.subscribe(e("autoQualityLimits"))).add(this.info.currentFormat$.subscribe(e("currentFormat"))).add(this.info.availableQualities$.subscribe(e("availableQualities"))).add(this.info.availableQualitiesFps$.subscribe(e("availableQualitiesFps"))).add(this.info.availableAudioTracks$.subscribe(e("availableAudioTracks"))).add(this.info.isAudioAvailable$.subscribe(e("isAudioAvailable"))).add(_t({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe(U(({currentQuality:i,videoBitrate:r})=>!!i&&!!r),z((i,r)=>i.currentQuality===r.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe(U(i=>i>0),z()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe(U(i=>i>0),z()).subscribe(e("currentAudioSegmentLength"))).add(this.info.hostname$.subscribe(e("hostname"))).add(this.info.currentTextTrack$.subscribe(e("currentTextTrack"))).add(this.info.availableTextTracks$.subscribe(e("availableTextTracks"))).add(this.info.autoQualityLimitingAvailable$.subscribe(e("autoQualityLimitingAvailable"))).add(_t({currentBuffer:this.info.currentBuffer$.pipe(U(i=>i.end>0),z((i,r)=>i.end===r.end&&i.start===r.start)),position:this.info.position$.pipe(z())}).pipe(Zd(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe(z()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe(z()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe(z()).subscribe(e("canChangePlaybackSpeed"))).add(_t({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(U(({liveTime:i,liveBufferTime:r})=>!!i&&!!r),Zd(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(z(),U(i=>i===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(z(),U(i=>i===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe(z()).subscribe(e("muted"))).add(this.info.volume$.pipe(z()).subscribe(e("volume"))).add(this.info.isEnded$.pipe(z(),U(i=>i===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add(_t({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(U(({throughputEstimation:i,rtt:r})=>!!i&&!!r),Zd(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(z(),U(i=>i===!0)).subscribe(e("is3DVideo"))).add(this.info.surface$.subscribe(e("surface"))).add(this.events.ended$.subscribe(e("ended"))).add(this.events.looped$.subscribe(e("looped"))).add(this.events.managedError$.subscribe(t("managedError"))).add(this.events.fatalError$.subscribe(t("fatalError"))).add(this.events.firstBytes$.subscribe(e("firstBytes"))).add(this.events.firstFrame$.subscribe(e("firstFrame"))).add(this.events.canplay$.subscribe(e("canplay")))}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e,t=()=>{e==null||e.release(),e=void 0},i=async()=>{t(),e=await window.navigator.wakeLock.request("screen").catch(r=>{r instanceof DOMException&&r.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:ru.DOM,message:String(r)})})};this.subscription.add(ai(Xd(document,"visibilitychange"),Xd(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let r=document.visibilityState==="visible",s=this.desiredState.playbackState.getState()==="playing",n=!!e&&!(e!=null&&e.released);r&&s?n||i():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let i=e.find(r=>r.quality===t);this.tracer.log("setVideoTrackIdByQuality",si({quality:t,availableTracks:si(e),track:si(i),isAutoQuality:!i})),i?this.desiredState.videoTrack.startTransitionTo(i):this.setAutoQuality(!0)}getActiveLiveDelay(e=!1){return e?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay}isNotActiveTabCase(){return document.hidden&&this.tuning.autoplayOnlyInActiveTab&&!Ra()}};import{Subscription as ZX,Observable as eJ,Subject as tJ,ValueSubject as iJ,VideoQuality as rJ}from"@vkontakte/videoplayer-shared/es2018";var aJ=`@vkontakte/videoplayer-core@${Fp}`;export{Ys as ChromecastState,du as HttpConnectionType,eJ as Observable,Le as PlaybackState,su as Player,Ks as PredefinedQualityLimits,aJ as SDK_VERSION,tJ as Subject,ZX as Subscription,pu as Surface,Fp as VERSION,iJ as ValueSubject,At as VideoFormat,rJ as VideoQuality,V$ as areValidLiveRecordSources,F as clientChecker,ga as isMobile};
|