@vkontakte/videoplayer-core 2.0.144-dev.3ba5a3c2.0 → 2.0.145-dev.9523ea02.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 +42 -42
- package/es2015.esm.js +43 -43
- package/es2018.cjs.js +42 -42
- package/es2018.esm.js +46 -46
- package/es2024.cjs.js +37 -37
- package/es2024.esm.js +34 -34
- package/esnext.cjs.js +37 -37
- package/esnext.esm.js +34 -34
- package/evergreen.esm.js +27 -27
- package/package.json +2 -2
- package/types/providers/ChromecastNewProvider/ChromecastConnector.d.ts +108 -0
- package/types/providers/ChromecastNewProvider/ChromecastNewInitializer.d.ts +25 -0
- package/types/providers/ChromecastNewProvider/ChromecastNewProvider.d.ts +32 -0
- package/types/providers/ChromecastNewProvider/ProgressTicker.d.ts +11 -0
- package/types/providers/ChromecastNewProvider/index.d.ts +3 -0
- package/types/providers/ChromecastNewProvider/types.d.ts +21 -0
- package/types/providers/ChromecastNewProvider/utils.d.ts +4 -0
- package/types/providers/ChromecastProvider/ChromecastInitializer/index.d.ts +2 -10
- package/types/providers/ChromecastProvider/ChromecastInitializer/types.d.ts +8 -1
- package/types/providers/ChromecastProvider/index.d.ts +2 -10
- package/types/providers/ChromecastProvider/types.d.ts +8 -0
- package/types/providers/ChromecastProvider/utils.d.ts +2 -0
- package/types/utils/ClientChecker/services/BrowserChecker.d.ts +1 -0
- package/types/utils/tuningConfig.d.ts +1 -0
package/es2018.esm.js
CHANGED
|
@@ -1,127 +1,127 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @vkontakte/videoplayer-core v2.0.
|
|
3
|
-
*
|
|
4
|
-
* https://st.mycdn.me/static/vkontakte-videoplayer/2-0-
|
|
2
|
+
* @vkontakte/videoplayer-core v2.0.145-dev.9523ea02.0
|
|
3
|
+
* Wed, 29 Oct 2025 15:10:30 GMT
|
|
4
|
+
* https://st.mycdn.me/static/vkontakte-videoplayer/2-0-145/doc/
|
|
5
5
|
*/
|
|
6
|
-
var zE=Object.create;var Wp=Object.defineProperty;var YE=Object.getOwnPropertyDescriptor;var KE=Object.getOwnPropertyNames;var XE=Object.getPrototypeOf,JE=Object.prototype.hasOwnProperty;var S=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports);var ZE=(a,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of KE(e))!JE.call(a,r)&&r!==t&&Wp(a,r,{get:()=>e[r],enumerable:!(i=YE(e,r))||i.enumerable});return a};var F=(a,e,t)=>(t=a!=null?zE(XE(a)):{},ZE(e||!a||!a.__esModule?Wp(t,"default",{value:a,enumerable:!0}):t,a));var ae=S((xu,Gp)=>{"use strict";var Zr=function(a){return a&&a.Math===Math&&a};Gp.exports=Zr(typeof globalThis=="object"&&globalThis)||Zr(typeof window=="object"&&window)||Zr(typeof self=="object"&&self)||Zr(typeof global=="object"&&global)||Zr(typeof xu=="object"&&xu)||function(){return this}()||Function("return this")()});var he=S((u_,zp)=>{"use strict";zp.exports=function(a){try{return!!a()}catch(e){return!0}}});var ea=S((l_,Yp)=>{"use strict";var ex=he();Yp.exports=!ex(function(){var a=function(){}.bind();return typeof a!="function"||a.hasOwnProperty("prototype")})});var wu=S((c_,Zp)=>{"use strict";var tx=ea(),Jp=Function.prototype,Kp=Jp.apply,Xp=Jp.call;Zp.exports=typeof Reflect=="object"&&Reflect.apply||(tx?Xp.bind(Kp):function(){return Xp.apply(Kp,arguments)})});var fe=S((d_,ih)=>{"use strict";var eh=ea(),th=Function.prototype,Au=th.call,ix=eh&&th.bind.bind(Au,Au);ih.exports=eh?ix:function(a){return function(){return Au.apply(a,arguments)}}});var gi=S((p_,ah)=>{"use strict";var rh=fe(),rx=rh({}.toString),ax=rh("".slice);ah.exports=function(a){return ax(rx(a),8,-1)}});var Ru=S((h_,sh)=>{"use strict";var sx=gi(),nx=fe();sh.exports=function(a){if(sx(a)==="Function")return nx(a)}});var se=S((f_,nh)=>{"use strict";var Pu=typeof document=="object"&&document.all;nh.exports=typeof Pu=="undefined"&&Pu!==void 0?function(a){return typeof a=="function"||a===Pu}:function(a){return typeof a=="function"}});var Ne=S((m_,oh)=>{"use strict";var ox=he();oh.exports=!ox(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var qe=S((b_,uh)=>{"use strict";var ux=ea(),pn=Function.prototype.call;uh.exports=ux?pn.bind(pn):function(){return pn.apply(pn,arguments)}});var ku=S(dh=>{"use strict";var lh={}.propertyIsEnumerable,ch=Object.getOwnPropertyDescriptor,lx=ch&&!lh.call({1:2},1);dh.f=lx?function(e){var t=ch(this,e);return!!t&&t.enumerable}:lh});var ta=S((S_,ph)=>{"use strict";ph.exports=function(a,e){return{enumerable:!(a&1),configurable:!(a&2),writable:!(a&4),value:e}}});var fh=S((v_,hh)=>{"use strict";var cx=fe(),dx=he(),px=gi(),Lu=Object,hx=cx("".split);hh.exports=dx(function(){return!Lu("z").propertyIsEnumerable(0)})?function(a){return px(a)==="String"?hx(a,""):Lu(a)}:Lu});var ia=S((y_,mh)=>{"use strict";mh.exports=function(a){return a==null}});var Wt=S((T_,bh)=>{"use strict";var fx=ia(),mx=TypeError;bh.exports=function(a){if(fx(a))throw new mx("Can't call method on "+a);return a}});var Si=S((I_,gh)=>{"use strict";var bx=fh(),gx=Wt();gh.exports=function(a){return bx(gx(a))}});var Me=S((E_,Sh)=>{"use strict";var Sx=se();Sh.exports=function(a){return typeof a=="object"?a!==null:Sx(a)}});var vi=S((x_,vh)=>{"use strict";vh.exports={}});var Rt=S((w_,Th)=>{"use strict";var $u=vi(),Mu=ae(),vx=se(),yh=function(a){return vx(a)?a:void 0};Th.exports=function(a,e){return arguments.length<2?yh($u[a])||yh(Mu[a]):$u[a]&&$u[a][e]||Mu[a]&&Mu[a][e]}});var ra=S((A_,Ih)=>{"use strict";var yx=fe();Ih.exports=yx({}.isPrototypeOf)});var yi=S((R_,wh)=>{"use strict";var Tx=ae(),Eh=Tx.navigator,xh=Eh&&Eh.userAgent;wh.exports=xh?String(xh):""});var Cu=S((P_,$h)=>{"use strict";var Lh=ae(),Du=yi(),Ah=Lh.process,Rh=Lh.Deno,Ph=Ah&&Ah.versions||Rh&&Rh.version,kh=Ph&&Ph.v8,it,hn;kh&&(it=kh.split("."),hn=it[0]>0&&it[0]<4?1:+(it[0]+it[1]));!hn&&Du&&(it=Du.match(/Edge\/(\d+)/),(!it||it[1]>=74)&&(it=Du.match(/Chrome\/(\d+)/),it&&(hn=+it[1])));$h.exports=hn});var Bu=S((k_,Dh)=>{"use strict";var Mh=Cu(),Ix=he(),Ex=ae(),xx=Ex.String;Dh.exports=!!Object.getOwnPropertySymbols&&!Ix(function(){var a=Symbol("symbol detection");return!xx(a)||!(Object(a)instanceof Symbol)||!Symbol.sham&&Mh&&Mh<41})});var Vu=S((L_,Ch)=>{"use strict";var wx=Bu();Ch.exports=wx&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var _u=S(($_,Bh)=>{"use strict";var Ax=Rt(),Rx=se(),Px=ra(),kx=Vu(),Lx=Object;Bh.exports=kx?function(a){return typeof a=="symbol"}:function(a){var e=Ax("Symbol");return Rx(e)&&Px(e.prototype,Lx(a))}});var aa=S((M_,Vh)=>{"use strict";var $x=String;Vh.exports=function(a){try{return $x(a)}catch(e){return"Object"}}});var ft=S((D_,_h)=>{"use strict";var Mx=se(),Dx=aa(),Cx=TypeError;_h.exports=function(a){if(Mx(a))return a;throw new Cx(Dx(a)+" is not a function")}});var sa=S((C_,Oh)=>{"use strict";var Bx=ft(),Vx=ia();Oh.exports=function(a,e){var t=a[e];return Vx(t)?void 0:Bx(t)}});var Nh=S((B_,Fh)=>{"use strict";var Ou=qe(),Fu=se(),Nu=Me(),_x=TypeError;Fh.exports=function(a,e){var t,i;if(e==="string"&&Fu(t=a.toString)&&!Nu(i=Ou(t,a))||Fu(t=a.valueOf)&&!Nu(i=Ou(t,a))||e!=="string"&&Fu(t=a.toString)&&!Nu(i=Ou(t,a)))return i;throw new _x("Can't convert object to primitive value")}});var rt=S((V_,qh)=>{"use strict";qh.exports=!0});var jh=S((__,Hh)=>{"use strict";var Uh=ae(),Ox=Object.defineProperty;Hh.exports=function(a,e){try{Ox(Uh,a,{value:e,configurable:!0,writable:!0})}catch(t){Uh[a]=e}return e}});var na=S((O_,Gh)=>{"use strict";var Fx=rt(),Nx=ae(),qx=jh(),Wh="__core-js_shared__",Qh=Gh.exports=Nx[Wh]||qx(Wh,{});(Qh.versions||(Qh.versions=[])).push({version:"3.43.0",mode:Fx?"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 qu=S((F_,Yh)=>{"use strict";var zh=na();Yh.exports=function(a,e){return zh[a]||(zh[a]=e||{})}});var Zi=S((N_,Kh)=>{"use strict";var Ux=Wt(),Hx=Object;Kh.exports=function(a){return Hx(Ux(a))}});var at=S((q_,Xh)=>{"use strict";var jx=fe(),Wx=Zi(),Qx=jx({}.hasOwnProperty);Xh.exports=Object.hasOwn||function(e,t){return Qx(Wx(e),t)}});var Uu=S((U_,Jh)=>{"use strict";var Gx=fe(),zx=0,Yx=Math.random(),Kx=Gx(1.1.toString);Jh.exports=function(a){return"Symbol("+(a===void 0?"":a)+")_"+Kx(++zx+Yx,36)}});var ve=S((H_,ef)=>{"use strict";var Xx=ae(),Jx=qu(),Zh=at(),Zx=Uu(),ew=Bu(),tw=Vu(),er=Xx.Symbol,Hu=Jx("wks"),iw=tw?er.for||er:er&&er.withoutSetter||Zx;ef.exports=function(a){return Zh(Hu,a)||(Hu[a]=ew&&Zh(er,a)?er[a]:iw("Symbol."+a)),Hu[a]}});var sf=S((j_,af)=>{"use strict";var rw=qe(),tf=Me(),rf=_u(),aw=sa(),sw=Nh(),nw=ve(),ow=TypeError,uw=nw("toPrimitive");af.exports=function(a,e){if(!tf(a)||rf(a))return a;var t=aw(a,uw),i;if(t){if(e===void 0&&(e="default"),i=rw(t,a,e),!tf(i)||rf(i))return i;throw new ow("Can't convert object to primitive value")}return e===void 0&&(e="number"),sw(a,e)}});var ju=S((W_,nf)=>{"use strict";var lw=sf(),cw=_u();nf.exports=function(a){var e=lw(a,"string");return cw(e)?e:e+""}});var fn=S((Q_,uf)=>{"use strict";var dw=ae(),of=Me(),Wu=dw.document,pw=of(Wu)&&of(Wu.createElement);uf.exports=function(a){return pw?Wu.createElement(a):{}}});var Qu=S((G_,lf)=>{"use strict";var hw=Ne(),fw=he(),mw=fn();lf.exports=!hw&&!fw(function(){return Object.defineProperty(mw("div"),"a",{get:function(){return 7}}).a!==7})});var pf=S(df=>{"use strict";var bw=Ne(),gw=qe(),Sw=ku(),vw=ta(),yw=Si(),Tw=ju(),Iw=at(),Ew=Qu(),cf=Object.getOwnPropertyDescriptor;df.f=bw?cf:function(e,t){if(e=yw(e),t=Tw(t),Ew)try{return cf(e,t)}catch(i){}if(Iw(e,t))return vw(!gw(Sw.f,e,t),e[t])}});var Gu=S((Y_,hf)=>{"use strict";var xw=he(),ww=se(),Aw=/#|\.prototype\./,oa=function(a,e){var t=Pw[Rw(a)];return t===Lw?!0:t===kw?!1:ww(e)?xw(e):!!e},Rw=oa.normalize=function(a){return String(a).replace(Aw,".").toLowerCase()},Pw=oa.data={},kw=oa.NATIVE="N",Lw=oa.POLYFILL="P";hf.exports=oa});var tr=S((K_,mf)=>{"use strict";var ff=Ru(),$w=ft(),Mw=ea(),Dw=ff(ff.bind);mf.exports=function(a,e){return $w(a),e===void 0?a:Mw?Dw(a,e):function(){return a.apply(e,arguments)}}});var zu=S((X_,bf)=>{"use strict";var Cw=Ne(),Bw=he();bf.exports=Cw&&Bw(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var mt=S((J_,gf)=>{"use strict";var Vw=Me(),_w=String,Ow=TypeError;gf.exports=function(a){if(Vw(a))return a;throw new Ow(_w(a)+" is not an object")}});var Ti=S(vf=>{"use strict";var Fw=Ne(),Nw=Qu(),qw=zu(),mn=mt(),Sf=ju(),Uw=TypeError,Yu=Object.defineProperty,Hw=Object.getOwnPropertyDescriptor,Ku="enumerable",Xu="configurable",Ju="writable";vf.f=Fw?qw?function(e,t,i){if(mn(e),t=Sf(t),mn(i),typeof e=="function"&&t==="prototype"&&"value"in i&&Ju in i&&!i[Ju]){var r=Hw(e,t);r&&r[Ju]&&(e[t]=i.value,i={configurable:Xu in i?i[Xu]:r[Xu],enumerable:Ku in i?i[Ku]:r[Ku],writable:!1})}return Yu(e,t,i)}:Yu:function(e,t,i){if(mn(e),t=Sf(t),mn(i),Nw)try{return Yu(e,t,i)}catch(r){}if("get"in i||"set"in i)throw new Uw("Accessors not supported");return"value"in i&&(e[t]=i.value),e}});var ir=S((eO,yf)=>{"use strict";var jw=Ne(),Ww=Ti(),Qw=ta();yf.exports=jw?function(a,e,t){return Ww.f(a,e,Qw(1,t))}:function(a,e,t){return a[e]=t,a}});var le=S((tO,If)=>{"use strict";var ua=ae(),Gw=wu(),zw=Ru(),Yw=se(),Kw=pf().f,Xw=Gu(),rr=vi(),Jw=tr(),ar=ir(),Tf=at();na();var Zw=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 Gw(a,this,arguments)};return e.prototype=a.prototype,e};If.exports=function(a,e){var t=a.target,i=a.global,r=a.stat,s=a.proto,n=i?ua:r?ua[t]:ua[t]&&ua[t].prototype,o=i?rr:rr[t]||ar(rr,t,{})[t],u=o.prototype,l,c,d,h,p,f,m,g,b;for(h in e)l=Xw(i?h:t+(r?".":"#")+h,a.forced),c=!l&&n&&Tf(n,h),f=o[h],c&&(a.dontCallGetSet?(b=Kw(n,h),m=b&&b.value):m=n[h]),p=c&&m?m:e[h],!(!l&&!s&&typeof f==typeof p)&&(a.bind&&c?g=Jw(p,ua):a.wrap&&c?g=Zw(p):s&&Yw(p)?g=zw(p):g=p,(a.sham||p&&p.sham||f&&f.sham)&&ar(g,"sham",!0),ar(o,h,g),s&&(d=t+"Prototype",Tf(rr,d)||ar(rr,d,{}),ar(rr[d],h,p),a.real&&u&&(l||!u[h])&&ar(u,h,p)))}});var bn=S((iO,xf)=>{"use strict";var eA=qu(),tA=Uu(),Ef=eA("keys");xf.exports=function(a){return Ef[a]||(Ef[a]=tA(a))}});var Af=S((rO,wf)=>{"use strict";var iA=he();wf.exports=!iA(function(){function a(){}return a.prototype.constructor=null,Object.getPrototypeOf(new a)!==a.prototype})});var gn=S((aO,Pf)=>{"use strict";var rA=at(),aA=se(),sA=Zi(),nA=bn(),oA=Af(),Rf=nA("IE_PROTO"),Zu=Object,uA=Zu.prototype;Pf.exports=oA?Zu.getPrototypeOf:function(a){var e=sA(a);if(rA(e,Rf))return e[Rf];var t=e.constructor;return aA(t)&&e instanceof t?t.prototype:e instanceof Zu?uA:null}});var Lf=S((sO,kf)=>{"use strict";var lA=Math.ceil,cA=Math.floor;kf.exports=Math.trunc||function(e){var t=+e;return(t>0?cA:lA)(t)}});var la=S((nO,$f)=>{"use strict";var dA=Lf();$f.exports=function(a){var e=+a;return e!==e||e===0?0:dA(e)}});var Df=S((oO,Mf)=>{"use strict";var pA=la(),hA=Math.max,fA=Math.min;Mf.exports=function(a,e){var t=pA(a);return t<0?hA(t+e,0):fA(t,e)}});var el=S((uO,Cf)=>{"use strict";var mA=la(),bA=Math.min;Cf.exports=function(a){var e=mA(a);return e>0?bA(e,9007199254740991):0}});var sr=S((lO,Bf)=>{"use strict";var gA=el();Bf.exports=function(a){return gA(a.length)}});var tl=S((cO,_f)=>{"use strict";var SA=Si(),vA=Df(),yA=sr(),Vf=function(a){return function(e,t,i){var r=SA(e),s=yA(r);if(s===0)return!a&&-1;var n=vA(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}};_f.exports={includes:Vf(!0),indexOf:Vf(!1)}});var Sn=S((dO,Of)=>{"use strict";Of.exports={}});var qf=S((pO,Nf)=>{"use strict";var TA=fe(),il=at(),IA=Si(),EA=tl().indexOf,xA=Sn(),Ff=TA([].push);Nf.exports=function(a,e){var t=IA(a),i=0,r=[],s;for(s in t)!il(xA,s)&&il(t,s)&&Ff(r,s);for(;e.length>i;)il(t,s=e[i++])&&(~EA(r,s)||Ff(r,s));return r}});var rl=S((hO,Uf)=>{"use strict";Uf.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var al=S((fO,Hf)=>{"use strict";var wA=qf(),AA=rl();Hf.exports=Object.keys||function(e){return wA(e,AA)}});var sl=S((mO,zf)=>{"use strict";var Wf=Ne(),RA=he(),Qf=fe(),PA=gn(),kA=al(),LA=Si(),$A=ku().f,Gf=Qf($A),MA=Qf([].push),DA=Wf&&RA(function(){var a=Object.create(null);return a[2]=2,!Gf(a,2)}),jf=function(a){return function(e){for(var t=LA(e),i=kA(t),r=DA&&PA(t)===null,s=i.length,n=0,o=[],u;s>n;)u=i[n++],(!Wf||(r?u in t:Gf(t,u)))&&MA(o,a?[u,t[u]]:t[u]);return o}};zf.exports={entries:jf(!0),values:jf(!1)}});var Yf=S(()=>{"use strict";var CA=le(),BA=sl().values;CA({target:"Object",stat:!0},{values:function(e){return BA(e)}})});var Xf=S((SO,Kf)=>{"use strict";Yf();var VA=vi();Kf.exports=VA.Object.values});var Zf=S((vO,Jf)=>{"use strict";var _A=Xf();Jf.exports=_A});var Ii=S((yO,em)=>{"use strict";var OA=Zf();em.exports=OA});var ca=S((TO,tm)=>{"use strict";tm.exports=function(){}});var im=S(()=>{"use strict";var FA=le(),NA=tl().includes,qA=he(),UA=ca(),HA=qA(function(){return!Array(1).includes()});FA({target:"Array",proto:!0,forced:HA},{includes:function(e){return NA(this,e,arguments.length>1?arguments[1]:void 0)}});UA("includes")});var Qt=S((xO,rm)=>{"use strict";var jA=Rt();rm.exports=jA});var sm=S((wO,am)=>{"use strict";im();var WA=Qt();am.exports=WA("Array","includes")});var om=S((AO,nm)=>{"use strict";var QA=sm();nm.exports=QA});var De=S((RO,um)=>{"use strict";var GA=om();um.exports=GA});var mm=S(()=>{"use strict";var tR=le(),iR=sl().entries;tR({target:"Object",stat:!0},{entries:function(e){return iR(e)}})});var gm=S((qO,bm)=>{"use strict";mm();var rR=vi();bm.exports=rR.Object.entries});var vm=S((UO,Sm)=>{"use strict";var aR=gm();Sm.exports=aR});var nr=S((HO,ym)=>{"use strict";var sR=vm();ym.exports=sR});var Ei=S((jO,Tm)=>{"use strict";Tm.exports={}});var xm=S((WO,Em)=>{"use strict";var nR=ae(),oR=se(),Im=nR.WeakMap;Em.exports=oR(Im)&&/native code/.test(String(Im))});var dl=S((QO,Rm)=>{"use strict";var uR=xm(),Am=ae(),lR=Me(),cR=ir(),ul=at(),ll=na(),dR=bn(),pR=Sn(),wm="Object already initialized",cl=Am.TypeError,hR=Am.WeakMap,Tn,da,In,fR=function(a){return In(a)?da(a):Tn(a,{})},mR=function(a){return function(e){var t;if(!lR(e)||(t=da(e)).type!==a)throw new cl("Incompatible receiver, "+a+" required");return t}};uR||ll.state?(st=ll.state||(ll.state=new hR),st.get=st.get,st.has=st.has,st.set=st.set,Tn=function(a,e){if(st.has(a))throw new cl(wm);return e.facade=a,st.set(a,e),e},da=function(a){return st.get(a)||{}},In=function(a){return st.has(a)}):(xi=dR("state"),pR[xi]=!0,Tn=function(a,e){if(ul(a,xi))throw new cl(wm);return e.facade=a,cR(a,xi,e),e},da=function(a){return ul(a,xi)?a[xi]:{}},In=function(a){return ul(a,xi)});var st,xi;Rm.exports={set:Tn,get:da,has:In,enforce:fR,getterFor:mR}});var fl=S((GO,km)=>{"use strict";var pl=Ne(),bR=at(),Pm=Function.prototype,gR=pl&&Object.getOwnPropertyDescriptor,hl=bR(Pm,"name"),SR=hl&&function(){}.name==="something",vR=hl&&(!pl||pl&&gR(Pm,"name").configurable);km.exports={EXISTS:hl,PROPER:SR,CONFIGURABLE:vR}});var $m=S(Lm=>{"use strict";var yR=Ne(),TR=zu(),IR=Ti(),ER=mt(),xR=Si(),wR=al();Lm.f=yR&&!TR?Object.defineProperties:function(e,t){ER(e);for(var i=xR(t),r=wR(t),s=r.length,n=0,o;s>n;)IR.f(e,o=r[n++],i[o]);return e}});var ml=S((YO,Mm)=>{"use strict";var AR=Rt();Mm.exports=AR("document","documentElement")});var vl=S((KO,Fm)=>{"use strict";var RR=mt(),PR=$m(),Dm=rl(),kR=Sn(),LR=ml(),$R=fn(),MR=bn(),Cm=">",Bm="<",gl="prototype",Sl="script",_m=MR("IE_PROTO"),bl=function(){},Om=function(a){return Bm+Sl+Cm+a+Bm+"/"+Sl+Cm},Vm=function(a){a.write(Om("")),a.close();var e=a.parentWindow.Object;return a=null,e},DR=function(){var a=$R("iframe"),e="java"+Sl+":",t;return a.style.display="none",LR.appendChild(a),a.src=String(e),t=a.contentWindow.document,t.open(),t.write(Om("document.F=Object")),t.close(),t.F},En,xn=function(){try{En=new ActiveXObject("htmlfile")}catch(e){}xn=typeof document!="undefined"?document.domain&&En?Vm(En):DR():Vm(En);for(var a=Dm.length;a--;)delete xn[gl][Dm[a]];return xn()};kR[_m]=!0;Fm.exports=Object.create||function(e,t){var i;return e!==null?(bl[gl]=RR(e),i=new bl,bl[gl]=null,i[_m]=e):i=xn(),t===void 0?i:PR.f(i,t)}});var or=S((XO,Nm)=>{"use strict";var CR=ir();Nm.exports=function(a,e,t,i){return i&&i.enumerable?a[e]=t:CR(a,e,t),a}});var El=S((JO,Hm)=>{"use strict";var BR=he(),VR=se(),_R=Me(),OR=vl(),qm=gn(),FR=or(),NR=ve(),qR=rt(),Il=NR("iterator"),Um=!1,Pt,yl,Tl;[].keys&&(Tl=[].keys(),"next"in Tl?(yl=qm(qm(Tl)),yl!==Object.prototype&&(Pt=yl)):Um=!0);var UR=!_R(Pt)||BR(function(){var a={};return Pt[Il].call(a)!==a});UR?Pt={}:qR&&(Pt=OR(Pt));VR(Pt[Il])||FR(Pt,Il,function(){return this});Hm.exports={IteratorPrototype:Pt,BUGGY_SAFARI_ITERATORS:Um}});var wn=S((ZO,Wm)=>{"use strict";var HR=ve(),jR=HR("toStringTag"),jm={};jm[jR]="z";Wm.exports=String(jm)==="[object z]"});var pa=S((eF,Qm)=>{"use strict";var WR=wn(),QR=se(),An=gi(),GR=ve(),zR=GR("toStringTag"),YR=Object,KR=An(function(){return arguments}())==="Arguments",XR=function(a,e){try{return a[e]}catch(t){}};Qm.exports=WR?An:function(a){var e,t,i;return a===void 0?"Undefined":a===null?"Null":typeof(t=XR(e=YR(a),zR))=="string"?t:KR?An(e):(i=An(e))==="Object"&&QR(e.callee)?"Arguments":i}});var zm=S((tF,Gm)=>{"use strict";var JR=wn(),ZR=pa();Gm.exports=JR?{}.toString:function(){return"[object "+ZR(this)+"]"}});var ha=S((iF,Km)=>{"use strict";var eP=wn(),tP=Ti().f,iP=ir(),rP=at(),aP=zm(),sP=ve(),Ym=sP("toStringTag");Km.exports=function(a,e,t,i){var r=t?a:a&&a.prototype;r&&(rP(r,Ym)||tP(r,Ym,{configurable:!0,value:e}),i&&!eP&&iP(r,"toString",aP))}});var Jm=S((rF,Xm)=>{"use strict";var nP=El().IteratorPrototype,oP=vl(),uP=ta(),lP=ha(),cP=Ei(),dP=function(){return this};Xm.exports=function(a,e,t,i){var r=e+" Iterator";return a.prototype=oP(nP,{next:uP(+!i,t)}),lP(a,r,!1,!0),cP[r]=dP,a}});var eb=S((aF,Zm)=>{"use strict";var pP=fe(),hP=ft();Zm.exports=function(a,e,t){try{return pP(hP(Object.getOwnPropertyDescriptor(a,e)[t]))}catch(i){}}});var ib=S((sF,tb)=>{"use strict";var fP=Me();tb.exports=function(a){return fP(a)||a===null}});var ab=S((nF,rb)=>{"use strict";var mP=ib(),bP=String,gP=TypeError;rb.exports=function(a){if(mP(a))return a;throw new gP("Can't set "+bP(a)+" as a prototype")}});var xl=S((oF,sb)=>{"use strict";var SP=eb(),vP=Me(),yP=Wt(),TP=ab();sb.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var a=!1,e={},t;try{t=SP(Object.prototype,"__proto__","set"),t(e,[]),a=e instanceof Array}catch(i){}return function(r,s){return yP(r),TP(s),vP(r)&&(a?t(r,s):r.__proto__=s),r}}():void 0)});var bb=S((uF,mb)=>{"use strict";var IP=le(),EP=qe(),Rn=rt(),hb=fl(),xP=se(),wP=Jm(),nb=gn(),ob=xl(),AP=ha(),RP=ir(),wl=or(),PP=ve(),ub=Ei(),fb=El(),kP=hb.PROPER,LP=hb.CONFIGURABLE,lb=fb.IteratorPrototype,Pn=fb.BUGGY_SAFARI_ITERATORS,fa=PP("iterator"),cb="keys",ma="values",db="entries",pb=function(){return this};mb.exports=function(a,e,t,i,r,s,n){wP(t,e,i);var o=function(b){if(b===r&&h)return h;if(!Pn&&b&&b in c)return c[b];switch(b){case cb:return function(){return new t(this,b)};case ma:return function(){return new t(this,b)};case db:return function(){return new t(this,b)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,c=a.prototype,d=c[fa]||c["@@iterator"]||r&&c[r],h=!Pn&&d||o(r),p=e==="Array"&&c.entries||d,f,m,g;if(p&&(f=nb(p.call(new a)),f!==Object.prototype&&f.next&&(!Rn&&nb(f)!==lb&&(ob?ob(f,lb):xP(f[fa])||wl(f,fa,pb)),AP(f,u,!0,!0),Rn&&(ub[u]=pb))),kP&&r===ma&&d&&d.name!==ma&&(!Rn&&LP?RP(c,"name",ma):(l=!0,h=function(){return EP(d,this)})),r)if(m={values:o(ma),keys:s?h:o(cb),entries:o(db)},n)for(g in m)(Pn||l||!(g in c))&&wl(c,g,m[g]);else IP({target:e,proto:!0,forced:Pn||l},m);return(!Rn||n)&&c[fa]!==h&&wl(c,fa,h,{name:r}),ub[e]=h,m}});var Sb=S((lF,gb)=>{"use strict";gb.exports=function(a,e){return{value:a,done:e}}});var Rl=S((cF,Eb)=>{"use strict";var $P=Si(),Al=ca(),vb=Ei(),Tb=dl(),MP=Ti().f,DP=bb(),kn=Sb(),CP=rt(),BP=Ne(),Ib="Array Iterator",VP=Tb.set,_P=Tb.getterFor(Ib);Eb.exports=DP(Array,"Array",function(a,e){VP(this,{type:Ib,target:$P(a),index:0,kind:e})},function(){var a=_P(this),e=a.target,t=a.index++;if(!e||t>=e.length)return a.target=null,kn(void 0,!0);switch(a.kind){case"keys":return kn(t,!1);case"values":return kn(e[t],!1)}return kn([t,e[t]],!1)},"values");var yb=vb.Arguments=vb.Array;Al("keys");Al("values");Al("entries");if(!CP&&BP&&yb.name!=="values")try{MP(yb,"name",{value:"values"})}catch(a){}});var wb=S((dF,xb)=>{"use strict";var OP=ve(),FP=Ei(),NP=OP("iterator"),qP=Array.prototype;xb.exports=function(a){return a!==void 0&&(FP.Array===a||qP[NP]===a)}});var Pl=S((pF,Rb)=>{"use strict";var UP=pa(),Ab=sa(),HP=ia(),jP=Ei(),WP=ve(),QP=WP("iterator");Rb.exports=function(a){if(!HP(a))return Ab(a,QP)||Ab(a,"@@iterator")||jP[UP(a)]}});var kb=S((hF,Pb)=>{"use strict";var GP=qe(),zP=ft(),YP=mt(),KP=aa(),XP=Pl(),JP=TypeError;Pb.exports=function(a,e){var t=arguments.length<2?XP(a):e;if(zP(t))return YP(GP(t,a));throw new JP(KP(a)+" is not iterable")}});var Mb=S((fF,$b)=>{"use strict";var ZP=qe(),Lb=mt(),ek=sa();$b.exports=function(a,e,t){var i,r;Lb(a);try{if(i=ek(a,"return"),!i){if(e==="throw")throw t;return t}i=ZP(i,a)}catch(s){r=!0,i=s}if(e==="throw")throw t;if(r)throw i;return Lb(i),t}});var $n=S((mF,Vb)=>{"use strict";var tk=tr(),ik=qe(),rk=mt(),ak=aa(),sk=wb(),nk=sr(),Db=ra(),ok=kb(),uk=Pl(),Cb=Mb(),lk=TypeError,Ln=function(a,e){this.stopped=a,this.result=e},Bb=Ln.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=tk(e,i),l,c,d,h,p,f,m,g=function(v){return l&&Cb(l,"normal"),new Ln(!0,v)},b=function(v){return r?(rk(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(c=uk(a),!c)throw new lk(ak(a)+" is not iterable");if(sk(c)){for(d=0,h=nk(a);h>d;d++)if(p=b(a[d]),p&&Db(Bb,p))return p;return new Ln(!1)}l=ok(a,c)}for(f=s?a.next:l.next;!(m=ik(f,l)).done;){try{p=b(m.value)}catch(v){Cb(l,"throw",v)}if(typeof p=="object"&&p&&Db(Bb,p))return p}return new Ln(!1)}});var Ob=S((bF,_b)=>{"use strict";var ck=Ne(),dk=Ti(),pk=ta();_b.exports=function(a,e,t){ck?dk.f(a,e,pk(0,t)):a[e]=t}});var Fb=S(()=>{"use strict";var hk=le(),fk=$n(),mk=Ob();hk({target:"Object",stat:!0},{fromEntries:function(e){var t={};return fk(e,function(i,r){mk(t,i,r)},{AS_ENTRIES:!0}),t}})});var qb=S((vF,Nb)=>{"use strict";Rl();Fb();var bk=vi();Nb.exports=bk.Object.fromEntries});var Hb=S((yF,Ub)=>{"use strict";Ub.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 Wb=S(()=>{"use strict";Rl();var gk=Hb(),Sk=ae(),vk=ha(),jb=Ei();for(Mn in gk)vk(Sk[Mn],Mn),jb[Mn]=jb.Array;var Mn});var Gb=S((EF,Qb)=>{"use strict";var yk=qb();Wb();Qb.exports=yk});var kl=S((xF,zb)=>{"use strict";var Tk=Gb();zb.exports=Tk});var Yb=S(()=>{"use strict"});var Ll=S((RF,Kb)=>{"use strict";var ba=ae(),Ik=yi(),Ek=gi(),Dn=function(a){return Ik.slice(0,a.length)===a};Kb.exports=function(){return Dn("Bun/")?"BUN":Dn("Cloudflare-Workers")?"CLOUDFLARE":Dn("Deno/")?"DENO":Dn("Node.js/")?"NODE":ba.Bun&&typeof Bun.version=="string"?"BUN":ba.Deno&&typeof Deno.version=="object"?"DENO":Ek(ba.process)==="process"?"NODE":ba.window&&ba.document?"BROWSER":"REST"}()});var Cn=S((PF,Xb)=>{"use strict";var xk=Ll();Xb.exports=xk==="NODE"});var Zb=S((kF,Jb)=>{"use strict";var wk=Ti();Jb.exports=function(a,e,t){return wk.f(a,e,t)}});var ig=S((LF,tg)=>{"use strict";var Ak=Rt(),Rk=Zb(),Pk=ve(),kk=Ne(),eg=Pk("species");tg.exports=function(a){var e=Ak(a);kk&&e&&!e[eg]&&Rk(e,eg,{configurable:!0,get:function(){return this}})}});var ag=S(($F,rg)=>{"use strict";var Lk=ra(),$k=TypeError;rg.exports=function(a,e){if(Lk(e,a))return a;throw new $k("Incorrect invocation")}});var Ml=S((MF,sg)=>{"use strict";var Mk=fe(),Dk=se(),$l=na(),Ck=Mk(Function.toString);Dk($l.inspectSource)||($l.inspectSource=function(a){return Ck(a)});sg.exports=$l.inspectSource});var Cl=S((DF,cg)=>{"use strict";var Bk=fe(),Vk=he(),ng=se(),_k=pa(),Ok=Rt(),Fk=Ml(),og=function(){},ug=Ok("Reflect","construct"),Dl=/^\s*(?:class|function)\b/,Nk=Bk(Dl.exec),qk=!Dl.test(og),ga=function(e){if(!ng(e))return!1;try{return ug(og,[],e),!0}catch(t){return!1}},lg=function(e){if(!ng(e))return!1;switch(_k(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return qk||!!Nk(Dl,Fk(e))}catch(t){return!0}};lg.sham=!0;cg.exports=!ug||Vk(function(){var a;return ga(ga.call)||!ga(Object)||!ga(function(){a=!0})||a})?lg:ga});var pg=S((CF,dg)=>{"use strict";var Uk=Cl(),Hk=aa(),jk=TypeError;dg.exports=function(a){if(Uk(a))return a;throw new jk(Hk(a)+" is not a constructor")}});var Bl=S((BF,fg)=>{"use strict";var hg=mt(),Wk=pg(),Qk=ia(),Gk=ve(),zk=Gk("species");fg.exports=function(a,e){var t=hg(a).constructor,i;return t===void 0||Qk(i=hg(t)[zk])?e:Wk(i)}});var bg=S((VF,mg)=>{"use strict";var Yk=fe();mg.exports=Yk([].slice)});var Sg=S((_F,gg)=>{"use strict";var Kk=TypeError;gg.exports=function(a,e){if(a<e)throw new Kk("Not enough arguments");return a}});var Vl=S((OF,vg)=>{"use strict";var Xk=yi();vg.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(Xk)});var Wl=S((FF,Pg)=>{"use strict";var Ue=ae(),Jk=wu(),Zk=tr(),yg=se(),eL=at(),Rg=he(),Tg=ml(),tL=bg(),Ig=fn(),iL=Sg(),rL=Vl(),aL=Cn(),Ul=Ue.setImmediate,Hl=Ue.clearImmediate,sL=Ue.process,_l=Ue.Dispatch,nL=Ue.Function,Eg=Ue.MessageChannel,oL=Ue.String,Ol=0,Sa={},xg="onreadystatechange",va,wi,Fl,Nl;Rg(function(){va=Ue.location});var jl=function(a){if(eL(Sa,a)){var e=Sa[a];delete Sa[a],e()}},ql=function(a){return function(){jl(a)}},wg=function(a){jl(a.data)},Ag=function(a){Ue.postMessage(oL(a),va.protocol+"//"+va.host)};(!Ul||!Hl)&&(Ul=function(e){iL(arguments.length,1);var t=yg(e)?e:nL(e),i=tL(arguments,1);return Sa[++Ol]=function(){Jk(t,void 0,i)},wi(Ol),Ol},Hl=function(e){delete Sa[e]},aL?wi=function(a){sL.nextTick(ql(a))}:_l&&_l.now?wi=function(a){_l.now(ql(a))}:Eg&&!rL?(Fl=new Eg,Nl=Fl.port2,Fl.port1.onmessage=wg,wi=Zk(Nl.postMessage,Nl)):Ue.addEventListener&&yg(Ue.postMessage)&&!Ue.importScripts&&va&&va.protocol!=="file:"&&!Rg(Ag)?(wi=Ag,Ue.addEventListener("message",wg,!1)):xg in Ig("script")?wi=function(a){Tg.appendChild(Ig("script"))[xg]=function(){Tg.removeChild(this),jl(a)}}:wi=function(a){setTimeout(ql(a),0)});Pg.exports={set:Ul,clear:Hl}});var $g=S((NF,Lg)=>{"use strict";var kg=ae(),uL=Ne(),lL=Object.getOwnPropertyDescriptor;Lg.exports=function(a){if(!uL)return kg[a];var e=lL(kg,a);return e&&e.value}});var Ql=S((qF,Dg)=>{"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}}};Dg.exports=Mg});var Bg=S((UF,Cg)=>{"use strict";var cL=yi();Cg.exports=/ipad|iphone|ipod/i.test(cL)&&typeof Pebble!="undefined"});var _g=S((HF,Vg)=>{"use strict";var dL=yi();Vg.exports=/web0s(?!.*chrome)/i.test(dL)});var jg=S((jF,Hg)=>{"use strict";var lr=ae(),pL=$g(),Og=tr(),Gl=Wl().set,hL=Ql(),fL=Vl(),mL=Bg(),bL=_g(),zl=Cn(),Fg=lr.MutationObserver||lr.WebKitMutationObserver,Ng=lr.document,qg=lr.process,Bn=lr.Promise,Xl=pL("queueMicrotask"),ur,Yl,Kl,Vn,Ug;Xl||(ya=new hL,Ta=function(){var a,e;for(zl&&(a=qg.domain)&&a.exit();e=ya.get();)try{e()}catch(t){throw ya.head&&ur(),t}a&&a.enter()},!fL&&!zl&&!bL&&Fg&&Ng?(Yl=!0,Kl=Ng.createTextNode(""),new Fg(Ta).observe(Kl,{characterData:!0}),ur=function(){Kl.data=Yl=!Yl}):!mL&&Bn&&Bn.resolve?(Vn=Bn.resolve(void 0),Vn.constructor=Bn,Ug=Og(Vn.then,Vn),ur=function(){Ug(Ta)}):zl?ur=function(){qg.nextTick(Ta)}:(Gl=Og(Gl,lr),ur=function(){Gl(Ta)}),Xl=function(a){ya.head||ur(),ya.add(a)});var ya,Ta;Hg.exports=Xl});var Qg=S((WF,Wg)=>{"use strict";Wg.exports=function(a,e){try{arguments.length===1?console.error(a):console.error(a,e)}catch(t){}}});var _n=S((QF,Gg)=>{"use strict";Gg.exports=function(a){try{return{error:!1,value:a()}}catch(e){return{error:!0,value:e}}}});var Ai=S((GF,zg)=>{"use strict";var gL=ae();zg.exports=gL.Promise});var cr=S((zF,Jg)=>{"use strict";var SL=ae(),Ia=Ai(),vL=se(),yL=Gu(),TL=Ml(),IL=ve(),Yg=Ll(),EL=rt(),Jl=Cu(),Kg=Ia&&Ia.prototype,xL=IL("species"),Zl=!1,Xg=vL(SL.PromiseRejectionEvent),wL=yL("Promise",function(){var a=TL(Ia),e=a!==String(Ia);if(!e&&Jl===66||EL&&!(Kg.catch&&Kg.finally))return!0;if(!Jl||Jl<51||!/native code/.test(a)){var t=new Ia(function(s){s(1)}),i=function(s){s(function(){},function(){})},r=t.constructor={};if(r[xL]=i,Zl=t.then(function(){})instanceof i,!Zl)return!0}return!e&&(Yg==="BROWSER"||Yg==="DENO")&&!Xg});Jg.exports={CONSTRUCTOR:wL,REJECTION_EVENT:Xg,SUBCLASSING:Zl}});var dr=S((YF,eS)=>{"use strict";var Zg=ft(),AL=TypeError,RL=function(a){var e,t;this.promise=new a(function(i,r){if(e!==void 0||t!==void 0)throw new AL("Bad Promise constructor");e=i,t=r}),this.resolve=Zg(e),this.reject=Zg(t)};eS.exports.f=function(a){return new RL(a)}});var yS=S(()=>{"use strict";var PL=le(),kL=rt(),qn=Cn(),Gt=ae(),LL=vi(),mr=qe(),tS=or(),iS=xl(),$L=ha(),ML=ig(),DL=ft(),Nn=se(),CL=Me(),BL=ag(),VL=Bl(),oS=Wl().set,ac=jg(),_L=Qg(),OL=_n(),FL=Ql(),uS=dl(),Un=Ai(),sc=cr(),lS=dr(),Hn="Promise",cS=sc.CONSTRUCTOR,NL=sc.REJECTION_EVENT,qL=sc.SUBCLASSING,ec=uS.getterFor(Hn),UL=uS.set,pr=Un&&Un.prototype,Ri=Un,On=pr,dS=Gt.TypeError,tc=Gt.document,nc=Gt.process,ic=lS.f,HL=ic,jL=!!(tc&&tc.createEvent&&Gt.dispatchEvent),pS="unhandledrejection",WL="rejectionhandled",rS=0,hS=1,QL=2,oc=1,fS=2,Fn,aS,mS,sS,bS=function(a){var e;return CL(a)&&Nn(e=a.then)?e:!1},gS=function(a,e){var t=e.value,i=e.state===hS,r=i?a.ok:a.fail,s=a.resolve,n=a.reject,o=a.domain,u,l,c;try{r?(i||(e.rejection===fS&&zL(e),e.rejection=oc),r===!0?u=t:(o&&o.enter(),u=r(t),o&&(o.exit(),c=!0)),u===a.promise?n(new dS("Promise-chain cycle")):(l=bS(u))?mr(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,ac(function(){for(var t=a.reactions,i;i=t.get();)gS(i,a);a.notified=!1,e&&!a.rejection&&GL(a)}))},vS=function(a,e,t){var i,r;jL?(i=tc.createEvent("Event"),i.promise=e,i.reason=t,i.initEvent(a,!1,!0),Gt.dispatchEvent(i)):i={promise:e,reason:t},!NL&&(r=Gt["on"+a])?r(i):a===pS&&_L("Unhandled promise rejection",t)},GL=function(a){mr(oS,Gt,function(){var e=a.facade,t=a.value,i=nS(a),r;if(i&&(r=OL(function(){qn?nc.emit("unhandledRejection",t,e):vS(pS,e,t)}),a.rejection=qn||nS(a)?fS:oc,r.error))throw r.value})},nS=function(a){return a.rejection!==oc&&!a.parent},zL=function(a){mr(oS,Gt,function(){var e=a.facade;qn?nc.emit("rejectionHandled",e):vS(WL,e,a.value)})},hr=function(a,e,t){return function(i){a(e,i,t)}},fr=function(a,e,t){a.done||(a.done=!0,t&&(a=t),a.value=e,a.state=QL,SS(a,!0))},rc=function(a,e,t){if(!a.done){a.done=!0,t&&(a=t);try{if(a.facade===e)throw new dS("Promise can't be resolved itself");var i=bS(e);i?ac(function(){var r={done:!1};try{mr(i,e,hr(rc,r,a),hr(fr,r,a))}catch(s){fr(r,s,a)}}):(a.value=e,a.state=hS,SS(a,!1))}catch(r){fr({done:!1},r,a)}}};if(cS&&(Ri=function(e){BL(this,On),DL(e),mr(Fn,this);var t=ec(this);try{e(hr(rc,t),hr(fr,t))}catch(i){fr(t,i)}},On=Ri.prototype,Fn=function(e){UL(this,{type:Hn,done:!1,notified:!1,parent:!1,reactions:new FL,rejection:!1,state:rS,value:null})},Fn.prototype=tS(On,"then",function(e,t){var i=ec(this),r=ic(VL(this,Ri));return i.parent=!0,r.ok=Nn(e)?e:!0,r.fail=Nn(t)&&t,r.domain=qn?nc.domain:void 0,i.state===rS?i.reactions.add(r):ac(function(){gS(r,i)}),r.promise}),aS=function(){var a=new Fn,e=ec(a);this.promise=a,this.resolve=hr(rc,e),this.reject=hr(fr,e)},lS.f=ic=function(a){return a===Ri||a===mS?new aS(a):HL(a)},!kL&&Nn(Un)&&pr!==Object.prototype)){sS=pr.then,qL||tS(pr,"then",function(e,t){var i=this;return new Ri(function(r,s){mr(sS,i,r,s)}).then(e,t)},{unsafe:!0});try{delete pr.constructor}catch(a){}iS&&iS(pr,On)}PL({global:!0,constructor:!0,wrap:!0,forced:cS},{Promise:Ri});mS=LL.Promise;$L(Ri,Hn,!1,!0);ML(Hn)});var wS=S((JF,xS)=>{"use strict";var YL=ve(),IS=YL("iterator"),ES=!1;try{TS=0,uc={next:function(){return{done:!!TS++}},return:function(){ES=!0}},uc[IS]=function(){return this},Array.from(uc,function(){throw 2})}catch(a){}var TS,uc;xS.exports=function(a,e){try{if(!e&&!ES)return!1}catch(r){return!1}var t=!1;try{var i={};i[IS]=function(){return{next:function(){return{done:t=!0}}}},a(i)}catch(r){}return t}});var lc=S((ZF,AS)=>{"use strict";var KL=Ai(),XL=wS(),JL=cr().CONSTRUCTOR;AS.exports=JL||!XL(function(a){KL.all(a).then(void 0,function(){})})});var RS=S(()=>{"use strict";var ZL=le(),e$=qe(),t$=ft(),i$=dr(),r$=_n(),a$=$n(),s$=lc();ZL({target:"Promise",stat:!0,forced:s$},{all:function(e){var t=this,i=i$.f(t),r=i.resolve,s=i.reject,n=r$(function(){var o=t$(t.resolve),u=[],l=0,c=1;a$(e,function(d){var h=l++,p=!1;c++,e$(o,t,d).then(function(f){p||(p=!0,u[h]=f,--c||r(u))},s)}),--c||r(u)});return n.error&&s(n.value),i.promise}})});var kS=S(()=>{"use strict";var n$=le(),o$=rt(),u$=cr().CONSTRUCTOR,dc=Ai(),l$=Rt(),c$=se(),d$=or(),PS=dc&&dc.prototype;n$({target:"Promise",proto:!0,forced:u$,real:!0},{catch:function(a){return this.then(void 0,a)}});!o$&&c$(dc)&&(cc=l$("Promise").prototype.catch,PS.catch!==cc&&d$(PS,"catch",cc,{unsafe:!0}));var cc});var LS=S(()=>{"use strict";var p$=le(),h$=qe(),f$=ft(),m$=dr(),b$=_n(),g$=$n(),S$=lc();p$({target:"Promise",stat:!0,forced:S$},{race:function(e){var t=this,i=m$.f(t),r=i.reject,s=b$(function(){var n=f$(t.resolve);g$(e,function(o){h$(n,t,o).then(i.resolve,r)})});return s.error&&r(s.value),i.promise}})});var $S=S(()=>{"use strict";var v$=le(),y$=dr(),T$=cr().CONSTRUCTOR;v$({target:"Promise",stat:!0,forced:T$},{reject:function(e){var t=y$.f(this),i=t.reject;return i(e),t.promise}})});var pc=S((uN,MS)=>{"use strict";var I$=mt(),E$=Me(),x$=dr();MS.exports=function(a,e){if(I$(a),E$(e)&&e.constructor===a)return e;var t=x$.f(a),i=t.resolve;return i(e),t.promise}});var BS=S(()=>{"use strict";var w$=le(),A$=Rt(),DS=rt(),R$=Ai(),CS=cr().CONSTRUCTOR,P$=pc(),k$=A$("Promise"),L$=DS&&!CS;w$({target:"Promise",stat:!0,forced:DS||CS},{resolve:function(e){return P$(L$&&this===k$?R$:this,e)}})});var VS=S(()=>{"use strict";yS();RS();kS();LS();$S();BS()});var NS=S(()=>{"use strict";var $$=le(),M$=rt(),jn=Ai(),D$=he(),OS=Rt(),FS=se(),C$=Bl(),_S=pc(),B$=or(),fc=jn&&jn.prototype,V$=!!jn&&D$(function(){fc.finally.call({then:function(){}},function(){})});$$({target:"Promise",proto:!0,real:!0,forced:V$},{finally:function(a){var e=C$(this,OS("Promise")),t=FS(a);return this.then(t?function(i){return _S(e,a()).then(function(){return i})}:a,t?function(i){return _S(e,a()).then(function(){throw i})}:a)}});!M$&&FS(jn)&&(hc=OS("Promise").prototype.finally,fc.finally!==hc&&B$(fc,"finally",hc,{unsafe:!0}));var hc});var US=S((mN,qS)=>{"use strict";Yb();VS();NS();var _$=Qt();qS.exports=_$("Promise","finally")});var jS=S((bN,HS)=>{"use strict";var O$=US();HS.exports=O$});var Wn=S((gN,WS)=>{"use strict";var F$=jS();WS.exports=F$});var yv=S(()=>{"use strict";var TM=le(),IM=Zi(),EM=sr(),xM=la(),wM=ca();TM({target:"Array",proto:!0},{at:function(e){var t=IM(this),i=EM(t),r=xM(e),s=r>=0?r:i+r;return s<0||s>=i?void 0:t[s]}});wM("at")});var Iv=S((uU,Tv)=>{"use strict";yv();var AM=Qt();Tv.exports=AM("Array","at")});var xv=S((lU,Ev)=>{"use strict";var RM=Iv();Ev.exports=RM});var nt=S((cU,wv)=>{"use strict";var PM=xv();wv.exports=PM});var Oc=S((tH,oy)=>{"use strict";var uD=gi();oy.exports=Array.isArray||function(e){return uD(e)==="Array"}});var ly=S((iH,uy)=>{"use strict";var lD=TypeError,cD=9007199254740991;uy.exports=function(a){if(a>cD)throw lD("Maximum allowed index exceeded");return a}});var py=S((rH,dy)=>{"use strict";var dD=Oc(),pD=sr(),hD=ly(),fD=tr(),cy=function(a,e,t,i,r,s,n,o){for(var u=r,l=0,c=n?fD(n,o):!1,d,h;l<i;)l in t&&(d=c?c(t[l],l,e):t[l],s>0&&dD(d)?(h=pD(d),u=cy(a,e,d,h,u,s-1)-1):(hD(u+1),a[u]=d),u++),l++;return u};dy.exports=cy});var by=S((aH,my)=>{"use strict";var hy=Oc(),mD=Cl(),bD=Me(),gD=ve(),SD=gD("species"),fy=Array;my.exports=function(a){var e;return hy(a)&&(e=a.constructor,mD(e)&&(e===fy||hy(e.prototype))?e=void 0:bD(e)&&(e=e[SD],e===null&&(e=void 0))),e===void 0?fy:e}});var Sy=S((sH,gy)=>{"use strict";var vD=by();gy.exports=function(a,e){return new(vD(a))(e===0?0:e)}});var vy=S(()=>{"use strict";var yD=le(),TD=py(),ID=ft(),ED=Zi(),xD=sr(),wD=Sy();yD({target:"Array",proto:!0},{flatMap:function(e){var t=ED(this),i=xD(t),r;return ID(e),r=wD(t,0),r.length=TD(r,t,t,i,0,1,e,arguments.length>1?arguments[1]:void 0),r}})});var yy=S(()=>{"use strict";var AD=ca();AD("flatMap")});var Iy=S((cH,Ty)=>{"use strict";vy();yy();var RD=Qt();Ty.exports=RD("Array","flatMap")});var xy=S((dH,Ey)=>{"use strict";var PD=Iy();Ey.exports=PD});var Oa=S((pH,wy)=>{"use strict";var kD=xy();wy.exports=kD});var Fa=S((hH,Ay)=>{"use strict";var LD=pa(),$D=String;Ay.exports=function(a){if(LD(a)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return $D(a)}});var Fc=S((fH,Ry)=>{"use strict";Ry.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 Ly=S((mH,ky)=>{"use strict";var MD=fe(),DD=Wt(),CD=Fa(),qc=Fc(),Py=MD("".replace),BD=RegExp("^["+qc+"]+"),VD=RegExp("(^|[^"+qc+"])["+qc+"]+$"),Nc=function(a){return function(e){var t=CD(DD(e));return a&1&&(t=Py(t,BD,"")),a&2&&(t=Py(t,VD,"$1")),t}};ky.exports={start:Nc(1),end:Nc(2),trim:Nc(3)}});var Cy=S((bH,Dy)=>{"use strict";var _D=fl().PROPER,OD=he(),$y=Fc(),My="\u200B\x85\u180E";Dy.exports=function(a){return OD(function(){return!!$y[a]()||My[a]()!==My||_D&&$y[a].name!==a})}});var Uc=S((gH,By)=>{"use strict";var FD=Ly().start,ND=Cy();By.exports=ND("trimStart")?function(){return FD(this)}:"".trimStart});var _y=S(()=>{"use strict";var qD=le(),Vy=Uc();qD({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==Vy},{trimLeft:Vy})});var Fy=S(()=>{"use strict";_y();var UD=le(),Oy=Uc();UD({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==Oy},{trimStart:Oy})});var qy=S((IH,Ny)=>{"use strict";Fy();var HD=Qt();Ny.exports=HD("String","trimLeft")});var Hy=S((EH,Uy)=>{"use strict";var jD=qy();Uy.exports=jD});var Wy=S((xH,jy)=>{"use strict";var WD=Hy();jy.exports=WD});var oT=S(()=>{"use strict"});var uT=S(()=>{"use strict"});var cT=S((cQ,lT)=>{"use strict";var mC=Me(),bC=gi(),gC=ve(),SC=gC("match");lT.exports=function(a){var e;return mC(a)&&((e=a[SC])!==void 0?!!e:bC(a)==="RegExp")}});var hT=S((dQ,pT)=>{"use strict";var vC=ae(),yC=he(),dT=vC.RegExp,TC=!yC(function(){var a=!0;try{dT(".","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(dT.prototype,"flags").get.call(e);return o!==i||t!==i});pT.exports={correct:TC}});var mT=S((pQ,fT)=>{"use strict";var IC=mt();fT.exports=function(){var a=IC(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=S((hQ,gT)=>{"use strict";var EC=qe(),xC=at(),wC=ra(),bT=hT(),AC=mT(),RC=RegExp.prototype;gT.exports=bT.correct?function(a){return a.flags}:function(a){return!bT.correct&&wC(RC,a)&&!xC(a,"flags")?EC(AC,a):a.flags}});var yT=S((fQ,vT)=>{"use strict";var Gc=fe(),PC=Zi(),kC=Math.floor,Wc=Gc("".charAt),LC=Gc("".replace),Qc=Gc("".slice),$C=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,MC=/\$([$&'`]|\d{1,2})/g;vT.exports=function(a,e,t,i,r,s){var n=t+a.length,o=i.length,u=MC;return r!==void 0&&(r=PC(r),u=$C),LC(s,u,function(l,c){var d;switch(Wc(c,0)){case"$":return"$";case"&":return a;case"`":return Qc(e,0,t);case"'":return Qc(e,n);case"<":d=r[Qc(c,1,-1)];break;default:var h=+c;if(h===0)return l;if(h>o){var p=kC(h/10);return p===0?l:p<=o?i[p-1]===void 0?Wc(c,1):i[p-1]+Wc(c,1):l}d=i[h-1]}return d===void 0?"":d})}});var ET=S(()=>{"use strict";var DC=le(),CC=qe(),Yc=fe(),TT=Wt(),BC=se(),VC=Me(),_C=cT(),Pr=Fa(),OC=sa(),FC=ST(),NC=yT(),qC=ve(),UC=rt(),HC=qC("replace"),jC=TypeError,zc=Yc("".indexOf),WC=Yc("".replace),IT=Yc("".slice),QC=Math.max;DC({target:"String",proto:!0},{replaceAll:function(e,t){var i=TT(this),r,s,n,o,u,l,c,d,h,p,f=0,m="";if(VC(e)){if(r=_C(e),r&&(s=Pr(TT(FC(e))),!~zc(s,"g")))throw new jC("`.replaceAll` does not allow non-global regexes");if(n=OC(e,HC),n)return CC(n,e,i,t);if(UC&&r)return WC(Pr(i),e,t)}for(o=Pr(i),u=Pr(e),l=BC(t),l||(t=Pr(t)),c=u.length,d=QC(1,c),h=zc(o,u);h!==-1;)p=l?Pr(t(u,h,o)):NC(u,o,h,[],void 0,t),m+=IT(o,f,h)+p,f=h+c,h=h+d>o.length?-1:zc(o,u,h+d);return f<o.length&&(m+=IT(o,f)),m}})});var wT=S((gQ,xT)=>{"use strict";oT();uT();ET();var GC=Qt();xT.exports=GC("String","replaceAll")});var RT=S((SQ,AT)=>{"use strict";var zC=wT();AT.exports=zC});var kT=S((vQ,PT)=>{"use strict";var YC=RT();PT.exports=YC});var $T=S((yQ,LT)=>{"use strict";var KC=la(),XC=Fa(),JC=Wt(),ZC=RangeError;LT.exports=function(e){var t=XC(JC(this)),i="",r=KC(e);if(r<0||r===1/0)throw new ZC("Wrong number of repetitions");for(;r>0;(r>>>=1)&&(t+=t))r&1&&(i+=t);return i}});var VT=S((TQ,BT)=>{"use strict";var CT=fe(),eB=el(),MT=Fa(),tB=$T(),iB=Wt(),rB=CT(tB),aB=CT("".slice),sB=Math.ceil,DT=function(a){return function(e,t,i){var r=MT(iB(e)),s=eB(t),n=r.length,o=i===void 0?" ":MT(i),u,l;return s<=n||o===""?r:(u=s-n,l=rB(o,sB(u/o.length)),l.length>u&&(l=aB(l,0,u)),a?r+l:l+r)}};BT.exports={start:DT(!1),end:DT(!0)}});var OT=S((IQ,_T)=>{"use strict";var nB=yi();_T.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(nB)});var FT=S(()=>{"use strict";var oB=le(),uB=VT().start,lB=OT();oB({target:"String",proto:!0,forced:lB},{padStart:function(e){return uB(this,e,arguments.length>1?arguments[1]:void 0)}})});var qT=S((wQ,NT)=>{"use strict";FT();var cB=Qt();NT.exports=cB("String","padStart")});var HT=S((AQ,UT)=>{"use strict";var dB=qT();UT.exports=dB});var WT=S((RQ,jT)=>{"use strict";var pB=HT();jT.exports=pB});var Qp="2.0.144-dev.3ba5a3c2.0";var $e=(r=>(r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused",r))($e||{}),At=(y=>(y.MPEG="MPEG",y.DASH="DASH",y.DASH_SEP="DASH_SEP",y.DASH_SEP_VK="DASH_SEP",y.DASH_WEBM="DASH_WEBM",y.DASH_WEBM_AV1="DASH_WEBM_AV1",y.DASH_STREAMS="DASH_STREAMS",y.DASH_WEBM_VK="DASH_WEBM",y.DASH_ONDEMAND="DASH_ONDEMAND",y.DASH_ONDEMAND_VK="DASH_ONDEMAND",y.DASH_LIVE="DASH_LIVE",y.DASH_LIVE_CMAF="DASH_LIVE_CMAF",y.DASH_LIVE_WEBM="DASH_LIVE_WEBM",y.HLS="HLS",y.HLS_ONDEMAND="HLS_ONDEMAND",y.HLS_JS="HLS",y.HLS_FMP4="HLS_FMP4",y.HLS_LIVE="HLS_LIVE",y.HLS_LIVE_CMAF="HLS_LIVE_CMAF",y.WEB_RTC_LIVE="WEB_RTC_LIVE",y))(At||{});var cn=(r=>(r.NOT_AVAILABLE="NOT_AVAILABLE",r.AVAILABLE="AVAILABLE",r.CONNECTING="CONNECTING",r.CONNECTED="CONNECTED",r))(cn||{}),Iu=(i=>(i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic",i))(Iu||{});var Eu=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(Eu||{}),dn=(i=>(i.TRAFFIC_SAVING="traffic_saving",i.HIGH_QUALITY="high_quality",i.UNKNOWN="unknown",i))(dn||{});var np=F(Ii(),1),NE=F(De(),1);import{assertNever as fm,assertNonNullable as zA,isNonNullable as vn,ValueSubject as nl,Subject as YA,Subscription as KA,merge as XA,observableFrom as JA,fromEvent as cm,map as dm,tap as pm,filterChanged as ZA,isNullable as ol,ErrorCategory as hm}from"@vkontakte/videoplayer-shared/es2018";var lm=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 yn=class{constructor(e){this.connection$=new nl(void 0);this.castState$=new nl("NOT_AVAILABLE");this.errorEvent$=new YA;this.realCastState$=new nl("NOT_AVAILABLE");this.subscription=new KA;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=vn((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||lm("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:hm.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(){vn(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();ol(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();ol(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(cm(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 fm(r.sessionState)}})).add(XA(cm(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(pm(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),dm(r=>r.castState)),JA([i.getCastState()])).pipe(ZA(),dm(eR),pm(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{var o,u;let s=r==="CONNECTED",n=vn(this.connection$.getValue());if(s&&!n){let l=i.getCurrentSession();zA(l);let c=l.getCastDevice(),d=(u=(o=l.getMediaSession())==null?void 0:o.media)==null?void 0:u.contentId;(ol(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"?vn(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:hm.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:s})}}},eR=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 fm(a)}};var Xd=F(De(),1),TE=F(nr(),1),IE=F(kl(),1);var ov=F(Wn(),1);import{assertNever as QS}from"@vkontakte/videoplayer-shared/es2018";var ne=(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:QS(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:QS(e)}};var $=(a,e,t=!1)=>{let i=a.getTransition();(t||!i||i.to===e)&&a.setState(e)};import{isNonNullable as N$,Subject as Qn,merge as GS}from"@vkontakte/videoplayer-shared/es2018";var U=class{constructor(e){this.transitionStarted$=new Qn;this.transitionEnded$=new Qn;this.transitionUpdated$=new Qn;this.forceChanged$=new Qn;this.stateChangeStarted$=GS(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=GS(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||N$(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 ev}from"@vkontakte/videoplayer-shared/es2018";var Gn=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 zS=F(De(),1);var Ea=()=>{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 zn=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,zS.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=Ea()}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 Yn=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,br=()=>{var a,e;return!!(window.ManagedMediaSource&&((e=(a=window.ManagedSourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},YS=()=>{var a,e;return!!(window.MediaSource&&((e=(a=window.SourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},Kn=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var q$=document.createElement("video"),U$='video/mp4; codecs="avc1.42000a,mp4a.40.2"',H$='video/mp4; codecs="hev1.1.6.L93.B0"',KS='video/webm; codecs="vp09.00.10.08"',XS='video/webm; codecs="av01.0.00M.08"',j$='audio/mp4; codecs="mp4a.40.2"',W$='audio/webm; codecs="opus"',JS,Q$=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:XS}}),window.navigator.mediaCapabilities.decodingInfo({...a,video:{...a.video,contentType:KS}})]);JS={DASH_WEBM_AV1:e,DASH_WEBM:t}};Q$().catch(a=>{console.log(q$),console.error(a)});var Xn=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 JS}get supportedCodecs(){return Object.keys(this._codecs).filter(e=>this._codecs[e])}get nativeHlsSupported(){return this._nativeHlsSupported}detect(){var e,t,i,r,s,n,o,u,l,c,d,h,p,f,m,g,b,v,T,y;this._video=document.createElement("video");try{this._protocols={mms:br(),mse:YS(),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,U$)),A=!!((h=(d=He())==null?void 0:d.isTypeSupported)!=null&&h.call(d,H$)),k=!!((f=(p=He())==null?void 0:p.isTypeSupported)!=null&&f.call(p,j$));this._codecs={h264:E,h265:A,vp9:!!((g=(m=He())==null?void 0:m.isTypeSupported)!=null&&g.call(m,KS)),av1:!!((v=(b=He())==null?void 0:b.isTypeSupported)!=null&&v.call(b,XS)),aac:k,opus:!!((y=(T=He())==null?void 0:T.isTypeSupported)!=null&&y.call(T,W$)),mpeg:(E||A)&&k},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 ZS="audio/mpeg",Jn=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,ZS))},this._codecs={mp3:!!((r=(i=He())==null?void 0:i.isTypeSupported)!=null&&r.call(i,ZS))}}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 G$}from"@vkontakte/videoplayer-shared/es2018";var mc=class{constructor(){this.isInited$=new G$(!1);this._displayChecker=new Yn,this._deviceChecker=new zn(this._displayChecker),this._browserChecker=new Gn,this._videoChecker=new Xn(this._deviceChecker,this._browserChecker),this._audioChecker=new Jn,this.detect()}get display(){return this._displayChecker}get device(){return this._deviceChecker}get browser(){return this._browserChecker}get video(){return this._videoChecker}get audio(){return this._audioChecker}async detect(){this._displayChecker.detect(),this._deviceChecker.detect(),this._browserChecker.detect(),this._videoChecker.detect(),this._audioChecker.detect(),this.isInited$.next(!0)}},_=new mc;var bc=a=>{let{containers:e,protocols:t,codecs:i,nativeHlsSupported:r}=_.video,s=(i.h264||i.h265)&&i.aac,n=t.mse||t.mms;return a.filter(o=>{switch(o){case"DASH_SEP":return n&&e.mp4&&s;case"DASH_WEBM":return n&&e.webm&&i.vp9&&i.opus;case"DASH_WEBM_AV1":return n&&e.webm&&i.av1&&i.opus;case"DASH_STREAMS":return n&&(e.mp4&&s||e.webm&&(i.vp9||i.av1)&&(i.opus||i.aac));case"DASH_LIVE":return n&&e.mp4&&s;case"DASH_LIVE_CMAF":return n&&e.mp4&&s&&e.cmaf;case"DASH_ONDEMAND":return n&&e.mp4&&s;case"HLS":case"HLS_ONDEMAND":case"HLS_FMP4":case"HLS_LIVE":case"HLS_LIVE_CMAF":return r;case"MPEG":return e.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return t.webrtc&&t.ws&&i.h264&&(e.mp4||e.webm);default:return ev(o)}})},gc=a=>{switch(a){case"MPEG":case"DASH":case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":case"HLS":case"HLS_FMP4":case"HLS_ONDEMAND":return!1;case"DASH_LIVE":case"DASH_LIVE_CMAF":case"HLS_LIVE":case"HLS_LIVE_CMAF":case"DASH_LIVE_WEBM":case"WEB_RTC_LIVE":return!0;default:return ev(a)}},z$=a=>{let t=Object.keys(a).filter(i=>!gc(i));return bc(t).length>0};import{assertNever as gr,assertNonNullable as Pi,debounce as tv,ErrorCategory as iv,fromEvent as ki,isNonNullable as rv,map as av,merge as sv,observableFrom as Y$,Subject as K$,Subscription as Sc,timeout as X$,getHighestQuality as J$}from"@vkontakte/videoplayer-shared/es2018";var Z$=5,eM=5,tM=500,nv=7e3,xa=class{constructor(e){this.subscription=new Sc;this.loadMediaTimeoutSubscription=new Sc;this.videoState=new U("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:gr(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:gr(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:gr(e)}break}default:gr(i)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(gc(e.format)),this.params.output.isAudioAvailable$.next(!0),this.handleRemoteVolumeChange({volume:this.params.connection.remotePlayer.volumeLevel,muted:this.params.connection.remotePlayer.isMuted});let t=this.params.connection.session.getMediaSession();t&&this.restoreSession(t),this.subscribe()}destroy(){this.log({message:"[destroy]"}),this.subscription.unsubscribe()}subscribe(){this.subscription.add(this.loadMediaTimeoutSubscription);let e=new Sc;this.subscription.add(e),this.subscription.add(sv(this.videoState.stateChangeStarted$.pipe(av(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe(av(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 K$;e.add(r.pipe(tv(tM)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add(ki(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)>Z$)&&r.next(o),s=o})),e.add(ki(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(ki(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(ki(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t(ki(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<eM&&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:gr(n)}}),t(ki(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t(ki(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});let i=sv(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Y$(["init"])).pipe(tv(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];Pi(c);let d=J$(Object.keys(c));Pi(d);let h=c[d];Pi(h),i=h,r="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_FMP4":case"HLS_ONDEMAND":{let c=t[e];Pi(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];Pi(c),i=c.url,r="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let c=t[e];Pi(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];Pi(c),i=ne(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:iv.VIDEO_PIPELINE,message:c,thrown:d}),d}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return gr(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 rv(o)&&(n.metadata.title=o),rv(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(X$(nv).subscribe(()=>s(`timeout(${nv})`)))});(0,ov.default)(Promise.race([t,i]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},r=>{let s=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${r}`;this.log({message:s}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:iv.VIDEO_PIPELINE,message:s,thrown:r})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var Vc=F(De(),1);import{clearVideoElement as lv}from"@vkontakte/videoplayer-shared/es2018";import{clearVideoElement as iM}from"@vkontakte/videoplayer-shared/es2018";var uv=a=>{try{a.pause(),a.playbackRate=0,iM(a),a.remove()}catch(e){console.error(e)}};import{fromEvent as rM,Subscription as aM}from"@vkontakte/videoplayer-shared/es2018";var vc=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)}},yc=window.WeakMap?new WeakMap:new vc,Tc=window.WeakMap?new WeakMap:new Map,sM=(a,e=20)=>{let t=0;return rM(a,"ratechange").subscribe(i=>{t++,t>=e&&(a.currentTime=a.currentTime,t=0)})},Ce=(a,{audioVideoSyncRate:e,disableYandexPiP:t})=>{let i=a.querySelector("video"),r=!!i;i?lv(i):(i=document.createElement("video"),a.appendChild(i)),yc.set(i,r);let s=new aM;return s.add(sM(i,e)),Tc.set(i,s),i.setAttribute("crossorigin","anonymous"),i.setAttribute("playsinline","playsinline"),t&&i.setAttribute("x-yandex-pip","false"),i.controls=!1,i.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),i},Be=a=>{let e=Tc.get(a);e==null||e.unsubscribe(),Tc.delete(a);let t=yc.get(a);yc.delete(a),t?lv(a):uv(a)};var Ec=F(Ii(),1);import{assertNonNullable as Aa,isNonNullable as gt,isNullable as uM,fromEvent as Sr,merge as cv,observableFrom as dv,filterChanged as pv,map as Ra,Subject as hv,Subscription as lM,ValueSubject as cM,ErrorCategory as dM}from"@vkontakte/videoplayer-shared/es2018";import{isNonNullable as Ic,isNullable as nM,Subscription as oM}from"@vkontakte/videoplayer-shared/es2018";var Zn=(a,e,t,{equal:i=(n,o)=>n===o,changed$:r,onError:s}={})=>{let n=a.getState(),o=e(),u=nM(r),l=new oM;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)=>Zn(e,()=>a.loop,i=>{Ic(i)&&(a.loop=i)},{onError:t}),Ve=(a,e,t,i)=>Zn(e,()=>({muted:a.muted,volume:a.volume}),r=>{Ic(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}),ze=(a,e,t,i)=>Zn(e,()=>a.playbackRate,r=>{Ic(r)&&(a.playbackRate=r)},{changed$:t,onError:i}),wa=Zn;var pM=a=>["__",a.language,a.label].join("|"),hM=(a,e)=>{if(a.id===e)return!0;let[t,i,r]=e.split("|");return a.language===i&&a.label===r},xc=class a{constructor(e){this.available$=new hv;this.current$=new cM(void 0);this.error$=new hv;this.subscription=new lM;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:dM.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(wa(t.internalTextTracks,()=>(0,Ec.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(Ra(s=>s.filter(({type:n})=>n==="internal"))),onError:r})),this.subscription.add(wa(t.externalTextTracks,()=>(0,Ec.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(Ra(s=>s.filter(({type:n})=>n==="external"))),onError:r})),this.subscription.add(wa(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(wa(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){Aa(this.video);let{textTracks:e}=this.video;this.subscription.add(Sr(e,"addtrack").subscribe(()=>{let i=this.current$.getValue();i&&this.select(i)})),this.subscription.add(cv(Sr(e,"addtrack"),Sr(e,"removetrack"),dv(["init"])).pipe(Ra(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),pv((i,r)=>i.length===r.length&&i.every(({id:s},n)=>s===r[n].id))).subscribe(this.available$)),this.subscription.add(cv(Sr(e,"change"),dv(["init"])).pipe(Ra(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),Ra(i=>i&&this.htmlTextTrackToITextTrack(i).id),pv()).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(Sr(e,"addtrack").subscribe(i=>{var s,n;(s=i.track)==null||s.addEventListener("cuechange",t);let r=o=>{var l,c,d,h,p;let u=(c=(l=o.target)==null?void 0:l.cues)!=null?c:null;u&&u.length&&(this.applyCueSettings((h=(d=o.target)==null?void 0:d.cues)!=null?h:null),(p=o.target)==null||p.removeEventListener("cuechange",r))};(n=i.track)==null||n.addEventListener("cuechange",r)})),this.subscription.add(Sr(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){Aa(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:pM(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){Aa(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(uM(e)||!hM(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){Aa(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){Aa(this.video);let t=Array.prototype.find.call(this.video.getElementsByTagName("track"),i=>i.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}},Ye=xc;var Li=class{constructor(){this.pausedTime=0;this.streamOffset=0;this.pauseTimestamp=0}getTotalPausedTime(){return this.pausedTime+this.getCurrentPausedTime()}getCurrentPausedTime(){return this.pauseTimestamp>0?Date.now()-this.pauseTimestamp:0}getStreamOffset(){return this.streamOffset}getTotalOffset(){return this.getTotalPausedTime()+this.streamOffset}pause(){this.pauseTimestamp===0&&(this.pauseTimestamp=Date.now())}resume(){this.pauseTimestamp>0&&(this.pausedTime+=this.getCurrentPausedTime(),this.pauseTimestamp=0)}resetTo(e,t=!1){this.streamOffset=e,this.pauseTimestamp=0,this.pausedTime=0,t&&this.pause()}};var fv=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},wc=a=>{let e=fv(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},mv=a=>{let e=fv(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)};import{fromEvent as we,map as St,merge as eo,filterChanged as gv,isNonNullable as Sv,Subject as mM,filter as Ac,mapTo as Rc,combine as bM,once as gM,shareReplay as Ae,throttle as SM,ErrorCategory as vM,ValueSubject as vv,Subscription as yM}from"@vkontakte/videoplayer-shared/es2018";var fM=3,bv=(a,e,t=fM)=>{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 _e=a=>{let e=R=>we(a,R).pipe(Rc(void 0),Ae(1)),t=new yM,i=()=>t.unsubscribe(),r=eo(we(a,"progress"),we(a,"timeupdate")).pipe(St(()=>bv(a.buffered,a.currentTime)),Ae(1)),s=_.browser.isSafari?bM({play:e("play").pipe(gM()),playing:e("playing")}).pipe(Rc(void 0),Ae(1)):e("playing"),n=we(a,"volumechange").pipe(St(()=>({muted:a.muted,volume:a.volume})),Ae(1)),o=we(a,"ratechange").pipe(St(()=>a.playbackRate),Ae(1)),u=we(a,"error").pipe(Ac(()=>!!(a.error||a.played.length)),St(()=>{var B;let R=a.error;return{id:R?`MediaError#${R.code}`:"HtmlVideoError",category:vM.VIDEO_PIPELINE,message:R?R.message:"Error event from HTML video element",thrown:(B=a.error)!=null?B:void 0}}),Ae(1)),l=we(a,"timeupdate").pipe(St(()=>a.currentTime),Ae(1)),c=["waiting","seeking","seeked","timeupdate"],d=new mM,h=.3,p;t.add(eo(...c.map(R=>we(a,R))).subscribe(R=>{let B=a.currentTime;a.loop&&Sv(p)&&Sv(B)&&p>=a.duration-h&&B<=h&&d.next(p),p=B}));let f=e("pause").pipe(Ac(()=>!a.error&&p!==a.duration),Ae(1)),m=we(a,"enterpictureinpicture").pipe(Ae(1)),g=we(a,"leavepictureinpicture").pipe(Ae(1)),b=new vv(mv(a));t.add(m.subscribe(()=>b.next(!0))),t.add(g.subscribe(()=>b.next(!1)));let v=new vv(wc(a)),T=we(a,"fullscreenchange").pipe(Ae(1));t.add(T.pipe(St(()=>wc(a))).subscribe(v));let y=.1,E=1e3,A=we(a,"timeupdate").pipe(St(R=>a.duration-a.currentTime<y),gv(),Ae(1)),k=eo(A.pipe(Ac(R=>!a.loop&&R)),we(a,"ended")).pipe(SM(E),Rc(void 0),Ae(1)),D=eo(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(R=>we(a,R)),A.pipe(St(R=>({type:R?"ended":"unknown"})))).pipe(St(R=>_.browser.isFirefox&&R.type==="ended"?a.readyState<2:a.readyState<3),gv(),Ae(1));return{playing$:s,pause$:f,canplay$:e("canplay"),ended$:k,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$:we(a,"durationchange").pipe(St(()=>a.duration),Ae(1)),isBuffering$:D,currentBuffer$:r,volumeState$:n,playbackRateState$:o,inPiP$:b,inFullscreen$:v,enterPip$:m,leavePip$:g,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 Pe=F(nt(),1),kc=F(De(),1),Mi=F(nr(),1);import{isNonNullable as X,isNullable as ao,now as Vv,isHigher as so,isHigherOrEqual as $i,isInvariantQuality as no,isLowerOrEqual as yr,videoSizeToQuality as _v,assertNotEmptyArray as oo,assertNonNullable as Ov}from"@vkontakte/videoplayer-shared/es2018";var Pc=!1,Lt={},Av=a=>{Pc=a},Rv=()=>{Lt={}},Pv=a=>{a(Lt)},Pa=(a,e)=>{var t;Pc&&(Lt.meta=(t=Lt.meta)!=null?t:{},Lt.meta[a]=e)},Re=class{constructor(e){this.name=e}next(e){var i,r;if(!Pc)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 kM,isHigherOrEqual as bU,isLower as kv,isLowerOrEqual as gU,isNonNullable as to,isNullable as LM,videoHeightToQuality as io}from"@vkontakte/videoplayer-shared/es2018";function Lv(a,e,t){return!a.max&&a.min===e?"high_quality":!a.min&&a.max===t?"traffic_saving":"unknown"}function vr(a,e,t){return LM(a)||to(a.min)&&to(a.max)&&kv(a.max,a.min)||to(a.min)&&e&&kM(a.min,e)||to(a.max)&&t&&kv(a.max,t)}function $v({limits:a,highestAvailableHeight:e,lowestAvailableHeight:t}){return vr({max:a!=null&&a.max?io(a.max):void 0,min:a!=null&&a.min?io(a.min):void 0},e?io(e):void 0,t?io(t):void 0)}var Fv=new Re("best_bitrate"),uo=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t;var Tr=a=>(e,t)=>a*(Number(e.bitrate)-Number(t.bitrate)),Xt=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=Vv()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},lo='Assertion "ABR Tracks is empty array" failed',ro=new WeakMap,Mv=new WeakMap,Dv=new WeakMap,ka=(a,e,t,i)=>{var u;let r=[...e].sort(Tr(1)),s=[...t].sort(Tr(1)),n=s.filter(l=>X(l.bitrate)&&X(a.bitrate)?a.bitrate/l.bitrate>i:!0),o=(u=(0,Pe.default)(s,Math.round(s.length*r.indexOf(a)/(r.length+1))))!=null?u:(0,Pe.default)(s,-1);return o&&(0,kc.default)(n,o)?o:n.length?(0,Pe.default)(n,-1):(0,Pe.default)(s,0)},La=(a,e,t,i)=>{var u;let r=ro.get(e);r||(r=[...e].sort(Tr(1)),ro.set(e,r));let s=ro.get(t);s||(s=[...t].sort(Tr(1)),ro.set(t,s));let n=Dv.get(a);n||(n=s.filter(l=>X(l.bitrate)&&X(a.bitrate)?a.bitrate/l.bitrate>i:!0),Dv.set(a,n));let o=(u=(0,Pe.default)(s,Math.round(s.length*r.indexOf(a)/(r.length+1))))!=null?u:(0,Pe.default)(s,-1);return o&&(0,kc.default)(n,o)?o:n.length?(0,Pe.default)(n,-1):(0,Pe.default)(s,0)},Cv=a=>"quality"in a,co=(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]&&Vv()-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=Cv(o)?"video":"audio",l=Cv(o)?o.quality:o.bitrate;return e({message:`
|
|
8
|
-
[last ${u} selected] ${
|
|
9
|
-
`}),o}return i==null||i.recordSwitch(t),t}
|
|
6
|
+
var hx=Object.create;var sh=Object.defineProperty;var fx=Object.getOwnPropertyDescriptor;var mx=Object.getOwnPropertyNames;var bx=Object.getPrototypeOf,gx=Object.prototype.hasOwnProperty;var v=(s,e)=>()=>(e||s((e={exports:{}}).exports,e),e.exports);var vx=(s,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of mx(e))!gx.call(s,r)&&r!==t&&sh(s,r,{get:()=>e[r],enumerable:!(i=fx(e,r))||i.enumerable});return s};var O=(s,e,t)=>(t=s!=null?hx(bx(s)):{},vx(e||!s||!s.__esModule?sh(t,"default",{value:s,enumerable:!0}):t,s));var se=v((Bu,nh)=>{"use strict";var ts=function(s){return s&&s.Math===Math&&s};nh.exports=ts(typeof globalThis=="object"&&globalThis)||ts(typeof window=="object"&&window)||ts(typeof self=="object"&&self)||ts(typeof global=="object"&&global)||ts(typeof Bu=="object"&&Bu)||function(){return this}()||Function("return this")()});var he=v((Q_,oh)=>{"use strict";oh.exports=function(s){try{return!!s()}catch(e){return!0}}});var is=v((G_,uh)=>{"use strict";var Sx=he();uh.exports=!Sx(function(){var s=function(){}.bind();return typeof s!="function"||s.hasOwnProperty("prototype")})});var Vu=v((z_,ph)=>{"use strict";var yx=is(),dh=Function.prototype,ch=dh.apply,lh=dh.call;ph.exports=typeof Reflect=="object"&&Reflect.apply||(yx?lh.bind(ch):function(){return lh.apply(ch,arguments)})});var fe=v((Y_,mh)=>{"use strict";var hh=is(),fh=Function.prototype,_u=fh.call,Tx=hh&&fh.bind.bind(_u,_u);mh.exports=hh?Tx:function(s){return function(){return _u.apply(s,arguments)}}});var vi=v((K_,gh)=>{"use strict";var bh=fe(),Ix=bh({}.toString),Ex=bh("".slice);gh.exports=function(s){return Ex(Ix(s),8,-1)}});var Ou=v((X_,vh)=>{"use strict";var xx=vi(),wx=fe();vh.exports=function(s){if(xx(s)==="Function")return wx(s)}});var ae=v((J_,Sh)=>{"use strict";var Fu=typeof document=="object"&&document.all;Sh.exports=typeof Fu=="undefined"&&Fu!==void 0?function(s){return typeof s=="function"||s===Fu}:function(s){return typeof s=="function"}});var Ne=v((Z_,yh)=>{"use strict";var Ax=he();yh.exports=!Ax(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var qe=v((eO,Th)=>{"use strict";var Px=is(),vn=Function.prototype.call;Th.exports=Px?vn.bind(vn):function(){return vn.apply(vn,arguments)}});var Nu=v(xh=>{"use strict";var Ih={}.propertyIsEnumerable,Eh=Object.getOwnPropertyDescriptor,Rx=Eh&&!Ih.call({1:2},1);xh.f=Rx?function(e){var t=Eh(this,e);return!!t&&t.enumerable}:Ih});var rs=v((iO,wh)=>{"use strict";wh.exports=function(s,e){return{enumerable:!(s&1),configurable:!(s&2),writable:!(s&4),value:e}}});var Ph=v((rO,Ah)=>{"use strict";var kx=fe(),$x=he(),Lx=vi(),qu=Object,Mx=kx("".split);Ah.exports=$x(function(){return!qu("z").propertyIsEnumerable(0)})?function(s){return Lx(s)==="String"?Mx(s,""):qu(s)}:qu});var ss=v((sO,Rh)=>{"use strict";Rh.exports=function(s){return s==null}});var Gt=v((aO,kh)=>{"use strict";var Cx=ss(),Dx=TypeError;kh.exports=function(s){if(Cx(s))throw new Dx("Can't call method on "+s);return s}});var Si=v((nO,$h)=>{"use strict";var Bx=Ph(),Vx=Gt();$h.exports=function(s){return Bx(Vx(s))}});var Ce=v((oO,Lh)=>{"use strict";var _x=ae();Lh.exports=function(s){return typeof s=="object"?s!==null:_x(s)}});var yi=v((uO,Mh)=>{"use strict";Mh.exports={}});var Rt=v((cO,Dh)=>{"use strict";var Uu=yi(),ju=se(),Ox=ae(),Ch=function(s){return Ox(s)?s:void 0};Dh.exports=function(s,e){return arguments.length<2?Ch(Uu[s])||Ch(ju[s]):Uu[s]&&Uu[s][e]||ju[s]&&ju[s][e]}});var as=v((lO,Bh)=>{"use strict";var Fx=fe();Bh.exports=Fx({}.isPrototypeOf)});var Ti=v((dO,Oh)=>{"use strict";var Nx=se(),Vh=Nx.navigator,_h=Vh&&Vh.userAgent;Oh.exports=_h?String(_h):""});var Wu=v((pO,Hh)=>{"use strict";var jh=se(),Hu=Ti(),Fh=jh.process,Nh=jh.Deno,qh=Fh&&Fh.versions||Nh&&Nh.version,Uh=qh&&qh.v8,it,Sn;Uh&&(it=Uh.split("."),Sn=it[0]>0&&it[0]<4?1:+(it[0]+it[1]));!Sn&&Hu&&(it=Hu.match(/Edge\/(\d+)/),(!it||it[1]>=74)&&(it=Hu.match(/Chrome\/(\d+)/),it&&(Sn=+it[1])));Hh.exports=Sn});var Qu=v((hO,Qh)=>{"use strict";var Wh=Wu(),qx=he(),Ux=se(),jx=Ux.String;Qh.exports=!!Object.getOwnPropertySymbols&&!qx(function(){var s=Symbol("symbol detection");return!jx(s)||!(Object(s)instanceof Symbol)||!Symbol.sham&&Wh&&Wh<41})});var Gu=v((fO,Gh)=>{"use strict";var Hx=Qu();Gh.exports=Hx&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var zu=v((mO,zh)=>{"use strict";var Wx=Rt(),Qx=ae(),Gx=as(),zx=Gu(),Yx=Object;zh.exports=zx?function(s){return typeof s=="symbol"}:function(s){var e=Wx("Symbol");return Qx(e)&&Gx(e.prototype,Yx(s))}});var ns=v((bO,Yh)=>{"use strict";var Kx=String;Yh.exports=function(s){try{return Kx(s)}catch(e){return"Object"}}});var ft=v((gO,Kh)=>{"use strict";var Xx=ae(),Jx=ns(),Zx=TypeError;Kh.exports=function(s){if(Xx(s))return s;throw new Zx(Jx(s)+" is not a function")}});var os=v((vO,Xh)=>{"use strict";var ew=ft(),tw=ss();Xh.exports=function(s,e){var t=s[e];return tw(t)?void 0:ew(t)}});var Zh=v((SO,Jh)=>{"use strict";var Yu=qe(),Ku=ae(),Xu=Ce(),iw=TypeError;Jh.exports=function(s,e){var t,i;if(e==="string"&&Ku(t=s.toString)&&!Xu(i=Yu(t,s))||Ku(t=s.valueOf)&&!Xu(i=Yu(t,s))||e!=="string"&&Ku(t=s.toString)&&!Xu(i=Yu(t,s)))return i;throw new iw("Can't convert object to primitive value")}});var rt=v((yO,ef)=>{"use strict";ef.exports=!0});var sf=v((TO,rf)=>{"use strict";var tf=se(),rw=Object.defineProperty;rf.exports=function(s,e){try{rw(tf,s,{value:e,configurable:!0,writable:!0})}catch(t){tf[s]=e}return e}});var us=v((IO,of)=>{"use strict";var sw=rt(),aw=se(),nw=sf(),af="__core-js_shared__",nf=of.exports=aw[af]||nw(af,{});(nf.versions||(nf.versions=[])).push({version:"3.43.0",mode:sw?"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 Ju=v((EO,cf)=>{"use strict";var uf=us();cf.exports=function(s,e){return uf[s]||(uf[s]=e||{})}});var er=v((xO,lf)=>{"use strict";var ow=Gt(),uw=Object;lf.exports=function(s){return uw(ow(s))}});var st=v((wO,df)=>{"use strict";var cw=fe(),lw=er(),dw=cw({}.hasOwnProperty);df.exports=Object.hasOwn||function(e,t){return dw(lw(e),t)}});var Zu=v((AO,pf)=>{"use strict";var pw=fe(),hw=0,fw=Math.random(),mw=pw(1.1.toString);pf.exports=function(s){return"Symbol("+(s===void 0?"":s)+")_"+mw(++hw+fw,36)}});var Se=v((PO,ff)=>{"use strict";var bw=se(),gw=Ju(),hf=st(),vw=Zu(),Sw=Qu(),yw=Gu(),tr=bw.Symbol,ec=gw("wks"),Tw=yw?tr.for||tr:tr&&tr.withoutSetter||vw;ff.exports=function(s){return hf(ec,s)||(ec[s]=Sw&&hf(tr,s)?tr[s]:Tw("Symbol."+s)),ec[s]}});var vf=v((RO,gf)=>{"use strict";var Iw=qe(),mf=Ce(),bf=zu(),Ew=os(),xw=Zh(),ww=Se(),Aw=TypeError,Pw=ww("toPrimitive");gf.exports=function(s,e){if(!mf(s)||bf(s))return s;var t=Ew(s,Pw),i;if(t){if(e===void 0&&(e="default"),i=Iw(t,s,e),!mf(i)||bf(i))return i;throw new Aw("Can't convert object to primitive value")}return e===void 0&&(e="number"),xw(s,e)}});var tc=v((kO,Sf)=>{"use strict";var Rw=vf(),kw=zu();Sf.exports=function(s){var e=Rw(s,"string");return kw(e)?e:e+""}});var yn=v(($O,Tf)=>{"use strict";var $w=se(),yf=Ce(),ic=$w.document,Lw=yf(ic)&&yf(ic.createElement);Tf.exports=function(s){return Lw?ic.createElement(s):{}}});var rc=v((LO,If)=>{"use strict";var Mw=Ne(),Cw=he(),Dw=yn();If.exports=!Mw&&!Cw(function(){return Object.defineProperty(Dw("div"),"a",{get:function(){return 7}}).a!==7})});var wf=v(xf=>{"use strict";var Bw=Ne(),Vw=qe(),_w=Nu(),Ow=rs(),Fw=Si(),Nw=tc(),qw=st(),Uw=rc(),Ef=Object.getOwnPropertyDescriptor;xf.f=Bw?Ef:function(e,t){if(e=Fw(e),t=Nw(t),Uw)try{return Ef(e,t)}catch(i){}if(qw(e,t))return Ow(!Vw(_w.f,e,t),e[t])}});var sc=v((CO,Af)=>{"use strict";var jw=he(),Hw=ae(),Ww=/#|\.prototype\./,cs=function(s,e){var t=Gw[Qw(s)];return t===Yw?!0:t===zw?!1:Hw(e)?jw(e):!!e},Qw=cs.normalize=function(s){return String(s).replace(Ww,".").toLowerCase()},Gw=cs.data={},zw=cs.NATIVE="N",Yw=cs.POLYFILL="P";Af.exports=cs});var ir=v((DO,Rf)=>{"use strict";var Pf=Ou(),Kw=ft(),Xw=is(),Jw=Pf(Pf.bind);Rf.exports=function(s,e){return Kw(s),e===void 0?s:Xw?Jw(s,e):function(){return s.apply(e,arguments)}}});var ac=v((BO,kf)=>{"use strict";var Zw=Ne(),eA=he();kf.exports=Zw&&eA(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var mt=v((VO,$f)=>{"use strict";var tA=Ce(),iA=String,rA=TypeError;$f.exports=function(s){if(tA(s))return s;throw new rA(iA(s)+" is not an object")}});var Ii=v(Mf=>{"use strict";var sA=Ne(),aA=rc(),nA=ac(),Tn=mt(),Lf=tc(),oA=TypeError,nc=Object.defineProperty,uA=Object.getOwnPropertyDescriptor,oc="enumerable",uc="configurable",cc="writable";Mf.f=sA?nA?function(e,t,i){if(Tn(e),t=Lf(t),Tn(i),typeof e=="function"&&t==="prototype"&&"value"in i&&cc in i&&!i[cc]){var r=uA(e,t);r&&r[cc]&&(e[t]=i.value,i={configurable:uc in i?i[uc]:r[uc],enumerable:oc in i?i[oc]:r[oc],writable:!1})}return nc(e,t,i)}:nc:function(e,t,i){if(Tn(e),t=Lf(t),Tn(i),aA)try{return nc(e,t,i)}catch(r){}if("get"in i||"set"in i)throw new oA("Accessors not supported");return"value"in i&&(e[t]=i.value),e}});var rr=v((OO,Cf)=>{"use strict";var cA=Ne(),lA=Ii(),dA=rs();Cf.exports=cA?function(s,e,t){return lA.f(s,e,dA(1,t))}:function(s,e,t){return s[e]=t,s}});var ce=v((FO,Bf)=>{"use strict";var ls=se(),pA=Vu(),hA=Ou(),fA=ae(),mA=wf().f,bA=sc(),sr=yi(),gA=ir(),ar=rr(),Df=st();us();var vA=function(s){var e=function(t,i,r){if(this instanceof e){switch(arguments.length){case 0:return new s;case 1:return new s(t);case 2:return new s(t,i)}return new s(t,i,r)}return pA(s,this,arguments)};return e.prototype=s.prototype,e};Bf.exports=function(s,e){var t=s.target,i=s.global,r=s.stat,a=s.proto,n=i?ls:r?ls[t]:ls[t]&&ls[t].prototype,o=i?sr:sr[t]||ar(sr,t,{})[t],u=o.prototype,c,d,l,h,p,f,m,g,b;for(h in e)c=bA(i?h:t+(r?".":"#")+h,s.forced),d=!c&&n&&Df(n,h),f=o[h],d&&(s.dontCallGetSet?(b=mA(n,h),m=b&&b.value):m=n[h]),p=d&&m?m:e[h],!(!c&&!a&&typeof f==typeof p)&&(s.bind&&d?g=gA(p,ls):s.wrap&&d?g=vA(p):a&&fA(p)?g=hA(p):g=p,(s.sham||p&&p.sham||f&&f.sham)&&ar(g,"sham",!0),ar(o,h,g),a&&(l=t+"Prototype",Df(sr,l)||ar(sr,l,{}),ar(sr[l],h,p),s.real&&u&&(c||!u[h])&&ar(u,h,p)))}});var In=v((NO,_f)=>{"use strict";var SA=Ju(),yA=Zu(),Vf=SA("keys");_f.exports=function(s){return Vf[s]||(Vf[s]=yA(s))}});var Ff=v((qO,Of)=>{"use strict";var TA=he();Of.exports=!TA(function(){function s(){}return s.prototype.constructor=null,Object.getPrototypeOf(new s)!==s.prototype})});var En=v((UO,qf)=>{"use strict";var IA=st(),EA=ae(),xA=er(),wA=In(),AA=Ff(),Nf=wA("IE_PROTO"),lc=Object,PA=lc.prototype;qf.exports=AA?lc.getPrototypeOf:function(s){var e=xA(s);if(IA(e,Nf))return e[Nf];var t=e.constructor;return EA(t)&&e instanceof t?t.prototype:e instanceof lc?PA:null}});var jf=v((jO,Uf)=>{"use strict";var RA=Math.ceil,kA=Math.floor;Uf.exports=Math.trunc||function(e){var t=+e;return(t>0?kA:RA)(t)}});var ds=v((HO,Hf)=>{"use strict";var $A=jf();Hf.exports=function(s){var e=+s;return e!==e||e===0?0:$A(e)}});var Qf=v((WO,Wf)=>{"use strict";var LA=ds(),MA=Math.max,CA=Math.min;Wf.exports=function(s,e){var t=LA(s);return t<0?MA(t+e,0):CA(t,e)}});var dc=v((QO,Gf)=>{"use strict";var DA=ds(),BA=Math.min;Gf.exports=function(s){var e=DA(s);return e>0?BA(e,9007199254740991):0}});var nr=v((GO,zf)=>{"use strict";var VA=dc();zf.exports=function(s){return VA(s.length)}});var pc=v((zO,Kf)=>{"use strict";var _A=Si(),OA=Qf(),FA=nr(),Yf=function(s){return function(e,t,i){var r=_A(e),a=FA(r);if(a===0)return!s&&-1;var n=OA(i,a),o;if(s&&t!==t){for(;a>n;)if(o=r[n++],o!==o)return!0}else for(;a>n;n++)if((s||n in r)&&r[n]===t)return s||n||0;return!s&&-1}};Kf.exports={includes:Yf(!0),indexOf:Yf(!1)}});var xn=v((YO,Xf)=>{"use strict";Xf.exports={}});var em=v((KO,Zf)=>{"use strict";var NA=fe(),hc=st(),qA=Si(),UA=pc().indexOf,jA=xn(),Jf=NA([].push);Zf.exports=function(s,e){var t=qA(s),i=0,r=[],a;for(a in t)!hc(jA,a)&&hc(t,a)&&Jf(r,a);for(;e.length>i;)hc(t,a=e[i++])&&(~UA(r,a)||Jf(r,a));return r}});var fc=v((XO,tm)=>{"use strict";tm.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var mc=v((JO,im)=>{"use strict";var HA=em(),WA=fc();im.exports=Object.keys||function(e){return HA(e,WA)}});var bc=v((ZO,om)=>{"use strict";var sm=Ne(),QA=he(),am=fe(),GA=En(),zA=mc(),YA=Si(),KA=Nu().f,nm=am(KA),XA=am([].push),JA=sm&&QA(function(){var s=Object.create(null);return s[2]=2,!nm(s,2)}),rm=function(s){return function(e){for(var t=YA(e),i=zA(t),r=JA&&GA(t)===null,a=i.length,n=0,o=[],u;a>n;)u=i[n++],(!sm||(r?u in t:nm(t,u)))&&XA(o,s?[u,t[u]]:t[u]);return o}};om.exports={entries:rm(!0),values:rm(!1)}});var um=v(()=>{"use strict";var ZA=ce(),eP=bc().values;ZA({target:"Object",stat:!0},{values:function(e){return eP(e)}})});var lm=v((iF,cm)=>{"use strict";um();var tP=yi();cm.exports=tP.Object.values});var pm=v((rF,dm)=>{"use strict";var iP=lm();dm.exports=iP});var Ei=v((sF,hm)=>{"use strict";var rP=pm();hm.exports=rP});var ps=v((aF,fm)=>{"use strict";fm.exports=function(){}});var mm=v(()=>{"use strict";var sP=ce(),aP=pc().includes,nP=he(),oP=ps(),uP=nP(function(){return!Array(1).includes()});sP({target:"Array",proto:!0,forced:uP},{includes:function(e){return aP(this,e,arguments.length>1?arguments[1]:void 0)}});oP("includes")});var zt=v((uF,bm)=>{"use strict";var cP=Rt();bm.exports=cP});var vm=v((cF,gm)=>{"use strict";mm();var lP=zt();gm.exports=lP("Array","includes")});var ym=v((lF,Sm)=>{"use strict";var dP=vm();Sm.exports=dP});var Ae=v((dF,Tm)=>{"use strict";var pP=ym();Tm.exports=pP});var Hm=v(()=>{"use strict";var GP=ce(),zP=bc().entries;GP({target:"Object",stat:!0},{entries:function(e){return zP(e)}})});var Qm=v((eq,Wm)=>{"use strict";Hm();var YP=yi();Wm.exports=YP.Object.entries});var zm=v((tq,Gm)=>{"use strict";var KP=Qm();Gm.exports=KP});var cr=v((iq,Ym)=>{"use strict";var XP=zm();Ym.exports=XP});var wi=v((rq,Km)=>{"use strict";Km.exports={}});var Zm=v((sq,Jm)=>{"use strict";var JP=se(),ZP=ae(),Xm=JP.WeakMap;Jm.exports=ZP(Xm)&&/native code/.test(String(Xm))});var Pc=v((aq,ib)=>{"use strict";var eR=Zm(),tb=se(),tR=Ce(),iR=rr(),xc=st(),wc=us(),rR=In(),sR=xn(),eb="Object already initialized",Ac=tb.TypeError,aR=tb.WeakMap,On,vs,Fn,nR=function(s){return Fn(s)?vs(s):On(s,{})},oR=function(s){return function(e){var t;if(!tR(e)||(t=vs(e)).type!==s)throw new Ac("Incompatible receiver, "+s+" required");return t}};eR||wc.state?(at=wc.state||(wc.state=new aR),at.get=at.get,at.has=at.has,at.set=at.set,On=function(s,e){if(at.has(s))throw new Ac(eb);return e.facade=s,at.set(s,e),e},vs=function(s){return at.get(s)||{}},Fn=function(s){return at.has(s)}):(Ai=rR("state"),sR[Ai]=!0,On=function(s,e){if(xc(s,Ai))throw new Ac(eb);return e.facade=s,iR(s,Ai,e),e},vs=function(s){return xc(s,Ai)?s[Ai]:{}},Fn=function(s){return xc(s,Ai)});var at,Ai;ib.exports={set:On,get:vs,has:Fn,enforce:nR,getterFor:oR}});var $c=v((nq,sb)=>{"use strict";var Rc=Ne(),uR=st(),rb=Function.prototype,cR=Rc&&Object.getOwnPropertyDescriptor,kc=uR(rb,"name"),lR=kc&&function(){}.name==="something",dR=kc&&(!Rc||Rc&&cR(rb,"name").configurable);sb.exports={EXISTS:kc,PROPER:lR,CONFIGURABLE:dR}});var nb=v(ab=>{"use strict";var pR=Ne(),hR=ac(),fR=Ii(),mR=mt(),bR=Si(),gR=mc();ab.f=pR&&!hR?Object.defineProperties:function(e,t){mR(e);for(var i=bR(t),r=gR(t),a=r.length,n=0,o;a>n;)fR.f(e,o=r[n++],i[o]);return e}});var Lc=v((uq,ob)=>{"use strict";var vR=Rt();ob.exports=vR("document","documentElement")});var Bc=v((cq,fb)=>{"use strict";var SR=mt(),yR=nb(),ub=fc(),TR=xn(),IR=Lc(),ER=yn(),xR=In(),cb=">",lb="<",Cc="prototype",Dc="script",pb=xR("IE_PROTO"),Mc=function(){},hb=function(s){return lb+Dc+cb+s+lb+"/"+Dc+cb},db=function(s){s.write(hb("")),s.close();var e=s.parentWindow.Object;return s=null,e},wR=function(){var s=ER("iframe"),e="java"+Dc+":",t;return s.style.display="none",IR.appendChild(s),s.src=String(e),t=s.contentWindow.document,t.open(),t.write(hb("document.F=Object")),t.close(),t.F},Nn,qn=function(){try{Nn=new ActiveXObject("htmlfile")}catch(e){}qn=typeof document!="undefined"?document.domain&&Nn?db(Nn):wR():db(Nn);for(var s=ub.length;s--;)delete qn[Cc][ub[s]];return qn()};TR[pb]=!0;fb.exports=Object.create||function(e,t){var i;return e!==null?(Mc[Cc]=SR(e),i=new Mc,Mc[Cc]=null,i[pb]=e):i=qn(),t===void 0?i:yR.f(i,t)}});var lr=v((lq,mb)=>{"use strict";var AR=rr();mb.exports=function(s,e,t,i){return i&&i.enumerable?s[e]=t:AR(s,e,t),s}});var Fc=v((dq,vb)=>{"use strict";var PR=he(),RR=ae(),kR=Ce(),$R=Bc(),bb=En(),LR=lr(),MR=Se(),CR=rt(),Oc=MR("iterator"),gb=!1,$t,Vc,_c;[].keys&&(_c=[].keys(),"next"in _c?(Vc=bb(bb(_c)),Vc!==Object.prototype&&($t=Vc)):gb=!0);var DR=!kR($t)||PR(function(){var s={};return $t[Oc].call(s)!==s});DR?$t={}:CR&&($t=$R($t));RR($t[Oc])||LR($t,Oc,function(){return this});vb.exports={IteratorPrototype:$t,BUGGY_SAFARI_ITERATORS:gb}});var Un=v((pq,yb)=>{"use strict";var BR=Se(),VR=BR("toStringTag"),Sb={};Sb[VR]="z";yb.exports=String(Sb)==="[object z]"});var Ss=v((hq,Tb)=>{"use strict";var _R=Un(),OR=ae(),jn=vi(),FR=Se(),NR=FR("toStringTag"),qR=Object,UR=jn(function(){return arguments}())==="Arguments",jR=function(s,e){try{return s[e]}catch(t){}};Tb.exports=_R?jn:function(s){var e,t,i;return s===void 0?"Undefined":s===null?"Null":typeof(t=jR(e=qR(s),NR))=="string"?t:UR?jn(e):(i=jn(e))==="Object"&&OR(e.callee)?"Arguments":i}});var Eb=v((fq,Ib)=>{"use strict";var HR=Un(),WR=Ss();Ib.exports=HR?{}.toString:function(){return"[object "+WR(this)+"]"}});var ys=v((mq,wb)=>{"use strict";var QR=Un(),GR=Ii().f,zR=rr(),YR=st(),KR=Eb(),XR=Se(),xb=XR("toStringTag");wb.exports=function(s,e,t,i){var r=t?s:s&&s.prototype;r&&(YR(r,xb)||GR(r,xb,{configurable:!0,value:e}),i&&!QR&&zR(r,"toString",KR))}});var Pb=v((bq,Ab)=>{"use strict";var JR=Fc().IteratorPrototype,ZR=Bc(),ek=rs(),tk=ys(),ik=wi(),rk=function(){return this};Ab.exports=function(s,e,t,i){var r=e+" Iterator";return s.prototype=ZR(JR,{next:ek(+!i,t)}),tk(s,r,!1,!0),ik[r]=rk,s}});var kb=v((gq,Rb)=>{"use strict";var sk=fe(),ak=ft();Rb.exports=function(s,e,t){try{return sk(ak(Object.getOwnPropertyDescriptor(s,e)[t]))}catch(i){}}});var Lb=v((vq,$b)=>{"use strict";var nk=Ce();$b.exports=function(s){return nk(s)||s===null}});var Cb=v((Sq,Mb)=>{"use strict";var ok=Lb(),uk=String,ck=TypeError;Mb.exports=function(s){if(ok(s))return s;throw new ck("Can't set "+uk(s)+" as a prototype")}});var Nc=v((yq,Db)=>{"use strict";var lk=kb(),dk=Ce(),pk=Gt(),hk=Cb();Db.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var s=!1,e={},t;try{t=lk(Object.prototype,"__proto__","set"),t(e,[]),s=e instanceof Array}catch(i){}return function(r,a){return pk(r),hk(a),dk(r)&&(s?t(r,a):r.__proto__=a),r}}():void 0)});var Wb=v((Tq,Hb)=>{"use strict";var fk=ce(),mk=qe(),Hn=rt(),Ub=$c(),bk=ae(),gk=Pb(),Bb=En(),Vb=Nc(),vk=ys(),Sk=rr(),qc=lr(),yk=Se(),_b=wi(),jb=Fc(),Tk=Ub.PROPER,Ik=Ub.CONFIGURABLE,Ob=jb.IteratorPrototype,Wn=jb.BUGGY_SAFARI_ITERATORS,Ts=yk("iterator"),Fb="keys",Is="values",Nb="entries",qb=function(){return this};Hb.exports=function(s,e,t,i,r,a,n){gk(t,e,i);var o=function(b){if(b===r&&h)return h;if(!Wn&&b&&b in d)return d[b];switch(b){case Fb:return function(){return new t(this,b)};case Is:return function(){return new t(this,b)};case Nb:return function(){return new t(this,b)}}return function(){return new t(this)}},u=e+" Iterator",c=!1,d=s.prototype,l=d[Ts]||d["@@iterator"]||r&&d[r],h=!Wn&&l||o(r),p=e==="Array"&&d.entries||l,f,m,g;if(p&&(f=Bb(p.call(new s)),f!==Object.prototype&&f.next&&(!Hn&&Bb(f)!==Ob&&(Vb?Vb(f,Ob):bk(f[Ts])||qc(f,Ts,qb)),vk(f,u,!0,!0),Hn&&(_b[u]=qb))),Tk&&r===Is&&l&&l.name!==Is&&(!Hn&&Ik?Sk(d,"name",Is):(c=!0,h=function(){return mk(l,this)})),r)if(m={values:o(Is),keys:a?h:o(Fb),entries:o(Nb)},n)for(g in m)(Wn||c||!(g in d))&&qc(d,g,m[g]);else fk({target:e,proto:!0,forced:Wn||c},m);return(!Hn||n)&&d[Ts]!==h&&qc(d,Ts,h,{name:r}),_b[e]=h,m}});var Gb=v((Iq,Qb)=>{"use strict";Qb.exports=function(s,e){return{value:s,done:e}}});var jc=v((Eq,Jb)=>{"use strict";var Ek=Si(),Uc=ps(),zb=wi(),Kb=Pc(),xk=Ii().f,wk=Wb(),Qn=Gb(),Ak=rt(),Pk=Ne(),Xb="Array Iterator",Rk=Kb.set,kk=Kb.getterFor(Xb);Jb.exports=wk(Array,"Array",function(s,e){Rk(this,{type:Xb,target:Ek(s),index:0,kind:e})},function(){var s=kk(this),e=s.target,t=s.index++;if(!e||t>=e.length)return s.target=null,Qn(void 0,!0);switch(s.kind){case"keys":return Qn(t,!1);case"values":return Qn(e[t],!1)}return Qn([t,e[t]],!1)},"values");var Yb=zb.Arguments=zb.Array;Uc("keys");Uc("values");Uc("entries");if(!Ak&&Pk&&Yb.name!=="values")try{xk(Yb,"name",{value:"values"})}catch(s){}});var eg=v((xq,Zb)=>{"use strict";var $k=Se(),Lk=wi(),Mk=$k("iterator"),Ck=Array.prototype;Zb.exports=function(s){return s!==void 0&&(Lk.Array===s||Ck[Mk]===s)}});var Hc=v((wq,ig)=>{"use strict";var Dk=Ss(),tg=os(),Bk=ss(),Vk=wi(),_k=Se(),Ok=_k("iterator");ig.exports=function(s){if(!Bk(s))return tg(s,Ok)||tg(s,"@@iterator")||Vk[Dk(s)]}});var sg=v((Aq,rg)=>{"use strict";var Fk=qe(),Nk=ft(),qk=mt(),Uk=ns(),jk=Hc(),Hk=TypeError;rg.exports=function(s,e){var t=arguments.length<2?jk(s):e;if(Nk(t))return qk(Fk(t,s));throw new Hk(Uk(s)+" is not iterable")}});var og=v((Pq,ng)=>{"use strict";var Wk=qe(),ag=mt(),Qk=os();ng.exports=function(s,e,t){var i,r;ag(s);try{if(i=Qk(s,"return"),!i){if(e==="throw")throw t;return t}i=Wk(i,s)}catch(a){r=!0,i=a}if(e==="throw")throw t;if(r)throw i;return ag(i),t}});var zn=v((Rq,dg)=>{"use strict";var Gk=ir(),zk=qe(),Yk=mt(),Kk=ns(),Xk=eg(),Jk=nr(),ug=as(),Zk=sg(),e$=Hc(),cg=og(),t$=TypeError,Gn=function(s,e){this.stopped=s,this.result=e},lg=Gn.prototype;dg.exports=function(s,e,t){var i=t&&t.that,r=!!(t&&t.AS_ENTRIES),a=!!(t&&t.IS_RECORD),n=!!(t&&t.IS_ITERATOR),o=!!(t&&t.INTERRUPTED),u=Gk(e,i),c,d,l,h,p,f,m,g=function(S){return c&&cg(c,"normal"),new Gn(!0,S)},b=function(S){return r?(Yk(S),o?u(S[0],S[1],g):u(S[0],S[1])):o?u(S,g):u(S)};if(a)c=s.iterator;else if(n)c=s;else{if(d=e$(s),!d)throw new t$(Kk(s)+" is not iterable");if(Xk(d)){for(l=0,h=Jk(s);h>l;l++)if(p=b(s[l]),p&&ug(lg,p))return p;return new Gn(!1)}c=Zk(s,d)}for(f=a?s.next:c.next;!(m=zk(f,c)).done;){try{p=b(m.value)}catch(S){cg(c,"throw",S)}if(typeof p=="object"&&p&&ug(lg,p))return p}return new Gn(!1)}});var hg=v((kq,pg)=>{"use strict";var i$=Ne(),r$=Ii(),s$=rs();pg.exports=function(s,e,t){i$?r$.f(s,e,s$(0,t)):s[e]=t}});var fg=v(()=>{"use strict";var a$=ce(),n$=zn(),o$=hg();a$({target:"Object",stat:!0},{fromEntries:function(e){var t={};return n$(e,function(i,r){o$(t,i,r)},{AS_ENTRIES:!0}),t}})});var bg=v((Mq,mg)=>{"use strict";jc();fg();var u$=yi();mg.exports=u$.Object.fromEntries});var vg=v((Cq,gg)=>{"use strict";gg.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 yg=v(()=>{"use strict";jc();var c$=vg(),l$=se(),d$=ys(),Sg=wi();for(Yn in c$)d$(l$[Yn],Yn),Sg[Yn]=Sg.Array;var Yn});var Ig=v((Vq,Tg)=>{"use strict";var p$=bg();yg();Tg.exports=p$});var Wc=v((_q,Eg)=>{"use strict";var h$=Ig();Eg.exports=h$});var xg=v(()=>{"use strict"});var Qc=v((Nq,wg)=>{"use strict";var Es=se(),f$=Ti(),m$=vi(),Kn=function(s){return f$.slice(0,s.length)===s};wg.exports=function(){return Kn("Bun/")?"BUN":Kn("Cloudflare-Workers")?"CLOUDFLARE":Kn("Deno/")?"DENO":Kn("Node.js/")?"NODE":Es.Bun&&typeof Bun.version=="string"?"BUN":Es.Deno&&typeof Deno.version=="object"?"DENO":m$(Es.process)==="process"?"NODE":Es.window&&Es.document?"BROWSER":"REST"}()});var Xn=v((qq,Ag)=>{"use strict";var b$=Qc();Ag.exports=b$==="NODE"});var Rg=v((Uq,Pg)=>{"use strict";var g$=Ii();Pg.exports=function(s,e,t){return g$.f(s,e,t)}});var Lg=v((jq,$g)=>{"use strict";var v$=Rt(),S$=Rg(),y$=Se(),T$=Ne(),kg=y$("species");$g.exports=function(s){var e=v$(s);T$&&e&&!e[kg]&&S$(e,kg,{configurable:!0,get:function(){return this}})}});var Cg=v((Hq,Mg)=>{"use strict";var I$=as(),E$=TypeError;Mg.exports=function(s,e){if(I$(e,s))return s;throw new E$("Incorrect invocation")}});var zc=v((Wq,Dg)=>{"use strict";var x$=fe(),w$=ae(),Gc=us(),A$=x$(Function.toString);w$(Gc.inspectSource)||(Gc.inspectSource=function(s){return A$(s)});Dg.exports=Gc.inspectSource});var Kc=v((Qq,Fg)=>{"use strict";var P$=fe(),R$=he(),Bg=ae(),k$=Ss(),$$=Rt(),L$=zc(),Vg=function(){},_g=$$("Reflect","construct"),Yc=/^\s*(?:class|function)\b/,M$=P$(Yc.exec),C$=!Yc.test(Vg),xs=function(e){if(!Bg(e))return!1;try{return _g(Vg,[],e),!0}catch(t){return!1}},Og=function(e){if(!Bg(e))return!1;switch(k$(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return C$||!!M$(Yc,L$(e))}catch(t){return!0}};Og.sham=!0;Fg.exports=!_g||R$(function(){var s;return xs(xs.call)||!xs(Object)||!xs(function(){s=!0})||s})?Og:xs});var qg=v((Gq,Ng)=>{"use strict";var D$=Kc(),B$=ns(),V$=TypeError;Ng.exports=function(s){if(D$(s))return s;throw new V$(B$(s)+" is not a constructor")}});var Xc=v((zq,jg)=>{"use strict";var Ug=mt(),_$=qg(),O$=ss(),F$=Se(),N$=F$("species");jg.exports=function(s,e){var t=Ug(s).constructor,i;return t===void 0||O$(i=Ug(t)[N$])?e:_$(i)}});var Wg=v((Yq,Hg)=>{"use strict";var q$=fe();Hg.exports=q$([].slice)});var Gg=v((Kq,Qg)=>{"use strict";var U$=TypeError;Qg.exports=function(s,e){if(s<e)throw new U$("Not enough arguments");return s}});var Jc=v((Xq,zg)=>{"use strict";var j$=Ti();zg.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(j$)});var ol=v((Jq,rv)=>{"use strict";var je=se(),H$=Vu(),W$=ir(),Yg=ae(),Q$=st(),iv=he(),Kg=Lc(),G$=Wg(),Xg=yn(),z$=Gg(),Y$=Jc(),K$=Xn(),sl=je.setImmediate,al=je.clearImmediate,X$=je.process,Zc=je.Dispatch,J$=je.Function,Jg=je.MessageChannel,Z$=je.String,el=0,ws={},Zg="onreadystatechange",As,Pi,tl,il;iv(function(){As=je.location});var nl=function(s){if(Q$(ws,s)){var e=ws[s];delete ws[s],e()}},rl=function(s){return function(){nl(s)}},ev=function(s){nl(s.data)},tv=function(s){je.postMessage(Z$(s),As.protocol+"//"+As.host)};(!sl||!al)&&(sl=function(e){z$(arguments.length,1);var t=Yg(e)?e:J$(e),i=G$(arguments,1);return ws[++el]=function(){H$(t,void 0,i)},Pi(el),el},al=function(e){delete ws[e]},K$?Pi=function(s){X$.nextTick(rl(s))}:Zc&&Zc.now?Pi=function(s){Zc.now(rl(s))}:Jg&&!Y$?(tl=new Jg,il=tl.port2,tl.port1.onmessage=ev,Pi=W$(il.postMessage,il)):je.addEventListener&&Yg(je.postMessage)&&!je.importScripts&&As&&As.protocol!=="file:"&&!iv(tv)?(Pi=tv,je.addEventListener("message",ev,!1)):Zg in Xg("script")?Pi=function(s){Kg.appendChild(Xg("script"))[Zg]=function(){Kg.removeChild(this),nl(s)}}:Pi=function(s){setTimeout(rl(s),0)});rv.exports={set:sl,clear:al}});var nv=v((Zq,av)=>{"use strict";var sv=se(),eL=Ne(),tL=Object.getOwnPropertyDescriptor;av.exports=function(s){if(!eL)return sv[s];var e=tL(sv,s);return e&&e.value}});var ul=v((eU,uv)=>{"use strict";var ov=function(){this.head=null,this.tail=null};ov.prototype={add:function(s){var e={item:s,next:null},t=this.tail;t?t.next=e:this.head=e,this.tail=e},get:function(){var s=this.head;if(s){var e=this.head=s.next;return e===null&&(this.tail=null),s.item}}};uv.exports=ov});var lv=v((tU,cv)=>{"use strict";var iL=Ti();cv.exports=/ipad|iphone|ipod/i.test(iL)&&typeof Pebble!="undefined"});var pv=v((iU,dv)=>{"use strict";var rL=Ti();dv.exports=/web0s(?!.*chrome)/i.test(rL)});var Sv=v((rU,vv)=>{"use strict";var pr=se(),sL=nv(),hv=ir(),cl=ol().set,aL=ul(),nL=Jc(),oL=lv(),uL=pv(),ll=Xn(),fv=pr.MutationObserver||pr.WebKitMutationObserver,mv=pr.document,bv=pr.process,Jn=pr.Promise,hl=sL("queueMicrotask"),dr,dl,pl,Zn,gv;hl||(Ps=new aL,Rs=function(){var s,e;for(ll&&(s=bv.domain)&&s.exit();e=Ps.get();)try{e()}catch(t){throw Ps.head&&dr(),t}s&&s.enter()},!nL&&!ll&&!uL&&fv&&mv?(dl=!0,pl=mv.createTextNode(""),new fv(Rs).observe(pl,{characterData:!0}),dr=function(){pl.data=dl=!dl}):!oL&&Jn&&Jn.resolve?(Zn=Jn.resolve(void 0),Zn.constructor=Jn,gv=hv(Zn.then,Zn),dr=function(){gv(Rs)}):ll?dr=function(){bv.nextTick(Rs)}:(cl=hv(cl,pr),dr=function(){cl(Rs)}),hl=function(s){Ps.head||dr(),Ps.add(s)});var Ps,Rs;vv.exports=hl});var Tv=v((sU,yv)=>{"use strict";yv.exports=function(s,e){try{arguments.length===1?console.error(s):console.error(s,e)}catch(t){}}});var eo=v((aU,Iv)=>{"use strict";Iv.exports=function(s){try{return{error:!1,value:s()}}catch(e){return{error:!0,value:e}}}});var Ri=v((nU,Ev)=>{"use strict";var cL=se();Ev.exports=cL.Promise});var hr=v((oU,Pv)=>{"use strict";var lL=se(),ks=Ri(),dL=ae(),pL=sc(),hL=zc(),fL=Se(),xv=Qc(),mL=rt(),fl=Wu(),wv=ks&&ks.prototype,bL=fL("species"),ml=!1,Av=dL(lL.PromiseRejectionEvent),gL=pL("Promise",function(){var s=hL(ks),e=s!==String(ks);if(!e&&fl===66||mL&&!(wv.catch&&wv.finally))return!0;if(!fl||fl<51||!/native code/.test(s)){var t=new ks(function(a){a(1)}),i=function(a){a(function(){},function(){})},r=t.constructor={};if(r[bL]=i,ml=t.then(function(){})instanceof i,!ml)return!0}return!e&&(xv==="BROWSER"||xv==="DENO")&&!Av});Pv.exports={CONSTRUCTOR:gL,REJECTION_EVENT:Av,SUBCLASSING:ml}});var fr=v((uU,kv)=>{"use strict";var Rv=ft(),vL=TypeError,SL=function(s){var e,t;this.promise=new s(function(i,r){if(e!==void 0||t!==void 0)throw new vL("Bad Promise constructor");e=i,t=r}),this.resolve=Rv(e),this.reject=Rv(t)};kv.exports.f=function(s){return new SL(s)}});var Yv=v(()=>{"use strict";var yL=ce(),TL=rt(),so=Xn(),Kt=se(),IL=yi(),vr=qe(),$v=lr(),Lv=Nc(),EL=ys(),xL=Lg(),wL=ft(),ro=ae(),AL=Ce(),PL=Cg(),RL=Xc(),Vv=ol().set,yl=Sv(),kL=Tv(),$L=eo(),LL=ul(),_v=Pc(),ao=Ri(),Tl=hr(),Ov=fr(),no="Promise",Fv=Tl.CONSTRUCTOR,ML=Tl.REJECTION_EVENT,CL=Tl.SUBCLASSING,bl=_v.getterFor(no),DL=_v.set,mr=ao&&ao.prototype,ki=ao,to=mr,Nv=Kt.TypeError,gl=Kt.document,Il=Kt.process,vl=Ov.f,BL=vl,VL=!!(gl&&gl.createEvent&&Kt.dispatchEvent),qv="unhandledrejection",_L="rejectionhandled",Mv=0,Uv=1,OL=2,El=1,jv=2,io,Cv,Hv,Dv,Wv=function(s){var e;return AL(s)&&ro(e=s.then)?e:!1},Qv=function(s,e){var t=e.value,i=e.state===Uv,r=i?s.ok:s.fail,a=s.resolve,n=s.reject,o=s.domain,u,c,d;try{r?(i||(e.rejection===jv&&NL(e),e.rejection=El),r===!0?u=t:(o&&o.enter(),u=r(t),o&&(o.exit(),d=!0)),u===s.promise?n(new Nv("Promise-chain cycle")):(c=Wv(u))?vr(c,u,a,n):a(u)):n(t)}catch(l){o&&!d&&o.exit(),n(l)}},Gv=function(s,e){s.notified||(s.notified=!0,yl(function(){for(var t=s.reactions,i;i=t.get();)Qv(i,s);s.notified=!1,e&&!s.rejection&&FL(s)}))},zv=function(s,e,t){var i,r;VL?(i=gl.createEvent("Event"),i.promise=e,i.reason=t,i.initEvent(s,!1,!0),Kt.dispatchEvent(i)):i={promise:e,reason:t},!ML&&(r=Kt["on"+s])?r(i):s===qv&&kL("Unhandled promise rejection",t)},FL=function(s){vr(Vv,Kt,function(){var e=s.facade,t=s.value,i=Bv(s),r;if(i&&(r=$L(function(){so?Il.emit("unhandledRejection",t,e):zv(qv,e,t)}),s.rejection=so||Bv(s)?jv:El,r.error))throw r.value})},Bv=function(s){return s.rejection!==El&&!s.parent},NL=function(s){vr(Vv,Kt,function(){var e=s.facade;so?Il.emit("rejectionHandled",e):zv(_L,e,s.value)})},br=function(s,e,t){return function(i){s(e,i,t)}},gr=function(s,e,t){s.done||(s.done=!0,t&&(s=t),s.value=e,s.state=OL,Gv(s,!0))},Sl=function(s,e,t){if(!s.done){s.done=!0,t&&(s=t);try{if(s.facade===e)throw new Nv("Promise can't be resolved itself");var i=Wv(e);i?yl(function(){var r={done:!1};try{vr(i,e,br(Sl,r,s),br(gr,r,s))}catch(a){gr(r,a,s)}}):(s.value=e,s.state=Uv,Gv(s,!1))}catch(r){gr({done:!1},r,s)}}};if(Fv&&(ki=function(e){PL(this,to),wL(e),vr(io,this);var t=bl(this);try{e(br(Sl,t),br(gr,t))}catch(i){gr(t,i)}},to=ki.prototype,io=function(e){DL(this,{type:no,done:!1,notified:!1,parent:!1,reactions:new LL,rejection:!1,state:Mv,value:null})},io.prototype=$v(to,"then",function(e,t){var i=bl(this),r=vl(RL(this,ki));return i.parent=!0,r.ok=ro(e)?e:!0,r.fail=ro(t)&&t,r.domain=so?Il.domain:void 0,i.state===Mv?i.reactions.add(r):yl(function(){Qv(r,i)}),r.promise}),Cv=function(){var s=new io,e=bl(s);this.promise=s,this.resolve=br(Sl,e),this.reject=br(gr,e)},Ov.f=vl=function(s){return s===ki||s===Hv?new Cv(s):BL(s)},!TL&&ro(ao)&&mr!==Object.prototype)){Dv=mr.then,CL||$v(mr,"then",function(e,t){var i=this;return new ki(function(r,a){vr(Dv,i,r,a)}).then(e,t)},{unsafe:!0});try{delete mr.constructor}catch(s){}Lv&&Lv(mr,to)}yL({global:!0,constructor:!0,wrap:!0,forced:Fv},{Promise:ki});Hv=IL.Promise;EL(ki,no,!1,!0);xL(no)});var eS=v((dU,Zv)=>{"use strict";var qL=Se(),Xv=qL("iterator"),Jv=!1;try{Kv=0,xl={next:function(){return{done:!!Kv++}},return:function(){Jv=!0}},xl[Xv]=function(){return this},Array.from(xl,function(){throw 2})}catch(s){}var Kv,xl;Zv.exports=function(s,e){try{if(!e&&!Jv)return!1}catch(r){return!1}var t=!1;try{var i={};i[Xv]=function(){return{next:function(){return{done:t=!0}}}},s(i)}catch(r){}return t}});var wl=v((pU,tS)=>{"use strict";var UL=Ri(),jL=eS(),HL=hr().CONSTRUCTOR;tS.exports=HL||!jL(function(s){UL.all(s).then(void 0,function(){})})});var iS=v(()=>{"use strict";var WL=ce(),QL=qe(),GL=ft(),zL=fr(),YL=eo(),KL=zn(),XL=wl();WL({target:"Promise",stat:!0,forced:XL},{all:function(e){var t=this,i=zL.f(t),r=i.resolve,a=i.reject,n=YL(function(){var o=GL(t.resolve),u=[],c=0,d=1;KL(e,function(l){var h=c++,p=!1;d++,QL(o,t,l).then(function(f){p||(p=!0,u[h]=f,--d||r(u))},a)}),--d||r(u)});return n.error&&a(n.value),i.promise}})});var sS=v(()=>{"use strict";var JL=ce(),ZL=rt(),eM=hr().CONSTRUCTOR,Pl=Ri(),tM=Rt(),iM=ae(),rM=lr(),rS=Pl&&Pl.prototype;JL({target:"Promise",proto:!0,forced:eM,real:!0},{catch:function(s){return this.then(void 0,s)}});!ZL&&iM(Pl)&&(Al=tM("Promise").prototype.catch,rS.catch!==Al&&rM(rS,"catch",Al,{unsafe:!0}));var Al});var aS=v(()=>{"use strict";var sM=ce(),aM=qe(),nM=ft(),oM=fr(),uM=eo(),cM=zn(),lM=wl();sM({target:"Promise",stat:!0,forced:lM},{race:function(e){var t=this,i=oM.f(t),r=i.reject,a=uM(function(){var n=nM(t.resolve);cM(e,function(o){aM(n,t,o).then(i.resolve,r)})});return a.error&&r(a.value),i.promise}})});var nS=v(()=>{"use strict";var dM=ce(),pM=fr(),hM=hr().CONSTRUCTOR;dM({target:"Promise",stat:!0,forced:hM},{reject:function(e){var t=pM.f(this),i=t.reject;return i(e),t.promise}})});var Rl=v((TU,oS)=>{"use strict";var fM=mt(),mM=Ce(),bM=fr();oS.exports=function(s,e){if(fM(s),mM(e)&&e.constructor===s)return e;var t=bM.f(s),i=t.resolve;return i(e),t.promise}});var lS=v(()=>{"use strict";var gM=ce(),vM=Rt(),uS=rt(),SM=Ri(),cS=hr().CONSTRUCTOR,yM=Rl(),TM=vM("Promise"),IM=uS&&!cS;gM({target:"Promise",stat:!0,forced:uS||cS},{resolve:function(e){return yM(IM&&this===TM?SM:this,e)}})});var dS=v(()=>{"use strict";Yv();iS();sS();aS();nS();lS()});var mS=v(()=>{"use strict";var EM=ce(),xM=rt(),oo=Ri(),wM=he(),hS=Rt(),fS=ae(),AM=Xc(),pS=Rl(),PM=lr(),$l=oo&&oo.prototype,RM=!!oo&&wM(function(){$l.finally.call({then:function(){}},function(){})});EM({target:"Promise",proto:!0,real:!0,forced:RM},{finally:function(s){var e=AM(this,hS("Promise")),t=fS(s);return this.then(t?function(i){return pS(e,s()).then(function(){return i})}:s,t?function(i){return pS(e,s()).then(function(){throw i})}:s)}});!xM&&fS(oo)&&(kl=hS("Promise").prototype.finally,$l.finally!==kl&&PM($l,"finally",kl,{unsafe:!0}));var kl});var gS=v((RU,bS)=>{"use strict";xg();dS();mS();var kM=zt();bS.exports=kM("Promise","finally")});var SS=v((kU,vS)=>{"use strict";var $M=gS();vS.exports=$M});var uo=v(($U,yS)=>{"use strict";var LM=SS();yS.exports=LM});var FS=v(()=>{"use strict";var aC=ce(),nC=er(),oC=nr(),uC=ds(),cC=ps();aC({target:"Array",proto:!0},{at:function(e){var t=nC(this),i=oC(t),r=uC(e),a=r>=0?r:i+r;return a<0||a>=i?void 0:t[a]}});cC("at")});var qS=v((L1,NS)=>{"use strict";FS();var lC=zt();NS.exports=lC("Array","at")});var jS=v((M1,US)=>{"use strict";var dC=qS();US.exports=dC});var nt=v((C1,HS)=>{"use strict";var pC=jS();HS.exports=pC});var Xl=v((xH,Ay)=>{"use strict";var QC=vi();Ay.exports=Array.isArray||function(e){return QC(e)==="Array"}});var Ry=v((wH,Py)=>{"use strict";var GC=TypeError,zC=9007199254740991;Py.exports=function(s){if(s>zC)throw GC("Maximum allowed index exceeded");return s}});var Ly=v((AH,$y)=>{"use strict";var YC=Xl(),KC=nr(),XC=Ry(),JC=ir(),ky=function(s,e,t,i,r,a,n,o){for(var u=r,c=0,d=n?JC(n,o):!1,l,h;c<i;)c in t&&(l=d?d(t[c],c,e):t[c],a>0&&YC(l)?(h=KC(l),u=ky(s,e,l,h,u,a-1)-1):(XC(u+1),s[u]=l),u++),c++;return u};$y.exports=ky});var By=v((PH,Dy)=>{"use strict";var My=Xl(),ZC=Kc(),eD=Ce(),tD=Se(),iD=tD("species"),Cy=Array;Dy.exports=function(s){var e;return My(s)&&(e=s.constructor,ZC(e)&&(e===Cy||My(e.prototype))?e=void 0:eD(e)&&(e=e[iD],e===null&&(e=void 0))),e===void 0?Cy:e}});var _y=v((RH,Vy)=>{"use strict";var rD=By();Vy.exports=function(s,e){return new(rD(s))(e===0?0:e)}});var Oy=v(()=>{"use strict";var sD=ce(),aD=Ly(),nD=ft(),oD=er(),uD=nr(),cD=_y();sD({target:"Array",proto:!0},{flatMap:function(e){var t=oD(this),i=uD(t),r;return nD(e),r=cD(t,0),r.length=aD(r,t,t,i,0,1,e,arguments.length>1?arguments[1]:void 0),r}})});var Fy=v(()=>{"use strict";var lD=ps();lD("flatMap")});var qy=v((CH,Ny)=>{"use strict";Oy();Fy();var dD=zt();Ny.exports=dD("Array","flatMap")});var jy=v((DH,Uy)=>{"use strict";var pD=qy();Uy.exports=pD});var Ws=v((BH,Hy)=>{"use strict";var hD=jy();Hy.exports=hD});var Qs=v((VH,Wy)=>{"use strict";var fD=Ss(),mD=String;Wy.exports=function(s){if(fD(s)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return mD(s)}});var Jl=v((_H,Qy)=>{"use strict";Qy.exports=`
|
|
7
|
+
\v\f\r \xA0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF`});var Yy=v((OH,zy)=>{"use strict";var bD=fe(),gD=Gt(),vD=Qs(),ed=Jl(),Gy=bD("".replace),SD=RegExp("^["+ed+"]+"),yD=RegExp("(^|[^"+ed+"])["+ed+"]+$"),Zl=function(s){return function(e){var t=vD(gD(e));return s&1&&(t=Gy(t,SD,"")),s&2&&(t=Gy(t,yD,"$1")),t}};zy.exports={start:Zl(1),end:Zl(2),trim:Zl(3)}});var Zy=v((FH,Jy)=>{"use strict";var TD=$c().PROPER,ID=he(),Ky=Jl(),Xy="\u200B\x85\u180E";Jy.exports=function(s){return ID(function(){return!!Ky[s]()||Xy[s]()!==Xy||TD&&Ky[s].name!==s})}});var td=v((NH,eT)=>{"use strict";var ED=Yy().start,xD=Zy();eT.exports=xD("trimStart")?function(){return ED(this)}:"".trimStart});var iT=v(()=>{"use strict";var wD=ce(),tT=td();wD({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==tT},{trimLeft:tT})});var sT=v(()=>{"use strict";iT();var AD=ce(),rT=td();AD({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==rT},{trimStart:rT})});var nT=v((WH,aT)=>{"use strict";sT();var PD=zt();aT.exports=PD("String","trimLeft")});var uT=v((QH,oT)=>{"use strict";var RD=nT();oT.exports=RD});var lT=v((GH,cT)=>{"use strict";var kD=uT();cT.exports=kD});var AT=v(()=>{"use strict"});var PT=v(()=>{"use strict"});var kT=v((CG,RT)=>{"use strict";var ZD=Ce(),eB=vi(),tB=Se(),iB=tB("match");RT.exports=function(s){var e;return ZD(s)&&((e=s[iB])!==void 0?!!e:eB(s)==="RegExp")}});var MT=v((DG,LT)=>{"use strict";var rB=se(),sB=he(),$T=rB.RegExp,aB=!sB(function(){var s=!0;try{$T(".","d")}catch(u){s=!1}var e={},t="",i=s?"dgimsy":"gimsy",r=function(u,c){Object.defineProperty(e,u,{get:function(){return t+=c,!0}})},a={dotAll:"s",global:"g",ignoreCase:"i",multiline:"m",sticky:"y"};s&&(a.hasIndices="d");for(var n in a)r(n,a[n]);var o=Object.getOwnPropertyDescriptor($T.prototype,"flags").get.call(e);return o!==i||t!==i});LT.exports={correct:aB}});var DT=v((BG,CT)=>{"use strict";var nB=mt();CT.exports=function(){var s=nB(this),e="";return s.hasIndices&&(e+="d"),s.global&&(e+="g"),s.ignoreCase&&(e+="i"),s.multiline&&(e+="m"),s.dotAll&&(e+="s"),s.unicode&&(e+="u"),s.unicodeSets&&(e+="v"),s.sticky&&(e+="y"),e}});var _T=v((VG,VT)=>{"use strict";var oB=qe(),uB=st(),cB=as(),BT=MT(),lB=DT(),dB=RegExp.prototype;VT.exports=BT.correct?function(s){return s.flags}:function(s){return!BT.correct&&cB(dB,s)&&!uB(s,"flags")?oB(lB,s):s.flags}});var FT=v((_G,OT)=>{"use strict";var nd=fe(),pB=er(),hB=Math.floor,sd=nd("".charAt),fB=nd("".replace),ad=nd("".slice),mB=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,bB=/\$([$&'`]|\d{1,2})/g;OT.exports=function(s,e,t,i,r,a){var n=t+s.length,o=i.length,u=bB;return r!==void 0&&(r=pB(r),u=mB),fB(a,u,function(c,d){var l;switch(sd(d,0)){case"$":return"$";case"&":return s;case"`":return ad(e,0,t);case"'":return ad(e,n);case"<":l=r[ad(d,1,-1)];break;default:var h=+d;if(h===0)return c;if(h>o){var p=hB(h/10);return p===0?c:p<=o?i[p-1]===void 0?sd(d,1):i[p-1]+sd(d,1):c}l=i[h-1]}return l===void 0?"":l})}});var UT=v(()=>{"use strict";var gB=ce(),vB=qe(),ud=fe(),NT=Gt(),SB=ae(),yB=Ce(),TB=kT(),kr=Qs(),IB=os(),EB=_T(),xB=FT(),wB=Se(),AB=rt(),PB=wB("replace"),RB=TypeError,od=ud("".indexOf),kB=ud("".replace),qT=ud("".slice),$B=Math.max;gB({target:"String",proto:!0},{replaceAll:function(e,t){var i=NT(this),r,a,n,o,u,c,d,l,h,p,f=0,m="";if(yB(e)){if(r=TB(e),r&&(a=kr(NT(EB(e))),!~od(a,"g")))throw new RB("`.replaceAll` does not allow non-global regexes");if(n=IB(e,PB),n)return vB(n,e,i,t);if(AB&&r)return kB(kr(i),e,t)}for(o=kr(i),u=kr(e),c=SB(t),c||(t=kr(t)),d=u.length,l=$B(1,d),h=od(o,u);h!==-1;)p=c?kr(t(u,h,o)):xB(u,o,h,[],void 0,t),m+=qT(o,f,h)+p,f=h+d,h=h+l>o.length?-1:od(o,u,h+l);return f<o.length&&(m+=qT(o,f)),m}})});var HT=v((NG,jT)=>{"use strict";AT();PT();UT();var LB=zt();jT.exports=LB("String","replaceAll")});var QT=v((qG,WT)=>{"use strict";var MB=HT();WT.exports=MB});var zT=v((UG,GT)=>{"use strict";var CB=QT();GT.exports=CB});var KT=v((jG,YT)=>{"use strict";var DB=ds(),BB=Qs(),VB=Gt(),_B=RangeError;YT.exports=function(e){var t=BB(VB(this)),i="",r=DB(e);if(r<0||r===1/0)throw new _B("Wrong number of repetitions");for(;r>0;(r>>>=1)&&(t+=t))r&1&&(i+=t);return i}});var tI=v((HG,eI)=>{"use strict";var ZT=fe(),OB=dc(),XT=Qs(),FB=KT(),NB=Gt(),qB=ZT(FB),UB=ZT("".slice),jB=Math.ceil,JT=function(s){return function(e,t,i){var r=XT(NB(e)),a=OB(t),n=r.length,o=i===void 0?" ":XT(i),u,c;return a<=n||o===""?r:(u=a-n,c=qB(o,jB(u/o.length)),c.length>u&&(c=UB(c,0,u)),s?r+c:c+r)}};eI.exports={start:JT(!1),end:JT(!0)}});var rI=v((WG,iI)=>{"use strict";var HB=Ti();iI.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(HB)});var sI=v(()=>{"use strict";var WB=ce(),QB=tI().start,GB=rI();WB({target:"String",proto:!0,forced:GB},{padStart:function(e){return QB(this,e,arguments.length>1?arguments[1]:void 0)}})});var nI=v((zG,aI)=>{"use strict";sI();var zB=zt();aI.exports=zB("String","padStart")});var uI=v((YG,oI)=>{"use strict";var YB=nI();oI.exports=YB});var lI=v((KG,cI)=>{"use strict";var KB=uI();cI.exports=KB});var ah="2.0.145-dev.9523ea02.0";var we=(r=>(r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused",r))(we||{}),Pt=(y=>(y.MPEG="MPEG",y.DASH="DASH",y.DASH_SEP="DASH_SEP",y.DASH_SEP_VK="DASH_SEP",y.DASH_WEBM="DASH_WEBM",y.DASH_WEBM_AV1="DASH_WEBM_AV1",y.DASH_STREAMS="DASH_STREAMS",y.DASH_WEBM_VK="DASH_WEBM",y.DASH_ONDEMAND="DASH_ONDEMAND",y.DASH_ONDEMAND_VK="DASH_ONDEMAND",y.DASH_LIVE="DASH_LIVE",y.DASH_LIVE_CMAF="DASH_LIVE_CMAF",y.DASH_LIVE_WEBM="DASH_LIVE_WEBM",y.HLS="HLS",y.HLS_ONDEMAND="HLS_ONDEMAND",y.HLS_JS="HLS",y.HLS_FMP4="HLS_FMP4",y.HLS_LIVE="HLS_LIVE",y.HLS_LIVE_CMAF="HLS_LIVE_CMAF",y.WEB_RTC_LIVE="WEB_RTC_LIVE",y))(Pt||{});var es=(r=>(r.NOT_AVAILABLE="NOT_AVAILABLE",r.AVAILABLE="AVAILABLE",r.CONNECTING="CONNECTING",r.CONNECTED="CONNECTED",r))(es||{}),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||{}),gn=(i=>(i.TRAFFIC_SAVING="traffic_saving",i.HIGH_QUALITY="high_quality",i.UNKNOWN="unknown",i))(gn||{});var Sp=O(Ei(),1),ax=O(Ae(),1);import{assertNever as Pm,assertNonNullable as hP,isNonNullable as wn,ValueSubject as gc,Subject as fP,Subscription as mP,merge as bP,observableFrom as gP,fromEvent as Em,map as xm,tap as wm,filterChanged as vP,isNullable as vc,ErrorCategory as Am}from"@vkontakte/videoplayer-shared/es2018";var Im=s=>new Promise((e,t)=>{let i=document.createElement("script");i.setAttribute("src",s),i.onload=()=>e(),i.onerror=r=>t(r),document.body.appendChild(i)});var An=class{constructor(e){this.connection$=new gc(void 0);this.castState$=new gc("NOT_AVAILABLE");this.errorEvent$=new fP;this.realCastState$=new gc("NOT_AVAILABLE");this.subscription=new mP;this.isDestroyed=!1;var a;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");let t="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${t}`}),e.isDisabled||!t)return;let i=wn((a=window.chrome)==null?void 0:a.cast),r=!!window.__onGCastApiAvailable;i?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&!this.isDestroyed&&this.initializeCastApi()},r||Im("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:Am.NETWORK,message:"Script loading failed!"})))}connect(){var e;(e=cast.framework.CastContext.getInstance())==null||e.requestSession()}disconnect(){var e,t;(t=(e=cast.framework.CastContext.getInstance())==null?void 0:e.getCurrentSession())==null||t.endSession(!0)}stopMedia(){return new Promise((e,t)=>{var i,r,a;(a=(r=(i=cast.framework.CastContext.getInstance())==null?void 0:i.getCurrentSession())==null?void 0:r.getMediaSession())==null||a.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){wn(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();vc(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();vc(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(Em(i,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(r=>{var a,n,o;switch(r.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(o=(n=(a=i.getCurrentSession())==null?void 0:a.getMediaSession())==null?void 0:n.media)==null?void 0:o.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return Pm(r.sessionState)}})).add(bP(Em(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(wm(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),xm(r=>r.castState)),gP([i.getCastState()])).pipe(vP(),xm(SP),wm(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{var o,u;let a=r==="CONNECTED",n=wn(this.connection$.getValue());if(a&&!n){let c=i.getCurrentSession();hP(c);let d=c.getCastDevice(),l=(u=(o=c.getMediaSession())==null?void 0:o.media)==null?void 0:u.contentId;(vc(l)||l===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:c,castDevice:d}))}else!a&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(r==="CONNECTED"?wn(this.connection$.getValue())?"CONNECTED":"AVAILABLE":r)}))}initializeCastApi(){var r;let e,t,i;try{e=cast.framework.CastContext.getInstance(),t=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,i=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(a){return}try{e.setOptions({receiverApplicationId:(r=this.params.receiverApplicationId)!=null?r:t,autoJoinPolicy:i}),this.initListeners()}catch(a){this.errorEvent$.next({id:"ChromecastInitializer",category:Am.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:a})}}},SP=s=>{switch(s){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return"NOT_AVAILABLE";case cast.framework.CastState.NOT_CONNECTED:return"AVAILABLE";case cast.framework.CastState.CONNECTING:return"CONNECTING";case cast.framework.CastState.CONNECTED:return"CONNECTED";default:return Pm(s)}};import{assertNonNullable as Tc,combine as Ic,debounce as Fm,ErrorCategory as CP,filter as ur,filterChanged as Nm,isNonNullable as Vn,map as DP,Subscription as BP,ValueSubject as Ec}from"@vkontakte/videoplayer-shared/es2018";import{assertNever as yP,assertNonNullable as xi,ErrorCategory as TP,getHighestQuality as IP,isNonNullable as km}from"@vkontakte/videoplayer-shared/es2018";import{assertNever as Rm}from"@vkontakte/videoplayer-shared/es2018";var ne=(s,e=0,t=0)=>{switch(t){case 0:return s.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case 1:{if(e===0)return s;let i=new URL(s);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}case 2:{let i=new URL(s);return!i.searchParams.get("offset_p")&&e===0?s:(i.searchParams.set("offset_p",e.toFixed(0)),i.toString())}default:Rm(t)}return s},Yt=(s,e)=>{var t;switch(e){case 0:return NaN;case 1:{let i=new URL(s);return Number(i.searchParams.get("playback_shift"))}case 2:{let i=new URL(s);return Number((t=i.searchParams.get("offset_p"))!=null?t:0)}default:Rm(e)}};var Rn=s=>{var l;let{source:e,format:t,meta:i,output:r}=s,a,n,o;switch(t){case"MPEG":{let h=e[t];xi(h);let p=IP(Object.keys(h));xi(p);let f=h[p];xi(f),a=f,n="video/mp4",o=Pn();break}case"HLS":case"HLS_FMP4":case"HLS_ONDEMAND":{let h=e[t];xi(h),a=h.url,n="application/x-mpegurl",o=Pn();break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":{let h=e[t];xi(h),a=h.url,n="application/dash+xml",o=Pn();break}case"DASH_LIVE_CMAF":{let h=e[t];xi(h),a=h.url,n="application/dash+xml",o=$m();break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let h=e[t];xi(h),a=ne(h.url),n="application/x-mpegurl",o=$m();break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let h="Unsupported format for Chromecast",p=new Error(h);throw r.error$.next({id:"ChromecastProvider.createMediaInfo()",category:TP.VIDEO_PIPELINE,message:h,thrown:p}),p}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${t} is no longer supported`);default:return yP(t)}let u=EP((l=i.videoId)!=null?l:a,n);u.contentUrl=a,u.streamType=o,u.metadata=xP();let{title:c,subtitle:d}=i;return km(c)&&(u.metadata.title=c),km(d)&&(u.metadata.subtitle=d),u};function Pn(){var s,e,t,i;return(i=(t=(e=(s=chrome.cast)==null?void 0:s.media)==null?void 0:e.StreamType)==null?void 0:t.BUFFERED)!=null?i:"BUFFERED"}function $m(){var s,e,t,i;return(i=(t=(e=(s=chrome.cast)==null?void 0:s.media)==null?void 0:e.StreamType)==null?void 0:t.LIVE)!=null?i:"LIVE"}function EP(s,e){var t,i;return(i=(t=chrome.cast)==null?void 0:t.media)!=null&&i.MediaInfo?new chrome.cast.media.MediaInfo(s,e):{contentId:s,contentType:e,metadata:{title:"",subtitle:""},streamType:Pn()}}function xP(){var s,e;return(e=(s=chrome.cast)==null?void 0:s.media)!=null&&e.GenericMediaMetadata?new chrome.cast.media.GenericMediaMetadata:{images:[],metadataType:0,releaseDate:"",subtitle:"",title:"",releaseYear:1970,type:0}}var k=(s,e,t=!1)=>{let i=s.getTransition();(t||!i||i.to===e)&&s.setState(e)};var kn=class{constructor(e){this.interval=0;this.params=e}start(e=0){clearInterval(this.interval),this.startVideoPosition=e,this.startTs=Date.now(),this.interval=window.setInterval(()=>{let t=(Date.now()-this.startTs)/1e3,i=this.startVideoPosition+t;this.params.output.position$.next(i)},1e3)}pause(){clearInterval(this.interval)}destroy(){clearInterval(this.interval)}};import{assertNever as Om}from"@vkontakte/videoplayer-shared/es2018";var Lm=O(Ae(),1);var $n=class{constructor(){this._isMiuiBrowser=!1}get current(){return this._current}get isChrome(){return this.current==="Chrome"}get isChromiumBased(){return(0,Lm.default)(["Chrome","Chromium","Opera","Yandex","Edge","SamsungBrowser"],this.current)}get isFirefox(){return this.current==="Firefox"}get isSafari(){return this.current==="Safari"}get isOpera(){return this.current==="Opera"}get isEdge(){return this.current==="Edge"}get isYandex(){return this.current==="Yandex"}get isSamsungBrowser(){return this.current==="SamsungBrowser"}get currentVersion(){return this._current_version}get chromeVersion(){return this._chromeVersion}get firefoxVersion(){return this._firefoxVersion}get safariVersion(){return this._safariVersion}get operaVersion(){return this._operaVersion}get edgeVersion(){return this._edgeVersion}get yandexVersion(){return this._yandexVersion}get isMiuiBrowser(){return this._isMiuiBrowser}detect(){let{userAgent:e}=navigator;try{let t=/yabrowser/i.test(e)?"Yandex":void 0,i=/samsungbrowser/i.test(e)?"SamsungBrowser":void 0,r=/chrome|crios/i.test(e)?"Chrome":void 0,a=/chromium/i.test(e)?"Chromium":void 0,n=/firefox|fxios/i.test(e)?"Firefox":void 0,o=/webkit|safari|khtml/i.test(e)?"Safari":void 0,u=/opr\//i.test(e)?"Opera":void 0,c=/edg/i.test(e)?"Edge":void 0;this._isMiuiBrowser=/(XiaoMi)|(MiuiBrowser)/i.test(e),this._current=t||i||n||u||c||r||a||o||"Rest"}catch(t){console.error(t)}this.isChrome&&this.detectChromeVersion(),this.isFirefox&&this.detectFirefoxVersion(),this.isSafari&&this.detectSafariVersion(),this.isOpera&&this.detectOperaVersion(),this.isEdge&&this.detectEdgeVersion(),this.isYandex&&this.detectYandexVersion()}detectVersion(e){try{let{userAgent:t}=window.navigator,i=t.match(e);if(!i)return;let r=i[1],a=parseInt(r,10);if(!isNaN(a))return this._current_version=a,a}catch(t){console.error(t)}}detectChromeVersion(){this._chromeVersion=this.detectVersion(/Chrome\/(\d+\.\d+)/)}detectFirefoxVersion(){this._firefoxVersion=this.detectVersion(/Firefox\/(\d+\.\d+)/)}detectSafariVersion(){this._safariVersion=this.detectVersion(/Version\/(\d+)/)}detectOperaVersion(){this._operaVersion=this.detectVersion(/OPR\/(\d+\.\d+)/)}detectEdgeVersion(){this._edgeVersion=this.detectVersion(/Edg\/(\d+\.\d+)/)}detectYandexVersion(){this._yandexVersion=this.detectVersion(/YaBrowser\/(\d+\.\d+\.\d+)/)}};var Mm=O(Ae(),1);var hs=()=>{var s,e;return/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test((s=navigator.appVersion)!=null?s:navigator.userAgent)||((e=navigator==null?void 0:navigator.userAgentData)==null?void 0:e.mobile)};var Ln=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,Mm.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=hs()}catch(t){console.error(t)}this.detectDevice(e),this.detectHighEntropyValues(),this.isIOS&&this.detectIOSVersion()}async detectHighEntropyValues(){let{userAgentData:e}=navigator;if(e!=null&&e.getHighEntropyValues){let t=await e.getHighEntropyValues(["architecture","bitness","brands","mobile","platform","formFactor","model","platformVersion","wow64"]);this._highEntropyValues=t}}detectDevice(e){try{let t=/android/i.test(e)?"Android":void 0,i=/iphone/i.test(e)?"iPhone":void 0,r=/ipad/i.test(e)?"iPad":void 0,a=/ipod/i.test(e)?"iPod":void 0,n=/mac/i.test(e)?"Mac":void 0,o=/webOS|BlackBerry|IEMobile|Opera Mini/i.test(e)?"RestMobile":void 0;this._current=t||i||r||a||o||n||"Desktop"}catch(t){console.error(t)}}detectIOSVersion(){try{if(this._highEntropyValues.platformVersion){let a=this._highEntropyValues.platformVersion.split(".").slice(0,2).join("."),n=parseFloat(a);this._iosVersion=n;return}let{userAgent:e}=window.navigator,t=e.match(/OS (\d+(_\d+)?)/i);if(!t)return;let i=t[1].replace(/_/g,".");if(!i)return;let r=parseFloat(i);if(isNaN(r))return;this._iosVersion=r}catch(e){console.error(e)}}};var Mn=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 Ue=()=>window.ManagedMediaSource||window.MediaSource,or=()=>{var s,e;return!!(window.ManagedMediaSource&&((e=(s=window.ManagedSourceBuffer)==null?void 0:s.prototype)!=null&&e.appendBuffer))},Cm=()=>{var s,e;return!!(window.MediaSource&&((e=(s=window.SourceBuffer)==null?void 0:s.prototype)!=null&&e.appendBuffer))},Cn=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var wP=document.createElement("video"),AP='video/mp4; codecs="avc1.42000a,mp4a.40.2"',PP='video/mp4; codecs="hev1.1.6.L93.B0"',Dm='video/webm; codecs="vp09.00.10.08"',Bm='video/webm; codecs="av01.0.00M.08"',RP='audio/mp4; codecs="mp4a.40.2"',kP='audio/webm; codecs="opus"',Vm,$P=async()=>{if(!window.navigator.mediaCapabilities)return;let s={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=await Promise.all([window.navigator.mediaCapabilities.decodingInfo({...s,video:{...s.video,contentType:Bm}}),window.navigator.mediaCapabilities.decodingInfo({...s,video:{...s.video,contentType:Dm}})]);Vm={DASH_WEBM_AV1:e,DASH_WEBM:t}};$P().catch(s=>{console.log(wP),console.error(s)});var Dn=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 Vm}get supportedCodecs(){return Object.keys(this._codecs).filter(e=>this._codecs[e])}get nativeHlsSupported(){return this._nativeHlsSupported}detect(){var e,t,i,r,a,n,o,u,c,d,l,h,p,f,m,g,b,S,T,y;this._video=document.createElement("video");try{this._protocols={mms:or(),mse:Cm(),hls:!!((t=(e=this._video).canPlayType)!=null&&t.call(e,"application/x-mpegurl")||(r=(i=this._video).canPlayType)!=null&&r.call(i,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},this._containers={mp4:!!((n=(a=this._video).canPlayType)!=null&&n.call(a,"video/mp4")),webm:!!((u=(o=this._video).canPlayType)!=null&&u.call(o,"video/webm")),cmaf:!0};let E=!!((d=(c=Ue())==null?void 0:c.isTypeSupported)!=null&&d.call(c,AP)),A=!!((h=(l=Ue())==null?void 0:l.isTypeSupported)!=null&&h.call(l,PP)),$=!!((f=(p=Ue())==null?void 0:p.isTypeSupported)!=null&&f.call(p,RP));this._codecs={h264:E,h265:A,vp9:!!((g=(m=Ue())==null?void 0:m.isTypeSupported)!=null&&g.call(m,Dm)),av1:!!((S=(b=Ue())==null?void 0:b.isTypeSupported)!=null&&S.call(b,Bm)),aac:$,opus:!!((y=(T=Ue())==null?void 0:T.isTypeSupported)!=null&&y.call(T,kP)),mpeg:(E||A)&&$},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 _m="audio/mpeg",Bn=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,_m))},this._codecs={mp3:!!((r=(i=Ue())==null?void 0:i.isTypeSupported)!=null&&r.call(i,_m))}}catch(a){console.error(a)}try{this.destroyAudioElement()}catch(a){console.error("Error destroying audio element:",a)}}destroyAudioElement(){var t;if(!this._audio)return;if(this._audio.pause(),this._audio.currentTime=0,this._audio.removeAttribute("src"),this._audio.src="",this._audio.load(),this._audio.remove){this._audio.remove(),this._audio=null;return}this._audio.parentNode&&this._audio.parentNode.removeChild(this._audio);let e=this._audio.cloneNode(!1);(t=this._audio.parentNode)==null||t.replaceChild(e,this._audio),this._audio=null}};import{ValueSubject as LP}from"@vkontakte/videoplayer-shared/es2018";var Sc=class{constructor(){this.isInited$=new LP(!1);this._displayChecker=new Mn,this._deviceChecker=new Ln(this._displayChecker),this._browserChecker=new $n,this._videoChecker=new Dn(this._deviceChecker,this._browserChecker),this._audioChecker=new Bn,this.detect()}get display(){return this._displayChecker}get device(){return this._deviceChecker}get browser(){return this._browserChecker}get video(){return this._videoChecker}get audio(){return this._audioChecker}async detect(){this._displayChecker.detect(),this._deviceChecker.detect(),this._browserChecker.detect(),this._videoChecker.detect(),this._audioChecker.detect(),this.isInited$.next(!0)}},_=new Sc;var yc=s=>{let{containers:e,protocols:t,codecs:i,nativeHlsSupported:r}=_.video,a=(i.h264||i.h265)&&i.aac,n=t.mse||t.mms;return s.filter(o=>{switch(o){case"DASH_SEP":return n&&e.mp4&&a;case"DASH_WEBM":return n&&e.webm&&i.vp9&&i.opus;case"DASH_WEBM_AV1":return n&&e.webm&&i.av1&&i.opus;case"DASH_STREAMS":return n&&(e.mp4&&a||e.webm&&(i.vp9||i.av1)&&(i.opus||i.aac));case"DASH_LIVE":return n&&e.mp4&&a;case"DASH_LIVE_CMAF":return n&&e.mp4&&a&&e.cmaf;case"DASH_ONDEMAND":return n&&e.mp4&&a;case"HLS":case"HLS_ONDEMAND":case"HLS_FMP4":case"HLS_LIVE":case"HLS_LIVE_CMAF":return r;case"MPEG":return e.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return t.webrtc&&t.ws&&i.h264&&(e.mp4||e.webm);default:return Om(o)}})},fs=s=>{switch(s){case"MPEG":case"DASH":case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":case"HLS":case"HLS_FMP4":case"HLS_ONDEMAND":return!1;case"DASH_LIVE":case"DASH_LIVE_CMAF":case"HLS_LIVE":case"HLS_LIVE_CMAF":case"DASH_LIVE_WEBM":case"WEB_RTC_LIVE":return!0;default:return Om(s)}},MP=s=>{let t=Object.keys(s).filter(i=>!fs(i));return yc(t).length>0};var ms=class{constructor(e){this.subscription=new BP;this.sessionId$=new Ec(null);this.mediaSessionId$=new Ec(null);this.contentId$=new Ec(null);this.media=null;this.syncMediaState=e=>{var a,n,o,u;this.media=e!=null?e:null,this.mediaSessionId$.next((a=e==null?void 0:e.mediaSessionId)!=null?a:null),this.contentId$.next((o=(n=e==null?void 0:e.media)==null?void 0:n.contentId)!=null?o:null);let t=e==null?void 0:e.playerState;this.syncPlaybackState(t);let i=(u=e==null?void 0:e.media)==null?void 0:u.duration;Vn(i)&&this.params.output.duration$.next(Math.max(0,i));let r=e==null?void 0:e.currentTime;if(Vn(r)){this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.params.output.position$.next(r);let d=this.params.output.isLive$.getValue();t==="PLAYING"&&!d?this.progressTicker.start(r):this.progressTicker.pause()}};this.params=e,this.progressTicker=new kn(e),this.log=this.params.dependencies.logger.createComponentLog("ChromecastNewProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(fs(e.format)),this.subscribe()}subscribe(){let e=i=>{var r;this.params.output.error$.next({category:CP.WTF,id:"ChromecastNewProvider",message:(r=i==null?void 0:i.message)!=null?r:"Unknown error",thrown:i})};this.subscription.add(this.params.chromecastConnector.message$.pipe(ur(i=>!!i)).subscribe(i=>{this.handleMessage(i)},e)),this.subscription.add(this.sessionId$.pipe(ur(Vn),Nm(),Fm(0)).subscribe(()=>{this.loadMedia()},e));let t=this.contentId$.pipe(ur(Vn),Nm(),DP(Boolean));this.subscription.add(Ic({seekState:this.params.desiredState.seekState.stateChangeEnded$,mediaLoaded:t}).pipe(ur(({mediaLoaded:i})=>i)).subscribe(()=>{let i=this.params.desiredState.seekState.getState();i.state==="requested"&&this.seek(i.position/1e3)},e)),this.subscription.add(Ic({playbackState:this.params.desiredState.playbackState.stateChangeStarted$,mediaLoaded:t}).pipe(ur(({mediaLoaded:i})=>i)).subscribe(()=>{this.syncPlayback()},e)),this.subscription.add(Ic({volumeState:this.params.desiredState.volume.stateChangeStarted$.pipe(Fm(30)),mediaLoaded:t}).pipe(ur(({mediaLoaded:i})=>i)).subscribe(({volumeState:i})=>{let{muted:r,volume:a}=i.to;this.setVolume(a,r)},e))}handleMessage(e){var t,i,r,a,n,o;switch(e.type){case"new_session":case"update_session":{this.sessionId$.next(e.message.sessionId);let u=(i=(t=e.message)==null?void 0:t.media)==null?void 0:i[0];this.syncMediaState(u);let c=(r=e.message)==null?void 0:r.receiver.volume;if(c){let{level:d,muted:l}=c;this.params.output.volume$.next({muted:l!=null?l:!1,volume:d!=null?d:0})}}break;case"v2_message":{switch((a=e.message)==null?void 0:a.type){case"MEDIA_STATUS":{let u=(o=(n=e.message)==null?void 0:n.status)==null?void 0:o[0];this.syncMediaState(u);break}}break}}}loadMedia(){var o;let e=Rn(this.params),t=(o=this.media)==null?void 0:o.currentTime,i=this.params.desiredState.seekState.getState(),r=t!=null?t:i.state!=="none"?i.position/1e3:0,n=this.params.desiredState.playbackState.getState()==="playing";this.params.chromecastConnector.sendV2Message({type:"LOAD",requestId:0,media:e,autoplay:n,currentTime:r,customData:null,activeTrackIds:null}),this.params.output.willSeekEvent$.next()}stop(){this.params.chromecastConnector.stopMedia()}play(){let e=this.mediaSessionId$.getValue();Tc(e,"play on null mediaSessionId"),this.params.chromecastConnector.sendV2Message({type:"PLAY",mediaSessionId:e,customData:null})}pause(){let e=this.mediaSessionId$.getValue();Tc(e,"pause on null mediaSessionId"),this.params.chromecastConnector.sendV2Message({type:"PAUSE",mediaSessionId:e,customData:null})}seek(e){let t=this.mediaSessionId$.getValue();Tc(t,"seek on null mediaSessionId"),this.params.chromecastConnector.sendV2Message({type:"SEEK",currentTime:e,mediaSessionId:t}),this.params.output.willSeekEvent$.next()}setVolume(e,t){this.log({message:`[setVolume] volume: ${e}, muted: ${t}`}),this.params.chromecastConnector.sendV2Message({type:"SET_VOLUME",requestId:0,volume:{level:t?0:e,muted:t?!0:null}})}syncPlaybackState(e){switch(e){case"PAUSED":k(this.params.desiredState.playbackState,"paused");break;case"PLAYING":k(this.params.desiredState.playbackState,"playing");break;case"IDLE":k(this.params.desiredState.playbackState,"ready");break;case"BUFFERING":break}}syncPlayback(){let e=this.params.desiredState.playbackState.getState();switch(this.log({message:`[syncPlayback] ${e}`}),e){case"ready":break;case"playing":this.play();break;case"paused":this.pause();break;case"stopped":this.stop();break}}destroy(){this.progressTicker.destroy(),this.subscription.unsubscribe()}};import{assertNonNullable as VP,ErrorCategory as _n,filter as _P,Subject as OP,Subscription as FP,tap as NP,ValueSubject as bs}from"@vkontakte/videoplayer-shared/es2018";var qm=()=>({castDevice:{},remotePlayer:{},remotePlayerController:{},session:{}}),Um=()=>String(Date.now())+String(Math.floor(Math.random()*1e5));var gs=class{constructor(e){this.capabilities=["WEB"];this.subscription=new FP;this.presentationRequest$=new bs(null);this.sessionId$=new bs(null);this.sequenceNumber=0;this.presentationAvailable$=new bs(!1);this.presentationConnection$=new bs(null);this.message$=new bs(null);this.errorEvent$=new OP;this.clientId=Um(),this.params=e,this.log=e.logger.createComponentLog("ChromecastConnector"),this.log({message:"constructor"}),this.reinitPresentation(),this.subscribe()}destroy(){this.log({message:"destroy"}),this.disconnect(),this.subscription.unsubscribe()}disconnect(){this.log({message:"disconnect"}),this.stopMedia();let e=this.presentationRequest$.getValue();e&&(e.onconnectionavailable=null),this.presentationRequest$.next(null);let t=this.presentationConnection$.getValue();t&&t.close(),this.presentationConnection$.next(null),this.resetSequenceNumber()}stopMedia(){this.log({message:"stopMedia"}),this.sendV2Message({type:"STOP"})}async reinitPresentation(e=!0){var t;try{let i=this.createCastUrl(),r=new PresentationRequest(i);this.presentationRequest$.next(r),this.log({message:"PresentationRequest created"}),r.onconnectionavailable=n=>{this.log({message:"PresentationRequest connection available"}),this.presentationConnection$.next(n.connection)};let a=await r.getAvailability();a.onchange=()=>{this.log({message:`PresentationRequest presentation availability: ${a.value}`}),this.presentationAvailable$.next(a.value)},e&&await r.reconnect("auto-join").then(()=>{this.log({message:"PresentationRequest reconnect success"})}).catch(()=>{})}catch(i){this.errorEvent$.next({category:_n.WTF,id:"ChromecastConnector",message:(t=i==null?void 0:i.message)!=null?t:"reinitPresentation error",thrown:i})}}async connect(){var e;this.log({message:"connect"});try{if(this.presentationRequest$.getValue()||(this.log({message:"reinitPresentation"}),await this.reinitPresentation(!1)),this.presentationConnection$.getValue()){this.log({message:"connection already established"});return}let t=this.presentationRequest$.getValue();VP(t,"connect with null presentationRequest"),await t.start()}catch(t){switch(t==null?void 0:t.name){case"AbortError":case"NotAllowedError":break;default:this.errorEvent$.next({category:_n.WTF,id:"ChromecastConnector",message:(e=t==null?void 0:t.message)!=null?e:"connect error",thrown:t});break}}}subscribe(){this.subscription.add(this.presentationAvailable$.subscribe(e=>{this.log({message:`presentationAvailable$: ${e}`})})).add(this.presentationConnection$.pipe(NP(e=>{this.log({message:`presentationConnection$: ${!!e}`})}),_P(e=>!!e)).subscribe(e=>{e.onmessage=t=>{let i=JSON.parse(t.data);i.clientId===this.clientId&&(this.handleMessage(i),this.message$.next(i))},e.onconnect=()=>{this.send("client_connect")},e.onclose=t=>{switch(t.reason){case"error":this.errorEvent$.next({category:_n.WTF,id:"ChromecastConnector",message:"Session error",thrown:t});break;case"closed":break}}}))}send(e){switch(e){case"client_connect":{let t={type:"client_connect",message:this.clientId,sequenceNumber:-1,timeoutMillis:0,clientId:this.clientId};this.safeSend(JSON.stringify(t));break}}}sendV2Message(e){let t=this.sessionId$.getValue();if(t){let i={type:"v2_message",sequenceNumber:this.getSequenceNumber(),timeoutMillis:0,clientId:this.clientId,message:{...e,sessionId:t}};this.safeSend(JSON.stringify(i))}}safeSend(e){try{this.log({message:`[send] ${e}`});let t=this.presentationConnection$.getValue();(t==null?void 0:t.state)==="connected"&&(t==null||t.send(e))}catch(t){this.errorEvent$.next({category:_n.WTF,id:"ChromecastConnector",message:"PresentationConnection send error",data:{message:e},thrown:t})}}handleMessage(e){var t;switch(e.type){case"new_session":case"update_session":this.sessionId$.next(e.message.sessionId);break;case"receiver_action":((t=e.message)==null?void 0:t.action)==="stop"&&this.disconnect();break}}createCastUrl(){return`cast:${this.params.appId}?clientId=${this.clientId}&autoJoinPolicy=origin_scoped&defaultActionPolicy=create_session&launchTimeout=60000&supportedAppTypes=${this.capabilities}&appParams=%7B%22launchCheckerParams%22%3A%7B%7D%7D`}getSequenceNumber(){let e=this.sequenceNumber;return this.sequenceNumber=(this.sequenceNumber+1)%Number.MAX_SAFE_INTEGER,e}resetSequenceNumber(){this.sequenceNumber=0}};import{ValueSubject as jm,Subject as qP,map as UP,Subscription as jP,combine as HP,filterChanged as WP,assertNonNullable as QP}from"@vkontakte/videoplayer-shared/es2018";var kt=class s{constructor(e){this.subscription=new jP;this.connection$=new jm(void 0);this.castState$=new jm("NOT_AVAILABLE");this.errorEvent$=new qP;var i;let t=s.isSupported();this.log=e.dependencies.logger.createComponentLog("ChromecastNewInitializer"),this.log({message:`[constructor] receiverApplicationId: ${e.receiverApplicationId}, isDisabled: ${e.isDisabled}, isSupported: ${t}`}),!(!t||e.isDisabled)&&(this.chromecastConnector=new gs({appId:(i=e.receiverApplicationId)!=null?i:"07A4434E",logger:e.dependencies.logger}),this.subscribe())}static isSupported(){return"chrome"in window&&"presentation"in navigator}subscribe(){QP(this.chromecastConnector,"subscribe with null chromecastConnector"),this.subscription.add(this.chromecastConnector.errorEvent$.subscribe(this.errorEvent$));let e=HP({connection:this.chromecastConnector.presentationConnection$,available:this.chromecastConnector.presentationAvailable$});this.subscription.add(e.pipe(UP(({connection:t})=>!!t),WP()).subscribe(t=>{this.connection$.next(t?qm():void 0)})).add(e.subscribe(({available:t,connection:i})=>{t?i?this.castState$.next("CONNECTED"):this.castState$.next("AVAILABLE"):this.castState$.next("NOT_AVAILABLE")}))}connect(){var e;this.log({message:"connect"}),(e=this.chromecastConnector)==null||e.connect()}disconnect(){var e;this.log({message:"disconnect"}),(e=this.chromecastConnector)==null||e.disconnect()}async stopMedia(){var e;this.log({message:"stopMedia"}),(e=this.chromecastConnector)==null||e.stopMedia()}toggleConnection(){var t;let e=!!((t=this.chromecastConnector)!=null&&t.presentationConnection$.getValue());this.log({message:`toggleConnection: isConnected - ${e}`}),e?this.disconnect():this.connect()}setVolume(e){}setMuted(e){}destroy(){var e;this.log({message:"destroy"}),(e=this.chromecastConnector)==null||e.destroy(),this.subscription.unsubscribe()}};var lp=O(Ae(),1),NE=O(cr(),1),qE=O(Wc(),1);var AS=O(uo(),1);import{isNonNullable as MM,Subject as co,merge as TS}from"@vkontakte/videoplayer-shared/es2018";var U=class{constructor(e){this.transitionStarted$=new co;this.transitionEnded$=new co;this.transitionUpdated$=new co;this.forceChanged$=new co;this.stateChangeStarted$=TS(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=TS(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||MM(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 $s,debounce as IS,ErrorCategory as CM,fromEvent as $i,map as ES,merge as xS,observableFrom as DM,Subject as BM,Subscription as Ll,timeout as VM}from"@vkontakte/videoplayer-shared/es2018";var _M=5,OM=5,FM=500,wS=7e3,Ls=class{constructor(e){this.subscription=new Ll;this.loadMediaTimeoutSubscription=new Ll;this.videoState=new U("stopped");this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(a)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.stop());return}if(!t){if((r==null?void 0:r.to)!=="paused"&&a.state==="requested"&&e!=="stopped"){this.seek(a.position/1e3);return}switch(i){case"ready":{switch(e){case"playing":case"paused":case"ready":break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:$s(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:$s(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:$s(e)}break}default:$s(i)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(fs(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 Ll;this.subscription.add(e),this.subscription.add(xS(this.videoState.stateChangeStarted$.pipe(ES(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe(ES(r=>`stateChangeEnded$ ${JSON.stringify(r)}`))).subscribe(r=>this.log({message:`[videoState] ${r}`})));let t=(r,a)=>this.subscription.add(r.subscribe(a));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{let r=new BM;e.add(r.pipe(IS(FM)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let a=NaN;e.add($i(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(n=>{this.logRemoteEvent(n);let o=n.value;this.params.output.position$.next(o),(this.params.desiredState.seekState.getState().state==="applying"||Math.abs(o-a)>_M)&&r.next(o),a=o})),e.add($i(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t($i(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t($i(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t($i(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),r=>{this.logRemoteEvent(r);let{remotePlayer:a}=this.params.connection,n=r.value,o=this.params.output.isBuffering$.getValue(),u=n===chrome.cast.media.PlayerState.BUFFERING;switch(o!==u&&this.params.output.isBuffering$.next(u),n){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&a.duration-a.currentTime<OM&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),k(this.params.desiredState.playbackState,"stopped");break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:$s(n)}}),t($i(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t($i(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});let i=xS(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,DM(["init"])).pipe(IS(0));t(i,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});let{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),k(this.params.desiredState.playbackState,"playing"));let i=this.params.output.isLive$.getValue();this.params.output.duration$.next(i?0:t.duration),this.params.output.position$.next(i?0:t.currentTime),this.params.desiredState.seekState.setState({state:"none"})}}prepare(){let e=this.params.format;this.log({message:`[prepare] format: ${e}`});let t=Rn(this.params),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"),k(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"),k(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"&&k(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){var r,a;let t=this.params.output.volume$.getValue(),i={volume:(r=e.volume)!=null?r:t.volume,muted:(a=e.muted)!=null?a:t.muted};(i.volume!==t.volume||i.muted!==i.muted)&&this.params.output.volume$.next(i)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:i}=this.params.connection;t.currentTime=e,i.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createLoadRequest(e){let t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;let i=this.params.desiredState.seekState.getState();return i.state==="applying"||i.state==="requested"?t.currentTime=this.params.output.isLive$.getValue()?0:i.position/1e3:t.currentTime=0,t}loadMedia(e){let t=this.params.connection.session.loadMedia(e),i=new Promise((r,a)=>{this.loadMediaTimeoutSubscription.add(VM(wS).subscribe(()=>a(`timeout(${wS})`)))});(0,AS.default)(Promise.race([t,i]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},r=>{let a=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${r}`;this.log({message:a}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:CM.VIDEO_PIPELINE,message:a,thrown:r})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var Yl=O(Ae(),1);import{clearVideoElement as RS}from"@vkontakte/videoplayer-shared/es2018";import{clearVideoElement as NM}from"@vkontakte/videoplayer-shared/es2018";var PS=s=>{try{s.pause(),s.playbackRate=0,NM(s),s.remove()}catch(e){console.error(e)}};import{fromEvent as qM,Subscription as UM}from"@vkontakte/videoplayer-shared/es2018";var Ml=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)}},Cl=window.WeakMap?new WeakMap:new Ml,Dl=window.WeakMap?new WeakMap:new Map,jM=(s,e=20)=>{let t=0;return qM(s,"ratechange").subscribe(i=>{t++,t>=e&&(s.currentTime=s.currentTime,t=0)})},De=(s,{audioVideoSyncRate:e,disableYandexPiP:t})=>{let i=s.querySelector("video"),r=!!i;i?RS(i):(i=document.createElement("video"),s.appendChild(i)),Cl.set(i,r);let a=new UM;return a.add(jM(i,e)),Dl.set(i,a),i.setAttribute("crossorigin","anonymous"),i.setAttribute("playsinline","playsinline"),t&&i.setAttribute("x-yandex-pip","false"),i.controls=!1,i.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),i},Be=s=>{let e=Dl.get(s);e==null||e.unsubscribe(),Dl.delete(s);let t=Cl.get(s);Cl.delete(s),t?RS(s):PS(s)};var Vl=O(Ei(),1);import{assertNonNullable as Cs,isNonNullable as vt,isNullable as QM,fromEvent as Sr,merge as kS,observableFrom as $S,filterChanged as LS,map as Ds,Subject as MS,Subscription as GM,ValueSubject as zM,ErrorCategory as YM}from"@vkontakte/videoplayer-shared/es2018";import{isNonNullable as Bl,isNullable as HM,Subscription as WM}from"@vkontakte/videoplayer-shared/es2018";var lo=(s,e,t,{equal:i=(n,o)=>n===o,changed$:r,onError:a}={})=>{let n=s.getState(),o=e(),u=HM(r),c=new WM;return r&&c.add(r.subscribe(d=>{let l=s.getState();i(d,l)&&s.setState(d)},a)),i(o,n)||(t(n),u&&s.setState(n)),c.add(s.stateChangeStarted$.subscribe(d=>{t(d.to),u&&s.setState(d.to)},a)),c},gt=(s,e,t)=>lo(e,()=>s.loop,i=>{Bl(i)&&(s.loop=i)},{onError:t}),Ve=(s,e,t,i)=>lo(e,()=>({muted:s.muted,volume:s.volume}),r=>{Bl(r)&&(s.muted=r.muted,s.volume=r.volume)},{equal:(r,a)=>r===a||(r==null?void 0:r.muted)===(a==null?void 0:a.muted)&&(r==null?void 0:r.volume)===(a==null?void 0:a.volume),changed$:t,onError:i}),ze=(s,e,t,i)=>lo(e,()=>s.playbackRate,r=>{Bl(r)&&(s.playbackRate=r)},{changed$:t,onError:i}),Ms=lo;var KM=s=>["__",s.language,s.label].join("|"),XM=(s,e)=>{if(s.id===e)return!0;let[t,i,r]=e.split("|");return s.language===i&&s.label===r},_l=class s{constructor(e){this.available$=new MS;this.current$=new zM(void 0);this.error$=new MS;this.subscription=new GM;this.externalTracks=new Map;this.internalTracks=new Map;this.baseURL=e}connect(e,t,i){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();let r=a=>{this.error$.next({id:"TextTracksManager",category:YM.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:a})};this.subscription.add(this.available$.subscribe(i.availableTextTracks$)),this.subscription.add(this.current$.subscribe(i.currentTextTrack$)),this.subscription.add(this.error$.subscribe(i.error$)),this.subscription.add(Ms(t.internalTextTracks,()=>(0,Vl.default)(this.internalTracks),a=>{vt(a)&&this.setInternal(a)},{equal:(a,n)=>vt(a)&&vt(n)&&a.length===n.length&&a.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(Ds(a=>a.filter(({type:n})=>n==="internal"))),onError:r})),this.subscription.add(Ms(t.externalTextTracks,()=>(0,Vl.default)(this.externalTracks),a=>{vt(a)&&this.setExternal(a)},{equal:(a,n)=>vt(a)&&vt(n)&&a.length===n.length&&a.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(Ds(a=>a.filter(({type:n})=>n==="external"))),onError:r})),this.subscription.add(Ms(t.currentTextTrack,()=>{if(this.video)return;let a=this.htmlTextTracksAsArray().find(({mode:n})=>n==="showing");return a&&this.htmlTextTrackToITextTrack(a).id},a=>this.select(a),{changed$:this.current$,onError:r})),this.subscription.add(Ms(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let a of this.htmlTextTracksAsArray())this.applyCueSettings(a.cues),this.applyCueSettings(a.activeCues)}))}subscribe(){Cs(this.video);let{textTracks:e}=this.video;this.subscription.add(Sr(e,"addtrack").subscribe(()=>{let i=this.current$.getValue();i&&this.select(i)})),this.subscription.add(kS(Sr(e,"addtrack"),Sr(e,"removetrack"),$S(["init"])).pipe(Ds(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),LS((i,r)=>i.length===r.length&&i.every(({id:a},n)=>a===r[n].id))).subscribe(this.available$)),this.subscription.add(kS(Sr(e,"change"),$S(["init"])).pipe(Ds(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),Ds(i=>i&&this.htmlTextTrackToITextTrack(i).id),LS()).subscribe(this.current$));let t=i=>{var r,a;return this.applyCueSettings((a=(r=i.target)==null?void 0:r.activeCues)!=null?a:null)};this.subscription.add(Sr(e,"addtrack").subscribe(i=>{var a,n;(a=i.track)==null||a.addEventListener("cuechange",t);let r=o=>{var c,d,l,h,p;let u=(d=(c=o.target)==null?void 0:c.cues)!=null?d:null;u&&u.length&&(this.applyCueSettings((h=(l=o.target)==null?void 0:l.cues)!=null?h:null),(p=o.target)==null||p.removeEventListener("cuechange",r))};(n=i.track)==null||n.addEventListener("cuechange",r)})),this.subscription.add(Sr(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;vt(t.align)&&(r.align=t.align),vt(t.position)&&(r.position=t.position),vt(t.size)&&(r.size=t.size),vt(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){Cs(this.video);let t=[...this.video.textTracks];return e?t:t.filter(s.isHealthyTrack)}htmlTextTrackToITextTrack(e){var o,u,c,d,l;let{language:t,label:i}=e,r=e.id?e.id:KM(e),a=this.externalTracks.has(r),n=(c=a?(o=this.externalTracks.get(r))==null?void 0:o.isAuto:(u=this.internalTracks.get(r))==null?void 0:u.isAuto)!=null?c:r.includes("auto");return a?{id:r,type:"external",isAuto:n,language:t,label:i,url:(d=this.externalTracks.get(r))==null?void 0:d.url}:{id:r,type:"internal",isAuto:n,language:t,label:i,url:(l=this.internalTracks.get(r))==null?void 0:l.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(i=>i.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){let t=[...this.externalTracks];e.filter(({id:i,language:r,isAuto:a})=>!this.internalTracks.has(i)&&!t.some(([,n])=>n.language===r&&n.isAuto===a)).forEach(i=>this.attach(i)),Array.from(this.internalTracks).filter(([i])=>!e.find(r=>r.id===i)).forEach(([,i])=>this.detach(i))}select(e){Cs(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(QM(e)||!XM(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){Cs(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){Cs(this.video);let t=Array.prototype.find.call(this.video.getElementsByTagName("track"),i=>i.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}},Ye=_l;var Li=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 CS=s=>{let e=s;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e==null?void 0:e.parentNode;return e!=null?e:void 0},Ol=s=>{let e=CS(s);return!!(e&&e.fullscreenElement&&e.fullscreenElement===s)},DS=s=>{let e=CS(s);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===s)};import{fromEvent as Pe,map as St,merge as po,filterChanged as VS,isNonNullable as _S,Subject as ZM,filter as Fl,mapTo as Nl,combine as eC,once as tC,shareReplay as Re,throttle as iC,ErrorCategory as rC,ValueSubject as OS,Subscription as sC}from"@vkontakte/videoplayer-shared/es2018";var JM=3,BS=(s,e,t=JM)=>{let i=0,r=0;for(let a=0;a<s.length;a++){let n=s.start(a),o=s.end(a);if(n<=e&&e<=o){if(i=n,r=o,!t)return{from:i,to:r};for(let u=a-1;u>=0;u--)s.end(u)+t>=i&&(i=s.start(u));for(let u=a+1;u<s.length;u++)s.start(u)-t<=r&&(r=s.end(u))}}return{from:i,to:r}};var _e=s=>{let e=P=>Pe(s,P).pipe(Nl(void 0),Re(1)),t=new sC,i=()=>t.unsubscribe(),r=po(Pe(s,"progress"),Pe(s,"timeupdate")).pipe(St(()=>BS(s.buffered,s.currentTime)),Re(1)),a=_.browser.isSafari?eC({play:e("play").pipe(tC()),playing:e("playing")}).pipe(Nl(void 0),Re(1)):e("playing"),n=Pe(s,"volumechange").pipe(St(()=>({muted:s.muted,volume:s.volume})),Re(1)),o=Pe(s,"ratechange").pipe(St(()=>s.playbackRate),Re(1)),u=Pe(s,"error").pipe(Fl(()=>!!(s.error||s.played.length)),St(()=>{var B;let P=s.error;return{id:P?`MediaError#${P.code}`:"HtmlVideoError",category:rC.VIDEO_PIPELINE,message:P?P.message:"Error event from HTML video element",thrown:(B=s.error)!=null?B:void 0}}),Re(1)),c=Pe(s,"timeupdate").pipe(St(()=>s.currentTime),Re(1)),d=["waiting","seeking","seeked","timeupdate"],l=new ZM,h=.3,p;t.add(po(...d.map(P=>Pe(s,P))).subscribe(P=>{let B=s.currentTime;s.loop&&_S(p)&&_S(B)&&p>=s.duration-h&&B<=h&&l.next(p),p=B}));let f=e("pause").pipe(Fl(()=>!s.error&&p!==s.duration),Re(1)),m=Pe(s,"enterpictureinpicture").pipe(Re(1)),g=Pe(s,"leavepictureinpicture").pipe(Re(1)),b=new OS(DS(s));t.add(m.subscribe(()=>b.next(!0))),t.add(g.subscribe(()=>b.next(!1)));let S=new OS(Ol(s)),T=Pe(s,"fullscreenchange").pipe(Re(1));t.add(T.pipe(St(()=>Ol(s))).subscribe(S));let y=.1,E=1e3,A=Pe(s,"timeupdate").pipe(St(P=>s.duration-s.currentTime<y),VS(),Re(1)),$=po(A.pipe(Fl(P=>!s.loop&&P)),Pe(s,"ended")).pipe(iC(E),Nl(void 0),Re(1)),C=po(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(P=>Pe(s,P)),A.pipe(St(P=>({type:P?"ended":"unknown"})))).pipe(St(P=>_.browser.isFirefox&&P.type==="ended"?s.readyState<2:s.readyState<3),VS(),Re(1));return{playing$:a,pause$:f,canplay$:e("canplay"),ended$:$,looped$:l,error$:u,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:c,durationChange$:Pe(s,"durationchange").pipe(St(()=>s.duration),Re(1)),isBuffering$:C,currentBuffer$:r,volumeState$:n,playbackRateState$:o,inPiP$:b,inFullscreen$:S,enterPip$:m,leavePip$:g,destroy:i}};import{VideoQuality as Xt}from"@vkontakte/videoplayer-shared/es2018";var Jt=s=>{switch(s){case"mobile":return Xt.Q_144P;case"lowest":return Xt.Q_240P;case"low":return Xt.Q_360P;case"sd":case"medium":return Xt.Q_480P;case"hd":case"high":return Xt.Q_720P;case"fullhd":case"full":return Xt.Q_1080P;case"quadhd":case"quad":return Xt.Q_1440P;case"ultrahd":case"ultra":return Xt.Q_2160P}};var $e=O(nt(),1),Ul=O(Ae(),1),Ci=O(cr(),1);import{isNonNullable as X,isNullable as bo,now as ty,isHigher as go,isHigherOrEqual as Mi,isInvariantQuality as vo,isLowerOrEqual as Tr,videoSizeToQuality as iy,assertNotEmptyArray as So,assertNonNullable as ry}from"@vkontakte/videoplayer-shared/es2018";var ql=!1,Lt={},WS=s=>{ql=s},QS=()=>{Lt={}},GS=s=>{s(Lt)},Bs=(s,e)=>{var t;ql&&(Lt.meta=(t=Lt.meta)!=null?t:{},Lt.meta[s]=e)},ke=class{constructor(e){this.name=e}next(e){var i,r;if(!ql)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 hC,isHigherOrEqual as F1,isLower as zS,isLowerOrEqual as N1,isNonNullable as ho,isNullable as fC,videoHeightToQuality as fo}from"@vkontakte/videoplayer-shared/es2018";function YS(s,e,t){return!s.max&&s.min===e?"high_quality":!s.min&&s.max===t?"traffic_saving":"unknown"}function yr(s,e,t){return fC(s)||ho(s.min)&&ho(s.max)&&zS(s.max,s.min)||ho(s.min)&&e&&hC(s.min,e)||ho(s.max)&&t&&zS(s.max,t)}function KS({limits:s,highestAvailableHeight:e,lowestAvailableHeight:t}){return yr({max:s!=null&&s.max?fo(s.max):void 0,min:s!=null&&s.min?fo(s.min):void 0},e?fo(e):void 0,t?fo(t):void 0)}var sy=new ke("best_bitrate"),yo=(s,e,t)=>(e-t)*Math.pow(2,-10*s)+t;var Ir=s=>(e,t)=>s*(Number(e.bitrate)-Number(t.bitrate)),Zt=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=ty()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},To='Assertion "ABR Tracks is empty array" failed',mo=new WeakMap,XS=new WeakMap,JS=new WeakMap,Vs=(s,e,t,i)=>{var u;let r=[...e].sort(Ir(1)),a=[...t].sort(Ir(1)),n=a.filter(c=>X(c.bitrate)&&X(s.bitrate)?s.bitrate/c.bitrate>i:!0),o=(u=(0,$e.default)(a,Math.round(a.length*r.indexOf(s)/(r.length+1))))!=null?u:(0,$e.default)(a,-1);return o&&(0,Ul.default)(n,o)?o:n.length?(0,$e.default)(n,-1):(0,$e.default)(a,0)},_s=(s,e,t,i)=>{var u;let r=mo.get(e);r||(r=[...e].sort(Ir(1)),mo.set(e,r));let a=mo.get(t);a||(a=[...t].sort(Ir(1)),mo.set(t,a));let n=JS.get(s);n||(n=a.filter(c=>X(c.bitrate)&&X(s.bitrate)?s.bitrate/c.bitrate>i:!0),JS.set(s,n));let o=(u=(0,$e.default)(a,Math.round(a.length*r.indexOf(s)/(r.length+1))))!=null?u:(0,$e.default)(a,-1);return o&&(0,Ul.default)(n,o)?o:n.length?(0,$e.default)(n,-1):(0,$e.default)(a,0)},ZS=s=>"quality"in s,Io=(s,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?s.trackCooldownIncreaseQuality:s.trackCooldownDecreaseQuality,a=t&&i&&i.history[t.id]&&ty()-i.history[t.id]<=r&&(!i.last||t.id!==i.last.id);if(t!=null&&t.id&&i&&!a&&i.recordSelection(t),a&&(i!=null&&i.last)){let o=i.last;i==null||i.recordSwitch(o);let u=ZS(o)?"video":"audio",c=ZS(o)?o.quality:o.bitrate;return e({message:`
|
|
8
|
+
[last ${u} selected] ${c}
|
|
9
|
+
`}),o}return i==null||i.recordSwitch(t),t},mC=(s,e)=>Math.log(e)/Math.log(s),ay=({tuning:s,container:e,limits:t,panelSize:i})=>{let r=s.containerSizeFactor;if(i)return{containerSizeLimit:i,containerSizeFactor:r};if(s.usePixelRatio&&_.display.pixelRatio){let a=_.display.pixelRatio;if(s.pixelRatioMultiplier)r*=s.pixelRatioMultiplier*(a-1)+1;else{let n=s.pixelRatioLogBase,[o=0,u=0,c=0]=s.pixelRatioLogCoefficients,d=mC(n,o*a+u)+c;Number.isFinite(d)&&(r*=d)}}return X(t==null?void 0:t.min)&&Mi(t.min,s.highQualityLimit)&&(r*=2),{containerSizeLimit:s.limitByContainer&&e&&e.width>0&&e.height>0?{width:e.width*r,height:e.height*r}:void 0,containerSizeFactor:r}},ey=new WeakMap,yt=(s,{container:e,estimatedThroughput:t,tuning:i,limits:r,reserve:a=0,forwardBufferHealth:n,playbackRate:o,current:u,history:c,visible:d,droppedVideoMaxQualityLimit:l,stallsVideoMaxQualityLimit:h,stallsPredictedThroughput:p,abrLogger:f,panelSize:m})=>{var F,Q,j,I,R;So(s,To);let{containerSizeFactor:g,containerSizeLimit:b}=ay({container:e,tuning:i,limits:r,panelSize:m}),S=i.considerPlaybackRate&&X(o)?o:1,T=ey.get(s);T||(T=s.filter(x=>!vo(x.quality)).sort((x,w)=>go(x.quality,w.quality)?-1:1),ey.set(s,T));let y=(F=(0,$e.default)(T,-1))==null?void 0:F.quality,E=(Q=(0,$e.default)(T,0))==null?void 0:Q.quality,A=yr(r,E,y),$=S*yo(n!=null?n:.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),L={},C=null;for(let x of T){let w=!0;if(b)if(x.size)w=x.size.width<=b.width&&x.size.height<=b.height;else{let Fe=b&&iy(b);w=Fe?Tr(x.quality,Fe):!0}if(!w){L[x.quality]="FitsContainer";continue}let V=p||t,G=X(V)&&isFinite(V)&&X(x.bitrate)?V-a>=x.bitrate*$:!0,lt=(r==null?void 0:r.min)===x.quality;if(!G&&!lt){L[x.quality]="FitsThroughput";continue}if(i.lazyQualitySwitch&&X(i.minBufferToSwitchUp)&&u&&!vo(u.quality)&&(n!=null?n:0)<i.minBufferToSwitchUp&&go(x.quality,u.quality)){L[x.quality]="Buffer";continue}if(!!l&&Mi(x.quality,l)&&!lt){L[x.quality]="DroppedFramesLimit";continue}if(!!h&&Mi(x.quality,h)&&!lt){L[x.quality]="StallsLimit";continue}let ge=A||(bo(r==null?void 0:r.max)||Tr(x.quality,r.max))&&(bo(r==null?void 0:r.min)||Mi(x.quality,r.min)),ve=X(d)&&!d?Tr(x.quality,i.backgroundVideoQualityLimit):!0;if(!ge||!ve){L[x.quality]="FitsQualityLimits";continue}C||(C=x)}C&&C.bitrate&&sy.next(C.bitrate);let P=(j=C!=null?C:(0,$e.default)(T,-1))!=null?j:s[0],B=c==null?void 0:c.last,M=Io(i,f,P,c);return X(c)&&M.quality!==(B==null?void 0:B.quality)&&f({message:`
|
|
10
10
|
[VIDEO TRACKS ABR]
|
|
11
11
|
[available video tracks]
|
|
12
|
-
${
|
|
12
|
+
${s.map(x=>{var w,V;return`{ id: ${x.id}, quality: ${x.quality}, bitrate: ${x.bitrate}, size: ${(w=x.size)==null?void 0:w.width}:${(V=x.size)==null?void 0:V.height} }`}).join(`
|
|
13
13
|
`)}
|
|
14
14
|
|
|
15
15
|
[tuning]
|
|
16
|
-
${(0,
|
|
16
|
+
${(0,Ci.default)(i!=null?i:{}).map(([x,w])=>`${x}: ${w}`).join(`
|
|
17
17
|
`)}
|
|
18
18
|
|
|
19
19
|
[limit params]
|
|
20
20
|
containerSizeFactor: ${g},
|
|
21
|
-
containerSizeLimit: ${(I=b==null?void 0:b.width)!=null?I:0} x ${(
|
|
21
|
+
containerSizeLimit: ${(I=b==null?void 0:b.width)!=null?I:0} x ${(R=b==null?void 0:b.height)!=null?R:0},
|
|
22
22
|
estimatedThroughput: ${t},
|
|
23
23
|
stallsPredictedThroughput: ${p},
|
|
24
|
-
reserve: ${
|
|
24
|
+
reserve: ${a},
|
|
25
25
|
playbackRate: ${o},
|
|
26
|
-
playbackRateFactor: ${
|
|
26
|
+
playbackRateFactor: ${S},
|
|
27
27
|
forwardBufferHealth: ${n},
|
|
28
|
-
bitrateFactor: ${
|
|
28
|
+
bitrateFactor: ${$},
|
|
29
29
|
minBufferToSwitchUp: ${i.minBufferToSwitchUp},
|
|
30
|
-
droppedVideoMaxQualityLimit: ${
|
|
30
|
+
droppedVideoMaxQualityLimit: ${l},
|
|
31
31
|
stallsVideoMaxQualityLimit: ${h},
|
|
32
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,Ci.default)(L).map(([x,w])=>`${x}: ${w}`).join(`
|
|
38
38
|
`)||"All tracks are available"}
|
|
39
39
|
|
|
40
|
-
[best video track] ${
|
|
40
|
+
[best video track] ${C==null?void 0:C.quality}
|
|
41
41
|
[selected video track] ${M==null?void 0:M.quality}
|
|
42
|
-
`}),M},
|
|
42
|
+
`}),M},Eo=(s,{container:e,estimatedThroughput:t,tuning:i,limits:r,reserve:a=0,forwardBufferHealth:n,playbackRate:o,current:u,history:c,visible:d,droppedVideoMaxQualityLimit:l,stallsVideoMaxQualityLimit:h,stallsPredictedThroughput:p,abrLogger:f,panelSize:m})=>{var Q,j,I,R,x;So(s,To);let{containerSizeFactor:g,containerSizeLimit:b}=ay({container:e,tuning:i,limits:r,panelSize:m}),S=i.considerPlaybackRate&&X(o)?o:1,T=s.filter(w=>!vo(w.quality)).sort((w,V)=>go(w.quality,V.quality)?-1:1),y=(Q=(0,$e.default)(T,-1))==null?void 0:Q.quality,E=(j=(0,$e.default)(T,0))==null?void 0:j.quality,A=yr(r,E,y),$=S*yo(n!=null?n:.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),L={},P=T.filter(w=>{let V=!0;if(b)if(w.size)V=w.size.width<=b.width&&w.size.height<=b.height;else{let wt=b&&iy(b);V=wt?Tr(w.quality,wt):!0}if(!V)return L[w.quality]="FitsContainer",!1;let G=p||t,lt=X(G)&&isFinite(G)&&X(w.bitrate)?G-a>=w.bitrate*$:!0,dt=(r==null?void 0:r.min)===w.quality;if(!lt&&!dt)return L[w.quality]="FitsThroughput",!1;if(i.lazyQualitySwitch&&X(i.minBufferToSwitchUp)&&u&&!vo(u.quality)&&(n!=null?n:0)<i.minBufferToSwitchUp&&go(w.quality,u.quality))return L[w.quality]="Buffer",!1;if(!!l&&Mi(w.quality,l)&&!dt)return L[w.quality]="DroppedFramesLimit",!1;if(!!h&&Mi(w.quality,h)&&!dt)return L[w.quality]="StallsLimit",!1;let ve=A||(bo(r==null?void 0:r.max)||Tr(w.quality,r.max))&&(bo(r==null?void 0:r.min)||Mi(w.quality,r.min)),Fe=X(d)&&!d?Tr(w.quality,i.backgroundVideoQualityLimit):!0;return!ve||!Fe?(L[w.quality]="FitsQualityLimits",!1):!0})[0];P&&P.bitrate&&sy.next(P.bitrate);let B=(I=P!=null?P:(0,$e.default)(T,-1))!=null?I:s[0],M=c==null?void 0:c.last,F=Io(i,f,B,c);return X(c)&&F.quality!==(M==null?void 0:M.quality)&&f({message:`
|
|
43
43
|
[VIDEO TRACKS ABR]
|
|
44
44
|
[available video tracks]
|
|
45
|
-
${
|
|
45
|
+
${s.map(w=>{var V,G;return`{ id: ${w.id}, quality: ${w.quality}, bitrate: ${w.bitrate}, size: ${(V=w.size)==null?void 0:V.width}:${(G=w.size)==null?void 0:G.height} }`}).join(`
|
|
46
46
|
`)}
|
|
47
47
|
|
|
48
48
|
[tuning]
|
|
49
|
-
${(0,
|
|
49
|
+
${(0,Ci.default)(i!=null?i:{}).map(([w,V])=>`${w}: ${V}`).join(`
|
|
50
50
|
`)}
|
|
51
51
|
|
|
52
52
|
[limit params]
|
|
53
53
|
containerSizeFactor: ${g},
|
|
54
|
-
containerSizeLimit: ${(
|
|
54
|
+
containerSizeLimit: ${(R=b==null?void 0:b.width)!=null?R:0} x ${(x=b==null?void 0:b.height)!=null?x:0},
|
|
55
55
|
estimatedThroughput: ${t},
|
|
56
56
|
stallsPredictedThroughput: ${p},
|
|
57
|
-
reserve: ${
|
|
57
|
+
reserve: ${a},
|
|
58
58
|
playbackRate: ${o},
|
|
59
|
-
playbackRateFactor: ${
|
|
59
|
+
playbackRateFactor: ${S},
|
|
60
60
|
forwardBufferHealth: ${n},
|
|
61
|
-
bitrateFactor: ${
|
|
61
|
+
bitrateFactor: ${$},
|
|
62
62
|
minBufferToSwitchUp: ${i.minBufferToSwitchUp},
|
|
63
|
-
droppedVideoMaxQualityLimit: ${
|
|
63
|
+
droppedVideoMaxQualityLimit: ${l},
|
|
64
64
|
stallsVideoMaxQualityLimit: ${h},
|
|
65
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,Ci.default)(L).map(([w,V])=>`${w}: ${V}`).join(`
|
|
71
71
|
`)||"All tracks are available"}
|
|
72
72
|
|
|
73
|
-
[best video track] ${
|
|
74
|
-
[selected video track] ${
|
|
75
|
-
`}),
|
|
73
|
+
[best video track] ${P==null?void 0:P.quality}
|
|
74
|
+
[selected video track] ${F==null?void 0:F.quality}
|
|
75
|
+
`}),F},xo=(s,e,t,{estimatedThroughput:i,tuning:r,playbackRate:a,forwardBufferHealth:n,history:o,abrLogger:u,stallsPredictedThroughput:c})=>{So(t,To);let d=r.considerPlaybackRate&&X(a)?a:1,l=[...t].sort(Ir(-1)),h=s.bitrate;ry(h);let p=d*yo(n!=null?n:.5,r.bitrateAudioFactorAtEmptyBuffer,r.bitrateAudioFactorAtFullBuffer),f,m=Vs(s,e,t,r.minVideoAudioRatio),g=c||i;X(g)&&isFinite(g)&&(f=l.find(T=>X(T.bitrate)&&X(m==null?void 0:m.bitrate)?g-h>=T.bitrate*p&&T.bitrate>=m.bitrate:!1)),f||(f=m);let b=o==null?void 0:o.last,S=f&&Io(r,u,f,o);return X(o)&&(S==null?void 0:S.bitrate)!==(b==null?void 0:b.bitrate)&&u({message:`
|
|
76
76
|
[AUDIO TRACKS ABR]
|
|
77
77
|
[available audio tracks]
|
|
78
78
|
${t.map(T=>`{ id: ${T.id}, bitrate: ${T.bitrate} }`).join(`
|
|
79
79
|
`)}
|
|
80
80
|
|
|
81
81
|
[tuning]
|
|
82
|
-
${(0,
|
|
82
|
+
${(0,Ci.default)(r!=null?r:{}).map(([T,y])=>`${T}: ${y}`).join(`
|
|
83
83
|
`)}
|
|
84
84
|
|
|
85
85
|
[limit params]
|
|
86
86
|
estimatedThroughput: ${i},
|
|
87
|
-
stallsPredictedThroughput: ${
|
|
87
|
+
stallsPredictedThroughput: ${c},
|
|
88
88
|
reserve: ${h},
|
|
89
|
-
playbackRate: ${
|
|
90
|
-
playbackRateFactor: ${
|
|
89
|
+
playbackRate: ${a},
|
|
90
|
+
playbackRateFactor: ${d},
|
|
91
91
|
forwardBufferHealth: ${n},
|
|
92
92
|
bitrateFactor: ${p},
|
|
93
93
|
minBufferToSwitchUp: ${r.minBufferToSwitchUp},
|
|
94
94
|
|
|
95
|
-
[selected audio track] ${
|
|
96
|
-
`}),
|
|
95
|
+
[selected audio track] ${S==null?void 0:S.id}
|
|
96
|
+
`}),S},wo=(s,e,t,{estimatedThroughput:i,tuning:r,playbackRate:a,forwardBufferHealth:n,history:o,abrLogger:u,stallsPredictedThroughput:c})=>{So(t,To);let d=r.considerPlaybackRate&&X(a)?a:1,l=XS.get(t);l||(l=[...t].sort(Ir(-1)),XS.set(t,l));let h=s.bitrate;ry(h);let p=d*yo(n!=null?n:.5,r.bitrateAudioFactorAtEmptyBuffer,r.bitrateAudioFactorAtFullBuffer),f,m=_s(s,e,t,r.minVideoAudioRatio),g=c||i;X(g)&&isFinite(g)&&(f=l.find(T=>X(T.bitrate)&&X(m==null?void 0:m.bitrate)?g-h>=T.bitrate*p&&T.bitrate>=m.bitrate:!1)),f||(f=m);let b=o==null?void 0:o.last,S=f&&Io(r,u,f,o);return X(o)&&(S==null?void 0:S.bitrate)!==(b==null?void 0:b.bitrate)&&u({message:`
|
|
97
97
|
[AUDIO TRACKS ABR]
|
|
98
98
|
[available audio tracks]
|
|
99
99
|
${t.map(T=>`{ id: ${T.id}, bitrate: ${T.bitrate} }`).join(`
|
|
100
100
|
`)}
|
|
101
101
|
|
|
102
102
|
[tuning]
|
|
103
|
-
${(0,
|
|
103
|
+
${(0,Ci.default)(r!=null?r:{}).map(([T,y])=>`${T}: ${y}`).join(`
|
|
104
104
|
`)}
|
|
105
105
|
|
|
106
106
|
[limit params]
|
|
107
107
|
estimatedThroughput: ${i},
|
|
108
|
-
stallsPredictedThroughput: ${
|
|
108
|
+
stallsPredictedThroughput: ${c},
|
|
109
109
|
reserve: ${h},
|
|
110
|
-
playbackRate: ${
|
|
111
|
-
playbackRateFactor: ${
|
|
110
|
+
playbackRate: ${a},
|
|
111
|
+
playbackRateFactor: ${d},
|
|
112
112
|
forwardBufferHealth: ${n},
|
|
113
113
|
bitrateFactor: ${p},
|
|
114
114
|
minBufferToSwitchUp: ${r.minBufferToSwitchUp},
|
|
115
115
|
|
|
116
|
-
[selected audio track] ${
|
|
117
|
-
`}),v};var ye=a=>new URL(a).hostname;import{assertNever as Xv,assertNonNullable as Jv,combine as JM,debounce as ZM,ErrorCategory as Zv,filter as ey,filterChanged as eD,isNonNullable as Cc,map as So,merge as ty,observableFrom as tD,once as iD,Subscription as rD,ValueSubject as Bc,videoQualityToHeight as iy,videoSizeToQuality as aD}from"@vkontakte/videoplayer-shared/es2018";var Gv=F(nt(),1);var Uv=F(De(),1),qv=a=>{if(a instanceof DOMException&&(0,Uv.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"))},Oe=async(a,e)=>{let t=a.muted;try{await a.play()}catch(i){if(!qv(i))return!1;if(e&&e(),t)return console.warn(i),!1;a.muted=!0;try{await a.play()}catch(r){return qv(r)&&(a.muted=!1,console.warn(r)),!1}}return!0};import{isNonNullable as bo,isNullable as CM,assertNonNullable as Da}from"@vkontakte/videoplayer-shared/es2018";var jv=F(Ii(),1);import{isNonNullable as Hv,assertNonNullable as mo,now as MM}from"@vkontakte/videoplayer-shared/es2018";function me(){return MM()}function Lc(a){return me()-a}function $c(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 Wv(a,e,t){let i=(...r)=>{t.apply(null,r),a.removeEventListener(e,i)};a.addEventListener(e,i)}function Ir(a,e,t,i){let r=window.XMLHttpRequest,s,n,o,u=!1,l=0,c,d,h=!1,p="arraybuffer",f=7e3,m=2e3,g=()=>{if(u)return;mo(c);let M=Lc(c),O;if(M<m){O=m-M,setTimeout(g,O);return}m*=2,m>f&&(m=f),n&&n.abort(),n=new r,A()},b=M=>(s=M,B),v=M=>(d=M,B),T=()=>(p="json",B),y=()=>{if(!u){if(--l>=0){g(),i&&i();return}u=!0,d&&d(),t&&t()}},E=M=>(h=M,B),A=()=>{c=me(),n=new r,n.open("get",a);let M=0,O,Q=0,H=()=>(mo(c),Math.max(c,Math.max(O||0,Q||0)));if(s&&n.addEventListener("progress",I=>{let P=me();s.updateChunk&&I.loaded>M&&(s.updateChunk(H(),I.loaded-M),M=I.loaded,O=P)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>y())),n.addEventListener("load",()=>{if(u)return;mo(n);let I=n.status;if(I>=200&&I<300){let{response:P,responseType:x}=n,w=P==null?void 0:P.byteLength;if(typeof w=="number"&&s){let V=w-M;V&&s.updateChunk&&s.updateChunk(H(),V)}x==="json"&&(!P||!(0,jv.default)(P).length)?y():(d&&d(),e(P))}else y()}),n.addEventListener("error",()=>{y()}),h){let I=()=>{mo(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(Q=me(),n.removeEventListener("readystatechange",I))};n.addEventListener("readystatechange",I)}return n.responseType=p,n.send(),B},B={withBitrateReporting:b,withParallel:E,withJSONResponse:T,withRetryCount:M=>(l=M,B),withRetryInterval:(M,O)=>(Hv(M)&&(m=M),Hv(O)&&(f=O),B),withTimeout:M=>(o=M,B),withFinally:v,send:A,abort:()=>{n&&(n.abort(),n=void 0),u=!0,d&&d()}};return B}var $a=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 Qv=F(Ii(),1);var Ma=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=me(),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=me()-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=Ir(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=me()}_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=me();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,Qv.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 BM}from"@vkontakte/videoplayer-shared/es2018";var go=1e4,Mc=3;var VM=6e4,_M=10,OM=1,FM=500,Ca=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 BM,this.chunkRateEstimator=new $a(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=$c(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=$c(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*(_.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||{};!$v({limits:this.autoQualityLimits,highestAvailableHeight:this.manifest[0].video.height,lowestAvailableHeight:(0,Gv.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||bo(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=()=>{Wv(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 Ma(Mc,go,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 y=s&&(!c||c===this.rep);return y||t("Not running!"),y},h=(y,E,A)=>{u&&u.abort(),u=Ir(this.urlResolver.resolve(y,!1),E,A,()=>this._retryCallback()).withTimeout(go).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Mc).withFinally(()=>{u=null}).send()},p=(y,E,A)=>{Da(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(y,!1),E,A,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},f=y=>{let E=i.playbackRate;i.playbackRate!==y&&(t(`Playback rate switch: ${E}=>${y}`),i.playbackRate=y)},m=y=>{this.lowLatency=y,t(`lowLatency changed to ${y}`),g()},g=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)f(1);else{let y=this._getBufferSizeSec();if(this.bufferStates.length<5){f(1);return}let A=me()-1e4,k=0;for(let D=0;D<this.bufferStates.length;D++){let R=this.bufferStates[D];y=Math.min(y,R.buf),R.ts<A&&k++}this.bufferStates.splice(0,k),t(`update playback rate; minBuffer=${y} drop=${k} jitter=${this.sourceJitter}`);let L=y-OM;this.sourceJitter>=0?L-=this.sourceJitter/2:this.sourceJitter-=1,L>3?f(1.15):L>1?f(1.1):L>.3?f(1.05):f(1)}},b=y=>{let E,A=()=>E&&E.start?E.start.length:0,k=I=>E.start[I]/1e3,L=I=>E.dur[I]/1e3,D=I=>E.fragIndex+I,R=(I,P)=>({chunkIdx:D(I),startTS:k(I),dur:L(I),discontinuity:P}),B=()=>{let I=0;if(E&&E.dur){let P=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,x=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,w=P;this.sourceJitter>1&&(w+=this.sourceJitter-1);let V=E.dur.length-1;for(;V>=0&&(w-=E.dur[V],!(w<=0));--V);I=Math.min(V,E.dur.length-1-x),I=Math.max(I,0)}return R(I,!0)},M=I=>{let P=A();if(!(P<=0)){if(bo(I)){for(let x=0;x<P;x++)if(k(x)>I)return R(x)}return B()}},O=I=>{let P=A(),x=I?I.chunkIdx+1:0,w=x-E.fragIndex;if(!(P<=0)){if(!I||w<0||w-P>_M)return t(`Resync: offset=${w} bChunks=${P} chunk=`+JSON.stringify(I)),B();if(!(w>=P))return R(x-E.fragIndex,!1)}},Q=(I,P,x)=>{l&&l.abort(),l=Ir(this.urlResolver.resolve(I,!0,this.lowLatency),P,x,()=>this._retryCallback()).withTimeout(go).withRetryCount(Mc).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(I,P)=>{Q(y,x=>{if(!d())return;E=x;let w=!!E.lowLatency;w!==this.lowLatency&&m(w);let V=0;for(let G=0;G<E.dur.length;++G)V+=E.dur[G];V>0&&(Da(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(V/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,I(M(P))},()=>this._handleNetworkError())},nextChunk:O}},v=()=>{s=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),Da(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:y=>{let{videoElement:E,logger:A}=this.params,k=b(e.jidxUrl),L,D,R,B,M=0,O,Q,H,I=()=>{O&&(clearTimeout(O),O=void 0);let Y=Math.max(FM,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),be=M+Y,ge=me(),Se=Math.min(1e4,be-ge);M=ge;let Fe=()=>{l||d()&&k.seek(()=>{d()&&(M=me(),P(),I())})};Se>0?O=window.setTimeout(()=>{this.paused?I():Fe()},Se):Fe()},P=()=>{let Y;for(;Y=k.nextChunk(B);)B=Y,ct(Y);let be=k.nextChunk(R);if(be){if(R&&be.discontinuity){A("Detected discontinuity; restarting playback"),this.paused?I():(v(),this._initPlayerWith(e));return}G(be)}else I()},x=(Y,be)=>{if(!d()||!this.sourceBuffer)return;let ge,Se,Fe,xt=Ot=>{window.setTimeout(()=>{d()&&x(Y,be)},Ot)};if(this.sourceBuffer.updating)A("Source buffer is updating; delaying appendBuffer"),xt(100);else{let Ot=me(),ci=E.currentTime;!this.paused&&E.buffered.length>1&&Q===ci&&Ot-H>500&&(A("Stall suspected; trying to fix"),this._fixupStall()),Q!==ci&&(Q=ci,H=Ot);let Qi=this._getBufferSizeSec();if(Qi>30)A(`Buffered ${Qi} seconds; delaying appendBuffer`),xt(2e3);else try{this.sourceBuffer.appendBuffer(Y),this.videoPlayStarted?(this.bufferStates.push({ts:Ot,buf:Qi}),g(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),be&&be()}catch(Gr){if(Gr.name==="QuotaExceededError")A("QuotaExceededError; delaying appendBuffer"),Fe=this.sourceBuffer.buffered.length,Fe!==0&&(ge=this.sourceBuffer.buffered.start(0),Se=ci,Se-ge>4&&this.sourceBuffer.remove(ge,Se-3)),xt(1e3);else throw Gr}}},w=()=>{D&&L&&(A([`Appending chunk, sz=${D.byteLength}:`,JSON.stringify(R)]),x(D,function(){D=null,P()}))},V=Y=>e.fragUrlTemplate.replace("%%id%%",Y.chunkIdx),G=Y=>{d()&&p(V(Y),(be,ge)=>{if(d()){if(ge/=1e3,D=be,R=Y,n=Y.startTS,ge){let Se=Math.min(10,Y.dur/ge);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*Se:Se}w()}},()=>this._handleNetworkError())},ct=Y=>{d()&&(Da(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(V(Y),!1)))},dt=Y=>{d()&&(e.cachedHeader=Y,x(Y,()=>{L=!0,w()}))};s=!0,k.seek(Y=>{if(d()){if(M=me(),!Y){I();return}B=Y,!CM(y)||Y.startTS>y?G(Y):(R=Y,P())}},y),e.cachedHeader?dt(e.cachedHeader):h(e.headerUrl,dt,()=>this._handleNetworkError())},stop:v,getTimestampSec:()=>n},c}_switchToQuality(e){let{logger:t,playerCallback:i}=this.params,r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),bo(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,Da(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return bo(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,i=d=>{if(!this.autoQuality)return;let h,p,f;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&d<this.bitrate&&(p=this._getBufferSizeSec(),f=d/this.bitrate,p>10&&f>.8||p>15&&f>.5||p>20&&f>.3)){e(`Not switching: buffer=${Math.floor(p)}; bitrate=${this.bitrate}; newRate=${Math.floor(d)}`);return}h=this._selectQuality(d),h?this._switchToQuality(h):e(`Could not find quality by bitrate ${d}`)},s={updateChunk:(h,p)=>{let f=me();if(this.chunkRateEstimator.addInterval(h,f,p)){let g=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:p,duration:f-h,speed:g}),!0}},get:()=>{let h=this.chunkRateEstimator.getBitRate();return h?h*.85:0}},n=-1/0,o,u=!0,l=()=>{let d=s.get();if(d&&o&&this.autoQuality){if(u&&d>o&&Lc(n)<3e4)return;i(d)}u=this.autoQuality};return{updateChunk:(d,h)=>{let p=s.updateChunk(d,h);return p&&l(),p},notifySwitch:d=>{let h=me();d<o&&(n=h),o=d}}}_fetchManifest(e,t,i){this.manifestRequest=Ir(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(go).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;Oe(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))},VM))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var Kv=F(nr(),1);import{debounce as NM,filter as zv,fromEvent as qM,interval as UM,isHigher as HM,isInvariantQuality as jM,isLower as WM,merge as QM,Subject as Yv,Subscription as GM}from"@vkontakte/videoplayer-shared/es2018";var Dc=class{constructor(){this.onDroopedVideoFramesLimit$=new Yv;this.subscription=new GM;this.playing=!1;this.tracks=[];this.forceChecker$=new Yv;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&&!jM(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&&HM(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(qM(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=UM(this.droppedFramesChecker.checkTime).pipe(zv(()=>this.playing),zv(()=>{let r=!!this.isForceCheckCounter;return r&&(this.isForceCheckCounter-=1),!r})),t=this.forceChecker$.pipe(NM(this.droppedFramesChecker.checkTime)),i=QM(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,Kv.default)(this.limitCounts).filter(([,s])=>s>=this.droppedFramesChecker.countLimit).sort(([s],[n])=>WM(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}},Er=Dc;import{map as zM,Observable as YM}from"@vkontakte/videoplayer-shared/es2018";import{fromEvent as KM}from"@vkontakte/videoplayer-shared/es2018";var Ba=()=>{var a;return!!((a=window.documentPictureInPicture)!=null&&a.window)||!!document.pictureInPictureElement};var XM=(a,e)=>new YM(t=>{if(!window.IntersectionObserver)return;let i={root:null},r=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||Ba()))},{...i,...e});r.observe(a);let s=KM(document,"visibilitychange").pipe(zM(n=>!document.hidden||Ba())).subscribe(n=>t.next(n));return()=>{r.unobserve(a),s.unsubscribe()}}),Ke=XM;var sD=["paused","playing","ready"],nD=["paused","playing","ready"],Va=class{constructor(e){this.subscription=new rD;this.videoState=new U("stopped");this.representations$=new Bc([]);this.droppedFramesManager=new Er;this.maxSeekBackTime$=new Bc(1/0);this.zeroTime$=new Bc(void 0);this.liveOffset=new Li;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:Zv.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:aD(u.video),d=u.bitrate/1e3,h={...u.video};if(!c)continue;let p={id:l,quality:c,bitrate:d,size:h};o.push({track:p,representation:u})}this.representations$.next(o),this.params.output.availableVideoTracks$.next(o.map(({track:u})=>u)),((r=this.videoState.getTransition())==null?void 0:r.to)==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let n=e.quality,o=(s=this.representations$.getValue().find(({representation:u})=>u===n))==null?void 0:s.track;this.params.output.hostname$.next(new URL(n.headerUrl,this.params.source.url).hostname),Cc(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,Vc.default)(nD,e)&&(n||o)){this.prepare();return}if((r==null?void 0:r.to)!=="paused"&&s.state==="requested"&&(0,Vc.default)(sD,e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(ne(this.params.source.url));return;case"manifest_ready":this.videoState.startTransitionTo("ready"),this.prepare();break;case"ready":if(i==="paused")this.videoState.setState("paused");else if(i==="playing"){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(ne(this.params.source.url,u))}return;default:return Xv(e)}};this.textTracksManager=new Ye(e.source.url),this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=r=>{e.output.error$.next({id:"DashLiveProvider",category:Zv.WTF,message:"DashLiveProvider internal logic error",thrown:r})};this.subscription.add(ty(this.videoState.stateChangeStarted$.pipe(So(r=>({transition:r,type:"start"}))),this.videoState.stateChangeEnded$.pipe(So(r=>({transition:r,type:"end"})))).subscribe(({transition:r,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(r)}`})})),this.video=Ce(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(ye(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);let i=_e(this.video);this.subscription.add(()=>i.destroy()),this.subscription.add(this.representations$.pipe(So(r=>r.map(({track:s})=>s)),ey(r=>!!r.length),iD()).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(eD(),So(r=>-r/1e3)).subscribe(this.params.output.duration$)).add(JM({zeroTime:this.zeroTime$.pipe(ey(Cc)),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(Ve(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(ze(this.video,this.params.desiredState.playbackRate,i.playbackRateState$,t)).add(i.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(i.loadedMetadata$.subscribe(this.params.output.loadedMetadataEvent$)).add(i.playing$.subscribe(this.params.output.firstFrameEvent$)).add(i.canplay$.subscribe(this.params.output.canplay$)).add(i.inPiP$.subscribe(this.params.output.inPiP$)).add(i.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(Ke(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:r,min:s}})=>{this.dash.setAutoQualityLimits({max:r&&iy(r),min:s&&iy(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 Xv(r.to)}},t)).add(ty(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,tD(["init"])).pipe(ZM(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),Be(this.video)}createLiveDashPlayer(){let e=new Ca({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,h,p,f;let e=this.representations$.getValue(),t=(c=(l=this.params.desiredState.videoTrack.getTransition())==null?void 0:l.to)!=null?c:this.params.desiredState.videoTrack.getState(),i=(h=(d=this.params.desiredState.autoVideoTrackSwitching.getTransition())==null?void 0:d.to)!=null?h:this.params.desiredState.autoVideoTrackSwitching.getState(),r=!i&&Cc(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=(f=e.find(({track:g})=>g.id===s))==null?void 0:f.representation;Jv(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;Jv(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(ne(this.params.source.url,n)),r&&this.dash.pause(),this.liveOffset.resetTo(n,r)}};var ry=Va;var Te=(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 JB,assertNonNullable as ZB,combine as e0,debounce as t0,ErrorCategory as yI,filter as Sd,filterChanged as Es,fromEvent as i0,isNonNullable as TI,isNullable as r0,map as xs,merge as ws,observableFrom as Go,once as II,Subscription as a0,throttle as s0}from"@vkontakte/videoplayer-shared/es2018";var{NativeAbortSignal:q1,NativeAbortController:U1}=function(a){return{NativeAbortSignal:a.AbortSignal,NativeAbortController:a.AbortController}}(typeof self!="undefined"?self:global);function ay(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 sy(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 vo=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}},xr=class extends vo{constructor(){super(),this.listeners||vo.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 Di;return setTimeout(()=>t.abort(new DOMException(`This signal is timeout in ${e}ms`,"TimeoutError")),e),t.signal}static any(e){let t=new Di;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}},Di=class{constructor(){Object.defineProperty(this,"signal",{value:new xr,writable:!0,configurable:!0})}abort(e){let t=sy(e),i=ay(t);this.signal.reason=t,this.signal.dispatchEvent(i)}toString(){return"[object AbortController]"}};typeof Symbol!="undefined"&&Symbol.toStringTag&&(Di.prototype[Symbol.toStringTag]="AbortController",xr.prototype[Symbol.toStringTag]="AbortSignal");function yo(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 _c(a){typeof a=="function"&&(a={fetch:a});let{fetch:e,Request:t=e.Request,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r=!1}=a;if(!yo({fetch:e,Request:t,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r}))return{fetch:e,Request:s};let s=t;(s&&!s.prototype.hasOwnProperty("signal")||r)&&(s=function(l,c){let d;c&&c.signal&&(d=c.signal,delete c.signal);let h=new t(l,c);return d&&Object.defineProperty(h,"signal",{writable:!1,enumerable:!1,configurable:!0,value:d}),h},s.prototype=t.prototype);let n=e;return{fetch:(u,l)=>{let c=s&&s.prototype.isPrototypeOf(u)?u.signal:l?l.signal:void 0;if(c){let d;try{d=new DOMException("Aborted","AbortError")}catch(p){d=new Error("Aborted"),d.name="AbortError"}if(c.aborted)return Promise.reject(d);let h=new Promise((p,f)=>{c.addEventListener("abort",()=>f(d),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([h,n(u,l)])}return n(u,l)},Request:s}}var oD=()=>"fetch"in window,_a=oD()&&yo({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),ny=_a?_c({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,Xe=_a?ny.fetch:window.fetch,J1=_a?ny.Request:window.Request,J=_a?Di:window.AbortController,Z1=_a?xr:window.AbortSignal;var fI=F(De(),1),pd=F(Oa(),1);var Qy=F(Wy(),1);import{ErrorCategory as Na}from"@vkontakte/videoplayer-shared/es2018";var To=a=>{if(!a)return{id:"EmptyResponse",category:Na.PARSER,message:"Empty response"};if(a.length<=2&&a.match(/^\d+$/))return{id:`UVError#${a}`,category:Na.NETWORK,message:`UV Error ${a}`};let e=(0,Qy.default)(a).substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:Na.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:Na.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:Na.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 ld,assertNonNullable as Br,combine as Vr,ErrorCategory as Je,filter as No,filterChanged as vs,flattenObject as ys,fromEvent as Bt,getTraceSubscriptionMethod as MB,interval as cd,isNonNullable as Ts,isNullable as dI,map as _r,merge as Oi,now as dd,Subject as ri,Subscription as pI,SubscriptionRemovable as DB,tap as CB,throttle as BB,ValueSubject as ie}from"@vkontakte/videoplayer-shared/es2018";var wo=F(De(),1),_i=F(nt(),1),Ao=F(Oa(),1);var QD=(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)},GD=a=>window.clearTimeout(a),Gy=a=>typeof a=="function"&&(a==null?void 0:a.toString().endsWith("{ [native code] }")),zy=!Gy(window.requestIdleCallback)||!Gy(window.cancelIdleCallback),wr=zy?QD:window.requestIdleCallback,yt=zy?GD:window.cancelIdleCallback;var aI=F(Wn(),1);import{assertNever as zD,ErrorCategory as Yy,Subject as Ky}from"@vkontakte/videoplayer-shared/es2018";var YD=18,Xy=!1;try{Xy=_.browser.isSafari&&!!_.browser.safariVersion&&_.browser.safariVersion<=YD}catch(a){console.error(a)}var Hc=class{constructor(e){this.bufferFull$=new Ky;this.error$=new Ky;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:Yy.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)};Xy&&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:Yy.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:zD(t)}}},Jy=Hc;var Ar=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 ke,ErrorCategory as Mt,fromEvent as rd,getExponentialDelay as ad,isHigher as gB,isNonNullable as ei,isNullable as ce,now as xo,once as SB,Subject as vB,Subscription as yB,ValueSubject as Vi}from"@vkontakte/videoplayer-shared/es2018";var Zy=F(nt(),1);var Io=a=>a.valid,j=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let i=this.readUint32();this.type=this.readString(4),i===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 Rr=class extends j{};import{assertNever as KD}from"@vkontakte/videoplayer-shared/es2018";var qa=class extends j{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:KD(e)}}};var Ua=class extends j{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 Ha=class extends j{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var te=class extends j{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 ja=class extends te{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 Wa=class extends j{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Qa=class extends j{constructor(e,t){super(e,t),this.data=this.content}};var Ci=class extends te{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 Ga=class extends j{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var za=class extends j{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ya=class extends te{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 Ka=class extends te{constructor(e,t){super(e,t),this.valid&&(this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32())}};var Xa=class extends te{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 Ja=class extends j{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Za=class extends te{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 es=class extends j{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ts=class extends j{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var is=class extends te{constructor(e,t){super(e,t),this.valid&&(this.sequenceNumber=this.readUint32())}};var rs=class extends j{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var as=class extends te{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 ss=class extends te{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 ns=class extends te{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 os=class extends j{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var us=class extends te{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 ls=class extends j{constructor(e,t){super(e,t),this.valid&&(this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+78,this.content.byteLength-78)))}};var JD={ftyp:Ua,moov:Ha,mvhd:ja,moof:Wa,mdat:Qa,sidx:Ci,trak:Ga,mdia:Ja,mfhd:is,tkhd:Za,traf:rs,tfhd:as,tfdt:ss,trun:ns,minf:es,sv3d:za,st3d:Ya,prhd:Ka,proj:ts,equi:Xa,uuid:qa,stbl:os,stsd:us,avc1:ls,unknown:Rr},$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||!Io(n))break;t.push(n),i+=n.size}return t}createBox(e,t){let i=JD[e];return i?new i(t,new a):new Rr(t,new a)}};var Jt=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{var i,r,s;Io(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 eC=new TextDecoder("ascii"),tC=a=>eC.decode(new DataView(a.buffer,a.byteOffset+4,4))==="ftyp",iC=a=>{let e=new Ci(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})},rC=(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)},aC=a=>{let t=new $t().parse(a),i=new Jt(t),r={},s=i.findAll("uuid"),n=(0,Zy.default)(s,-1);return n?{serverDataReceivedTimestamp:n.userData.received,serverDataPreparedTime:n.userData.received}:r},sC=a=>{var r;let t=new $t().parse(a);return(r=new Jt(t).find("sidx"))==null?void 0:r.timescale},nC=(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,h)=>d+h,0):l=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+l)/e*1e3},oC=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},eT={validateData:tC,parseInit:oC,getIndexRange:()=>{},parseSegments:iC,parseFeedableSegmentChunk:rC,getChunkEndTime:nC,getServerLatencyTimestamps:aC,getTimescaleFromIndex:sC};var ps=F(De(),1);import{assertNonNullable as jc,isNonNullable as aT,isNullable as lC}from"@vkontakte/videoplayer-shared/es2018";import{assertNever as uC}from"@vkontakte/videoplayer-shared/es2018";var tT={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"}},iT=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=ds(a,t),r=i in tT,s=r?tT[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=ds(u),d=l*2**((o-1)*8)+c,h=t+o,p;return h+d>a.byteLength?p=new DataView(a.buffer,a.byteOffset+h):p=new DataView(a.buffer,a.byteOffset+h,d),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:s,tagHeaderSize:h,tagSize:h+d,value:p,valueSize:d}},ds=(a,e=a.byteLength)=>{switch(e){case 1:return a.getUint8(0);case 2:return a.getUint16(0);case 3:return a.getUint8(0)*2**16+a.getUint16(1);case 4:return a.getUint32(0);case 5:return a.getUint8(0)*2**32+a.getUint32(1);case 6:return a.getUint16(0)*2**32+a.getUint32(2);case 7:{let t=a.getUint8(0)*281474976710656+a.getUint16(1)*4294967296+a.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},ot=(a,e)=>{switch(e){case"int":return a.getInt8(0);case"uint":return ds(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:uC(e)}},Bi=(a,e)=>{let t=0;for(;t<a.byteLength;){let i=new DataView(a.buffer,a.byteOffset+t),r=iT(i);if(!e(r))return;r.type==="master"&&Bi(r.value,e),t=r.value.byteOffset-a.byteOffset+r.valueSize}},rT=a=>{if(a.getUint32(0)!==440786851)return!1;let e,t,i,r=iT(a);return Bi(r.value,({tag:s,type:n,value:o})=>(s===17143?e=ot(o,n):s===17026?t=ot(o,n):s===17029&&(i=ot(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)};var sT=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],cC=[231,22612,22743,167,171,163,160,175],dC=a=>{let e,t,i,r,s=!1,n=!1,o=!1,u,l,c=!1,d=0;return Bi(a,({tag:h,type:p,value:f,valueSize:m})=>{if(h===21419){let g=ot(f,p);l=ds(g)}else h!==21420&&(l=void 0);return h===408125543?(e=f.byteOffset,t=f.byteOffset+m):h===357149030?s=!0:h===290298740?n=!0:h===2807729?i=ot(f,p):h===17545?r=ot(f,p):h===21420&&l===475249515?u=ot(f,p):h===374648427?Bi(f,({tag:g,type:b,value:v})=>g===30321?(c=ot(v,b)===1,!1):!0):s&&n&&(0,ps.default)(sT,h)&&(o=!0),!o}),jc(e,"Failed to parse webm Segment start"),jc(t,"Failed to parse webm Segment end"),jc(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}}}},pC=a=>{if(lC(a.cuesSeekPosition))return;let e=a.segmentStart+a.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},hC=(a,e)=>{let t=!1,i=!1,r=o=>aT(o.time)&&aT(o.position),s=[],n;return Bi(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=ot(l,u));break;case 183:break;case 241:n&&(n.position=ot(l,u));break;default:t&&(0,ps.default)(sT,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}}})},fC=a=>{let e=0,t=!1;try{Bi(a,i=>i.tag===524531317?i.tagSize<=a.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):(0,ps.default)(cC,i.tag)?(e+i.tagSize<=a.byteLength&&(e+=i.tagSize,t||(t=(0,ps.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},nT={validateData:rT,parseInit:dC,getIndexRange:pC,parseSegments:hC,parseFeedableSegmentChunk:fC};var Tt=a=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(a);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return nT;case"mp4":return eT}}throw new ReferenceError(`Unsupported mime type ${a}`)};var It=a=>a instanceof DOMException&&(a.name==="AbortError"||a.code===20);var Xc=F(kT(),1),XT=F(nr(),1),JT=F(WT(),1),ZT=F(nt(),1),Jc=F(Ii(),1);var QT=F(De(),1),Kc=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,QT.default)(["6E","7A","F4"],o)}}return!1};import{isNonNullable as fB,isNullable as YT}from"@vkontakte/videoplayer-shared/es2018";var GT=a=>{if(a.includes("/")){let e=a.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(a)};var zT=a=>{var e;try{let t=hB(),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 hB(){let a="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",c=`^(?:(?<langtag>${`
|
|
118
|
-
(?<language>${`(?:[a-z]{2,3}(?:-${
|
|
116
|
+
[selected audio track] ${S==null?void 0:S.id}
|
|
117
|
+
`}),S};var ye=s=>new URL(s).hostname;import{assertNever as by,assertNonNullable as gy,combine as VC,debounce as _C,ErrorCategory as vy,filter as Sy,filterChanged as OC,isNonNullable as Gl,map as ko,merge as yy,observableFrom as FC,once as NC,Subscription as qC,ValueSubject as zl,videoQualityToHeight as Ty,videoSizeToQuality as UC}from"@vkontakte/videoplayer-shared/es2018";var py=O(nt(),1);var oy=O(Ae(),1),ny=s=>{if(s instanceof DOMException&&(0,oy.default)(["Failed to load because no supported source was found.","The element has no supported sources."],s.message))throw s;return!(s instanceof DOMException&&(s.code===20||s.name==="AbortError"))},Oe=async(s,e)=>{let t=s.muted;try{await s.play()}catch(i){if(!ny(i))return!1;if(e&&e(),t)return console.warn(i),!1;s.muted=!0;try{await s.play()}catch(r){return ny(r)&&(s.muted=!1,console.warn(r)),!1}}return!0};import{isNonNullable as Po,isNullable as vC,assertNonNullable as Ns}from"@vkontakte/videoplayer-shared/es2018";var cy=O(Ei(),1);import{isNonNullable as uy,assertNonNullable as Ao,now as bC}from"@vkontakte/videoplayer-shared/es2018";function me(){return bC()}function jl(s){return me()-s}function Hl(s){let e=s.split("/"),t=e.slice(0,e.length-1).join("/"),i=/^([a-z]+:)?\/\//i,r=n=>i.test(n);return{resolve:(n,o,u=!1)=>{r(n)||(n.startsWith("/")||(n="/"+n),n=t+n);let c=n.indexOf("?")>-1?"&":"?";return u&&(n+=c+"lowLat=1",c="&"),o&&(n+=c+"_rnd="+Math.floor(999999999*Math.random())),n}}}function ly(s,e,t){let i=(...r)=>{t.apply(null,r),s.removeEventListener(e,i)};s.addEventListener(e,i)}function Er(s,e,t,i){let r=window.XMLHttpRequest,a,n,o,u=!1,c=0,d,l,h=!1,p="arraybuffer",f=7e3,m=2e3,g=()=>{if(u)return;Ao(d);let M=jl(d),F;if(M<m){F=m-M,setTimeout(g,F);return}m*=2,m>f&&(m=f),n&&n.abort(),n=new r,A()},b=M=>(a=M,B),S=M=>(l=M,B),T=()=>(p="json",B),y=()=>{if(!u){if(--c>=0){g(),i&&i();return}u=!0,l&&l(),t&&t()}},E=M=>(h=M,B),A=()=>{d=me(),n=new r,n.open("get",s);let M=0,F,Q=0,j=()=>(Ao(d),Math.max(d,Math.max(F||0,Q||0)));if(a&&n.addEventListener("progress",I=>{let R=me();a.updateChunk&&I.loaded>M&&(a.updateChunk(j(),I.loaded-M),M=I.loaded,F=R)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>y())),n.addEventListener("load",()=>{if(u)return;Ao(n);let I=n.status;if(I>=200&&I<300){let{response:R,responseType:x}=n,w=R==null?void 0:R.byteLength;if(typeof w=="number"&&a){let V=w-M;V&&a.updateChunk&&a.updateChunk(j(),V)}x==="json"&&(!R||!(0,cy.default)(R).length)?y():(l&&l(),e(R))}else y()}),n.addEventListener("error",()=>{y()}),h){let I=()=>{Ao(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(Q=me(),n.removeEventListener("readystatechange",I))};n.addEventListener("readystatechange",I)}return n.responseType=p,n.send(),B},B={withBitrateReporting:b,withParallel:E,withJSONResponse:T,withRetryCount:M=>(c=M,B),withRetryInterval:(M,F)=>(uy(M)&&(m=M),uy(F)&&(f=F),B),withTimeout:M=>(o=M,B),withFinally:S,send:A,abort:()=>{n&&(n.abort(),n=void 0),u=!0,l&&l()}};return B}var Os=class{constructor(e){this.intervals=[];this.currentRate=0;this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,i){return{start:e,end:t,bytes:i}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;let e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-500;if(t-e>2e3){let i=0,r=0;for(;this.intervals.length>0;){let a=this.intervals[0];if(a.end<=t)i+=a.end-a.start,r+=a.bytes,this.intervals.splice(0,1);else{if(a.start>=t)break;{let n=t-a.start,o=a.end-a.start;i+=n;let u=a.bytes*n/o;r+=u,a.start=t,a.bytes-=u}}}if(r>0&&i>0){let a=r*8/(i/1e3);return this._updateRate(a),this.logger(`rate updated, new=${Math.round(a/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(r)}/${Math.round(i)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,i){return this.intervals.push(this._createInterval(e,t,i)),this._joinIntervals(),this.intervals.length>100&&(this.logger(`too many intervals (${this.intervals.length}); will merge`,{type:"warn"}),this._doMergeIntervals(this.intervals[1],this.intervals[0]),this.intervals.splice(0,1)),this._flushIntervals()}getBitRate(){return this.currentRate}};var dy=O(Ei(),1);var Fs=class{constructor(e,t,i,r,a){this.pendingQueue=[];this.activeRequests={};this.completeRequests={};this.averageSegmentDuration=2e3;this.lastPrefetchStart=0;this.throttleTimeout=null;this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=i,this.MAX_PARALLEL_REQUESTS=r,this.logger=a}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){let t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){let i=me(),r=u=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=u,e._errorCB?e._errorCB(u):(this.limitCompleteCount(),this.completeRequests[t]=e)},a=u=>{e._complete=1,e._responseData=u,e._downloadTime=me()-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=Er(t,a,()=>r("error"),o),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(n),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=me()}_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=me();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,dy.default)(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,i,r){let a={};return a.send=()=>{let n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=i,n._retryCB=r,n._finallyCB=a._finallyCB,n._error||n._complete?(this._removeFromActive(e),setTimeout(()=>{n._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(n._responseData,n._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),i(n._errorMsg)),a._finallyCB&&a._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{let o=this.pendingQueue.indexOf(e);o!==-1&&this.pendingQueue.splice(o,1),this.logger(`Request not prefetched, starting new request, url=${e}${o===-1?"":"; removed pending"}`),this._sendRequest(a,e)}},a._cb=t,a._errorCB=i,a._retryCB=r,a.abort=function(){a.request&&a.request.abort()},a.withFinally=n=>(a._finallyCB=n,a),a}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}};import{Subject as SC}from"@vkontakte/videoplayer-shared/es2018";var Ro=1e4,Wl=3;var yC=6e4,TC=10,IC=1,EC=500,qs=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 SC,this.chunkRateEstimator=new Os(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=Hl(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=Hl(e),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){let e=this.params.videoElement,t=0,i=e.buffered.length;return i!==0&&(t=e.buffered.end(i-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){let{videoElement:e,logger:t}=this.params;e.addEventListener("error",()=>{var r,a;!!e.error&&!this.destroyed&&(t(`Video element error: ${(r=e.error)==null?void 0:r.code}, details: ${(a=e.error)==null?void 0:a.message}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{let i=this._getBufferSizeSec();!this.paused&&i<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(i+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){let{logger:e,videoElement:t}=this.params,i=t.buffered.length,r;i!==0&&!this.waitingForFirstBufferAfterSrcChange&&(r=t.buffered.start(i-1),t.currentTime<r&&(e("Fixup stall"),t.currentTime=r))}_selectQuality(e){let{videoElement:t}=this.params,i,r,a,n=t&&1.62*(_.display.pixelRatio||1)*t.offsetHeight||520;for(let o=0;o<this.manifest.length;++o){a=this.manifest[o];let{max:u,min:c}=this.autoQualityLimits||{};!KS({limits:this.autoQualityLimits,highestAvailableHeight:this.manifest[0].video.height,lowestAvailableHeight:(0,py.default)(this.manifest,-1).video.height})&&(u&&a.video.height>u||c&&a.video.height<c)||(a.bitrate<e&&n>Math.min(a.video.height,a.video.width)?(!r||a.bitrate>r.bitrate)&&(r=a):(!i||i.bitrate>a.bitrate)&&(i=a))}return r||i}shouldPlay(){if(this.paused)return!1;let t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||Po(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){let{logger:i,videoElement:r,playerCallback:a}=this.params;this.mediaSource=new window.MediaSource,i("setting video src"),r.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,r.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});let n=()=>{ly(r,"progress",()=>{r.buffered.length?(r.currentTime=r.buffered.start(0),this.waitingForFirstBufferAfterSrcChange=!1,a({name:"playing"})):n()})};this.waitingForFirstBufferAfterSrcChange=!0,n()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new Fs(Wl,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,a=!1,n=null,o=null,u=null,c=null,d=!1,l=()=>{let y=a&&(!d||d===this.rep);return y||t("Not running!"),y},h=(y,E,A)=>{u&&u.abort(),u=Er(this.urlResolver.resolve(y,!1),E,A,()=>this._retryCallback()).withTimeout(Ro).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Wl).withFinally(()=>{u=null}).send()},p=(y,E,A)=>{Ns(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(y,!1),E,A,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},f=y=>{let E=i.playbackRate;i.playbackRate!==y&&(t(`Playback rate switch: ${E}=>${y}`),i.playbackRate=y)},m=y=>{this.lowLatency=y,t(`lowLatency changed to ${y}`),g()},g=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)f(1);else{let y=this._getBufferSizeSec();if(this.bufferStates.length<5){f(1);return}let A=me()-1e4,$=0;for(let C=0;C<this.bufferStates.length;C++){let P=this.bufferStates[C];y=Math.min(y,P.buf),P.ts<A&&$++}this.bufferStates.splice(0,$),t(`update playback rate; minBuffer=${y} drop=${$} jitter=${this.sourceJitter}`);let L=y-IC;this.sourceJitter>=0?L-=this.sourceJitter/2:this.sourceJitter-=1,L>3?f(1.15):L>1?f(1.1):L>.3?f(1.05):f(1)}},b=y=>{let E,A=()=>E&&E.start?E.start.length:0,$=I=>E.start[I]/1e3,L=I=>E.dur[I]/1e3,C=I=>E.fragIndex+I,P=(I,R)=>({chunkIdx:C(I),startTS:$(I),dur:L(I),discontinuity:R}),B=()=>{let I=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 V=E.dur.length-1;for(;V>=0&&(w-=E.dur[V],!(w<=0));--V);I=Math.min(V,E.dur.length-1-x),I=Math.max(I,0)}return P(I,!0)},M=I=>{let R=A();if(!(R<=0)){if(Po(I)){for(let x=0;x<R;x++)if($(x)>I)return P(x)}return B()}},F=I=>{let R=A(),x=I?I.chunkIdx+1:0,w=x-E.fragIndex;if(!(R<=0)){if(!I||w<0||w-R>TC)return t(`Resync: offset=${w} bChunks=${R} chunk=`+JSON.stringify(I)),B();if(!(w>=R))return P(x-E.fragIndex,!1)}},Q=(I,R,x)=>{c&&c.abort(),c=Er(this.urlResolver.resolve(I,!0,this.lowLatency),R,x,()=>this._retryCallback()).withTimeout(Ro).withRetryCount(Wl).withFinally(()=>{c=null}).withJSONResponse().send()};return{seek:(I,R)=>{Q(y,x=>{if(!l())return;E=x;let w=!!E.lowLatency;w!==this.lowLatency&&m(w);let V=0;for(let G=0;G<E.dur.length;++G)V+=E.dur[G];V>0&&(Ns(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(V/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,I(M(R))},()=>this._handleNetworkError())},nextChunk:F}},S=()=>{a=!1,o&&o.abort(),u&&u.abort(),c&&c.abort(),Ns(this.filesFetcher),this.filesFetcher.abortAll()};return d={start:y=>{let{videoElement:E,logger:A}=this.params,$=b(e.jidxUrl),L,C,P,B,M=0,F,Q,j,I=()=>{F&&(clearTimeout(F),F=void 0);let Y=Math.max(EC,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),be=M+Y,ge=me(),ve=Math.min(1e4,be-ge);M=ge;let Fe=()=>{c||l()&&$.seek(()=>{l()&&(M=me(),R(),I())})};ve>0?F=window.setTimeout(()=>{this.paused?I():Fe()},ve):Fe()},R=()=>{let Y;for(;Y=$.nextChunk(B);)B=Y,lt(Y);let be=$.nextChunk(P);if(be){if(P&&be.discontinuity){A("Detected discontinuity; restarting playback"),this.paused?I():(S(),this._initPlayerWith(e));return}G(be)}else I()},x=(Y,be)=>{if(!l()||!this.sourceBuffer)return;let ge,ve,Fe,wt=Nt=>{window.setTimeout(()=>{l()&&x(Y,be)},Nt)};if(this.sourceBuffer.updating)A("Source buffer is updating; delaying appendBuffer"),wt(100);else{let Nt=me(),di=E.currentTime;!this.paused&&E.buffered.length>1&&Q===di&&Nt-j>500&&(A("Stall suspected; trying to fix"),this._fixupStall()),Q!==di&&(Q=di,j=Nt);let Gi=this._getBufferSizeSec();if(Gi>30)A(`Buffered ${Gi} seconds; delaying appendBuffer`),wt(2e3);else try{this.sourceBuffer.appendBuffer(Y),this.videoPlayStarted?(this.bufferStates.push({ts:Nt,buf:Gi}),g(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),be&&be()}catch(zr){if(zr.name==="QuotaExceededError")A("QuotaExceededError; delaying appendBuffer"),Fe=this.sourceBuffer.buffered.length,Fe!==0&&(ge=this.sourceBuffer.buffered.start(0),ve=di,ve-ge>4&&this.sourceBuffer.remove(ge,ve-3)),wt(1e3);else throw zr}}},w=()=>{C&&L&&(A([`Appending chunk, sz=${C.byteLength}:`,JSON.stringify(P)]),x(C,function(){C=null,R()}))},V=Y=>e.fragUrlTemplate.replace("%%id%%",Y.chunkIdx),G=Y=>{l()&&p(V(Y),(be,ge)=>{if(l()){if(ge/=1e3,C=be,P=Y,n=Y.startTS,ge){let ve=Math.min(10,Y.dur/ge);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*ve:ve}w()}},()=>this._handleNetworkError())},lt=Y=>{l()&&(Ns(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(V(Y),!1)))},dt=Y=>{l()&&(e.cachedHeader=Y,x(Y,()=>{L=!0,w()}))};a=!0,$.seek(Y=>{if(l()){if(M=me(),!Y){I();return}B=Y,!vC(y)||Y.startTS>y?G(Y):(P=Y,R())}},y),e.cachedHeader?dt(e.cachedHeader):h(e.headerUrl,dt,()=>this._handleNetworkError())},stop:S,getTimestampSec:()=>n},d}_switchToQuality(e){let{logger:t,playerCallback:i}=this.params,r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),Po(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,Ns(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return Po(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,i=l=>{if(!this.autoQuality)return;let h,p,f;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&l<this.bitrate&&(p=this._getBufferSizeSec(),f=l/this.bitrate,p>10&&f>.8||p>15&&f>.5||p>20&&f>.3)){e(`Not switching: buffer=${Math.floor(p)}; bitrate=${this.bitrate}; newRate=${Math.floor(l)}`);return}h=this._selectQuality(l),h?this._switchToQuality(h):e(`Could not find quality by bitrate ${l}`)},a={updateChunk:(h,p)=>{let f=me();if(this.chunkRateEstimator.addInterval(h,f,p)){let g=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:p,duration:f-h,speed:g}),!0}},get:()=>{let h=this.chunkRateEstimator.getBitRate();return h?h*.85:0}},n=-1/0,o,u=!0,c=()=>{let l=a.get();if(l&&o&&this.autoQuality){if(u&&l>o&&jl(n)<3e4)return;i(l)}u=this.autoQuality};return{updateChunk:(l,h)=>{let p=a.updateChunk(l,h);return p&&c(),p},notifySwitch:l=>{let h=me();l<o&&(n=h),o=l}}}_fetchManifest(e,t,i){this.manifestRequest=Er(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;Oe(e,()=>{this.soundProhibitedEvent$.next()}).then(t=>{t||(this.params.liveOffset.pause(),this.params.videoState.setState("paused"))})}_handleManifestUpdate(e){let{logger:t,playerCallback:i,videoElement:r}=this.params,a=n=>{let o=[];return n!=null&&n.length?(n.forEach((u,c)=>{var d,l;u.video&&r.canPlayType(u.codecs).replace(/no/,"")&&((l=(d=window.MediaSource)==null?void 0:d.isTypeSupported)!=null&&l.call(d,u.codecs))&&(u.index=c,o.push(u))}),o.sort(function(u,c){return u.video&&c.video?c.video.height-u.video.height:c.bitrate-u.bitrate}),o):(i({name:"error",type:"empty_manifest"}),[])};this.manifest=a(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),i({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},yC))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var my=O(cr(),1);import{debounce as xC,filter as hy,fromEvent as wC,interval as AC,isHigher as PC,isInvariantQuality as RC,isLower as kC,merge as $C,Subject as fy,Subscription as LC}from"@vkontakte/videoplayer-shared/es2018";var Ql=class{constructor(){this.onDroopedVideoFramesLimit$=new fy;this.subscription=new LC;this.playing=!1;this.tracks=[];this.forceChecker$=new fy;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&&!RC(e.quality)&&this.onChangeQuality(e.quality)};this.checkDroppedFrames=()=>{var n;let{totalVideoFrames:e,droppedVideoFrames:t}=this.video.getVideoPlaybackQuality(),i=e-this.prevTotalVideoFrames,r=t-this.prevDroppedVideoFrames,a=1-(i-r)/i;!isNaN(a)&&a>0&&this.log({message:`[dropped]. current dropped percent: ${a}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(a)&&a>=this.droppedFramesChecker.percentLimit&&PC(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(wC(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=AC(this.droppedFramesChecker.checkTime).pipe(hy(()=>this.playing),hy(()=>{let r=!!this.isForceCheckCounter;return r&&(this.isForceCheckCounter-=1),!r})),t=this.forceChecker$.pipe(xC(this.droppedFramesChecker.checkTime)),i=$C(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,my.default)(this.limitCounts).filter(([,a])=>a>=this.droppedFramesChecker.countLimit).sort(([a],[n])=>kC(a,n)?-1:1))==null?void 0:i[0])==null?void 0:r[0];return e!=null?e:t}get isEnabled(){return this.droppedFramesChecker.enabled&&this.isDroppedFramesCheckerSupport}get isDroppedFramesCheckerSupport(){return!!this.video&&typeof this.video.getVideoPlaybackQuality=="function"}savePrevFrameCounts(e,t){this.prevTotalVideoFrames=e,this.prevDroppedVideoFrames=t}},xr=Ql;import{map as MC,Observable as CC}from"@vkontakte/videoplayer-shared/es2018";import{fromEvent as DC}from"@vkontakte/videoplayer-shared/es2018";var Us=()=>{var s;return!!((s=window.documentPictureInPicture)!=null&&s.window)||!!document.pictureInPictureElement};var BC=(s,e)=>new CC(t=>{if(!window.IntersectionObserver)return;let i={root:null},r=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||Us()))},{...i,...e});r.observe(s);let a=DC(document,"visibilitychange").pipe(MC(n=>!document.hidden||Us())).subscribe(n=>t.next(n));return()=>{r.unobserve(s),a.unsubscribe()}}),Ke=BC;var jC=["paused","playing","ready"],HC=["paused","playing","ready"],js=class{constructor(e){this.subscription=new qC;this.videoState=new U("stopped");this.representations$=new zl([]);this.droppedFramesManager=new xr;this.maxSeekBackTime$=new zl(1/0);this.zeroTime$=new zl(void 0);this.liveOffset=new Li;this._dashCb=e=>{var t,i,r,a;switch(e.name){case"buffering":{let n=e.isBuffering;this.params.output.isBuffering$.next(n);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,category:vy.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{let n=e.manifest,o=[];for(let u of n){let c=(t=u.name)!=null?t:u.index.toString(10),d=(i=Jt(u.name))!=null?i:UC(u.video),l=u.bitrate/1e3,h={...u.video};if(!d)continue;let p={id:c,quality:d,bitrate:l,size:h};o.push({track:p,representation:u})}this.representations$.next(o),this.params.output.availableVideoTracks$.next(o.map(({track:u})=>u)),((r=this.videoState.getTransition())==null?void 0:r.to)==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let n=e.quality,o=(a=this.representations$.getValue().find(({representation:u})=>u===n))==null?void 0:a.track;this.params.output.hostname$.next(new URL(n.headerUrl,this.params.source.url).hostname),Gl(o)&&this.params.output.currentVideoTrack$.next(o);break}case"bandwidth":{let{size:n,duration:o}=e;this.params.dependencies.throughputEstimator.addRawSpeed(n,o);break}case"index":{this.maxSeekBackTime$.next(e.shiftDuration||0),this.zeroTime$.next(e.zeroTime);break}}};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; seekState: ${JSON.stringify(a)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"));return}if(t)return;let n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if((0,Yl.default)(HC,e)&&(n||o)){this.prepare();return}if((r==null?void 0:r.to)!=="paused"&&a.state==="requested"&&(0,Yl.default)(jC,e)){this.seek(a.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(ne(this.params.source.url));return;case"manifest_ready":this.videoState.startTransitionTo("ready"),this.prepare();break;case"ready":if(i==="paused")this.videoState.setState("paused");else if(i==="playing"){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(ne(this.params.source.url,u))}return;default:return by(e)}};this.textTracksManager=new Ye(e.source.url),this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=r=>{e.output.error$.next({id:"DashLiveProvider",category:vy.WTF,message:"DashLiveProvider internal logic error",thrown:r})};this.subscription.add(yy(this.videoState.stateChangeStarted$.pipe(ko(r=>({transition:r,type:"start"}))),this.videoState.stateChangeEnded$.pipe(ko(r=>({transition:r,type:"end"})))).subscribe(({transition:r,type:a})=>{this.log({message:`[videoState change] ${a}: ${JSON.stringify(r)}`})})),this.video=De(e.container,e.tuning),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.subscription.add(this.dash.soundProhibitedEvent$.subscribe(this.params.output.soundProhibitedEvent$)),this.params.output.duration$.next(1/0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(ye(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);let i=_e(this.video);this.subscription.add(()=>i.destroy()),this.subscription.add(this.representations$.pipe(ko(r=>r.map(({track:a})=>a)),Sy(r=>!!r.length),NC()).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(OC(),ko(r=>-r/1e3)).subscribe(this.params.output.duration$)).add(VC({zeroTime:this.zeroTime$.pipe(Sy(Gl)),position:i.timeUpdate$}).subscribe(({zeroTime:r,position:a})=>this.params.output.liveTime$.next(r+a*1e3),t)).add(gt(this.video,this.params.desiredState.isLooped,t)).add(Ve(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(ze(this.video,this.params.desiredState.playbackRate,i.playbackRateState$,t)).add(i.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(i.loadedMetadata$.subscribe(this.params.output.loadedMetadataEvent$)).add(i.playing$.subscribe(this.params.output.firstFrameEvent$)).add(i.canplay$.subscribe(this.params.output.canplay$)).add(i.inPiP$.subscribe(this.params.output.inPiP$)).add(i.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(Ke(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:r,min:a}})=>{this.dash.setAutoQualityLimits({max:r&&Ty(r),min:a&&Ty(a)}),this.params.output.autoVideoTrackLimits$.next({max:r,min:a})})).add(this.videoState.stateChangeEnded$.subscribe(r=>{var a;switch(r.to){case"stopped":this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState("stopped");break;case"manifest_ready":case"ready":((a=this.params.desiredState.playbackState.getTransition())==null?void 0:a.to)==="ready"&&this.params.desiredState.playbackState.setState("ready");break;case"paused":this.params.desiredState.playbackState.setState("paused");break;case"playing":this.params.desiredState.playbackState.setState("playing");break;default:return by(r.to)}},t)).add(yy(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,FC(["init"])).pipe(_C(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),Be(this.video)}createLiveDashPlayer(){let e=new qs({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 c,d,l,h,p,f;let e=this.representations$.getValue(),t=(d=(c=this.params.desiredState.videoTrack.getTransition())==null?void 0:c.to)!=null?d:this.params.desiredState.videoTrack.getState(),i=(h=(l=this.params.desiredState.autoVideoTrackSwitching.getTransition())==null?void 0:l.to)!=null?h:this.params.desiredState.autoVideoTrackSwitching.getState(),r=!i&&Gl(t)?t:yt(e.map(({track:m})=>m),{container:this.video.getBoundingClientRect(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),a=r==null?void 0:r.id,n=this.params.desiredState.videoTrack.getTransition(),o=(p=this.params.desiredState.videoTrack.getState())==null?void 0:p.id,u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(r&&(n||a!==o)&&this.setVideoTrack(r),u&&this.setAutoQuality(i),n||u||a!==o){let m=(f=e.find(({track:g})=>g.id===a))==null?void 0:f.representation;gy(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;gy(t,`No such representation ${e.id}`),this.dash.switchByName(t.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),r=t==="paused"&&i==="paused",a=-e,n=a<=this.maxSeekBackTime$.getValue()?a:0;this.params.output.position$.next(e/1e3),this.dash.reinit(ne(this.params.source.url,n)),r&&this.dash.pause(),this.liveOffset.resetTo(n,r)}};var Iy=js;var Te=(s,e)=>{let t=0;for(let i=0;i<s.length;i++){let r=s.start(i)*1e3,a=s.end(i)*1e3;r<=e&&e<=a&&(t=a)}return Math.max(t-e,0)};import{assertNever as V0,assertNonNullable as _0,combine as O0,debounce as F0,ErrorCategory as FI,filter as Ld,filterChanged as $a,fromEvent as N0,isNonNullable as NI,isNullable as q0,map as La,merge as Ma,observableFrom as su,once as qI,Subscription as U0,throttle as j0}from"@vkontakte/videoplayer-shared/es2018";var{NativeAbortSignal:lH,NativeAbortController:dH}=function(s){return{NativeAbortSignal:s.AbortSignal,NativeAbortController:s.AbortController}}(typeof self!="undefined"?self:global);function Ey(s){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=s,e}function xy(s){if(s===void 0)if(typeof document=="undefined")s=new Error("This operation was aborted"),s.name="AbortError";else try{s=new DOMException("signal is aborted without reason"),Object.defineProperty(s,"name",{value:"AbortError"})}catch(e){s=new Error("This operation was aborted"),s.name="AbortError"}return s}var $o=class{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,i){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:i})}removeEventListener(e,t){if(!(e in this.listeners))return;let i=this.listeners[e];for(let r=0,a=i.length;r<a;r++)if(i[r].callback===t){i.splice(r,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;let i=this.listeners[e.type].slice();for(let r=0,a=i.length;r<a;r++){let n=i[r];try{n.callback.call(this,e)}catch(o){Promise.resolve().then(()=>{throw o})}n.options&&n.options.once&&this.removeEventListener(e.type,n.callback)}return!e.defaultPrevented}},wr=class extends $o{constructor(){super(),this.listeners||$o.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 Di;return setTimeout(()=>t.abort(new DOMException(`This signal is timeout in ${e}ms`,"TimeoutError")),e),t.signal}static any(e){let t=new Di;function i(){t.abort(this.reason),r()}function r(){for(let a of e)a.removeEventListener("abort",i)}for(let a of e)if(a.aborted){t.abort(a.reason);break}else a.addEventListener("abort",i);return t.signal}},Di=class{constructor(){Object.defineProperty(this,"signal",{value:new wr,writable:!0,configurable:!0})}abort(e){let t=xy(e),i=Ey(t);this.signal.reason=t,this.signal.dispatchEvent(i)}toString(){return"[object AbortController]"}};typeof Symbol!="undefined"&&Symbol.toStringTag&&(Di.prototype[Symbol.toStringTag]="AbortController",wr.prototype[Symbol.toStringTag]="AbortSignal");function Lo(s){return s.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof s.Request=="function"&&!s.Request.prototype.hasOwnProperty("signal")||!s.AbortController}function Kl(s){typeof s=="function"&&(s={fetch:s});let{fetch:e,Request:t=e.Request,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r=!1}=s;if(!Lo({fetch:e,Request:t,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r}))return{fetch:e,Request:a};let a=t;(a&&!a.prototype.hasOwnProperty("signal")||r)&&(a=function(c,d){let l;d&&d.signal&&(l=d.signal,delete d.signal);let h=new t(c,d);return l&&Object.defineProperty(h,"signal",{writable:!1,enumerable:!1,configurable:!0,value:l}),h},a.prototype=t.prototype);let n=e;return{fetch:(u,c)=>{let d=a&&a.prototype.isPrototypeOf(u)?u.signal:c?c.signal:void 0;if(d){let l;try{l=new DOMException("Aborted","AbortError")}catch(p){l=new Error("Aborted"),l.name="AbortError"}if(d.aborted)return Promise.reject(l);let h=new Promise((p,f)=>{d.addEventListener("abort",()=>f(l),{once:!0})});return c&&c.signal&&delete c.signal,Promise.race([h,n(u,c)])}return n(u,c)},Request:a}}var WC=()=>"fetch"in window,Hs=WC()&&Lo({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),wy=Hs?Kl({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,Xe=Hs?wy.fetch:window.fetch,TH=Hs?wy.Request:window.Request,J=Hs?Di:window.AbortController,IH=Hs?wr:window.AbortSignal;var CI=O(Ae(),1),wd=O(Ws(),1);var dT=O(lT(),1);import{ErrorCategory as Gs}from"@vkontakte/videoplayer-shared/es2018";var Mo=s=>{if(!s)return{id:"EmptyResponse",category:Gs.PARSER,message:"Empty response"};if(s.length<=2&&s.match(/^\d+$/))return{id:`UVError#${s}`,category:Gs.NETWORK,message:`UV Error ${s}`};let e=(0,dT.default)(s).substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:Gs.NETWORK,message:"Received unexpected HTML, possibly a ISP block"};if(e.startsWith("<?xml"))return new DOMParser().parseFromString(s,"text/xml").querySelector("parsererror")?{id:"InvalidXML",category:Gs.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:Gs.PARSER,message:"Response is valid XML, but parser failed"}};var Ie=(s,e,t=0)=>{for(let i=0;i<s.length;i++)if(s.start(i)*1e3-t<=e&&s.end(i)*1e3+t>e)return!0;return!1};import{abortable as Id,assertNonNullable as Vr,combine as _r,ErrorCategory as Je,filter as Xo,filterChanged as Aa,flattenObject as Pa,fromEvent as Vt,getTraceSubscriptionMethod as b0,interval as Ed,isNonNullable as Ra,isNullable as $I,map as Or,merge as Fi,now as xd,Subject as ai,Subscription as LI,SubscriptionRemovable as g0,tap as v0,throttle as S0,ValueSubject as ie}from"@vkontakte/videoplayer-shared/es2018";var Vo=O(Ae(),1),Oi=O(nt(),1),_o=O(Ws(),1);var $D=(s,e={})=>{let i=e.timeout||1,r=performance.now();return window.setTimeout(()=>{s({get didTimeout(){return e.timeout?!1:performance.now()-r-1>i},timeRemaining(){return Math.max(0,1+(performance.now()-r))}})},1)},LD=s=>window.clearTimeout(s),pT=s=>typeof s=="function"&&(s==null?void 0:s.toString().endsWith("{ [native code] }")),hT=!pT(window.requestIdleCallback)||!pT(window.cancelIdleCallback),Ar=hT?$D:window.requestIdleCallback,Tt=hT?LD:window.cancelIdleCallback;var EI=O(uo(),1);import{assertNever as MD,ErrorCategory as fT,Subject as mT}from"@vkontakte/videoplayer-shared/es2018";var CD=18,bT=!1;try{bT=_.browser.isSafari&&!!_.browser.safariVersion&&_.browser.safariVersion<=CD}catch(s){console.error(s)}var id=class{constructor(e){this.bufferFull$=new mT;this.error$=new mT;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:fT.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(i=>{let r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(r=>{let a={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(a),this.pull()})}async abort(e){return new Promise(t=>{let i,r=a=>{this.abortRequested=!1,t(a)};bT&&e?i={operation:"safariAbort",init:e,callback:r}:i={operation:"abort",callback:r};for(let{callback:a}of this.queue)a(!1);this.abortRequested=!0,i&&(this.queue=[i]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){var r;if((this.buffer.updating||this.currentTask||this.destroyed)&&!this.abortRequested)return;let e=this.queue.shift();if(!e)return;if((r=e.signal)!=null&&r.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(a){a instanceof DOMException&&a.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):a instanceof DOMException&&a.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:fT.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:a}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){let{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:MD(t)}}},gT=id;var Pr=s=>{let e=0;for(let t=0;t<s.length;t++)e+=s.end(t)-s.start(t);return e*1e3};import{abortable as ti,assertNonNullable as Le,ErrorCategory as Ct,fromEvent as bd,getExponentialDelay as gd,isHigher as t0,isNonNullable as ii,isNullable as le,now as Bo,once as i0,Subject as r0,Subscription as s0,ValueSubject as _i}from"@vkontakte/videoplayer-shared/es2018";var vT=O(nt(),1);var Co=s=>s.valid,H=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let i=this.readUint32();this.type=this.readString(4),i===1&&(this.cursor+=8);let r=e.byteOffset+this.cursor,a;i===0?(this.size=void 0,this.valid=!1,a=void 0):i===1?(this.size=void 0,this.valid=!1,a=void 0):i>e.byteLength?(this.size=i,this.valid=!1,a=Math.min(i-this.cursor,e.byteLength-this.cursor)):(this.size=i,this.valid=!0,a=i-this.cursor),this.content=new DataView(e.buffer,r,a)}get id(){return this.type}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t="ascii"){let r=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,r}readUint8(){let e=this.source.getUint8(this.cursor);return this.cursor+=1,e}readUint16(){let e=this.source.getUint16(this.cursor);return this.cursor+=2,e}readUint32(){let e=this.source.getUint32(this.cursor);return this.cursor+=4,e}readUint64(){let e=this.source.getBigInt64(this.cursor);return this.cursor+=8,e}};var Rr=class extends H{};import{assertNever as DD}from"@vkontakte/videoplayer-shared/es2018";var zs=class extends H{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:DD(e)}}};var Ys=class extends H{constructor(e,t){if(super(e,t),!this.valid)return;this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let i=new DataView(this.content.buffer,this.content.byteOffset+8,this.content.byteLength-8);for(let r=0;r<i.byteLength;r+=4){let a=this.readString(4);this.compatibleBrands.push(a)}}};var Ks=class extends H{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var te=class extends H{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 Xs=class extends te{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 Js=class extends H{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Zs=class extends H{constructor(e,t){super(e,t),this.data=this.content}};var Bi=class extends te{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e,t){if(super(e,t),!!this.valid){this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let i=0;i<this.referenceCount;i++){let r=this.readUint32(),a=r>>>31,n=r<<1>>>1,o=this.readUint32();r=this.readUint32();let u=r>>>28,c=r<<3>>>3;this.segments.push({referenceType:a,referencedSize:n,subsegmentDuration:o,SAPType:u,SAPDeltaTime:c})}}}};var ea=class extends H{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ta=class extends H{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ia=class extends te{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 ra=class extends te{constructor(e,t){super(e,t),this.valid&&(this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32())}};var sa=class extends te{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 aa=class extends H{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var na=class extends te{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 oa=class extends H{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ua=class extends H{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ca=class extends te{constructor(e,t){super(e,t),this.valid&&(this.sequenceNumber=this.readUint32())}};var la=class extends H{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var da=class extends te{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 pa=class extends te{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 ha=class extends te{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 fa=class extends H{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ma=class extends te{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 ba=class extends H{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 VD={ftyp:Ys,moov:Ks,mvhd:Xs,moof:Js,mdat:Zs,sidx:Bi,trak:ea,mdia:aa,mfhd:ca,tkhd:na,traf:la,tfhd:da,tfdt:pa,trun:ha,minf:oa,sv3d:ta,st3d:ia,prhd:ra,proj:ua,equi:sa,uuid:zs,stbl:fa,stsd:ma,avc1:ba,unknown:Rr},Mt=class s{constructor(e={}){this.options={offset:0,...e}}parse(e){let t=[],i=this.options.offset;for(;i<e.byteLength;){let a=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+i+4,4)),n;try{n=this.createBox(a,new DataView(e.buffer,e.byteOffset+i,e.byteLength-i))}catch(o){if(!(o instanceof RangeError))throw o}if(!n||!Co(n))break;t.push(n),i+=n.size}return t}createBox(e,t){let i=VD[e];return i?new i(t,new s):new Rr(t,new s)}};var ei=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{var i,r,a;Co(t)&&((a=(i=this.index)[r=t.type])!=null||(i[r]=[]),this.index[t.type].push(t),t.children.length>0&&this.indexBoxLevel(t.children))})}find(e){return this.index[e]&&this.index[e][0]?this.index[e][0]:null}findAll(e){return this.index[e]||[]}};var OD=new TextDecoder("ascii"),FD=s=>OD.decode(new DataView(s.buffer,s.byteOffset+4,4))==="ftyp",ND=s=>{let e=new Bi(s,new Mt),t=e.earliestPresentationTime/e.timescale*1e3,i=s.byteOffset+s.byteLength+e.firstOffset;return e.segments.map(a=>{if(a.referenceType!==0)throw new Error("Unsupported multilevel sidx");let n=a.subsegmentDuration/e.timescale*1e3,o={status:"none",time:{from:t,to:t+n},byte:{from:i,to:i+a.referencedSize-1}};return t+=n,i+=a.referencedSize,o})},qD=(s,e)=>{let i=new Mt().parse(s),r=new ei(i),a=r.findAll("moof"),n=e?r.findAll("uuid"):r.findAll("mdat");if(!(n.length&&a.length))return null;let o=a[0],u=n[n.length-1],c=o.source.byteOffset,l=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(s.buffer,c,l)},UD=s=>{let t=new Mt().parse(s),i=new ei(t),r={},a=i.findAll("uuid"),n=(0,vT.default)(a,-1);return n?{serverDataReceivedTimestamp:n.userData.received,serverDataPreparedTime:n.userData.received}:r},jD=s=>{var r;let t=new Mt().parse(s);return(r=new ei(t).find("sidx"))==null?void 0:r.timescale},HD=(s,e)=>{let i=new Mt().parse(s),a=new ei(i).findAll("traf"),n=a[a.length-1].children.find(l=>l.type==="tfhd"),o=a[a.length-1].children.find(l=>l.type==="tfdt"),u=a[a.length-1].children.find(l=>l.type==="trun"),c=0;return u.sampleDuration.length?c=u.sampleDuration.reduce((l,h)=>l+h,0):c=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+c)/e*1e3},WD=s=>{let e={is3dVideo:!1,stereoMode:0,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}},i=new Mt().parse(s),r=new ei(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},ST={validateData:FD,parseInit:WD,getIndexRange:()=>{},parseSegments:ND,parseFeedableSegmentChunk:qD,getChunkEndTime:HD,getServerLatencyTimestamps:UD,getTimescaleFromIndex:jD};var Sa=O(Ae(),1);import{assertNonNullable as rd,isNonNullable as ET,isNullable as GD}from"@vkontakte/videoplayer-shared/es2018";import{assertNever as QD}from"@vkontakte/videoplayer-shared/es2018";var yT={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"}},TT=s=>{let e=s.getUint8(0),t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);let i=va(s,t),r=i in yT,a=r?yT[i].type:"binary",n=s.getUint8(t),o=0;n&128?o=1:n&64?o=2:n&32?o=3:n&16?o=4:n&8?o=5:n&4?o=6:n&2?o=7:n&1&&(o=8);let u=new DataView(s.buffer,s.byteOffset+t+1,o-1),c=n&255>>o,d=va(u),l=c*2**((o-1)*8)+d,h=t+o,p;return h+l>s.byteLength?p=new DataView(s.buffer,s.byteOffset+h):p=new DataView(s.buffer,s.byteOffset+h,l),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:a,tagHeaderSize:h,tagSize:h+l,value:p,valueSize:l}},va=(s,e=s.byteLength)=>{switch(e){case 1:return s.getUint8(0);case 2:return s.getUint16(0);case 3:return s.getUint8(0)*2**16+s.getUint16(1);case 4:return s.getUint32(0);case 5:return s.getUint8(0)*2**32+s.getUint32(1);case 6:return s.getUint16(0)*2**32+s.getUint32(2);case 7:{let t=s.getUint8(0)*281474976710656+s.getUint16(1)*4294967296+s.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},ot=(s,e)=>{switch(e){case"int":return s.getInt8(0);case"uint":return va(s);case"float":return s.byteLength===4?s.getFloat32(0):s.getFloat64(0);case"string":return new TextDecoder("ascii").decode(s);case"utf8":return new TextDecoder("utf-8").decode(s);case"date":return new Date(Date.UTC(2001,0)+s.getInt8(0)).getTime();case"master":return s;case"binary":return s;default:QD(e)}},Vi=(s,e)=>{let t=0;for(;t<s.byteLength;){let i=new DataView(s.buffer,s.byteOffset+t),r=TT(i);if(!e(r))return;r.type==="master"&&Vi(r.value,e),t=r.value.byteOffset-s.byteOffset+r.valueSize}},IT=s=>{if(s.getUint32(0)!==440786851)return!1;let e,t,i,r=TT(s);return Vi(r.value,({tag:a,type:n,value:o})=>(a===17143?e=ot(o,n):a===17026?t=ot(o,n):a===17029&&(i=ot(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)};var xT=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],zD=[231,22612,22743,167,171,163,160,175],YD=s=>{let e,t,i,r,a=!1,n=!1,o=!1,u,c,d=!1,l=0;return Vi(s,({tag:h,type:p,value:f,valueSize:m})=>{if(h===21419){let g=ot(f,p);c=va(g)}else h!==21420&&(c=void 0);return h===408125543?(e=f.byteOffset,t=f.byteOffset+m):h===357149030?a=!0:h===290298740?n=!0:h===2807729?i=ot(f,p):h===17545?r=ot(f,p):h===21420&&c===475249515?u=ot(f,p):h===374648427?Vi(f,({tag:g,type:b,value:S})=>g===30321?(d=ot(S,b)===1,!1):!0):a&&n&&(0,Sa.default)(xT,h)&&(o=!0),!o}),rd(e,"Failed to parse webm Segment start"),rd(t,"Failed to parse webm Segment end"),rd(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:l,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},KD=s=>{if(GD(s.cuesSeekPosition))return;let e=s.segmentStart+s.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},XD=(s,e)=>{let t=!1,i=!1,r=o=>ET(o.time)&&ET(o.position),a=[],n;return Vi(s,({tag:o,type:u,value:c})=>{switch(o){case 475249515:t=!0;break;case 187:n&&r(n)&&a.push(n),n={};break;case 179:n&&(n.time=ot(c,u));break;case 183:break;case 241:n&&(n.position=ot(c,u));break;default:t&&(0,Sa.default)(xT,o)&&(i=!0)}return!(t&&i)}),n&&r(n)&&a.push(n),a.map((o,u)=>{let{time:c,position:d}=o,l=a[u+1];return{status:"none",time:{from:c,to:l?l.time:e.segmentDuration},byte:{from:e.segmentStart+d,to:l?e.segmentStart+l.position-1:e.segmentEnd-1}}})},JD=s=>{let e=0,t=!1;try{Vi(s,i=>i.tag===524531317?i.tagSize<=s.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):(0,Sa.default)(zD,i.tag)?(e+i.tagSize<=s.byteLength&&(e+=i.tagSize,t||(t=(0,Sa.default)([163,160,175],i.tag))),!0):!1)}catch(i){}return e>0&&e<=s.byteLength&&t?new DataView(s.buffer,s.byteOffset,e):null},wT={validateData:IT,parseInit:YD,getIndexRange:KD,parseSegments:XD,parseFeedableSegmentChunk:JD};var It=s=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(s);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return wT;case"mp4":return ST}}throw new ReferenceError(`Unsupported mime type ${s}`)};var Et=s=>s instanceof DOMException&&(s.name==="AbortError"||s.code===20);var ld=O(zT(),1),bI=O(cr(),1),gI=O(lI(),1),vI=O(nt(),1),dd=O(Ei(),1);var dI=O(Ae(),1),cd=s=>{let e=s.split("."),[t,...i]=e;if(!t)return!1;switch(t){case"av01":{let[r,a,n]=i;return!!(n&&parseInt(n,10)>8)}case"vp09":{let[r,a,n]=i;return!!(r&&parseInt(r,10)>=2&&n&&parseInt(n,10)>8)}case"avc1":{let r=i[0];if(!r||r.length!==6)return!1;let[a,n]=r.toUpperCase(),o=a+n;return(0,dI.default)(["6E","7A","F4"],o)}}return!1};import{isNonNullable as JB,isNullable as fI}from"@vkontakte/videoplayer-shared/es2018";var pI=s=>{if(s.includes("/")){let e=s.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(s)};var hI=s=>{var e;try{let t=XB(),i=s.match(t),{groups:r}=i!=null?i:{};if(r){let a={};if(r.extensions){let u=r.extensions.toLowerCase().match(/(?:[0-9a-wy-z](?:-[a-z0-9]{2,8})+)/g);Array.from(u||[]).forEach(c=>{a[c[0]]=c.slice(2)})}let n=(e=r.variants)==null?void 0:e.split(/-/).filter(u=>u!==""),o={extlang:r.extlang,langtag:r.langtag,language:r.language,privateuse:r.privateuse||r.privateuse2,region:r.region,script:r.script,extensions:a,variants:n};return Object.keys(o).forEach(u=>{let c=o[u];(typeof c=="undefined"||c==="")&&delete o[u]}),o}return null}catch(t){return null}};function XB(){let s="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",d=`^(?:(?<langtag>${`
|
|
118
|
+
(?<language>${`(?:[a-z]{2,3}(?:-${s})?|[a-z]{4}|[a-z]{5,8})`})
|
|
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(c,"i")}var KT=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},ut=(a,e)=>{let t=a;t=(0,Xc.default)(t,"$$","$");let i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[r,s]of(0,XT.default)(i)){let n=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=(0,Xc.default)(t,n,(o,u)=>YT(s)?o:YT(u)?s:(0,JT.default)(s,parseInt(u,10),"0"))}return t},Eo=(a,e)=>{var D,R,B,M,O,Q,H,I,P,x,w,V,G,ct,dt,Y,be,ge,Se,Fe,xt,Ot,ci,Qi,Gr,op,up,lp,cp,dp,pp,hp,fp,mp,bp,gp,Sp,vp,yp,Tp,Ip,Ep,xp,wp,Ap,Rp,Pp,kp,Lp,$p,Mp,Dp,Cp,Bp,Vp,_p,Op,Fp,Np,qp,Up;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 ee,di;return(di=(ee=Ze.textContent)==null?void 0:ee.trim())!=null?di:""}),o=(D=(0,ZT.default)(n,0))!=null?D:"",u=s.getAttribute("type")==="dynamic",l=s.getAttribute("availabilityStartTime"),c=s.getAttribute("publishTime"),d=s.getElementsByTagName("vk:Attrs")[0],h=d==null?void 0:d.getElementsByTagName("vk:XLatestSegmentPublishTime")[0].textContent,p=d==null?void 0:d.getElementsByTagName("vk:XStreamIsLive")[0].textContent,f=d==null?void 0:d.getElementsByTagName("vk:XStreamIsUnpublished")[0].textContent,m=d==null?void 0:d.getElementsByTagName("vk:XPlaybackDuration")[0].textContent,g;u&&(g={availabilityStartTime:l?new Date(l).getTime():0,publishTime:c?new Date(c).getTime():0,latestSegmentPublishTime:h?new Date(h).getTime():0,streamIsAlive:p==="yes",streamIsUnpublished:f==="yes"});let b,v=s.getAttribute("mediaPresentationDuration"),T=[...s.getElementsByTagName("Period")],y=T.reduce((Ze,ee)=>({...Ze,[ee.id]:ee.children}),{}),E=T.reduce((Ze,ee)=>({...Ze,[ee.id]:ee.getAttribute("duration")}),{});v?b=KT(v):(0,Jc.default)(E).filter(Ze=>Ze).length&&!u?b=(0,Jc.default)(E).reduce((Ze,ee)=>{var di;return Ze+((di=KT(ee))!=null?di:0)},0):m&&(b=parseInt(m,10));let A=0,k=(B=(R=s.getAttribute("profiles"))==null?void 0:R.split(","))!=null?B:[];for(let Ze of T.map(ee=>ee.id))for(let ee of y[Ze]){let di=(M=ee.getAttribute("id"))!=null?M:"id"+(A++).toString(10),zr=(O=ee.getAttribute("mimeType"))!=null?O:"",gu=(Q=ee.getAttribute("codecs"))!=null?Q:"",Su=(H=ee.getAttribute("contentType"))!=null?H:zr==null?void 0:zr.split("/")[0],qE=(P=(I=ee.getAttribute("profiles"))==null?void 0:I.split(","))!=null?P:[],Hp=(w=zT((x=ee.getAttribute("lang"))!=null?x:""))!=null?w:{},Ys=(ct=(G=(V=ee.querySelector("Label"))==null?void 0:V.textContent)==null?void 0:G.trim())!=null?ct:void 0,UE=ee.querySelectorAll("Representation"),HE=ee.querySelector("SegmentTemplate"),jE=(Y=(dt=ee.querySelector("Role"))==null?void 0:dt.getAttribute("value"))!=null?Y:void 0,Gi=Su,ue={id:di,language:Hp.language,isDefault:jE==="main",label:Ys,codecs:gu,hdr:Gi==="video"&&Kc(gu),mime:zr,representations:[]};for(let Z of UE){let Ft=(be=Z.getAttribute("lang"))!=null?be:void 0,Ks=(Se=(ge=Ys!=null?Ys:ee.getAttribute("label"))!=null?ge:Z.getAttribute("label"))!=null?Se:void 0,Xs=(Ot=(xt=(Fe=Z.querySelector("BaseURL"))==null?void 0:Fe.textContent)==null?void 0:xt.trim())!=null?Ot:"",pi=new URL(Xs||o,e).toString(),Nt=(ci=Z.getAttribute("mimeType"))!=null?ci:zr,Js=(Gr=(Qi=Z.getAttribute("codecs"))!=null?Qi:gu)!=null?Gr:"",Zs;if(Su==="text"){let qt=Z.getAttribute("id")||"",en=((op=Hp.privateuse)==null?void 0:op.includes("x-auto"))||qt.includes("_auto"),hi=Z.querySelector("SegmentTemplate");if(hi){let Yr={representationId:(up=Z.getAttribute("id"))!=null?up:void 0,bandwidth:(lp=Z.getAttribute("bandwidth"))!=null?lp:void 0},tn=parseInt((cp=Z.getAttribute("bandwidth"))!=null?cp:"",10)/1e3,rn=(pp=parseInt((dp=hi.getAttribute("startNumber"))!=null?dp:"",10))!=null?pp:1,zi=parseInt((hp=hi.getAttribute("timescale"))!=null?hp:"",10),vu=(fp=hi.querySelectorAll("SegmentTimeline S"))!=null?fp:[],Yi=hi.getAttribute("media");if(!Yi)continue;let an=[],sn=0,nn="",Ki=0,Kr=rn,xe=0;for(let et of vu){let fi=parseInt((mp=et.getAttribute("d"))!=null?mp:"",10),Ge=parseInt((bp=et.getAttribute("r"))!=null?bp:"",10)||0,Ut=parseInt((gp=et.getAttribute("t"))!=null?gp:"",10);xe=Number.isFinite(Ut)?Ut:xe;let mi=fi/zi*1e3,Ht=xe/zi*1e3;for(let pt=0;pt<Ge+1;pt++){let jt=ut(Yi,{...Yr,segmentNumber:Kr.toString(10),segmentTime:(xe+pt*fi).toString(10)}),Xi=(Ht!=null?Ht:0)+pt*mi,Jr=Xi+mi;Kr++,an.push({time:{from:Xi,to:Jr},url:jt})}xe+=(Ge+1)*fi,sn+=(Ge+1)*mi}Ki=xe/zi*1e3,nn=ut(Yi,{...Yr,segmentNumber:Kr.toString(10),segmentTime:xe.toString(10)});let Xr={time:{from:Ki,to:1/0},url:nn},wt={type:"template",baseUrl:pi,segmentTemplateUrl:Yi,initUrl:"",totalSegmentsDurationMs:sn,segments:an,nextSegmentBeyondManifest:Xr,timescale:zi};Zs={id:qt,kind:"text",segmentReference:wt,profiles:[],duration:b,bitrate:tn,mime:"",codecs:"",width:0,height:0,isAuto:en}}else Zs={id:qt,isAuto:en,kind:"text",url:pi}}else{let qt=(vp=(Sp=Z.getAttribute("contentType"))!=null?Sp:Nt==null?void 0:Nt.split("/")[0])!=null?vp:Su,en=(Tp=(yp=ee.getAttribute("profiles"))==null?void 0:yp.split(","))!=null?Tp:[],hi=parseInt((Ip=Z.getAttribute("width"))!=null?Ip:"",10),Yr=parseInt((Ep=Z.getAttribute("height"))!=null?Ep:"",10),tn=parseInt((xp=Z.getAttribute("bandwidth"))!=null?xp:"",10)/1e3,rn=(wp=Z.getAttribute("frameRate"))!=null?wp:"",zi=(Ap=Z.getAttribute("quality"))!=null?Ap:void 0,vu=rn?GT(rn):void 0,Yi=(Rp=Z.getAttribute("id"))!=null?Rp:"id"+(A++).toString(10),an=qt==="video"?`${Yr}p`:qt==="audio"?`${tn}Kbps`:Js,sn=`${Yi}@${an}`,nn=[...k,...qE,...en],Ki,Kr=Z.querySelector("SegmentBase"),xe=(Pp=Z.querySelector("SegmentTemplate"))!=null?Pp:HE;if(Kr){let wt=(Lp=(kp=Z.querySelector("SegmentBase Initialization"))==null?void 0:kp.getAttribute("range"))!=null?Lp:"",[et,fi]=wt.split("-").map(jt=>parseInt(jt,10)),Ge={from:et,to:fi},Ut=($p=Z.querySelector("SegmentBase"))==null?void 0:$p.getAttribute("indexRange"),[mi,Ht]=Ut?Ut.split("-").map(jt=>parseInt(jt,10)):[],pt=Ut?{from:mi,to:Ht}:void 0;Ki={type:"byteRange",url:pi,initRange:Ge,indexRange:pt}}else if(xe){let wt={representationId:(Mp=Z.getAttribute("id"))!=null?Mp:void 0,bandwidth:(Dp=Z.getAttribute("bandwidth"))!=null?Dp:void 0},et=parseInt((Cp=xe.getAttribute("timescale"))!=null?Cp:"",10),fi=(Bp=xe.getAttribute("initialization"))!=null?Bp:"",Ge=xe.getAttribute("media"),Ut=(_p=parseInt((Vp=xe.getAttribute("startNumber"))!=null?Vp:"",10))!=null?_p:1,mi=ut(fi,wt);if(!Ge)throw new ReferenceError("No media attribute in SegmentTemplate");let Ht=(Op=xe.querySelectorAll("SegmentTimeline S"))!=null?Op:[],pt=[],jt=0,Xi="",Jr=0;if(Ht.length){let on=Ut,tt=0;for(let Ji of Ht){let ht=parseInt((Fp=Ji.getAttribute("d"))!=null?Fp:"",10),bi=parseInt((Np=Ji.getAttribute("r"))!=null?Np:"",10)||0,un=parseInt((qp=Ji.getAttribute("t"))!=null?qp:"",10);tt=Number.isFinite(un)?un:tt;let yu=ht/et*1e3,Tu=tt/et*1e3;for(let ln=0;ln<bi+1;ln++){let QE=ut(Ge,{...wt,segmentNumber:on.toString(10),segmentTime:(tt+ln*ht).toString(10)}),jp=(Tu!=null?Tu:0)+ln*yu,GE=jp+yu;on++,pt.push({time:{from:jp,to:GE},url:QE})}tt+=(bi+1)*ht,jt+=(bi+1)*yu}Jr=tt/et*1e3,Xi=ut(Ge,{...wt,segmentNumber:on.toString(10),segmentTime:tt.toString(10)})}else if(fB(b)){let tt=parseInt((Up=xe.getAttribute("duration"))!=null?Up:"",10)/et*1e3,Ji=Math.ceil(b/tt),ht=0;for(let bi=1;bi<Ji;bi++){let un=ut(Ge,{...wt,segmentNumber:bi.toString(10),segmentTime:ht.toString(10)});pt.push({time:{from:ht,to:ht+tt},url:un}),ht+=tt}Jr=ht,Xi=ut(Ge,{...wt,segmentNumber:Ji.toString(10),segmentTime:ht.toString(10)})}let WE={time:{from:Jr,to:1/0},url:Xi};Ki={type:"template",baseUrl:pi,segmentTemplateUrl:Ge,initUrl:mi,totalSegmentsDurationMs:jt,segments:pt,nextSegmentBeyondManifest:WE,timescale:et}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!qt||!Nt)continue;let Xr={video:"video",audio:"audio",text:"text"}[qt];if(!Xr)continue;Gi||(Gi=Xr),Zs={id:sn,kind:Xr,segmentReference:Ki,profiles:nn,duration:b,bitrate:tn,mime:Nt,codecs:Js,width:hi,height:Yr,fps:vu,quality:zi}}ue.language||(ue.language=Ft),ue.label||(ue.label=Ks),ue.mime||(ue.mime=Nt),ue.codecs||(ue.codecs=Js),ue.hdr||(ue.hdr=Gi==="video"&&Kc(Js)),ue.representations.push(Zs)}if(Gi){let Z=r[Gi].find(Ft=>Ft.id===ue.id);if(Z&&ue.representations.every(Ft=>Ft.segmentReference.type==="template"))for(let Ft of Z.representations){let Ks=ue.representations.find(Nt=>Nt.id===Ft.id);if(!Ks)continue;let Xs=Ks.segmentReference,pi=Ft.segmentReference;pi.segments.push(...Xs.segments),pi.nextSegmentBeyondManifest=Xs.nextSegmentBeyondManifest}else r[Gi].push(ue)}}return{duration:b,streams:r,baseUrls:n,live:g}};var Zc=F(nt(),1);import{videoSizeToQuality as mB}from"@vkontakte/videoplayer-shared/es2018";var hs=({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:mB({width:e,height:t});return o&&{id:a,quality:o,bitrate:i,size:{width:e,height:t},fps:r,streamId:n}},eI=({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}),ed=({id:a,language:e,label:t,codecs:i,isDefault:r})=>({id:a,language:e,label:t,codec:(0,Zc.default)(i.split("."),0),isDefault:r}),td=({id:a,language:e,label:t,hdr:i,codecs:r})=>({id:a,language:e,hdr:i,label:t,codec:(0,Zc.default)(r.split("."),0)}),id=a=>"url"in a,je=a=>a.type==="template";import{isNonNullable as rI}from"@vkontakte/videoplayer-shared/es2018";var N=(a,e)=>rI(a)&&rI(e)&&a.readyState==="open"&&bB(a,e);function bB(a,e){for(let t=0;t<a.activeSourceBuffers.length;++t)if(a.activeSourceBuffers[t]===e)return!0;return!1}var fs=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 vB;this.gaps=[];this.subscription=new yB;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new J;this.switchAbortController=new J;this.destroyAbortController=new J;this.useSmartRepresentationSwitch=!1;this.bufferLimit=1/0;this.failedDownloads=0;this.baseUrls=[];this.baseUrlsIndex=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.lastDataObtainedTimestampMs=0;this.loadByteRangeSegmentsTimeoutId=0;this.startWith=Zt(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);ke(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new Jy(this.sourceBuffer),this.subscription.add(rd(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(rd(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,Ar(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);ke(i,"No init buffer for starting representation"),ke(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);ke(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if(ce(s)||ce(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),ke(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();ei(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);ke(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if(ce(s)||ce(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),ke(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();ei(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;let t=(0,Ao.default)(e,l=>l.representations);if(!this.downloadingRepresentationId||!t.length)return;this.isSeekingLive=!0;for(let l of this.representations.keys()){let c=t.find(p=>p.id===l);c&&this.representations.set(l,c);let d=this.representations.get(l);if(!d||!je(d.segmentReference)){this.isSeekingLive=!1;return}let h=this.getActualLiveStartingSegments(d.segmentReference);this.segments.set(d.id,h)}let i=(u=this.switchingToRepresentationId)!=null?u:this.downloadingRepresentationId,r=this.representations.get(i);ke(r,`Representation not found by id ${i}`);let s=this.segments.get(i);ke(s,"No segments for starting representation");let n=this.initData.get(i);if(ke(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer)){this.isSeekingLive=!1;return}let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(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 J,Zt(this.switchAbortController.signal,async function*(i,r=!1){this.switchingToRepresentationId=i;let s=this.representations.get(i);ke(s,`No such representation ${i}`);let n=this.segments.get(i),o=this.initData.get(i);if(ce(o)||ce(n)?yield this.loadInit(s,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(i),ke(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();ei(u)&&!this.isLive&&(this.bufferLimit=this.forwardBufferTarget,yield this.pruneBuffer(u,1/0,!0)),this.downloadingRepresentationId=i,this.switchingToRepresentationId=void 0}this.maintain()}}.bind(this))(e,t))}warmUpMediaSource(){!ce(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}async abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);return this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new J,this.abortBuffer()}maintain(e=this.getCurrentPosition()){var h;if(ce(e)||ce(this.downloadingRepresentationId)||ce(this.playingRepresentationId)||ce(this.sourceBuffer)||!N(this.mediaSource,this.sourceBuffer)||ei(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.representations.get(this.playingRepresentationId),r=this.segments.get(this.downloadingRepresentationId),s=this.segments.get(this.playingRepresentationId);if(ke(t,`No such representation ${this.downloadingRepresentationId}`),ke(i,`No such representation ${this.playingRepresentationId}`),ce(r)||ce(s))return;let n=r.find(p=>e>=p.time.from&&e<p.time.to);ei(n)&&isFinite(n.time.from)&&isFinite(n.time.to)&&this.currentSegmentLength$.next((n==null?void 0:n.time.to)-n.time.from);let o=e,u=100;if(this.playingRepresentationId!==this.downloadingRepresentationId){let p=this.getForwardBufferDuration(e),f=hs(i),m=hs(t),g=this.useSmartRepresentationSwitch&&this.tuning.dash.useNewRepresentationSwitch&&this.tuning.dash.useSmartRepresentationSwitch&&ei(f)&&ei(m)&&gB(f.quality,m.quality),b=this.useSmartRepresentationSwitch&&this.tuning.dash.useNewRepresentationSwitch&&this.tuning.dash.useDelayedRepresentationSwitch;if(g||b?o+=Math.min(p,this.tuning.dash.representationSwitchForwardBufferGap):n&&n.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&p>=n.time.to-e+u&&(o=n?n.time.to+u:-1/0),this.tuning.dash.useNewRepresentationSwitch){let T=(h=[...this.segments.entries()].map(([y,E])=>{let A=E.find(k=>e>=k.time.from&&e<k.time.to);return{representationId:y,status:A==null?void 0:A.status}}).find(y=>y.status==="fed"))==null?void 0:h.representationId;T&&(this.playingRepresentationId=T,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)))}}if(isFinite(this.bufferLimit)&&Ar(this.sourceBuffer.buffered)>=this.bufferLimit){let p=this.getForwardBufferDuration(e),f=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,p<f).catch(m=>{this.handleAsyncError(m,"pruneBuffer")});return}let c=[];if(!this.activeSegments.size&&(c=this.selectForwardBufferSegments(r,t.segmentReference.type,o),c.length)){let p="auto";if(this.tuning.dash.useFetchPriorityHints&&n)if((0,wo.default)(c,n))p="high";else{let f=(0,_i.default)(c,0);f&&f.time.from-n.time.to>=this.forwardBufferTarget/2&&(p="low")}this.loadSegments(c,t,p).catch(f=>{this.handleAsyncError(f,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&n&&n.status==="fed"&&!c.length&&this.getForwardBufferDuration(e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let d=(0,_i.default)(r,-1);!this.isLive&&d&&(this.fullyBuffered$.next(d.time.to-e-this.getForwardBufferDuration(e)<u),this.onLastSegment$.next(e-d.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;ei(t.duration)&&t.duration-i>0&&!this.isLive&&this.gaps.push({representation:t.id,from:i,to:t.duration,persistent:!0})}getActualLiveStartingSegments(e){let t=e.segments,i=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,r=[],s=0,n=t.length-1;do r.unshift(t[n]),s+=t[n].time.to-t[n].time.from,n--;while(s<i&&n>=0);return this.liveInitialAdditionalOffset=s-i,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){let t=e==null?void 0:e.streams[this.kind];if(!t)return;let i=(0,Ao.default)(t,s=>s.representations).find(s=>s.id===this.downloadingRepresentationId);if(!i)return;let r=this.segments.get(i.id);if(r!=null&&r.length)return{from:r[0].time.from,to:r[r.length-1].time.to}}updateLive(e){var i,r,s;if(!e||[...this.segments.values()].every(n=>!n.length))return;let t=(0,Ao.default)(e.streams[this.kind],n=>n.representations);for(let n of t){if(!n||!je(n.segmentReference))return;let o=n.segmentReference.segments.map(h=>({...h,status:"none",size:void 0})),u=100,l=(i=this.segments.get(n.id))!=null?i:[],c=(s=(r=(0,_i.default)(l,-1))==null?void 0:r.time.to)!=null?s:0,d=o==null?void 0:o.findIndex(h=>c>=h.time.from+u&&c<=h.time.to+u);if(d===-1){this.liveUpdateSegmentIndex=0;let h=this.getActualLiveStartingSegments(n.segmentReference);this.segments.set(n.id,h)}else{let h=o.slice(d+1);this.segments.set(n.id,[...l,...h])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;ke(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}setSmartRepresentationSwitch(e){this.useSmartRepresentationSwitch=e}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),c=ut(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:h,time:{from:p,to:f}},m)=>{let g=p<=i&&f>=i,b=p>i||g||m===0&&i===0,v=Math.min(this.forwardBufferTarget,this.bufferLimit),T=this.preloadOnly&&p<=i+v||r<v&&f-p>=v||f<=i+v;return(h==="none"||h==="partially_ejected"&&b&&T&&this.sourceBuffer&&N(this.mediaSource,this.sourceBuffer)&&!(Ie(this.sourceBuffer.buffered,p)&&Ie(this.sourceBuffer.buffered,f)))&&b&&T});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 h=s;h<n.length&&(o<=c||u<=d);h++){let p=n[h];if(o+=p.byte.to+1-p.byte.from,u+=p.time.to+1-p.time.from,p.status==="none"||p.status==="partially_ejected")l.push(p);else break}return l}async loadSegments(e,t,i="auto"){je(t.segmentReference)?await this.loadTemplateSegment(e[0],t,i):await this.loadByteRangeSegments(e,t,i)}async loadTemplateSegment(e,t,i="auto"){e.status="downloading";let r={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(r);let{range:s,url:n,signal:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await Zt(o,async function*(){let c=ad(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=xo(),!c)return;let d=new DataView(c),h=Tt(t.mime);if(!isFinite(r.segment.time.to)){let m=t.segmentReference.timescale;r.segment.time.to=h.getChunkEndTime(d,m)}u&&r.feedingBytes&&l?await Promise.all(l):await this.sourceBufferTaskQueue.append(d,o);let{serverDataReceivedTimestamp:p,serverDataPreparedTime:f}=h.getServerLatencyTimestamps(d);p&&f&&this.currentLiveSegmentServerLatency$.next(f-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())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 Zt(n,async function*(){let u=ad(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),rd(window,"online").pipe(SB()).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=xo(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),It(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,_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=xo(),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(!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,c)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=xo();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,wo.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,h=d-c+1,p=c<r,f=d<=r;if(!p)continue;let m=Tt(o.mime);if(l.status==="downloading"&&f){l.status="downloaded";let g=new DataView(e.buffer,e.byteOffset+c,h);await this.sourceBufferTaskQueue.append(g,s)&&!s.aborted?this.onSegmentFullyAppended(u,t):await n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(l.status==="downloading"||l.status==="partially_fed")&&(u.loadedBytes=Math.min(h,r-c),u.loadedBytes>u.feedingBytes)){let g=new DataView(e.buffer,e.byteOffset+c+u.feedingBytes,u.loadedBytes-u.feedingBytes),b=u.loadedBytes===h?g:m.parseFeedableSegmentChunk(g);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===h&&this.onSegmentFullyAppended(u,t)):await n())}}}onSegmentFullyAppended(e,t){var i;if(!(ce(this.sourceBuffer)||!N(this.mediaSource,this.sourceBuffer))){!this.isLive&&_.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.tuning.dash.useNewRepresentationSwitch||(this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId))),e.segment.status="fed",id(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=wr(()=>(0,aI.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=ad(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 h=c;this.isLive&&je(e.segmentReference)&&(h=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,h),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||ce(e))return!1;let r=[],s=0,n=u=>{u.sort((c,d)=>c.from-d.from);let l=[u[0]];for(let c=1;c<u.length;c++){let{from:d,to:h}=u[c],p=l[l.length-1];p.to>=d?p.to=Math.max(p.to,h):l.push(u[c])}return l},o=u=>{var c;if(s>=t)return r;r.push({...u.time}),r=n(r);let l=id(u)?(c=u.size)!=null?c:0:u.byte.to-u.byte.from;s+=l};for(let u of this.segments.values())for(let l of u){let c=l.time.to<=e-this.tuning.dash.bufferPruningSafeZone,d=l.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(c||d)&&l.status==="fed"&&o(l)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let l=this.sourceBuffer.buffered.start(u)*1e3,c=this.sourceBuffer.buffered.end(u)*1e3,d=0;for(let h of this.segments.values())for(let p of h)(0,wo.default)(["none","partially_ejected"],p.status)&&Math.round(p.time.from)<=Math.round(l)&&Math.round(p.time.to)>=Math.round(c)&&d++;if(d===this.segments.size){let h={time:{from:l,to:c},url:"",status:"none"};o(h)}}if(r.length&&i){let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let l of this.segments.values())for(let c of l)c.time.from>=e+u&&c.status==="fed"&&o(c)}return r.length?(await Promise.all(r.map(l=>this.sourceBufferTaskQueue.remove(l.from,l.to)))).reduce((l,c)=>l||c,!1):!1}async abortBuffer(){if(!this.sourceBuffer||!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||ce(e)?0:Te(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!(!this.sourceBuffer||!N(this.mediaSource,this.sourceBuffer)))for(let i of t){let r={representation:e,from:i.time.from,to:i.time.to,persistent:!1},{buffered:s}=this.sourceBuffer;for(let n=0;n<s.length;n++){let o=s.start(n)*1e3,u=s.end(n)*1e3;if(!(u<=i.time.from||o>=i.time.to)){if(o<=i.time.from&&u>=i.time.to){r=void 0;break}u>i.time.from&&u<i.time.to&&(r.from=u),o<i.time.to&&o>i.time.from&&(r.to=o)}}r&&r.to-r.from>1&&!this.gaps.some(n=>r&&n.from===r.from&&n.to===r.to)&&this.gaps.push(r)}}detectGapsWhenIdle(e,t){if(this.gapDetectionIdleCallback||!this.sourceBuffer||!N(this.mediaSource,this.sourceBuffer))return;let{buffered:i}=this.sourceBuffer,{usePersistentGaps:r}=this.tuning.dash;this.gaps=this.gaps.filter(s=>{if(r&&s.persistent)return!0;let n=Math.round(s.from),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}),this.gapDetectionIdleCallback=wr(()=>{try{this.detectGaps(e,t)}catch(s){this.error$.next({id:"GapDetection",category:Mt.WTF,message:"detectGaps threw",thrown:s})}finally{this.gapDetectionIdleCallback=null}})}checkEjectedSegments(){if(ce(this.sourceBuffer)||!N(this.mediaSource,this.sourceBuffer)||ce(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 ti=a=>{let e=new URL(a);return e.searchParams.set("quic","1"),e.toString()};var Ro=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 ms,assertNever as sI,fromEvent as nI,merge as TB,now as bs,Subject as $r,ValueSubject as sd,flattenObject as Mr,ErrorCategory as gs,SubscriptionRemovable as IB}from"@vkontakte/videoplayer-shared/es2018";var Po=a=>{let e=new URL(a);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var Lo=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:s=!1}){this.manifestRequested=new $r;this.manifestReceived=new $r;this.firstBytesRequested=new $r;this.firstBytesReceived=new $r;this.lastConnectionType$=new sd(void 0);this.lastConnectionReused$=new sd(void 0);this.lastRequestFirstBytes$=new sd(void 0);this.recoverableError$=new $r;this.error$=new $r;this.abortAllController=new J;this.subscription=new IB;this.fetchManifest=ms(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=ti(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=Po(i)),this.manifestRequested.next();let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(ko);return r?(t.log("success",Mr({url:i,message:"Request successfully executed"})),t.end(),this.manifestReceived.next(),this.onHeadersReceived(r.headers),r.text()):(t.error("error",Mr({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=ms(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 O,Q,H;let c=e,d=new Headers,h=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{d.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let I=new URL(c,location.href);I.searchParams.append("bytes",`${i.from}-${i.to}`),c=I.toString();break}default:sI(t)}this.requestQuic&&(c=ti(c));let p=this.abortAllController.signal,f;if(n){let I=new J;if(f=TB(nI(this.abortAllController.signal,"abort"),nI(n,"abort")).subscribe(()=>{try{I.abort()}catch(P){ko(P)}}),this.subscription.add(f),this.abortAllController.signal.aborted||n.aborted)try{I.abort()}catch(P){ko(P)}p=I.signal}let m=0,g=bs();h.log("startRequest",Mr({url:c,priority:s,rangeMethod:t,range:i,isLowLatency:u,requestStartedAt:g})),this.firstBytesRequested.next();let b=yield this.doFetch(c,{priority:s,headers:d,signal:p}),v=bs();if(!b)return h.error("error",{message:"No response in request"}),h.end(),this.unsubscribeAbortSubscription(f),null;if((O=this.throughputEstimator)==null||O.addRawRtt(v-g),!b.ok||!b.body){this.unsubscribeAbortSubscription(f);let I=`Fetch error ${b.status}: ${b.statusText}`;return h.error("error",{message:I}),h.end(),Promise.reject(new Error(`Fetch error ${b.status}: ${b.statusText}`))}if(this.onHeadersReceived(b.headers),!r&&!o){this.unsubscribeAbortSubscription(f);let I=bs(),P={requestStartedAt:g,requestEndedAt:I,duration:I-g};return h.log("endRequest",Mr(P)),h.end(),b.arrayBuffer()}let T=b.body;if(o){let I;[T,I]=b.body.tee(),(Q=this.throughputEstimator)==null||Q.trackStream(I,u)}let y=T.getReader(),E,A=parseInt((H=b.headers.get("content-length"))!=null?H:"",10);Number.isFinite(A)&&(E=A),!E&&i&&(E=i.to-i.from+1);let k=E?new Uint8Array(E):new Uint8Array(0),L=!1,D=I=>{this.unsubscribeAbortSubscription(f),L=!0,ko(I)},R=ms(p,async function*({done:I,value:P}){if(m===0&&(this.lastRequestFirstBytes$.next(bs()-g),this.firstBytesReceived.next()),p.aborted){this.unsubscribeAbortSubscription(f);return}if(!I&&P){if(l&&E)k.set(P,m),m+=P.byteLength;else{let x=new Uint8Array(k.length+P.length);x.set(k),x.set(P,k.length),k=x,m+=P.byteLength}r==null||r(new DataView(k.buffer),m),yield y==null?void 0:y.read().then(R,D)}}.bind(this));yield y==null?void 0:y.read().then(R,D),this.unsubscribeAbortSubscription(f);let B=bs(),M={failed:L,requestStartedAt:g,requestEndedAt:B,duration:B-g};return L?(h.error("endRequest",Mr(M)),h.end(),null):(h.log("endRequest",Mr(M)),h.end(),k.buffer)}.bind(this));this.fetchByteRangeRepresentation=ms(this.abortAllController.signal,async function*(e,t,i){var b;if(e.type!=="byteRange")return null;let{from:r,to:s}=e.initRange,n=r,o=s,u=!1,l,c;e.indexRange&&(l=e.indexRange.from,c=e.indexRange.to,u=s+1===l,u&&(n=Math.min(l,r),o=Math.max(c,s))),n=Math.min(n,0);let d=yield this.fetch(e.url,{range:{from:n,to:o},priority:i,measureThroughput:!1});if(!d)return null;let h=new DataView(d,r-n,s-n+1);if(!t.validateData(h))throw new Error("Invalid media file");let p=t.parseInit(h),f=(b=e.indexRange)!=null?b:t.getIndexRange(p);if(!f)throw new ReferenceError("No way to load representation index");let m;if(u)m=new DataView(d,f.from-n,f.to-f.from+1);else{let v=yield this.fetch(e.url,{range:f,priority:i,measureThroughput:!1});if(!v)return null;m=new DataView(v)}let g=t.parseSegments(m,p,f);return{init:p,dataView:new DataView(d),segments:g}}.bind(this));this.fetchTemplateRepresentation=ms(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}=Ro(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:sI(r)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}async doFetch(e,t){let i=await Xe(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:gs.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:gs.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:gs.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:gs.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${s})`,category:gs.FATAL})}}unsubscribeAbortSubscription(e){e&&(e.unsubscribe(),this.subscription.remove(e))}},ko=a=>{if(!It(a))throw a};var Dt=(a,e,t)=>t*e+(1-t)*a,nd=(a,e)=>a.reduce((t,i)=>t+i,0)/e,oI=(a,e,t,i)=>{let r=0,s=t,n=nd(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 EB,ValueSubject as uI}from"@vkontakte/videoplayer-shared/es2018";var ii=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 uI(e.initial),this.debounced$=new uI(e.initial);let t=(i=e.label)!=null?i:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new Re(`raw_${t}`),this.smoothedSeries$=new Re(`smoothed_${t}`),this.reportedSeries$=new Re(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,i=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=(this.pastMeasures[o]-this.smoothed)**2,i++);this.takenMeasures=i,t/=i;let r=Math.sqrt(t),s=this.smoothed+this.params.deviationFactor*r,n=this.smoothed-this.params.deviationFactor*r;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>s||this.smoothed<n)&&(EB(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 $o=class extends ii{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 Mo=class extends ii{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=nd(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Dt(this.emaSmoothed,e,this.params.emaAlpha);let i=oI(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}};var Do=class extends ii{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 $o({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new Mo({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 Do({initial:e,label:"liveEdgeDelay",...t})}};var Dr=(a,e)=>{a&&a.playbackRate!==e&&(a.playbackRate=e)};import{isNullable as xB,ValueSubject as wB}from"@vkontakte/videoplayer-shared/es2018";var Ss=class a{constructor(e,t){this.currentRepresentation$=new wB(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(!xB(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&&je(t.segmentReference))}};var Bo=F(nt(),1),od=F(De(),1);import{assertNever as Vo}from"@vkontakte/videoplayer-shared/es2018";var Co=a=>{let{webmDecodingInfo:e}=_.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:Vo(a)}return[t,i]},lI=({webmCodec:a,androidPreferredFormat:e,iosPreferredFormat:t,preferMultiStream:i})=>{let r=[...i?["DASH_STREAMS"]:[],...Co(a),"DASH_SEP","DASH_ONDEMAND",...i?[]:["DASH_STREAMS"]],s=[...i?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...i?[]:["DASH_STREAMS"]];if(_.device.isAndroid)switch(e){case"mpeg":return["MPEG",...r,"HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...r,"MPEG"];case"dash":return[...r,"HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return[...s,"MPEG",...Co(a),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...Co(a),"MPEG",...s,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...Co(a),...s,"HLS","HLS_ONDEMAND"];default:Vo(e)}if(_.video.nativeHlsSupported)switch(t){case"hls":return[...r,"HLS","HLS_FMP4","HLS_ONDEMAND","MPEG"];case"hls_fmp4":return[...r,"HLS_FMP4","HLS","HLS_ONDEMAND","MPEG"];default:Vo(t)}return[...r,"HLS","HLS_ONDEMAND","MPEG"]},cI=({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=_.device.isMac&&_.browser.isSafari;if(_.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:Vo(a)}else _.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"]},ud=a=>a?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],_o=a=>{if(a.size===0)return;if(a.size===1){let t=a.values().next();return(0,Bo.default)(t.value.split("."),0)}for(let t of a){let i=(0,Bo.default)(t.split("."),0);if(i==="opus"||i==="vp09"||i==="av01")return i}let e=a.values().next();return(0,Bo.default)(e.value.split("."),0)},Oo=a=>{let e=a.map(i=>Cr(i)),{codecs:t}=_.video;return kB().filter(i=>{if((0,od.default)(e,i))switch(i){case"av1":return t.av1;case"vp9":return t.vp9;case"avc1":return t.h264;case"hev1":return t.h265;default:return!1}else return!1})},Fo=a=>{let e=a.map(i=>Cr(i)),{codecs:t}=_.video;return LB().filter(i=>{if((0,od.default)(e,i))switch(i){case"opus":return t.opus;case"mp4a":return t.aac;default:return!1}else return!1})},Cr=a=>a.split(".")[0].replace("0",""),kB=()=>["av1","vp9","hev1","avc1"],LB=()=>["opus","mp4a"];var VB=["timeupdate","progress","play","seeked","stalled","waiting"],_B=["timeupdate","progress","loadeddata","playing","seeked"];var qo=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.bufferManagers=[];this.subscription=new pI;this.subscriptionRemovable=new DB;this.representationSubscription=new pI;this.state$=new U("none");this.currentVideoRepresentation$=new ie(void 0);this.currentVideoRepresentationInit$=new ie(void 0);this.currentAudioRepresentation$=new ie(void 0);this.currentVideoSegmentLength$=new ie(0);this.currentAudioSegmentLength$=new ie(0);this.error$=new ri;this.manifestRequested=new ri;this.manifestReceived=new ri;this.firstBytesRequested=new ri;this.firstBytesReceived=new ri;this.lastConnectionType$=new ie(void 0);this.lastConnectionReused$=new ie(void 0);this.lastRequestFirstBytes$=new ie(void 0);this.currentLiveTextRepresentation$=new ie(null);this.isLive$=new ie(!1);this.isActiveLive$=new ie(!1);this.isLowLatency$=new ie(!1);this.liveDuration$=new ie(0);this.liveSeekableDuration$=new ie(0);this.liveAvailabilityStartTime$=new ie(0);this.liveStreamStatus$=new ie(void 0);this.bufferLength$=new ie(0);this.liveLatency$=new ie(void 0);this.liveLoadBufferLength$=new ie(0);this.livePositionFromPlayer$=new ie(0);this.currentStallDuration$=new ie(0);this.videoLastDataObtainedTimestamp$=new ie(0);this.fetcherRecoverableError$=new ri;this.fetcherError$=new ri;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new ri;this.gapWatchdogActive=!1;this.liveWasInterrupted=!1;this.destroyController=new J;this.initManifest=ld(this.destroyController.signal,async function*(e,t,i){var r;this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=ne(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:Je.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=ld(this.destroyController.signal,async function*(){var u,l;this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(c=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:Je.NETWORK,message:"Failed to load manifest",thrown:c})});if(!e)return null;let t=null;try{t=Eo(e!=null?e:"",this.manifestUrlString)}catch(c){let d=(u=To(e))!=null?u:{id:"ManifestParsing",category:Je.PARSER,message:"Failed to parse MPD manifest",thrown:c};this.error$.next(d)}if(!t)return null;let i=(c,d,h)=>{var p,f,m,g;return!!((f=(p=this.element)==null?void 0:p.canPlayType)!=null&&f.call(p,d)&&((g=(m=He())==null?void 0:m.isTypeSupported)!=null&&g.call(m,`${d}; codecs="${h}"`))||c==="text")};if(t.live){this.isLive$.next(!0);let{availabilityStartTime:c,latestSegmentPublishTime:d,streamIsUnpublished:h,streamIsAlive:p}=t.live,f=((l=t.duration)!=null?l:0)/1e3;this.liveSeekableDuration$.next(-1*f),this.liveDuration$.next((d-c)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let m="active";if(p||(m=h?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(m),p&&this.liveWasInterrupted){this.liveWasInterrupted=!1,this.stopStallWatchdogSubscription();let g=this.normalizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(g).catch(b=>{this.error$.next({id:"updateManifest",category:Je.VIDEO_PIPELINE,message:"seekLive after stream restore failed",thrown:b})})}}let r={text:t.streams.text,video:[],audio:[]},s,n;for(let c of["video","audio"]){let h=t.streams[c].filter(({mime:f,codecs:m})=>i(c,f,m));r[c]=h;let p;if(this.tuning.dash.codecsPrioritizeEnabled){let f=h.map(({codecs:m})=>m);c==="audio"&&(n=Fo(f),p=n[0]),c==="video"&&(s=Oo(f),this.forceVideoCodec&&(0,fI.default)(s,this.forceVideoCodec)?p=this.forceVideoCodec:p=s[0]),p&&(r[c]=h.filter(({codecs:m})=>Cr(m)===p))}else{let f=new Set(h.map(({codecs:m})=>m));p=_o(f),p&&(r[c]=h.filter(({codecs:m})=>m.startsWith(p)))}if(c==="video"){let f=this.tuning.preferHDR,m=r.video.some(b=>b.hdr),g=r.video.some(b=>!b.hdr);_.display.isHDR&&f&&m?r.video=r.video.filter(b=>b.hdr):g&&(r.video=r.video.filter(b=>!b.hdr))}}let o={...t,streams:r};return this.tuning.dash.codecsPrioritizeEnabled&&(o.codecs={video:s,audio:n}),this.tracer.log("updateManifestEnd",ys(o)),o}.bind(this));this.initRepresentations=ld(this.destroyController.signal,async function*(e,t,i){var d;this.tracer.log("initRepresentationsStart",ys({initialVideo:e,initialAudio:t,sourceHls:i})),Br(this.manifest),Br(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let r=h=>{this.representationSubscription.add(Bt(h,"error").pipe(No(p=>{var f;return!!((f=this.element)!=null&&f.played.length)})).subscribe(p=>{this.error$.next({id:"VideoSource",category:Je.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:p})}))};this.source=Kn();let s=document.createElement("source");if(r(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),br())if(i){let h=document.createElement("source");r(h),h.type="application/x-mpegurl",h.src=i.url,this.element.appendChild(h)}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((h,p)=>[...h,...p.representations],[]);if(this.videoBufferManager=new fs("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],Ts(t)){let h=this.manifest.streams.audio.reduce((p,f)=>[...p,...f.representations],[]);this.audioBufferManager=new fs("audio",this.source,h,n),this.bufferManagers.push(this.audioBufferManager)}if(Ss.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new Ss(this.manifest.streams.text,n)),this.representationSubscription.add(this.fetcher.manifestRequested.subscribe(this.manifestRequested)),this.representationSubscription.add(this.fetcher.manifestReceived.subscribe(this.manifestReceived)),this.representationSubscription.add(this.fetcher.firstBytesRequested.subscribe(this.firstBytesRequested)),this.representationSubscription.add(this.fetcher.firstBytesReceived.subscribe(this.firstBytesReceived)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add(Oi(..._B.map(h=>Bt(this.element,h))).pipe(_r(h=>this.element?Te(this.element.buffered,this.element.currentTime*1e3):0),vs(),CB(h=>{h>this.tuning.dash.bufferEmptinessTolerance&&this.stopStallWatchdogSubscription()})).subscribe(this.bufferLength$)),this.representationSubscription.add(Oi(Bt(this.element,"ended"),this.forceEnded$).subscribe(()=>{this.stopStallWatchdogSubscription()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe(vs()).subscribe(p=>this.liveStreamEndTimestamp=dd())),this.subscription.add(Bt(this.element,"pause").subscribe(()=>{let{liveUpdateInterval:p}=this.tuning.dash;this.livePauseWatchdogSubscription=cd(p).subscribe(f=>{let m=zt(this.manifestUrlString,2);this.manifestUrlString=ne(this.manifestUrlString,m+p,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add(Bt(this.element,"play").subscribe(p=>{var f;return(f=this.livePauseWatchdogSubscription)==null?void 0:f.unsubscribe()})),this.representationSubscription.add(Vr({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(_r(({isActiveLive:p,isLowLatency:f})=>p&&f),vs()).subscribe(p=>{this.isManualDecreasePlaybackInLive()||Dr(this.element,1)})),this.representationSubscription.add(Vr({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(No(({bufferLength:p,isActiveLive:f,isLowLatency:m})=>f&&m&&!!p)).subscribe(({bufferLength:p})=>this.liveBuffer.next(p))),this.representationSubscription.add(this.videoBufferManager.currentLowLatencySegmentLength$.subscribe(p=>{if(!this.isActiveLive$.getValue()&&!this.isLowLatency$.getValue()&&!p)return;let f=this.liveSeekableDuration$.getValue()-p/1e3;this.liveSeekableDuration$.next(Math.max(f,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+p/1e3)})),this.representationSubscription.add(Vr({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(No(({isLive:p})=>p),vs((p,f)=>f.bufferLength<p.bufferLength),_r(({rtt:p,bufferLength:f,segmentServerLatency:m})=>{let g=zt(this.manifestUrlString,2);return(p/2+f+m+g)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(Vr({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:p,isActiveLive:f,isLowLatency:m})=>{if(!m||!f)return;let g=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,b=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,v=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,T=p-g;if(this.isManualDecreasePlaybackInLive())return;let y=1;Math.abs(T)>b&&(y=1+Math.sign(T)*v),Dr(this.element,y)})),this.representationSubscription.add(this.bufferLength$.subscribe(p=>{var m,g;let f=0;if(p){let b=((g=(m=this.element)==null?void 0:m.currentTime)!=null?g:0)*1e3;f=Math.min(...this.bufferManagers.map(T=>{var y,E;return(E=(y=T.getLiveSegmentsToLoadState(this.manifest))==null?void 0:y.to)!=null?E:b}))-b}this.liveLoadBufferLength$.getValue()!==f&&this.liveLoadBufferLength$.next(f)}));let h=0;this.representationSubscription.add(Vr({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(BB(this.tuning.dash.liveUpdateInterval)).subscribe(async({liveLoadBufferLength:p,bufferLength:f})=>{if(!this.element||this.isUpdatingLive)return;let m=this.element.playbackRate,g=zt(this.manifestUrlString,2),b=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,v=Math.min(b,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*m),T=this.tuning.dashCmafLive.normalizedActualBufferOffset*m,y=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*m,E=isFinite(p)?p:f,A=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),k=b<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(k);let L="none";if(A?L="active_low_latency":this.isLowLatency$.getValue()&&k?(this.bufferManagers.forEach(D=>D.proceedLowLatencyLive()),L="active_low_latency"):g!==0&&E<v?L="live_forward_buffering":E<v+y&&(L="live_with_target_offset"),isFinite(p)&&(h=p>h?p:h),L==="live_forward_buffering"||L==="live_with_target_offset"){let D=h-(v+T),R=this.normalizeLiveOffset(Math.trunc(g+D/m)),B=Math.abs(R-g),M=0;!p||B<=this.tuning.dashCmafLive.offsetCalculationError?M=g:R>0&&B>this.tuning.dashCmafLive.offsetCalculationError&&(M=R),this.manifestUrlString=ne(this.manifestUrlString,M,2)}(L==="live_with_target_offset"||L==="live_forward_buffering")&&(h=0,await this.updateLive())},p=>{this.error$.next({id:"updateLive",category:Je.VIDEO_PIPELINE,thrown:p,message:"Failed to update live with subscription"})}))}let u=Oi(...this.bufferManagers.map(h=>h.fullyBuffered$)).pipe(_r(()=>this.bufferManagers.every(h=>h.fullyBuffered$.getValue()))),l=Oi(...this.bufferManagers.map(h=>h.onLastSegment$)).pipe(_r(()=>this.bufferManagers.some(h=>h.onLastSegment$.getValue()))),c=Vr({allBuffersFull:u,someBufferEnded:l}).pipe(vs(),_r(({allBuffersFull:h,someBufferEnded:p})=>h&&p),No(h=>h));if(this.representationSubscription.add(Oi(this.forceEnded$,c).subscribe(()=>{var h;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(p=>!p.updating))try{(h=this.source)==null||h.endOfStream()}catch(p){this.error$.next({id:"EndOfStream",category:Je.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:p})}})),this.representationSubscription.add(Oi(...this.bufferManagers.map(h=>h.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 h=this.tuning.dash.sourceOpenTimeout>=0;yield new Promise(p=>{var f;h&&(this.timeoutSourceOpenId=setTimeout(()=>{var m;if(((m=this.source)==null?void 0:m.readyState)==="open"){p();return}this.error$.next({id:"OpenOfStream",category:Je.VIDEO_PIPELINE,message:"Failed to open MediaSource",thrown:new Error("Timeout reject when wait sourceopen event"),traceAsLog:!0})},this.tuning.dash.sourceOpenTimeout)),(f=this.source)==null||f.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),p()},{once:!0})})}if(!this.isLive$.getValue()){let h=[(d=this.manifest.duration)!=null?d:0,...(0,pd.default)((0,pd.default)([...this.manifest.streams.audio,...this.manifest.streams.video],p=>p.representations),p=>{let f=[];return p.duration&&f.push(p.duration),je(p.segmentReference)&&p.segmentReference.totalSegmentsDurationMs&&f.push(p.segmentReference.totalSegmentsDurationMs),f})];this.source.duration=Math.max(...h)/1e3}this.audioBufferManager&&Ts(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=cd(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),n=>{this.error$.next({id:"GapWatchdog",category:Je.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.forceVideoCodec=e.forceVideoCodec,this.fetcher=new Lo({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()}setSmartRepresentationSwitch(e){this.bufferManagers.forEach(t=>t.setSmartRepresentationSwitch(e))}async seekLive(e){Br(this.element),this.updateManifestUrlWithTimeOffset(e),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await this.updateLiveBuffersFromManifest(this.manifest))}updateManifestUrlWithTimeOffset(e){let t=this.liveStreamStatus$.getValue()!=="active"?dd()-this.liveStreamEndTimestamp:0,i=this.normalizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=ne(this.manifestUrlString,i,2)}async updateLiveBuffersFromManifest(e){var t,i,r;await((t=this.videoBufferManager)==null?void 0:t.seekLive(e.streams.video)),await((i=this.audioBufferManager)==null?void 0:i.seekLive(e.streams.audio)),(r=this.liveTextManager)==null||r.seekLive(e.streams.text)}stopStallWatchdogSubscription(){var e;(e=this.stallWatchdogSubscription)==null||e.unsubscribe(),this.currentStallDuration$.next(0)}initBuffer(){Br(this.element),this.state$.setState("running"),this.subscription.add(Oi(...VB.map(e=>Bt(this.element,e)),Bt(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:Je.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(Bt(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(Bt(this.element,"waiting").subscribe(()=>{this.tuning.dash.useVideoElementWaitingCurrentTimeReassign&&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 y,E,A,k,L,D,R,B,M,O,Q;let{keepSilentStallWatchdogWhenNotActive:t}=this.tuning.dashCmafLive,{crashOnStallTimeout:i,crashOnStallTWithoutDataTimeout:r,liveStallReinitInterval:s,stallWatchdogInterval:n}=this.tuning.dash,o=this.isLive$.getValue(),l=this.liveStreamStatus$.getValue()==="active";if(!this.element||((y=this.source)==null?void 0:y.readyState)!=="open")return;let c=this.currentStallDuration$.getValue();c+=n,this.currentStallDuration$.next(c);let d={timeInWaiting:c},h=dd(),p=100,f=(A=(E=this.videoBufferManager)==null?void 0:E.lastDataObtainedTimestamp)!=null?A:0;this.videoLastDataObtainedTimestamp$.next(f);let m=(L=(k=this.audioBufferManager)==null?void 0:k.lastDataObtainedTimestamp)!=null?L:0,g=(R=(D=this.videoBufferManager)==null?void 0:D.getForwardBufferDuration())!=null?R:0,b=(M=(B=this.audioBufferManager)==null?void 0:B.getForwardBufferDuration())!=null?M:0,v=g<p&&h-f>r,T=this.audioBufferManager&&b<p&&h-m>r;if((!t||l)&&((v||T)&&c>r||c>=i))throw new Error(`Stall timeout exceeded: ${c} ms`);if(o&&c%s===0){let H=this.normalizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);!l&&t?(this.liveWasInterrupted=!0,this.updateManifestUrlWithTimeOffset(H),this.updateManifest()):this.seekLive(H).catch(I=>{this.error$.next({id:"stallIntervalCallback",category:Je.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:I})}),d.liveLastOffset=H}else{let H=this.element.currentTime*1e3;(O=this.videoBufferManager)==null||O.maintain(H),(Q=this.audioBufferManager)==null||Q.maintain(H),d.position=H}this.tracer.log("stallIntervalCallback",ys(d))};this.stallWatchdogSubscription&&(this.stallWatchdogSubscription.unsubscribe(),this.subscriptionRemovable.remove(this.stallWatchdogSubscription)),this.stallWatchdogSubscription=cd(this.tuning.dash.stallWatchdogInterval).subscribe(e,t=>{this.error$.next({id:"StallWatchdogCallback",category:Je.NETWORK,message:"Can't restore DASH after stall.",thrown:t})}),this.subscriptionRemovable.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,i=!1){let r={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return this.tuning.useNewSwitchTo?this.currentStallDuration$.getValue()>0?r==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()]),!(dI(this.element)||dI(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),(u=this.audioBufferManager)==null||u.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",ys({requestedPosition:e,forcePrecise:t,position:i})))}warmUpMediaSourceIfNeeded(e=(t=>(t=this.element)==null?void 0:t.currentTime)()){var i;Ts(this.element)&&Ts(this.source)&&Ts(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}getCodecs(){var e;return(e=this.manifest)==null?void 0:e.codecs}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){var e;this.subscription.unsubscribe(),this.subscriptionRemovable.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))}normalizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){var e;this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&(this.bufferManagers.forEach(t=>t.updateLive(this.manifest)),(e=this.liveTextManager)==null||e.updateLive(this.manifest)),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getDebugBufferState();if(!e)return;let t=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),i={isJumpGapAfterSeekLive:this.isJumpGapAfterSeekLive,isActiveLowLatency:t,initialCurrentTime:this.element.currentTime},{usePersistentGaps:r}=this.tuning.dash;this.isJumpGapAfterSeekLive&&!t&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let s=this.element.currentTime*1e3,n=[],o=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let u of this.bufferManagers)for(let l of u.gaps)(r&&l.persistent||u.playingRepresentation$.getValue()===l.representation)&&l.from-o<=s&&l.to+o>s&&(this.element.duration*1e3-l.to<this.tuning.endGapTolerance?n.push(1/0):n.push(l.to));if(n.length){let u=Math.max(...n)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,u===1/0?this.forceEnded$.next():(this.element.currentTime=u/1e3,i={...i,gapEnds:n,jumpTo:u,resultCurrentTime:this.element.currentTime},this.tracer.log("jumpGap",ys(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 Uo=class{constructor(e,t){this.fov=e,this.orientation=t}};var Ho=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 mI=`attribute vec2 a_vertex;
|
|
124
|
+
`})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(d,"i")}var mI=s=>{if(!(s!=null&&s.startsWith("P")))return;let e=(n,o)=>{let u=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(u)?0:u)*o},i=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(s),r=(i==null?void 0:i[1])==="-"?-1:1,a={days:e(i==null?void 0:i[5],r),hours:e(i==null?void 0:i[6],r),minutes:e(i==null?void 0:i[7],r),seconds:e(i==null?void 0:i[8],r)};return a.days*24*60*60*1e3+a.hours*60*60*1e3+a.minutes*60*1e3+a.seconds*1e3},ut=(s,e)=>{let t=s;t=(0,ld.default)(t,"$$","$");let i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[r,a]of(0,bI.default)(i)){let n=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=(0,ld.default)(t,n,(o,u)=>fI(a)?o:fI(u)?a:(0,gI.default)(a,parseInt(u,10),"0"))}return t},Do=(s,e)=>{var C,P,B,M,F,Q,j,I,R,x,w,V,G,lt,dt,Y,be,ge,ve,Fe,wt,Nt,di,Gi,zr,yp,Tp,Ip,Ep,xp,wp,Ap,Pp,Rp,kp,$p,Lp,Mp,Cp,Dp,Bp,Vp,_p,Op,Fp,Np,qp,Up,jp,Hp,Wp,Qp,Gp,zp,Yp,Kp,Xp,Jp,Zp,eh,th;let i=new DOMParser().parseFromString(s,"application/xml"),r={video:[],audio:[],text:[]},a=i.children[0],n=Array.from(a.querySelectorAll("MPD > BaseURL").values()).map(Ze=>{var ee,pi;return(pi=(ee=Ze.textContent)==null?void 0:ee.trim())!=null?pi:""}),o=(C=(0,vI.default)(n,0))!=null?C:"",u=a.getAttribute("type")==="dynamic",c=a.getAttribute("availabilityStartTime"),d=a.getAttribute("publishTime"),l=a.getElementsByTagName("vk:Attrs")[0],h=l==null?void 0:l.getElementsByTagName("vk:XLatestSegmentPublishTime")[0].textContent,p=l==null?void 0:l.getElementsByTagName("vk:XStreamIsLive")[0].textContent,f=l==null?void 0:l.getElementsByTagName("vk:XStreamIsUnpublished")[0].textContent,m=l==null?void 0:l.getElementsByTagName("vk:XPlaybackDuration")[0].textContent,g;u&&(g={availabilityStartTime:c?new Date(c).getTime():0,publishTime:d?new Date(d).getTime():0,latestSegmentPublishTime:h?new Date(h).getTime():0,streamIsAlive:p==="yes",streamIsUnpublished:f==="yes"});let b,S=a.getAttribute("mediaPresentationDuration"),T=[...a.getElementsByTagName("Period")],y=T.reduce((Ze,ee)=>({...Ze,[ee.id]:ee.children}),{}),E=T.reduce((Ze,ee)=>({...Ze,[ee.id]:ee.getAttribute("duration")}),{});S?b=mI(S):(0,dd.default)(E).filter(Ze=>Ze).length&&!u?b=(0,dd.default)(E).reduce((Ze,ee)=>{var pi;return Ze+((pi=mI(ee))!=null?pi:0)},0):m&&(b=parseInt(m,10));let A=0,$=(B=(P=a.getAttribute("profiles"))==null?void 0:P.split(","))!=null?B:[];for(let Ze of T.map(ee=>ee.id))for(let ee of y[Ze]){let pi=(M=ee.getAttribute("id"))!=null?M:"id"+(A++).toString(10),Yr=(F=ee.getAttribute("mimeType"))!=null?F:"",Ru=(Q=ee.getAttribute("codecs"))!=null?Q:"",ku=(j=ee.getAttribute("contentType"))!=null?j:Yr==null?void 0:Yr.split("/")[0],nx=(R=(I=ee.getAttribute("profiles"))==null?void 0:I.split(","))!=null?R:[],ih=(w=hI((x=ee.getAttribute("lang"))!=null?x:""))!=null?w:{},rn=(lt=(G=(V=ee.querySelector("Label"))==null?void 0:V.textContent)==null?void 0:G.trim())!=null?lt:void 0,ox=ee.querySelectorAll("Representation"),ux=ee.querySelector("SegmentTemplate"),cx=(Y=(dt=ee.querySelector("Role"))==null?void 0:dt.getAttribute("value"))!=null?Y:void 0,zi=ku,ue={id:pi,language:ih.language,isDefault:cx==="main",label:rn,codecs:Ru,hdr:zi==="video"&&cd(Ru),mime:Yr,representations:[]};for(let Z of ox){let qt=(be=Z.getAttribute("lang"))!=null?be:void 0,sn=(ve=(ge=rn!=null?rn:ee.getAttribute("label"))!=null?ge:Z.getAttribute("label"))!=null?ve:void 0,an=(Nt=(wt=(Fe=Z.querySelector("BaseURL"))==null?void 0:Fe.textContent)==null?void 0:wt.trim())!=null?Nt:"",hi=new URL(an||o,e).toString(),Ut=(di=Z.getAttribute("mimeType"))!=null?di:Yr,nn=(zr=(Gi=Z.getAttribute("codecs"))!=null?Gi:Ru)!=null?zr:"",on;if(ku==="text"){let jt=Z.getAttribute("id")||"",un=((yp=ih.privateuse)==null?void 0:yp.includes("x-auto"))||jt.includes("_auto"),fi=Z.querySelector("SegmentTemplate");if(fi){let Kr={representationId:(Tp=Z.getAttribute("id"))!=null?Tp:void 0,bandwidth:(Ip=Z.getAttribute("bandwidth"))!=null?Ip:void 0},cn=parseInt((Ep=Z.getAttribute("bandwidth"))!=null?Ep:"",10)/1e3,ln=(wp=parseInt((xp=fi.getAttribute("startNumber"))!=null?xp:"",10))!=null?wp:1,Yi=parseInt((Ap=fi.getAttribute("timescale"))!=null?Ap:"",10),$u=(Pp=fi.querySelectorAll("SegmentTimeline S"))!=null?Pp:[],Ki=fi.getAttribute("media");if(!Ki)continue;let dn=[],pn=0,hn="",Xi=0,Xr=ln,xe=0;for(let et of $u){let mi=parseInt((Rp=et.getAttribute("d"))!=null?Rp:"",10),Ge=parseInt((kp=et.getAttribute("r"))!=null?kp:"",10)||0,Ht=parseInt(($p=et.getAttribute("t"))!=null?$p:"",10);xe=Number.isFinite(Ht)?Ht:xe;let bi=mi/Yi*1e3,Wt=xe/Yi*1e3;for(let pt=0;pt<Ge+1;pt++){let Qt=ut(Ki,{...Kr,segmentNumber:Xr.toString(10),segmentTime:(xe+pt*mi).toString(10)}),Ji=(Wt!=null?Wt:0)+pt*bi,Zr=Ji+bi;Xr++,dn.push({time:{from:Ji,to:Zr},url:Qt})}xe+=(Ge+1)*mi,pn+=(Ge+1)*bi}Xi=xe/Yi*1e3,hn=ut(Ki,{...Kr,segmentNumber:Xr.toString(10),segmentTime:xe.toString(10)});let Jr={time:{from:Xi,to:1/0},url:hn},At={type:"template",baseUrl:hi,segmentTemplateUrl:Ki,initUrl:"",totalSegmentsDurationMs:pn,segments:dn,nextSegmentBeyondManifest:Jr,timescale:Yi};on={id:jt,kind:"text",segmentReference:At,profiles:[],duration:b,bitrate:cn,mime:"",codecs:"",width:0,height:0,isAuto:un}}else on={id:jt,isAuto:un,kind:"text",url:hi}}else{let jt=(Mp=(Lp=Z.getAttribute("contentType"))!=null?Lp:Ut==null?void 0:Ut.split("/")[0])!=null?Mp:ku,un=(Dp=(Cp=ee.getAttribute("profiles"))==null?void 0:Cp.split(","))!=null?Dp:[],fi=parseInt((Bp=Z.getAttribute("width"))!=null?Bp:"",10),Kr=parseInt((Vp=Z.getAttribute("height"))!=null?Vp:"",10),cn=parseInt((_p=Z.getAttribute("bandwidth"))!=null?_p:"",10)/1e3,ln=(Op=Z.getAttribute("frameRate"))!=null?Op:"",Yi=(Fp=Z.getAttribute("quality"))!=null?Fp:void 0,$u=ln?pI(ln):void 0,Ki=(Np=Z.getAttribute("id"))!=null?Np:"id"+(A++).toString(10),dn=jt==="video"?`${Kr}p`:jt==="audio"?`${cn}Kbps`:nn,pn=`${Ki}@${dn}`,hn=[...$,...nx,...un],Xi,Xr=Z.querySelector("SegmentBase"),xe=(qp=Z.querySelector("SegmentTemplate"))!=null?qp:ux;if(Xr){let At=(jp=(Up=Z.querySelector("SegmentBase Initialization"))==null?void 0:Up.getAttribute("range"))!=null?jp:"",[et,mi]=At.split("-").map(Qt=>parseInt(Qt,10)),Ge={from:et,to:mi},Ht=(Hp=Z.querySelector("SegmentBase"))==null?void 0:Hp.getAttribute("indexRange"),[bi,Wt]=Ht?Ht.split("-").map(Qt=>parseInt(Qt,10)):[],pt=Ht?{from:bi,to:Wt}:void 0;Xi={type:"byteRange",url:hi,initRange:Ge,indexRange:pt}}else if(xe){let At={representationId:(Wp=Z.getAttribute("id"))!=null?Wp:void 0,bandwidth:(Qp=Z.getAttribute("bandwidth"))!=null?Qp:void 0},et=parseInt((Gp=xe.getAttribute("timescale"))!=null?Gp:"",10),mi=(zp=xe.getAttribute("initialization"))!=null?zp:"",Ge=xe.getAttribute("media"),Ht=(Kp=parseInt((Yp=xe.getAttribute("startNumber"))!=null?Yp:"",10))!=null?Kp:1,bi=ut(mi,At);if(!Ge)throw new ReferenceError("No media attribute in SegmentTemplate");let Wt=(Xp=xe.querySelectorAll("SegmentTimeline S"))!=null?Xp:[],pt=[],Qt=0,Ji="",Zr=0;if(Wt.length){let fn=Ht,tt=0;for(let Zi of Wt){let ht=parseInt((Jp=Zi.getAttribute("d"))!=null?Jp:"",10),gi=parseInt((Zp=Zi.getAttribute("r"))!=null?Zp:"",10)||0,mn=parseInt((eh=Zi.getAttribute("t"))!=null?eh:"",10);tt=Number.isFinite(mn)?mn:tt;let Lu=ht/et*1e3,Mu=tt/et*1e3;for(let bn=0;bn<gi+1;bn++){let dx=ut(Ge,{...At,segmentNumber:fn.toString(10),segmentTime:(tt+bn*ht).toString(10)}),rh=(Mu!=null?Mu:0)+bn*Lu,px=rh+Lu;fn++,pt.push({time:{from:rh,to:px},url:dx})}tt+=(gi+1)*ht,Qt+=(gi+1)*Lu}Zr=tt/et*1e3,Ji=ut(Ge,{...At,segmentNumber:fn.toString(10),segmentTime:tt.toString(10)})}else if(JB(b)){let tt=parseInt((th=xe.getAttribute("duration"))!=null?th:"",10)/et*1e3,Zi=Math.ceil(b/tt),ht=0;for(let gi=1;gi<Zi;gi++){let mn=ut(Ge,{...At,segmentNumber:gi.toString(10),segmentTime:ht.toString(10)});pt.push({time:{from:ht,to:ht+tt},url:mn}),ht+=tt}Zr=ht,Ji=ut(Ge,{...At,segmentNumber:Zi.toString(10),segmentTime:ht.toString(10)})}let lx={time:{from:Zr,to:1/0},url:Ji};Xi={type:"template",baseUrl:hi,segmentTemplateUrl:Ge,initUrl:bi,totalSegmentsDurationMs:Qt,segments:pt,nextSegmentBeyondManifest:lx,timescale:et}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!jt||!Ut)continue;let Jr={video:"video",audio:"audio",text:"text"}[jt];if(!Jr)continue;zi||(zi=Jr),on={id:pn,kind:Jr,segmentReference:Xi,profiles:hn,duration:b,bitrate:cn,mime:Ut,codecs:nn,width:fi,height:Kr,fps:$u,quality:Yi}}ue.language||(ue.language=qt),ue.label||(ue.label=sn),ue.mime||(ue.mime=Ut),ue.codecs||(ue.codecs=nn),ue.hdr||(ue.hdr=zi==="video"&&cd(nn)),ue.representations.push(on)}if(zi){let Z=r[zi].find(qt=>qt.id===ue.id);if(Z&&ue.representations.every(qt=>qt.segmentReference.type==="template"))for(let qt of Z.representations){let sn=ue.representations.find(Ut=>Ut.id===qt.id);if(!sn)continue;let an=sn.segmentReference,hi=qt.segmentReference;hi.segments.push(...an.segments),hi.nextSegmentBeyondManifest=an.nextSegmentBeyondManifest}else r[zi].push(ue)}}return{duration:b,streams:r,baseUrls:n,live:g}};var pd=O(nt(),1);import{videoSizeToQuality as ZB}from"@vkontakte/videoplayer-shared/es2018";var ya=({id:s,width:e,height:t,bitrate:i,fps:r,quality:a,streamId:n})=>{var u;let o=(u=a?Jt(a):void 0)!=null?u:ZB({width:e,height:t});return o&&{id:s,quality:o,bitrate:i,size:{width:e,height:t},fps:r,streamId:n}},SI=({id:s,bitrate:e})=>({id:s,bitrate:e}),yI=({language:s,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:s,label:e}),TI=({language:s,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:s,label:e}),hd=({id:s,language:e,label:t,codecs:i,isDefault:r})=>({id:s,language:e,label:t,codec:(0,pd.default)(i.split("."),0),isDefault:r}),fd=({id:s,language:e,label:t,hdr:i,codecs:r})=>({id:s,language:e,hdr:i,label:t,codec:(0,pd.default)(r.split("."),0)}),md=s=>"url"in s,He=s=>s.type==="template";import{isNonNullable as II}from"@vkontakte/videoplayer-shared/es2018";var N=(s,e)=>II(s)&&II(e)&&s.readyState==="open"&&e0(s,e);function e0(s,e){for(let t=0;t<s.activeSourceBuffers.length;++t)if(s.activeSourceBuffers[t]===e)return!0;return!1}var Ta=class{constructor(e,t,i,{fetcher:r,tuning:a,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:c}){this.currentLiveSegmentServerLatency$=new _i(0);this.currentLowLatencySegmentLength$=new _i(0);this.currentSegmentLength$=new _i(0);this.onLastSegment$=new _i(!1);this.fullyBuffered$=new _i(!1);this.playingRepresentation$=new _i(void 0);this.playingRepresentationInit$=new _i(void 0);this.error$=new r0;this.gaps=[];this.subscription=new s0;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new J;this.switchAbortController=new J;this.destroyAbortController=new J;this.useSmartRepresentationSwitch=!1;this.bufferLimit=1/0;this.failedDownloads=0;this.baseUrls=[];this.baseUrlsIndex=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.lastDataObtainedTimestampMs=0;this.loadByteRangeSegmentsTimeoutId=0;this.startWith=ti(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);Le(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new gT(this.sourceBuffer),this.subscription.add(bd(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:Ct.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o!=null||(o={id:"SegmentEjection",category:Ct.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),this.error$.next(o)})),this.subscription.add(bd(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:Ct.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,Pr(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let c=this.getForwardBufferDuration(o),d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,n*2,c<d).catch(l=>{this.handleAsyncError(l,"pruneBuffer")})})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);let i=this.initData.get(t.id),r=this.segments.get(t.id),a=this.parsedInitData.get(t.id);Le(i,"No init buffer for starting representation"),Le(r,"No segments for starting representation"),i instanceof ArrayBuffer&&(this.searchGaps(r,t),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(a))}.bind(this));this.switchTo=ti(this.destroyAbortController.signal,async function*(e,t=!1){if(!N(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);Le(i,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if(le(a)||le(r)?yield this.loadInit(i,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),Le(r,"No segments for starting representation"),a=this.initData.get(e),!(!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer||!N(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(a,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer();else{let n=this.getCurrentPosition();ii(n)&&!this.isLive&&(this.bufferLimit=1/0,await this.pruneBuffer(n,1/0,!0)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}this.maintain()}}.bind(this));this.switchToOld=ti(this.destroyAbortController.signal,async function*(e,t=!1){if(!N(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);Le(i,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if(le(a)||le(r)?yield this.loadInit(i,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),Le(r,"No segments for starting representation"),a=this.initData.get(e),!(!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer||!N(this.mediaSource,this.sourceBuffer)))if(yield this.abort(),yield this.sourceBufferTaskQueue.append(a,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let n=this.getCurrentPosition();ii(n)&&(this.isLive||(this.bufferLimit=1/0,await this.pruneBuffer(n,1/0,!0)),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}}.bind(this));this.seekLive=ti(this.destroyAbortController.signal,async function*(e){var u;let t=(0,_o.default)(e,c=>c.representations);if(!this.downloadingRepresentationId||!t.length)return;this.isSeekingLive=!0;for(let c of this.representations.keys()){let d=t.find(p=>p.id===c);d&&this.representations.set(c,d);let l=this.representations.get(c);if(!l||!He(l.segmentReference)){this.isSeekingLive=!1;return}let h=this.getActualLiveStartingSegments(l.segmentReference);this.segments.set(l.id,h)}let i=(u=this.switchingToRepresentationId)!=null?u:this.downloadingRepresentationId,r=this.representations.get(i);Le(r,`Representation not found by id ${i}`);let a=this.segments.get(i);Le(a,"No segments for starting representation");let n=this.initData.get(i);if(Le(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer)){this.isSeekingLive=!1;return}let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(a,r),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));var d;this.fetcher=r,this.tuning=a,this.compatibilityMode=u,this.forwardBufferTarget=a.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!(c!=null&&c.live),this.baseUrls=(d=c==null?void 0:c.baseUrls)!=null?d:[],this.initData=new Map(i.map(l=>[l.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(l=>[l.id,l])),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 J,ti(this.switchAbortController.signal,async function*(i,r=!1){this.switchingToRepresentationId=i;let a=this.representations.get(i);Le(a,`No such representation ${i}`);let n=this.segments.get(i),o=this.initData.get(i);if(le(o)||le(n)?yield this.loadInit(a,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(i),Le(n,"No segments for starting representation"),o=this.initData.get(i),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer||!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();ii(u)&&!this.isLive&&(this.bufferLimit=this.forwardBufferTarget,yield this.pruneBuffer(u,1/0,!0)),this.downloadingRepresentationId=i,this.switchingToRepresentationId=void 0}this.maintain()}}.bind(this))(e,t))}warmUpMediaSource(){!le(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}async abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);return this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new J,this.abortBuffer()}maintain(e=this.getCurrentPosition()){var h;if(le(e)||le(this.downloadingRepresentationId)||le(this.playingRepresentationId)||le(this.sourceBuffer)||!N(this.mediaSource,this.sourceBuffer)||ii(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.representations.get(this.playingRepresentationId),r=this.segments.get(this.downloadingRepresentationId),a=this.segments.get(this.playingRepresentationId);if(Le(t,`No such representation ${this.downloadingRepresentationId}`),Le(i,`No such representation ${this.playingRepresentationId}`),le(r)||le(a))return;let n=r.find(p=>e>=p.time.from&&e<p.time.to);ii(n)&&isFinite(n.time.from)&&isFinite(n.time.to)&&this.currentSegmentLength$.next((n==null?void 0:n.time.to)-n.time.from);let o=e,u=100;if(this.playingRepresentationId!==this.downloadingRepresentationId){let p=this.getForwardBufferDuration(e),f=ya(i),m=ya(t),g=this.useSmartRepresentationSwitch&&this.tuning.dash.useNewRepresentationSwitch&&this.tuning.dash.useSmartRepresentationSwitch&&ii(f)&&ii(m)&&t0(f.quality,m.quality),b=this.useSmartRepresentationSwitch&&this.tuning.dash.useNewRepresentationSwitch&&this.tuning.dash.useDelayedRepresentationSwitch;if(g||b?o+=Math.min(p,this.tuning.dash.representationSwitchForwardBufferGap):n&&n.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&p>=n.time.to-e+u&&(o=n?n.time.to+u:-1/0),this.tuning.dash.useNewRepresentationSwitch){let T=(h=[...this.segments.entries()].map(([y,E])=>{let A=E.find($=>e>=$.time.from&&e<$.time.to);return{representationId:y,status:A==null?void 0:A.status}}).find(y=>y.status==="fed"))==null?void 0:h.representationId;T&&(this.playingRepresentationId=T,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)))}}if(isFinite(this.bufferLimit)&&Pr(this.sourceBuffer.buffered)>=this.bufferLimit){let p=this.getForwardBufferDuration(e),f=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,p<f).catch(m=>{this.handleAsyncError(m,"pruneBuffer")});return}let d=[];if(!this.activeSegments.size&&(d=this.selectForwardBufferSegments(r,t.segmentReference.type,o),d.length)){let p="auto";if(this.tuning.dash.useFetchPriorityHints&&n)if((0,Vo.default)(d,n))p="high";else{let f=(0,Oi.default)(d,0);f&&f.time.from-n.time.to>=this.forwardBufferTarget/2&&(p="low")}this.loadSegments(d,t,p).catch(f=>{this.handleAsyncError(f,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&n&&n.status==="fed"&&!d.length&&this.getForwardBufferDuration(e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let l=(0,Oi.default)(r,-1);!this.isLive&&l&&(this.fullyBuffered$.next(l.time.to-e-this.getForwardBufferDuration(e)<u),this.onLastSegment$.next(e-l.time.from>0))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let i=0,r=this.isLive?this.liveInitialAdditionalOffset:0;for(let a of e)Math.trunc(a.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:a.time.from+r,persistent:!0}),i=a.time.to;ii(t.duration)&&t.duration-i>0&&!this.isLive&&this.gaps.push({representation:t.id,from:i,to:t.duration,persistent:!0})}getActualLiveStartingSegments(e){let t=e.segments,i=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,r=[],a=0,n=t.length-1;do r.unshift(t[n]),a+=t[n].time.to-t[n].time.from,n--;while(a<i&&n>=0);return this.liveInitialAdditionalOffset=a-i,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){let t=e==null?void 0:e.streams[this.kind];if(!t)return;let i=(0,_o.default)(t,a=>a.representations).find(a=>a.id===this.downloadingRepresentationId);if(!i)return;let r=this.segments.get(i.id);if(r!=null&&r.length)return{from:r[0].time.from,to:r[r.length-1].time.to}}updateLive(e){var i,r,a;if(!e||[...this.segments.values()].every(n=>!n.length))return;let t=(0,_o.default)(e.streams[this.kind],n=>n.representations);for(let n of t){if(!n||!He(n.segmentReference))return;let o=n.segmentReference.segments.map(h=>({...h,status:"none",size:void 0})),u=100,c=(i=this.segments.get(n.id))!=null?i:[],d=(a=(r=(0,Oi.default)(c,-1))==null?void 0:r.time.to)!=null?a:0,l=o==null?void 0:o.findIndex(h=>d>=h.time.from+u&&d<=h.time.to+u);if(l===-1){this.liveUpdateSegmentIndex=0;let h=this.getActualLiveStartingSegments(n.segmentReference);this.segments.set(n.id,h)}else{let h=o.slice(l+1);this.segments.set(n.id,[...c,...h])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;Le(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,Oi.default)(e,-1))==null?void 0:t.time.to:0)||0}setSmartRepresentationSwitch(e){this.useSmartRepresentationSwitch=e}updateLowLatencyLiveIfNeeded(e){var i;let t=0;for(let r of this.representations.values()){let a=r.segmentReference;if(!He(a))return;let n=(i=this.segments.get(r.id))!=null?i:[],o=n.find(c=>Math.floor(c.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(c=>Math.floor(c.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let c=Math.round(e.time.to*a.timescale/1e3).toString(10),d=ut(a.segmentTemplateUrl,{segmentTime:c});n.push({status:"none",time:{from:e.time.to,to:1/0},url:d})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){var a,n,o;let t=(n=(a=this.switchingToRepresentationId)!=null?a:this.downloadingRepresentationId)!=null?n:this.playingRepresentationId;if(!t)return;let i=this.segments.get(t);if(!i)return;let r=i.find(u=>u.time.from<=e&&u.time.to>=e);return(o=r==null?void 0:r.time.from)!=null?o:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)==null||e.destroy(),this.gapDetectionIdleCallback&&Tt&&Tt(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&Tt&&Tt(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}this.sourceBuffer=null,this.downloadAbortController.abort(),this.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,i){return this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){let i=e.findIndex(r=>t>=r.time.from&&t<r.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=i),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,i){let r=this.getForwardBufferDuration(i),a=e.findIndex(({status:h,time:{from:p,to:f}},m)=>{let g=p<=i&&f>=i,b=p>i||g||m===0&&i===0,S=Math.min(this.forwardBufferTarget,this.bufferLimit),T=this.preloadOnly&&p<=i+S||r<S&&f-p>=S||f<=i+S;return(h==="none"||h==="partially_ejected"&&b&&T&&this.sourceBuffer&&N(this.mediaSource,this.sourceBuffer)&&!(Ie(this.sourceBuffer.buffered,p)&&Ie(this.sourceBuffer.buffered,f)))&&b&&T});if(a===-1)return[];if(t!=="byteRange")return e.slice(a,a+1);let n=e,o=0,u=0,c=[],d=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,l=this.preloadOnly?this.forwardBufferTarget:0;for(let h=a;h<n.length&&(o<=d||u<=l);h++){let p=n[h];if(o+=p.byte.to+1-p.byte.from,u+=p.time.to+1-p.time.from,p.status==="none"||p.status==="partially_ejected")c.push(p);else break}return c}async loadSegments(e,t,i="auto"){He(t.segmentReference)?await this.loadTemplateSegment(e[0],t,i):await this.loadByteRangeSegments(e,t,i)}async loadTemplateSegment(e,t,i="auto"){e.status="downloading";let r={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(r);let{range:a,url:n,signal:o,onProgress:u,onProgressTasks:c}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await ti(o,async function*(){let d=gd(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>setTimeout(l,d))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let d=await this.fetcher.fetch(n,{range:a,signal:o,onProgress:u,priority:i,isLowLatency:this.isActiveLowLatency(),bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation});if(this.lastDataObtainedTimestampMs=Bo(),!d)return;let l=new DataView(d),h=It(t.mime);if(!isFinite(r.segment.time.to)){let m=t.segmentReference.timescale;r.segment.time.to=h.getChunkEndTime(l,m)}u&&r.feedingBytes&&c?await Promise.all(c):await this.sourceBufferTaskQueue.append(l,o);let{serverDataReceivedTimestamp:p,serverDataPreparedTime:f}=h.getServerLatencyTimestamps(l);p&&f&&this.currentLiveSegmentServerLatency$.next(f-p),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(d){this.abortActiveSegments([e]),Et(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())He(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}async loadByteRangeSegments(e,t,i="auto"){if(!e.length)return;for(let u of e)u.status="downloading",this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:r,url:a,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(await ti(n,async function*(){let u=gd(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(c,u),bd(window,"online").pipe(i0()).subscribe(()=>{c(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(a,{range:r,onProgress:o,signal:n,priority:i,bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation}),this.lastDataObtainedTimestampMs=Bo(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),Et(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(He(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:(0,Oi.default)(e,0).byte.from,to:(0,Oi.default)(e,-1).byte.to},{signal:a}=this.downloadAbortController;return{url:i,range:r,signal:a,onProgress:async(o,u)=>{if(!a.aborted)try{this.lastDataObtainedTimestampMs=Bo(),await this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:a,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(c){this.error$.next({id:"SegmentFeeding",category:Ct.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}}}}prepareTemplateFetchSegmentParams(e,t){if(!He(t.segmentReference))throw new Error("Representation is not template type");let i=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&i.searchParams.set("low-latency","yes");let r=i.toString(),{signal:a}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(c,d)=>{if(!a.aborted)try{this.lastDataObtainedTimestampMs=Bo();let l=this.onSomeTemplateDataLoaded({dataView:c,loaded:d,signal:a,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(l)}catch(l){this.error$.next({id:"SegmentFeeding",category:Ct.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}:void 0;return{url:r,signal:a,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:a}){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(a.aborted){r();continue}if(o.loadedBytes=i,o.loadedBytes>o.feedingBytes){let c=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),d=It(n.mime).parseFeedableSegmentChunk(c,this.isLive);d!=null&&d.byteLength&&(u.status="partially_fed",o.feedingBytes+=d.byteLength,await this.sourceBufferTaskQueue.append(d),o.fedBytes+=d.byteLength)}}}}async onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:a,onSegmentAppendFailed:n}){if(!this.activeSegments.size||!N(this.mediaSource,this.sourceBuffer))return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){let{segment:c}=u;if(u.representationId!==t)continue;if(a.aborted){await n();continue}let d=c.byte.from-i,l=c.byte.to-i,h=l-d+1,p=d<r,f=l<=r;if(!p)continue;let m=It(o.mime);if(c.status==="downloading"&&f){c.status="downloaded";let g=new DataView(e.buffer,e.byteOffset+d,h);await this.sourceBufferTaskQueue.append(g,a)&&!a.aborted?this.onSegmentFullyAppended(u,t):await n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(c.status==="downloading"||c.status==="partially_fed")&&(u.loadedBytes=Math.min(h,r-d),u.loadedBytes>u.feedingBytes)){let g=new DataView(e.buffer,e.byteOffset+d+u.feedingBytes,u.loadedBytes-u.feedingBytes),b=u.loadedBytes===h?g:m.parseFeedableSegmentChunk(g);b!=null&&b.byteLength&&(c.status="partially_fed",u.feedingBytes+=b.byteLength,await this.sourceBufferTaskQueue.append(b,a)&&!a.aborted?(u.fedBytes+=b.byteLength,u.fedBytes===h&&this.onSegmentFullyAppended(u,t)):await n())}}}onSegmentFullyAppended(e,t){var i;if(!(le(this.sourceBuffer)||!N(this.mediaSource,this.sourceBuffer))){!this.isLive&&_.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:Ct.VIDEO_PIPELINE,message:"Browser stuck on empty result of adding segment to source buffer"})),this.tuning.dash.useNewRepresentationSwitch||(this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId))),e.segment.status="fed",md(e.segment)&&(e.segment.size=e.fedBytes);for(let r of this.representations.values())if(r.id!==t)for(let a of(i=this.segments.get(r.id))!=null?i:[])a.status==="fed"&&Math.round(a.time.from)===Math.round(e.segment.time.from)&&Math.round(a.time.to)===Math.round(e.segment.time.to)&&(a.status="none");this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}}abortSegment(e){e.status==="partially_fed"?e.status="partially_ejected":e.status!=="partially_ejected"&&(e.status="none");for(let t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[r,a]of this.initData.entries()){let n=a instanceof Promise;t||(t=n),a===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let i=this.representations.get(e);i&&(this.initLoadIdleCallback=Ar(()=>(0,EI.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,It(e.mime),r)).then(async o=>{if(!o)return;let{init:u,dataView:c,segments:d}=o,l=c.buffer.slice(c.byteOffset,c.byteOffset+c.byteLength);this.initData.set(e.id,l);let h=d;this.isLive&&He(e.segmentReference)&&(h=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,h),u&&this.parsedInitData.set(e.id,u)}).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:Ct.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||le(e))return!1;let r=[],a=0,n=u=>{u.sort((d,l)=>d.from-l.from);let c=[u[0]];for(let d=1;d<u.length;d++){let{from:l,to:h}=u[d],p=c[c.length-1];p.to>=l?p.to=Math.max(p.to,h):c.push(u[d])}return c},o=u=>{var d;if(a>=t)return r;r.push({...u.time}),r=n(r);let c=md(u)?(d=u.size)!=null?d:0:u.byte.to-u.byte.from;a+=c};for(let u of this.segments.values())for(let c of u){let d=c.time.to<=e-this.tuning.dash.bufferPruningSafeZone,l=c.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(d||l)&&c.status==="fed"&&o(c)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let c=this.sourceBuffer.buffered.start(u)*1e3,d=this.sourceBuffer.buffered.end(u)*1e3,l=0;for(let h of this.segments.values())for(let p of h)(0,Vo.default)(["none","partially_ejected"],p.status)&&Math.round(p.time.from)<=Math.round(c)&&Math.round(p.time.to)>=Math.round(d)&&l++;if(l===this.segments.size){let h={time:{from:c,to:d},url:"",status:"none"};o(h)}}if(r.length&&i){let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let c of this.segments.values())for(let d of c)d.time.from>=e+u&&d.status==="fed"&&o(d)}return r.length?(await Promise.all(r.map(c=>this.sourceBufferTaskQueue.remove(c.from,c.to)))).reduce((c,d)=>c||d,!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||le(e)?0:Te(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!(!this.sourceBuffer||!N(this.mediaSource,this.sourceBuffer)))for(let i of t){let r={representation:e,from:i.time.from,to:i.time.to,persistent:!1},{buffered:a}=this.sourceBuffer;for(let n=0;n<a.length;n++){let o=a.start(n)*1e3,u=a.end(n)*1e3;if(!(u<=i.time.from||o>=i.time.to)){if(o<=i.time.from&&u>=i.time.to){r=void 0;break}u>i.time.from&&u<i.time.to&&(r.from=u),o<i.time.to&&o>i.time.from&&(r.to=o)}}r&&r.to-r.from>1&&!this.gaps.some(n=>r&&n.from===r.from&&n.to===r.to)&&this.gaps.push(r)}}detectGapsWhenIdle(e,t){if(this.gapDetectionIdleCallback||!this.sourceBuffer||!N(this.mediaSource,this.sourceBuffer))return;let{buffered:i}=this.sourceBuffer,{usePersistentGaps:r}=this.tuning.dash;this.gaps=this.gaps.filter(a=>{if(r&&a.persistent)return!0;let n=Math.round(a.from),o=Math.round(a.to);for(let u=0;u<i.length;u++)if(n>=Math.round(i.start(u)*1e3)&&o<=Math.round(i.end(u)*1e3))return!1;return!0}),this.gapDetectionIdleCallback=Ar(()=>{try{this.detectGaps(e,t)}catch(a){this.error$.next({id:"GapDetection",category:Ct.WTF,message:"detectGaps threw",thrown:a})}finally{this.gapDetectionIdleCallback=null}})}checkEjectedSegments(){if(le(this.sourceBuffer)||!N(this.mediaSource,this.sourceBuffer)||le(this.playingRepresentationId))return;let e=[];for(let i=0;i<this.sourceBuffer.buffered.length;i++){let r=Math.floor(this.sourceBuffer.buffered.start(i)*1e3),a=Math.ceil(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:r,to:a})}let t=100;for(let i of this.segments.values())for(let r of i){let{status:a}=r;if(a!=="fed"&&a!=="partially_ejected")continue;let n=Math.floor(r.time.from),o=Math.ceil(r.time.to),u=e.some(d=>d.from-t<=n&&d.to+t>=o),c=e.filter(d=>n>=d.from&&n<d.to-t||o>d.from+t&&o<=d.to);u||(c.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:Ct.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}};var ri=s=>{let e=new URL(s);return e.searchParams.set("quic","1"),e.toString()};var Oo=s=>{var a;let e=s.get("X-Delivery-Type"),t=s.get("X-Reused"),i=e===null?"http1":e!=null?e:void 0,r=t===null?void 0:(a={1:!0,0:!1}[t])!=null?a:void 0;return{type:i,reused:r}};import{abortable as Ia,assertNever as xI,fromEvent as wI,merge as a0,now as Ea,Subject as Mr,ValueSubject as vd,flattenObject as Cr,ErrorCategory as xa,SubscriptionRemovable as n0}from"@vkontakte/videoplayer-shared/es2018";var Fo=s=>{let e=new URL(s);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var qo=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:a=!1}){this.manifestRequested=new Mr;this.manifestReceived=new Mr;this.firstBytesRequested=new Mr;this.firstBytesReceived=new Mr;this.lastConnectionType$=new vd(void 0);this.lastConnectionReused$=new vd(void 0);this.lastRequestFirstBytes$=new vd(void 0);this.recoverableError$=new Mr;this.error$=new Mr;this.abortAllController=new J;this.subscription=new n0;this.fetchManifest=Ia(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=ri(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=Fo(i)),this.manifestRequested.next();let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(No);return r?(t.log("success",Cr({url:i,message:"Request successfully executed"})),t.end(),this.manifestReceived.next(),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=Ia(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:a="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1,bufferOptimisation:c=!1}={}){var F,Q,j;let d=e,l=new Headers,h=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{l.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let I=new URL(d,location.href);I.searchParams.append("bytes",`${i.from}-${i.to}`),d=I.toString();break}default:xI(t)}this.requestQuic&&(d=ri(d));let p=this.abortAllController.signal,f;if(n){let I=new J;if(f=a0(wI(this.abortAllController.signal,"abort"),wI(n,"abort")).subscribe(()=>{try{I.abort()}catch(R){No(R)}}),this.subscription.add(f),this.abortAllController.signal.aborted||n.aborted)try{I.abort()}catch(R){No(R)}p=I.signal}let m=0,g=Ea();h.log("startRequest",Cr({url:d,priority:a,rangeMethod:t,range:i,isLowLatency:u,requestStartedAt:g})),this.firstBytesRequested.next();let b=yield this.doFetch(d,{priority:a,headers:l,signal:p}),S=Ea();if(!b)return h.error("error",{message:"No response in request"}),h.end(),this.unsubscribeAbortSubscription(f),null;if((F=this.throughputEstimator)==null||F.addRawRtt(S-g),!b.ok||!b.body){this.unsubscribeAbortSubscription(f);let I=`Fetch error ${b.status}: ${b.statusText}`;return h.error("error",{message:I}),h.end(),Promise.reject(new Error(`Fetch error ${b.status}: ${b.statusText}`))}if(this.onHeadersReceived(b.headers),!r&&!o){this.unsubscribeAbortSubscription(f);let I=Ea(),R={requestStartedAt:g,requestEndedAt:I,duration:I-g};return h.log("endRequest",Cr(R)),h.end(),b.arrayBuffer()}let T=b.body;if(o){let I;[T,I]=b.body.tee(),(Q=this.throughputEstimator)==null||Q.trackStream(I,u)}let y=T.getReader(),E,A=parseInt((j=b.headers.get("content-length"))!=null?j:"",10);Number.isFinite(A)&&(E=A),!E&&i&&(E=i.to-i.from+1);let $=E?new Uint8Array(E):new Uint8Array(0),L=!1,C=I=>{this.unsubscribeAbortSubscription(f),L=!0,No(I)},P=Ia(p,async function*({done:I,value:R}){if(m===0&&(this.lastRequestFirstBytes$.next(Ea()-g),this.firstBytesReceived.next()),p.aborted){this.unsubscribeAbortSubscription(f);return}if(!I&&R){if(c&&E)$.set(R,m),m+=R.byteLength;else{let x=new Uint8Array($.length+R.length);x.set($),x.set(R,$.length),$=x,m+=R.byteLength}r==null||r(new DataView($.buffer),m),yield y==null?void 0:y.read().then(P,C)}}.bind(this));yield y==null?void 0:y.read().then(P,C),this.unsubscribeAbortSubscription(f);let B=Ea(),M={failed:L,requestStartedAt:g,requestEndedAt:B,duration:B-g};return L?(h.error("endRequest",Cr(M)),h.end(),null):(h.log("endRequest",Cr(M)),h.end(),$.buffer)}.bind(this));this.fetchByteRangeRepresentation=Ia(this.abortAllController.signal,async function*(e,t,i){var b;if(e.type!=="byteRange")return null;let{from:r,to:a}=e.initRange,n=r,o=a,u=!1,c,d;e.indexRange&&(c=e.indexRange.from,d=e.indexRange.to,u=a+1===c,u&&(n=Math.min(c,r),o=Math.max(d,a))),n=Math.min(n,0);let l=yield this.fetch(e.url,{range:{from:n,to:o},priority:i,measureThroughput:!1});if(!l)return null;let h=new DataView(l,r-n,a-n+1);if(!t.validateData(h))throw new Error("Invalid media file");let p=t.parseInit(h),f=(b=e.indexRange)!=null?b:t.getIndexRange(p);if(!f)throw new ReferenceError("No way to load representation index");let m;if(u)m=new DataView(l,f.from-n,f.to-f.from+1);else{let S=yield this.fetch(e.url,{range:f,priority:i,measureThroughput:!1});if(!S)return null;m=new DataView(S)}let g=t.parseSegments(m,p,f);return{init:p,dataView:new DataView(l),segments:g}}.bind(this));this.fetchTemplateRepresentation=Ia(this.abortAllController.signal,async function*(e,t){if(e.type!=="template")return null;let i=new URL(e.initUrl,e.baseUrl).toString(),r=yield this.fetch(i,{priority:t,measureThroughput:!1});return r?{init:null,segments:e.segments.map(n=>({...n,status:"none",size:void 0})),dataView:new DataView(r)}:null}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=r,this.tracer=i.createComponentTracer("Fetcher"),this.useEnableSubtitlesParam=a}onHeadersReceived(e){let{type:t,reused:i}=Oo(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,t,i="auto"){var a,n;let{type:r}=e;switch(r){case"byteRange":return(a=await this.fetchByteRangeRepresentation(e,t,i))!=null?a:null;case"template":return(n=await this.fetchTemplateRepresentation(e,i))!=null?n:null;default:xI(r)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}async doFetch(e,t){let i=await Xe(e,t);if(i.ok)return i;let r=await i.text(),a=parseInt(r);if(!isNaN(a))switch(a){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:xa.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:xa.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:xa.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:xa.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${a})`,category:xa.FATAL})}}unsubscribeAbortSubscription(e){e&&(e.unsubscribe(),this.subscription.remove(e))}},No=s=>{if(!Et(s))throw s};var Dt=(s,e,t)=>t*e+(1-t)*s,Sd=(s,e)=>s.reduce((t,i)=>t+i,0)/e,AI=(s,e,t,i)=>{let r=0,a=t,n=Sd(s,e),o=e<i?e:i;for(let u=0;u<o;u++)s[a]>n?r++:r--,a=(s.length+a-1)%s.length;return Math.abs(r)===o};import{isNullable as o0,ValueSubject as PI}from"@vkontakte/videoplayer-shared/es2018";var si=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 PI(e.initial),this.debounced$=new PI(e.initial);let t=(i=e.label)!=null?i:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new ke(`raw_${t}`),this.smoothedSeries$=new ke(`smoothed_${t}`),this.reportedSeries$=new ke(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,i=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=(this.pastMeasures[o]-this.smoothed)**2,i++);this.takenMeasures=i,t/=i;let r=Math.sqrt(t),a=this.smoothed+this.params.deviationFactor*r,n=this.smoothed-this.params.deviationFactor*r;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>a||this.smoothed<n)&&(o0(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 Uo=class extends si{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 jo=class extends si{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=Sd(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Dt(this.emaSmoothed,e,this.params.emaAlpha);let i=AI(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}};var Ho=class extends si{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 Bt=class{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new Uo({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new jo({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 Ho({initial:e,label:"liveEdgeDelay",...t})}};var Dr=(s,e)=>{s&&s.playbackRate!==e&&(s.playbackRate=e)};import{isNullable as u0,ValueSubject as c0}from"@vkontakte/videoplayer-shared/es2018";var wa=class s{constructor(e,t){this.currentRepresentation$=new c0(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(!u0(e))for(let i of this.representations)for(let r of i){let a=r.segmentReference,n=a.segments.length,o=a.segments[0].time.from,u=a.segments[n-1].time.to;if(e<o||e>u)continue;let c=a.segments.find(d=>d.time.from<=e&&d.time.to>=e);!c||((t=this.currentSegment)==null?void 0:t.time.from)===c.time.from&&this.currentSegment.time.to===c.time.to||(this.currentSegment=c,this.currentRepresentation$.next({...r,label:"Live Text",language:"ru",isAuto:!0,url:new URL(c.url,a.baseUrl).toString()}))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e!=null?e:[]){let i=s.filterRepresentations(t.representations);if(i){this.representations[this.representationsCursor]=i,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!(e!=null&&e.some(t=>s.filterRepresentations(t.representations)))}static filterRepresentations(e){return e==null?void 0:e.filter(t=>t.kind==="text"&&"segmentReference"in t&&He(t.segmentReference))}};var Qo=O(nt(),1),yd=O(Ae(),1);import{assertNever as Go}from"@vkontakte/videoplayer-shared/es2018";var Wo=s=>{let{webmDecodingInfo:e}=_.video,t="DASH_WEBM",i="DASH_WEBM_AV1";switch(s){case"vp9":return[t,i];case"av1":return[i,t];case"none":return[];case"smooth":return e?e[i].smooth?[i,t]:e[t].smooth?[t,i]:[i,t]:[t,i];case"power_efficient":return e?e[i].powerEfficient?[i,t]:e[t].powerEfficient?[t,i]:[i,t]:[t,i];default:Go(s)}},RI=({webmCodec:s,androidPreferredFormat:e,iosPreferredFormat:t,preferMultiStream:i})=>{let r=[...i?["DASH_STREAMS"]:[],...Wo(s),"DASH_SEP","DASH_ONDEMAND",...i?[]:["DASH_STREAMS"]],a=[...i?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...i?[]:["DASH_STREAMS"]];if(_.device.isAndroid)switch(e){case"mpeg":return["MPEG",...r,"HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...r,"MPEG"];case"dash":return[...r,"HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return[...a,"MPEG",...Wo(s),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...Wo(s),"MPEG",...a,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...Wo(s),...a,"HLS","HLS_ONDEMAND"];default:Go(e)}if(_.video.nativeHlsSupported)switch(t){case"hls":return[...r,"HLS","HLS_FMP4","HLS_ONDEMAND","MPEG"];case"hls_fmp4":return[...r,"HLS_FMP4","HLS","HLS_ONDEMAND","MPEG"];default:Go(t)}return[...r,"HLS","HLS_ONDEMAND","MPEG"]},kI=({androidPreferredFormat:s,preferCMAF:e,preferWebRTC:t})=>{let i=e?["DASH_LIVE_CMAF","DASH_LIVE"]:["DASH_LIVE","DASH_LIVE_CMAF"],r=e?["HLS_LIVE_CMAF","HLS_LIVE"]:["HLS_LIVE","HLS_LIVE_CMAF"],a=[...i,...r],n=[...r,...i],o,u=_.device.isMac&&_.browser.isSafari;if(_.device.isAndroid)switch(s){case"dash":case"dash_any_mpeg":case"dash_any_webm":case"dash_sep":{o=a;break}case"hls":case"mpeg":{o=n;break}default:Go(s)}else _.video.nativeHlsSupported&&!u&&!_.browser.isChromiumBased?o=n:u?o=e?["DASH_LIVE_CMAF","HLS_LIVE_CMAF","HLS_LIVE","DASH_LIVE"]:["HLS_LIVE","DASH_LIVE","DASH_LIVE_CMAF","HLS_LIVE_CMAF"]:o=a;return t?["WEB_RTC_LIVE",...o]:[...o,"WEB_RTC_LIVE"]},Td=s=>s?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],zo=s=>{if(s.size===0)return;if(s.size===1){let t=s.values().next();return(0,Qo.default)(t.value.split("."),0)}for(let t of s){let i=(0,Qo.default)(t.split("."),0);if(i==="opus"||i==="vp09"||i==="av01")return i}let e=s.values().next();return(0,Qo.default)(e.value.split("."),0)},Yo=s=>{let e=s.map(i=>Br(i)),{codecs:t}=_.video;return h0().filter(i=>{if((0,yd.default)(e,i))switch(i){case"av1":return t.av1;case"vp9":return t.vp9;case"avc1":return t.h264;case"hev1":return t.h265;default:return!1}else return!1})},Ko=s=>{let e=s.map(i=>Br(i)),{codecs:t}=_.video;return f0().filter(i=>{if((0,yd.default)(e,i))switch(i){case"opus":return t.opus;case"mp4a":return t.aac;default:return!1}else return!1})},Br=s=>s.split(".")[0].replace("0",""),h0=()=>["av1","vp9","hev1","avc1"],f0=()=>["opus","mp4a"];var y0=["timeupdate","progress","play","seeked","stalled","waiting"],T0=["timeupdate","progress","loadeddata","playing","seeked"];var Jo=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.bufferManagers=[];this.subscription=new LI;this.subscriptionRemovable=new g0;this.representationSubscription=new LI;this.state$=new U("none");this.currentVideoRepresentation$=new ie(void 0);this.currentVideoRepresentationInit$=new ie(void 0);this.currentAudioRepresentation$=new ie(void 0);this.currentVideoSegmentLength$=new ie(0);this.currentAudioSegmentLength$=new ie(0);this.error$=new ai;this.manifestRequested=new ai;this.manifestReceived=new ai;this.firstBytesRequested=new ai;this.firstBytesReceived=new ai;this.lastConnectionType$=new ie(void 0);this.lastConnectionReused$=new ie(void 0);this.lastRequestFirstBytes$=new ie(void 0);this.currentLiveTextRepresentation$=new ie(null);this.isLive$=new ie(!1);this.isActiveLive$=new ie(!1);this.isLowLatency$=new ie(!1);this.liveDuration$=new ie(0);this.liveSeekableDuration$=new ie(0);this.liveAvailabilityStartTime$=new ie(0);this.liveStreamStatus$=new ie(void 0);this.bufferLength$=new ie(0);this.liveLatency$=new ie(void 0);this.liveLoadBufferLength$=new ie(0);this.livePositionFromPlayer$=new ie(0);this.currentStallDuration$=new ie(0);this.videoLastDataObtainedTimestamp$=new ie(0);this.fetcherRecoverableError$=new ai;this.fetcherError$=new ai;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new ai;this.gapWatchdogActive=!1;this.liveWasInterrupted=!1;this.destroyController=new J;this.initManifest=Id(this.destroyController.signal,async function*(e,t,i){var r;this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=ne(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:Je.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=Id(this.destroyController.signal,async function*(){var u,c;this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(d=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:Je.NETWORK,message:"Failed to load manifest",thrown:d})});if(!e)return null;let t=null;try{t=Do(e!=null?e:"",this.manifestUrlString)}catch(d){let l=(u=Mo(e))!=null?u:{id:"ManifestParsing",category:Je.PARSER,message:"Failed to parse MPD manifest",thrown:d};this.error$.next(l)}if(!t)return null;let i=(d,l,h)=>{var p,f,m,g;return!!((f=(p=this.element)==null?void 0:p.canPlayType)!=null&&f.call(p,l)&&((g=(m=Ue())==null?void 0:m.isTypeSupported)!=null&&g.call(m,`${l}; codecs="${h}"`))||d==="text")};if(t.live){this.isLive$.next(!0);let{availabilityStartTime:d,latestSegmentPublishTime:l,streamIsUnpublished:h,streamIsAlive:p}=t.live,f=((c=t.duration)!=null?c:0)/1e3;this.liveSeekableDuration$.next(-1*f),this.liveDuration$.next((l-d)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let m="active";if(p||(m=h?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(m),p&&this.liveWasInterrupted){this.liveWasInterrupted=!1,this.stopStallWatchdogSubscription();let g=this.normalizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(g).catch(b=>{this.error$.next({id:"updateManifest",category:Je.VIDEO_PIPELINE,message:"seekLive after stream restore failed",thrown:b})})}}let r={text:t.streams.text,video:[],audio:[]},a,n;for(let d of["video","audio"]){let h=t.streams[d].filter(({mime:f,codecs:m})=>i(d,f,m));r[d]=h;let p;if(this.tuning.dash.codecsPrioritizeEnabled){let f=h.map(({codecs:m})=>m);d==="audio"&&(n=Ko(f),p=n[0]),d==="video"&&(a=Yo(f),this.forceVideoCodec&&(0,CI.default)(a,this.forceVideoCodec)?p=this.forceVideoCodec:p=a[0]),p&&(r[d]=h.filter(({codecs:m})=>Br(m)===p))}else{let f=new Set(h.map(({codecs:m})=>m));p=zo(f),p&&(r[d]=h.filter(({codecs:m})=>m.startsWith(p)))}if(d==="video"){let f=this.tuning.preferHDR,m=r.video.some(b=>b.hdr),g=r.video.some(b=>!b.hdr);_.display.isHDR&&f&&m?r.video=r.video.filter(b=>b.hdr):g&&(r.video=r.video.filter(b=>!b.hdr))}}let o={...t,streams:r};return this.tuning.dash.codecsPrioritizeEnabled&&(o.codecs={video:a,audio:n}),this.tracer.log("updateManifestEnd",Pa(o)),o}.bind(this));this.initRepresentations=Id(this.destroyController.signal,async function*(e,t,i){var l;this.tracer.log("initRepresentationsStart",Pa({initialVideo:e,initialAudio:t,sourceHls:i})),Vr(this.manifest),Vr(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let r=h=>{this.representationSubscription.add(Vt(h,"error").pipe(Xo(p=>{var f;return!!((f=this.element)!=null&&f.played.length)})).subscribe(p=>{this.error$.next({id:"VideoSource",category:Je.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:p})}))};this.source=Cn();let a=document.createElement("source");if(r(a),a.src=URL.createObjectURL(this.source),this.element.appendChild(a),or())if(i){let h=document.createElement("source");r(h),h.type="application/x-mpegurl",h.src=i.url,this.element.appendChild(h)}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((h,p)=>[...h,...p.representations],[]);if(this.videoBufferManager=new Ta("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],Ra(t)){let h=this.manifest.streams.audio.reduce((p,f)=>[...p,...f.representations],[]);this.audioBufferManager=new Ta("audio",this.source,h,n),this.bufferManagers.push(this.audioBufferManager)}if(wa.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new wa(this.manifest.streams.text,n)),this.representationSubscription.add(this.fetcher.manifestRequested.subscribe(this.manifestRequested)),this.representationSubscription.add(this.fetcher.manifestReceived.subscribe(this.manifestReceived)),this.representationSubscription.add(this.fetcher.firstBytesRequested.subscribe(this.firstBytesRequested)),this.representationSubscription.add(this.fetcher.firstBytesReceived.subscribe(this.firstBytesReceived)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add(Fi(...T0.map(h=>Vt(this.element,h))).pipe(Or(h=>this.element?Te(this.element.buffered,this.element.currentTime*1e3):0),Aa(),v0(h=>{h>this.tuning.dash.bufferEmptinessTolerance&&this.stopStallWatchdogSubscription()})).subscribe(this.bufferLength$)),this.representationSubscription.add(Fi(Vt(this.element,"ended"),this.forceEnded$).subscribe(()=>{this.stopStallWatchdogSubscription()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe(Aa()).subscribe(p=>this.liveStreamEndTimestamp=xd())),this.subscription.add(Vt(this.element,"pause").subscribe(()=>{let{liveUpdateInterval:p}=this.tuning.dash;this.livePauseWatchdogSubscription=Ed(p).subscribe(f=>{let m=Yt(this.manifestUrlString,2);this.manifestUrlString=ne(this.manifestUrlString,m+p,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add(Vt(this.element,"play").subscribe(p=>{var f;return(f=this.livePauseWatchdogSubscription)==null?void 0:f.unsubscribe()})),this.representationSubscription.add(_r({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(Or(({isActiveLive:p,isLowLatency:f})=>p&&f),Aa()).subscribe(p=>{this.isManualDecreasePlaybackInLive()||Dr(this.element,1)})),this.representationSubscription.add(_r({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(Xo(({bufferLength:p,isActiveLive:f,isLowLatency:m})=>f&&m&&!!p)).subscribe(({bufferLength:p})=>this.liveBuffer.next(p))),this.representationSubscription.add(this.videoBufferManager.currentLowLatencySegmentLength$.subscribe(p=>{if(!this.isActiveLive$.getValue()&&!this.isLowLatency$.getValue()&&!p)return;let f=this.liveSeekableDuration$.getValue()-p/1e3;this.liveSeekableDuration$.next(Math.max(f,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+p/1e3)})),this.representationSubscription.add(_r({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(Xo(({isLive:p})=>p),Aa((p,f)=>f.bufferLength<p.bufferLength),Or(({rtt:p,bufferLength:f,segmentServerLatency:m})=>{let g=Yt(this.manifestUrlString,2);return(p/2+f+m+g)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(_r({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:p,isActiveLive:f,isLowLatency:m})=>{if(!m||!f)return;let g=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,b=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,S=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,T=p-g;if(this.isManualDecreasePlaybackInLive())return;let y=1;Math.abs(T)>b&&(y=1+Math.sign(T)*S),Dr(this.element,y)})),this.representationSubscription.add(this.bufferLength$.subscribe(p=>{var m,g;let f=0;if(p){let b=((g=(m=this.element)==null?void 0:m.currentTime)!=null?g:0)*1e3;f=Math.min(...this.bufferManagers.map(T=>{var y,E;return(E=(y=T.getLiveSegmentsToLoadState(this.manifest))==null?void 0:y.to)!=null?E:b}))-b}this.liveLoadBufferLength$.getValue()!==f&&this.liveLoadBufferLength$.next(f)}));let h=0;this.representationSubscription.add(_r({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(S0(this.tuning.dash.liveUpdateInterval)).subscribe(async({liveLoadBufferLength:p,bufferLength:f})=>{if(!this.element||this.isUpdatingLive)return;let m=this.element.playbackRate,g=Yt(this.manifestUrlString,2),b=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,S=Math.min(b,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*m),T=this.tuning.dashCmafLive.normalizedActualBufferOffset*m,y=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*m,E=isFinite(p)?p:f,A=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),$=b<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next($);let L="none";if(A?L="active_low_latency":this.isLowLatency$.getValue()&&$?(this.bufferManagers.forEach(C=>C.proceedLowLatencyLive()),L="active_low_latency"):g!==0&&E<S?L="live_forward_buffering":E<S+y&&(L="live_with_target_offset"),isFinite(p)&&(h=p>h?p:h),L==="live_forward_buffering"||L==="live_with_target_offset"){let C=h-(S+T),P=this.normalizeLiveOffset(Math.trunc(g+C/m)),B=Math.abs(P-g),M=0;!p||B<=this.tuning.dashCmafLive.offsetCalculationError?M=g:P>0&&B>this.tuning.dashCmafLive.offsetCalculationError&&(M=P),this.manifestUrlString=ne(this.manifestUrlString,M,2)}(L==="live_with_target_offset"||L==="live_forward_buffering")&&(h=0,await this.updateLive())},p=>{this.error$.next({id:"updateLive",category:Je.VIDEO_PIPELINE,thrown:p,message:"Failed to update live with subscription"})}))}let u=Fi(...this.bufferManagers.map(h=>h.fullyBuffered$)).pipe(Or(()=>this.bufferManagers.every(h=>h.fullyBuffered$.getValue()))),c=Fi(...this.bufferManagers.map(h=>h.onLastSegment$)).pipe(Or(()=>this.bufferManagers.some(h=>h.onLastSegment$.getValue()))),d=_r({allBuffersFull:u,someBufferEnded:c}).pipe(Aa(),Or(({allBuffersFull:h,someBufferEnded:p})=>h&&p),Xo(h=>h));if(this.representationSubscription.add(Fi(this.forceEnded$,d).subscribe(()=>{var h;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(p=>!p.updating))try{(h=this.source)==null||h.endOfStream()}catch(p){this.error$.next({id:"EndOfStream",category:Je.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:p})}})),this.representationSubscription.add(Fi(...this.bufferManagers.map(h=>h.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 h=this.tuning.dash.sourceOpenTimeout>=0;yield new Promise(p=>{var f;h&&(this.timeoutSourceOpenId=setTimeout(()=>{var m;if(((m=this.source)==null?void 0:m.readyState)==="open"){p();return}this.error$.next({id:"OpenOfStream",category:Je.VIDEO_PIPELINE,message:"Failed to open MediaSource",thrown:new Error("Timeout reject when wait sourceopen event"),traceAsLog:!0})},this.tuning.dash.sourceOpenTimeout)),(f=this.source)==null||f.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),p()},{once:!0})})}if(!this.isLive$.getValue()){let h=[(l=this.manifest.duration)!=null?l:0,...(0,wd.default)((0,wd.default)([...this.manifest.streams.audio,...this.manifest.streams.video],p=>p.representations),p=>{let f=[];return p.duration&&f.push(p.duration),He(p.segmentReference)&&p.segmentReference.totalSegmentsDurationMs&&f.push(p.segmentReference.totalSegmentsDurationMs),f})];this.source.duration=Math.max(...h)/1e3}this.audioBufferManager&&Ra(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")}.bind(this));this.tick=()=>{var t,i,r,a;if(!this.element||!this.videoBufferManager||((t=this.source)==null?void 0:t.readyState)!=="open")return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),(i=this.audioBufferManager)==null||i.maintain(e),(r=this.liveTextManager)==null||r.maintain(e),(this.videoBufferManager.gaps.length||(a=this.audioBufferManager)!=null&&a.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=Ed(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),n=>{this.error$.next({id:"GapWatchdog",category:Je.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.forceVideoCodec=e.forceVideoCodec,this.fetcher=new qo({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=Bt.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator}),this.initTracerSubscription()}setSmartRepresentationSwitch(e){this.bufferManagers.forEach(t=>t.setSmartRepresentationSwitch(e))}async seekLive(e){Vr(this.element),this.updateManifestUrlWithTimeOffset(e),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await this.updateLiveBuffersFromManifest(this.manifest))}updateManifestUrlWithTimeOffset(e){let t=this.liveStreamStatus$.getValue()!=="active"?xd()-this.liveStreamEndTimestamp:0,i=this.normalizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=ne(this.manifestUrlString,i,2)}async updateLiveBuffersFromManifest(e){var t,i,r;await((t=this.videoBufferManager)==null?void 0:t.seekLive(e.streams.video)),await((i=this.audioBufferManager)==null?void 0:i.seekLive(e.streams.audio)),(r=this.liveTextManager)==null||r.seekLive(e.streams.text)}stopStallWatchdogSubscription(){var e;(e=this.stallWatchdogSubscription)==null||e.unsubscribe(),this.currentStallDuration$.next(0)}initBuffer(){Vr(this.element),this.state$.setState("running"),this.subscription.add(Fi(...y0.map(e=>Vt(this.element,e)),Vt(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:Je.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(Vt(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(Vt(this.element,"waiting").subscribe(()=>{this.tuning.dash.useVideoElementWaitingCurrentTimeReassign&&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 y,E,A,$,L,C,P,B,M,F,Q;let{keepSilentStallWatchdogWhenNotActive:t}=this.tuning.dashCmafLive,{crashOnStallTimeout:i,crashOnStallTWithoutDataTimeout:r,liveStallReinitInterval:a,stallWatchdogInterval:n}=this.tuning.dash,o=this.isLive$.getValue(),c=this.liveStreamStatus$.getValue()==="active";if(!this.element||((y=this.source)==null?void 0:y.readyState)!=="open")return;let d=this.currentStallDuration$.getValue();d+=n,this.currentStallDuration$.next(d);let l={timeInWaiting:d},h=xd(),p=100,f=(A=(E=this.videoBufferManager)==null?void 0:E.lastDataObtainedTimestamp)!=null?A:0;this.videoLastDataObtainedTimestamp$.next(f);let m=(L=($=this.audioBufferManager)==null?void 0:$.lastDataObtainedTimestamp)!=null?L:0,g=(P=(C=this.videoBufferManager)==null?void 0:C.getForwardBufferDuration())!=null?P:0,b=(M=(B=this.audioBufferManager)==null?void 0:B.getForwardBufferDuration())!=null?M:0,S=g<p&&h-f>r,T=this.audioBufferManager&&b<p&&h-m>r;if((!t||c)&&((S||T)&&d>r||d>=i))throw new Error(`Stall timeout exceeded: ${d} ms`);if(o&&d%a===0){let j=this.normalizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);!c&&t?(this.liveWasInterrupted=!0,this.updateManifestUrlWithTimeOffset(j),this.updateManifest()):this.seekLive(j).catch(I=>{this.error$.next({id:"stallIntervalCallback",category:Je.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:I})}),l.liveLastOffset=j}else{let j=this.element.currentTime*1e3;(F=this.videoBufferManager)==null||F.maintain(j),(Q=this.audioBufferManager)==null||Q.maintain(j),l.position=j}this.tracer.log("stallIntervalCallback",Pa(l))};this.stallWatchdogSubscription&&(this.stallWatchdogSubscription.unsubscribe(),this.subscriptionRemovable.remove(this.stallWatchdogSubscription)),this.stallWatchdogSubscription=Ed(this.tuning.dash.stallWatchdogInterval).subscribe(e,t=>{this.error$.next({id:"StallWatchdogCallback",category:Je.NETWORK,message:"Can't restore DASH after stall.",thrown:t})}),this.subscriptionRemovable.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,i=!1){let r={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return this.tuning.useNewSwitchTo?this.currentStallDuration$.getValue()>0?r==null?void 0:r.switchToWithPreviousAbort(t,i):r==null?void 0:r.switchTo(t,i):r==null?void 0:r.switchToOld(t,i)}async seek(e,t){var r,a,n,o,u;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=(a=this.audioBufferManager)==null?void 0:a.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()]),!($I(this.element)||$I(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),(u=this.audioBufferManager)==null||u.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",Pa({requestedPosition:e,forcePrecise:t,position:i})))}warmUpMediaSourceIfNeeded(e=(t=>(t=this.element)==null?void 0:t.currentTime)()){var i;Ra(this.element)&&Ra(this.source)&&Ra(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}getCodecs(){var e;return(e=this.manifest)==null?void 0:e.codecs}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){var e;this.subscription.unsubscribe(),this.subscriptionRemovable.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=b0(this.tracer.error.bind(this.tracer));this.subscription.add(this.error$.subscribe(e("error")))}isManualDecreasePlaybackInLive(){if(!this.element||!this.isLive$.getValue())return!1;let e=1-this.element.playbackRate;return Number(e.toFixed(2))>Number(this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup.toFixed(2))}normalizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){var e;this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&(this.bufferManagers.forEach(t=>t.updateLive(this.manifest)),(e=this.liveTextManager)==null||e.updateLive(this.manifest)),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getDebugBufferState();if(!e)return;let t=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),i={isJumpGapAfterSeekLive:this.isJumpGapAfterSeekLive,isActiveLowLatency:t,initialCurrentTime:this.element.currentTime},{usePersistentGaps:r}=this.tuning.dash;this.isJumpGapAfterSeekLive&&!t&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let a=this.element.currentTime*1e3,n=[],o=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let u of this.bufferManagers)for(let c of u.gaps)(r&&c.persistent||u.playingRepresentation$.getValue()===c.representation)&&c.from-o<=a&&c.to+o>a&&(this.element.duration*1e3-c.to<this.tuning.endGapTolerance?n.push(1/0):n.push(c.to));if(n.length){let u=Math.max(...n)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,u===1/0?this.forceEnded$.next():(this.element.currentTime=u/1e3,i={...i,gapEnds:n,jumpTo:u,resultCurrentTime:this.element.currentTime},this.tracer.log("jumpGap",Pa(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 Zo=class{constructor(e,t){this.fov=e,this.orientation=t}};var eu=class{constructor(e,t){this.rotating=!1;this.fading=!1;this.lastTickTS=0;this.lastCameraTurnTS=0;this.fadeStartSpeed=null;this.fadeTime=0;this.camera=e,this.options=t,this.rotationSpeed={x:0,y:0,z:0},this.fadeCorrection=1/(this.options.speedFadeTime/1e3)**2}turnCamera(e=0,t=0,i=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+i)}pointCameraTo(e=0,t=0,i=0){t=this.limitCameraRotationY(t);let r=e-this.camera.orientation.x,a=t-this.camera.orientation.y,n=i-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=i,this.lastCameraTurn={x:r,y:a,z:n},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,i){this.rotationSpeed.x=e!=null?e:this.rotationSpeed.x,this.rotationSpeed.y=t!=null?t:this.rotationSpeed.y,this.rotationSpeed.z=i!=null?i:this.rotationSpeed.z}startRotation(){this.rotating=!0}stopRotation(e=!1){e?(this.setRotationSpeed(0,0,0),this.fadeStartSpeed=null):this.startFading(this.rotationSpeed.x,this.rotationSpeed.y,this.rotationSpeed.z),this.rotating=!1}onCameraRelease(){if(this.lastCameraTurn&&this.lastCameraTurnTS){let e=Date.now()-this.lastCameraTurnTS;if(e<this.options.speedFadeThreshold){let t=(1-e/this.options.speedFadeThreshold)*this.options.rotationSpeedCorrection;this.startFading(this.lastCameraTurn.x*t,this.lastCameraTurn.y*t,this.lastCameraTurn.z*t)}}}startFading(e,t,i){this.setRotationSpeed(e,t,i),this.fadeStartSpeed={...this.rotationSpeed},this.fading=!0}stopFading(){this.fadeStartSpeed=null,this.fading=!0,this.fadeTime=0}limitCameraRotationY(e){return Math.max(-this.options.maxYawAngle,Math.min(e,this.options.maxYawAngle))}tick(e){if(!this.lastTickTS){this.lastTickTS=e,this.lastCameraTurnTS=Date.now();return}let t=e-this.lastTickTS,i=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i);else if(this.fading&&this.fadeStartSpeed){let r=-this.fadeCorrection*(this.fadeTime/1e3)**2+1;this.setRotationSpeed(this.fadeStartSpeed.x*r,this.fadeStartSpeed.y*r,this.fadeStartSpeed.z*r),r>0?this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}};var DI=`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 BI=`#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 Or=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 Uo(this.params.fov,this.params.orientation),this.cameraRotationManager=new Ho(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(mI,this.gl.VERTEX_SHADER),i=this.createShader(bI,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,i),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){let e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,i=1,r=this.frameHeight/(this.frameWidth/this.viewportWidth);return r>this.viewportHeight?t=this.viewportHeight/r:i=r/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-i,t,-i,t,i,-t,i]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){let e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,i=this.camera.fov.x/360/2,r=this.camera.fov.y/180/2,s=e-i,n=t-r,o=e+i,u=t-r,l=e+i,c=t+r,d=e-i,h=t+r;return[s,n,o,u,l,c,d,h]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){let e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}};import{isNullable as NB,now as Is,once as qB,Subscription as UB,ValueSubject as hd,isNonNullable as HB,safeStorage as fd,filterChanged as jB}from"@vkontakte/videoplayer-shared/es2018";var jo="stalls_manager_metrics",md="stalls_manager_abr_params",gI="stalls_manager_default_tuning_abr_params",bd=class{constructor(){this.isSeeked$=new hd(!1);this.isBuffering$=new hd(!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 UB;this.severeStallOccurred$=new hd(!1)}init(e){this.currentStallDuration$=e.currentStallDuration$,this.videoLastDataObtainedTimestamp$=e.videoLastDataObtainedTimestamp$,this.throughput$=e.throughput$,this.rtt$=e.rtt$,this.tuning=e.tuning,this.abrParams=e.abrParams,this.duration=e.duration,this.resetStoredAbrParamsIfNeeded(),this.subscribe(e)}get videoMaxQualityLimit(){return this.maxQualityLimit}get predictedThroughput(){return this.predictedThroughputWithoutData}get abrTuningParams(){let t=(this.tuning.ignoreDynamicAbrForShortVideo?this.tuning.enabled&&this.duration>this.tuning.minTvtToBeCounted:this.tuning.enabled)?this.getStoredData(md):{};return{...this.abrParams,...t}}set lastVideoTrackSelected(e){var t;((t=this.lastUniqueVideoTrackSelected)==null?void 0:t.id)!==e.id&&(this.lastUniqueVideoTrackSelected=e,this.lastUniqueVideoTrackSelectedTimestamp=Is(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe(),this.currentStallDuration$.getValue()!==0&&this.updateStallData();let e=(Is()-this.providerStartWatchingTimestamp-this.sumStallsDuration)/1e3,t=this.sumStallsDuration;this.addStallInfoToHistory(e,t),this.updateStoredAbrParams()}resetStoredAbrParamsIfNeeded(){let{bitrateFactorAtEmptyBuffer:e,bitrateFactorAtFullBuffer:t,containerSizeFactor:i}={...this.getStoredData(gI)},{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:s,containerSizeFactor:n}={...this.abrParams};this.tuning.enabled&&e===r&&t===s&&i===n||(this.removeStoredData(md),this.setStoredData(gI,{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:s,containerSizeFactor:n}))}updateStoredAbrParams(){let e=[],t=this.getStoredData(jo,"[]");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(jo,[]),this.setStoredData(md,r)}calculateOptimalAbrParams(e,t){let{targetStallsDurationPerTvt:i,deviationStallsDurationPerTvt:r,criticalStallsDurationPerTvt:s,abrAdjustingSpeed:n,significantTvt:o}=this.tuning,u=n*Math.min(t/o,1),l=this.abrTuningParams;return e<i-r?l={bitrateFactorAtEmptyBuffer:Math.max(l.bitrateFactorAtEmptyBuffer-u,this.abrParams.minBitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.max(l.bitrateFactorAtFullBuffer-u,this.abrParams.minBitrateFactorAtFullBuffer),containerSizeFactor:Math.min(l.containerSizeFactor+u,this.abrParams.maxContainerSizeFactor)}:e>i+r&&(l={bitrateFactorAtEmptyBuffer:Math.min(l.bitrateFactorAtEmptyBuffer+u,this.abrParams.maxBitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.min(l.bitrateFactorAtFullBuffer+u,this.abrParams.maxBitrateFactorAtFullBuffer),containerSizeFactor:Math.max(l.containerSizeFactor-u,this.abrParams.minContainerSizeFactor)}),e>s&&(l={bitrateFactorAtEmptyBuffer:Math.max(l.bitrateFactorAtEmptyBuffer,this.abrParams.bitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.max(l.bitrateFactorAtFullBuffer,this.abrParams.bitrateFactorAtFullBuffer),containerSizeFactor:Math.min(l.containerSizeFactor,this.abrParams.containerSizeFactor)}),l}getStoredData(e,t="{}"){var i;return JSON.parse((i=fd.get(e))!=null?i:t)}setStoredData(e,t){fd.set(e,JSON.stringify(t))}removeStoredData(e){fd.remove(e)}addStallInfoToHistory(e,t){if(e<this.tuning.minTvtToBeCounted||e>this.tuning.maxTvtToBeCounted||e*1e3<t)return;let i=this.getStoredData(jo,"[]"),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(jo,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(qB()).subscribe(t=>this.providerStartWatchingTimestamp=Is())),this.subscription.add(this.currentStallDuration$.pipe(jB()).subscribe(t=>{let{stallDurationNoDataBeforeQualityDecrease:i,stallCountBeforeQualityDecrease:r,resetQualityRestrictionTimeout:s,ignoreStallsOnSeek:n}=this.tuning;if(NB(this.lastUniqueVideoTrackSelected)||n&&this.isSeeked$.getValue())return;let o=this.rtt$.getValue(),u=this.throughput$.getValue(),l=this.videoLastDataObtainedTimestamp$.getValue(),c=Is(),d=r&&this.currentStallsCount>=r,h=i&&c-this.lastUniqueVideoTrackSelectedTimestamp>=i+o&&c-l>=i+o&&t>=i;(d||h)&&(this.severeStallOccurred$.next(!0),window.clearTimeout(this.qualityRestrictionTimer),this.maxQualityLimit=this.lastUniqueVideoTrackSelected.quality,HB(this.lastUniqueVideoTrackSelected.bitrate)&&u>this.lastUniqueVideoTrackSelected.bitrate&&(this.predictedThroughputWithoutData=this.lastUniqueVideoTrackSelected.bitrate)),!t&&Is()-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}))}},Wo=bd;import{combine as WB,map as QB,observeElementSize as GB,Subscription as zB,ValueSubject as gd,noop as YB}from"@vkontakte/videoplayer-shared/es2018";var Qo=class{constructor(){this.subscription=new zB;this.pipSize$=new gd(void 0);this.videoSize$=new gd(void 0);this.elementSize$=new gd(void 0);this.pictureInPictureWindowRemoveEventListener=YB}connect({observableVideo:e,video:t}){let i=r=>{let s=r.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add(GB(t).subscribe(this.videoSize$)).add(e.enterPip$.subscribe(({pictureInPictureWindow:r})=>{this.pipSize$.next({width:r.width,height:r.height}),r.addEventListener("resize",i),this.pictureInPictureWindowRemoveEventListener=()=>{r.removeEventListener("resize",i)}})).add(e.leavePip$.subscribe(()=>{this.pictureInPictureWindowRemoveEventListener()})).add(WB({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(QB(({videoSize:r,inPip:s,pipSize:n})=>s?n:r)).subscribe(this.elementSize$))}getValue(){return this.elementSize$.getValue()}subscribe(e,t){return this.elementSize$.subscribe(e,t)}getObservable(){return this.elementSize$}destroy(){this.pictureInPictureWindowRemoveEventListener(),this.subscription.unsubscribe()}};import{filter as SI,map as KB,once as vI}from"@vkontakte/videoplayer-shared/es2018";var Fr=({subscription:a,desiredState:e,videoElement$:t,observableVideo:i})=>{if(!_.browser.isSafari)return;let r=0,s=!1;a.add(e.volume.stateChangeStarted$.pipe(KB(()=>{let n=e.volume.getTransition(),o=t.getValue();return!o||!n?!1:!n.to.muted&&o.muted}),SI(n=>!!n),vI()).subscribe(()=>{r=performance.now(),s=!0})),a.add(i.playbackRateState$.pipe(SI(()=>s),vI()).subscribe(()=>{let n=t.getValue(),o=e.playbackRate.getState();n&&o!==n.playbackRate&&performance.now()-r<1e3&&(n.playbackRate=o)}))};var Fi=class{constructor(e){this.subscription=new a0;this.videoState=new U("stopped");this.observableVideo=null;this.droppedFramesManager=new Er;this.stallsManager=new Wo;this.elementSizeManager=new Qo;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Xt;this.audioTrackSwitchHistory=new Xt;this.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 JB(e)}}};this.init3DScene=e=>{var i,r,s;if(this.scene3D)return;this.scene3D=new Or(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 Ye(e.source.url),this.params=e,this.video=Ce(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(ye(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,forceVideoCodec:this.params.forceVideoCodec}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params;r0(this.observableVideo)&&(this.observableVideo=_e(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:yI.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(d=>!!d.length),II()).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(xs(d=>d.to.state!=="none"),Es());this.stallsManager.init({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$,videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,tuning:this.params.tuning.stallsManager,abrParams:this.params.tuning.autoTrackSelection,isBuffering$:i.isBuffering$,looped$:i.looped$,playing$:i.playing$,duration:this.video.duration}),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(this.player.error$,e.error$),s(this.player.fetcherRecoverableError$,e.fetcherRecoverableError$),s(this.player.fetcherError$,e.fetcherError$),s(this.player.lastConnectionType$,e.httpConnectionType$),s(this.player.lastConnectionReused$,e.httpConnectionReused$),s(this.player.isLive$,e.isLive$),s(this.player.lastRequestFirstBytes$.pipe(Sd(TI),II()),e.firstBytesEvent$),s(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),s(this.videoState.stateChangeEnded$.pipe(xs(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(i.volumeState$.subscribe(this.params.output.volume$,r)),Fr({subscription:this.subscription,desiredState:t,videoElement$:this.params.output.element$,observableVideo:i}),this.subscription.add(Ve(this.video,t.volume,i.volumeState$,r)),this.subscription.add(ze(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),s(Ke(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),$(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.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(i.ended$.subscribe(()=>{this.videoState.setState("paused"),$(t.playbackState,"paused")})),this.subscription.add(this.player.manifestRequested.subscribe(this.params.output.manifestRequested$)).add(this.player.manifestReceived.subscribe(this.params.output.manifestReceived$)).add(this.player.firstBytesRequested.subscribe(this.params.output.firstBytesRequested$)).add(this.player.firstBytesReceived.subscribe(this.params.output.firstBytesReceived$)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:d})=>{if(d==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let h=this.player.getStreams(),p=this.player.getCodecs();if(ZB(h,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let m=[];for(let g of h.audio){m.push(ed(g));let b=[];for(let v of g.representations){let T=eI(v);b.push(T),this.audioTracksMap.set(T,{stream:g,representation:v})}this.audioStreamsMap.set(g,b)}this.params.output.availableAudioStreams$.next(m)}let f=[];for(let m of h.video){f.push(td(m));let g=[];for(let b of m.representations){let v=hs({...b,streamId:m.id});v&&(g.push(v),this.videoTracksMap.set(v,{stream:m,representation:b}))}this.videoStreamsMap.set(m,g)}this.params.output.availableVideoStreams$.next(f);for(let m of h.text)for(let g of m.representations){let b=tI(m,g);this.textTracksMap.set(b,{stream:m,representation:g})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),p!=null&&p.video&&this.params.output.availableVideoCodecs$.next(p.video),p!=null&&p.audio&&this.params.output.availableAudioCodecs$.next(p.audio),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 o=ws(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$,i0(this.video,"progress")).pipe(Sd(()=>this.videoTracksMap.size>0)),{abrThrottle:u}=this.params.tuning.dash;u&&(o=o.pipe(s0(u))),this.subscription.add(o.subscribe(async()=>{let d=this.player.state$.getState(),h=this.player.state$.getTransition();if(d!=="manifest_ready"&&d!=="running"||h)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let p=this.selectVideoAudioRepresentations();if(!p)return;let[f,m]=p,g=[...this.videoTracksMap.keys()].find(v=>{var T;return((T=this.videoTracksMap.get(v))==null?void 0:T.representation.id)===f.id});TI(g)&&(this.stallsManager.lastVideoTrackSelected=g);let b=this.params.desiredState.autoVideoTrackLimits.getTransition();if(b&&this.params.output.autoVideoTrackLimits$.next(b.to),d==="manifest_ready")await this.player.initRepresentations(f.id,m==null?void 0:m.id,this.params.sourceHls);else if(await this.player.switchRepresentation("video",f.id),m){let v=!!t.audioStream.getTransition();await this.player.switchRepresentation("audio",m.id,v)}},r)),this.subscription.add(e0({videoState:this.videoState.stateChangeEnded$,autoVideoTrackState:ws(Go([t.autoVideoTrackSwitching.getState()]),t.autoVideoTrackSwitching.stateChangeEnded$.pipe(xs(d=>d.to)))}).pipe(xs(({videoState:d,autoVideoTrackState:h})=>d.to!=="stopped"&&h),Es()).subscribe(d=>this.player.setSmartRepresentationSwitch(d))),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(Es()).subscribe(d=>{let h=[...this.videoTracksMap.entries()].find(([,{representation:b}])=>b.id===d);if(!h){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[p,{stream:f}]=h,m=this.params.desiredState.videoStream.getTransition();m&&m.to&&m.to.id===f.id&&this.params.desiredState.videoStream.setState(m.to),e.currentVideoTrack$.next(p),e.currentVideoStream$.next(td(f));let g=this.player.calculateDurationFromSegments();g&&this.params.output.duration$.next(g/1e3)},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(Es()).subscribe(d=>{let h=[...this.audioTracksMap.entries()].find(([,{representation:g}])=>g.id===d);if(!h){e.currentAudioStream$.next(void 0);return}let[p,{stream:f}]=h,m=this.params.desiredState.audioStream.getTransition();m&&m.to&&m.to.id===f.id&&this.params.desiredState.audioStream.setState(m.to),e.currentAudioStream$.next(ed(f))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(d=>{var h,p;if(d!=null&&d.is3dVideo&&((h=this.params.tuning.spherical)!=null&&h.enabled))try{this.init3DScene(d),e.is3DVideo$.next(!0)}catch(f){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${f}`})}else this.destroy3DScene(),(p=this.params.tuning.spherical)!=null&&p.enabled&&e.is3DVideo$.next(!1)},r)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,r)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,r)),this.textTracksManager.connect(this.video,t,e);let l=t.playbackState.stateChangeStarted$.pipe(xs(({to:d})=>d==="ready"),Es());this.subscription.add(ws(l,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,Go(["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(ws(l,this.player.state$.stateChangeEnded$,Go(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let c=ws(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Go(["init"])).pipe(t0(0));this.subscription.add(c.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){var L,D,R,B,M,O,Q,H,I,P,x,w,V;if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?La:ka,t=this.params.tuning.useNewAutoSelectVideoTrack?fo:ho,i=this.params.tuning.useNewAutoSelectVideoTrack?vt:po,{desiredState:r,output:s}=this.params,n=r.autoVideoTrackSwitching.getState(),o=(L=r.videoTrack.getState())==null?void 0:L.id,u=[...this.videoTracksMap.keys()].find(({id:G})=>G===o),l=s.currentVideoTrack$.getValue(),c=((B=(R=r.videoStream.getState())!=null?R:u&&((D=this.videoTracksMap.get(u))==null?void 0:D.stream))!=null?B:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!c)return;let d=[...this.videoStreamsMap.keys()].find(({id:G})=>G===c.id),h=d&&this.videoStreamsMap.get(d);if(!h)return;let p=Te(this.video.buffered,this.video.currentTime*1e3),f;this.player.isActiveLive$.getValue()?f=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?f=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:f=n?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let m=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,g=Math.min(p/Math.min(f,m||1/0),1),b=(M=r.audioStream.getState())!=null?M:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,v=(O=[...this.audioStreamsMap.keys()].find(({id:G})=>G===(b==null?void 0:b.id)))!=null?O:this.audioStreamsMap.keys().next().value,T=0;if(v){if(u&&!n){let G=e(u,h,(Q=this.audioStreamsMap.get(v))!=null?Q:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);T=Math.max(T,(H=G==null?void 0:G.bitrate)!=null?H:-1/0)}if(l){let G=e(l,h,(I=this.audioStreamsMap.get(v))!=null?I:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);T=Math.max(T,(P=G==null?void 0:G.bitrate)!=null?P:-1/0)}}let y=u;(n||!y)&&(y=i(h,{container:this.elementSizeManager.getValue(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.stallsManager.abrTuningParams,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:T,forwardBufferHealth:g,current:l,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,stallsVideoMaxQualityLimit:this.stallsManager.videoMaxQualityLimit,stallsPredictedThroughput:this.stallsManager.predictedThroughput,abrLogger:this.params.dependencies.abrLogger}));let E=v&&t(y,h,(x=this.audioStreamsMap.get(v))!=null?x:[],{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}),A=(w=this.videoTracksMap.get(y))==null?void 0:w.representation,k=E&&((V=this.audioTracksMap.get(E))==null?void 0:V.representation);if(A&&k)return[A,k];if(A&&!k&&this.audioTracksMap.size===0)return[A,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Oe(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:yI.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.stallsManager.destroy(),this.elementSizeManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),this.params.output.currentVideoStream$.next(void 0),Be(this.video),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 vd,merge as EI,filter as xI,filterChanged as wI,isNullable as yd,map as AI,ValueSubject as Td,isNonNullable as n0}from"@vkontakte/videoplayer-shared/es2018";var Rs=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 Td(1);n(r.playbackRateState$,o),this.params.tuning.dashCmafLive.catchupLiveForMutedInactiveTab&&this.subscription.add(i.elementVisible$.pipe(wI()).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(AI(u=>u.to)).subscribe(this.player.isLowLatency$)).add(vd({liveBufferTime:i.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(AI(({liveBufferTime:u,liveAvailabilityStartTime:l})=>u&&l?u+l:void 0)).subscribe(i.liveTime$)).add(vd({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:EI(r.playbackRateState$,new Td(1))}).pipe(xI(({liveStreamStatus:u,liveDuration:l})=>u==="active"&&!!l)).subscribe(({liveDuration:u,playbackRate:l})=>{let c=i.liveBufferTime$.getValue(),d=i.position$.getValue(),{playbackCatchupSpeedup:h}=this.params.tuning.dashCmafLive.lowLatency;d||l<1-h||this.video.paused||yd(c)||(t=u-c)})).add(vd({time:i.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:EI(r.playbackRateState$,new Td(1))}).pipe(wI((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:h}=this.params.tuning.dashCmafLive.lowLatency;if(!d&&!this.video.paused&&c>=1-h||yd(u)||yd(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=iI(u);this.params.output.availableTextTracks$.next([l])}})),this.params.tuning.dashCmafLive.externalStopControl||this.subscription.add(this.player.liveStreamStatus$.pipe(xI(u=>n0(u))).subscribe(u=>i.isLiveEnded$.next(u==="unpublished"&&i.position$.getValue()===0)))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=Math.trunc(t/1e3<=Math.abs(this.params.output.duration$.getValue())?t:0);this.player.seekLive(i).then(()=>{this.params.output.position$.next(e/1e3)})}};import{assertNever as C0,assertNonNullable as B0,combine as V0,debounce as _0,ErrorCategory as HI,filter as _d,filterChanged as _s,fromEvent as O0,isNonNullable as jI,isNullable as F0,map as Os,merge as Fs,observableFrom as au,once as WI,Subscription as N0}from"@vkontakte/videoplayer-shared/es2018";var UI=F(De(),1),Bd=F(Oa(),1);import{abortable as $d,assertNonNullable as Ur,combine as Hr,ErrorCategory as lt,filter as tu,filterChanged as Cs,flattenObject as Bs,fromEvent as Et,getTraceSubscriptionMethod as E0,interval as Md,isNonNullable as Vs,isNullable as NI,map as jr,merge as ji,now as Dd,Subject as ni,Subscription as Cd,SubscriptionRemovable as x0,tap as w0,throttle as qI,ValueSubject as re}from"@vkontakte/videoplayer-shared/es2018";var Xo=F(De(),1),Hi=F(nt(),1),Jo=F(Oa(),1);var VI=F(Wn(),1);import{assertNever as o0,ErrorCategory as RI,Subject as PI}from"@vkontakte/videoplayer-shared/es2018";var u0=18,kI=!1;try{kI=_.browser.isSafari&&!!_.browser.safariVersion&&_.browser.safariVersion<=u0}catch(a){console.error(a)}var Id=class{constructor(e){this.bufferFull$=new PI;this.error$=new PI;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:RI.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)};kI&&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:RI.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:o0(t)}}},LI=Id;import{abortable as ai,assertNonNullable as Le,ErrorCategory as qi,fromEvent as Rd,getExponentialDelay as Pd,isHigher as h0,isNonNullable as si,isNullable as de,now as Ko,once as f0,Subject as m0,Subscription as b0,ValueSubject as Ui}from"@vkontakte/videoplayer-shared/es2018";var Ed=F(nt(),1);import{videoSizeToQuality as l0,throttleFn as c0}from"@vkontakte/videoplayer-shared/es2018";var Ps=({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:l0({width:e,height:t});return o&&{id:a,quality:o,bitrate:i,size:{width:e,height:t},fps:r,streamId:n}},$I=({id:a,bitrate:e})=>({id:a,bitrate:e}),MI=({language:a,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),DI=({language:a,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),xd=({id:a,language:e,label:t,codecs:i,isDefault:r})=>({id:a,language:e,label:t,codec:(0,Ed.default)(i.split("."),0),isDefault:r}),wd=({id:a,language:e,label:t,hdr:i,codecs:r})=>({id:a,language:e,hdr:i,label:t,codec:(0,Ed.default)(r.split("."),0)}),Ad=a=>"url"in a,We=a=>a.type==="template";var CI=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},Ni=(a,e)=>{for(let t of a)if(e(t))return t;return null},BI=a=>{let e=!1,t=c0(()=>{e=!0},a);return()=>{try{return t(),e}finally{e=!1}}};import{fromEvent as d0,Subscription as p0}from"@vkontakte/videoplayer-shared/es2018";var zo=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 Yo=class{constructor(e,t){this.lastUpdateTs=0;this.lastCallTs=0;this.prevRanges=[];this.subscription=new p0;this.mediaSource=e,this.sourceBuffer=t,this.subscription.add(d0(this.sourceBuffer,"updateend").subscribe(()=>this.updateend()))}updateend(){if(!N(this.mediaSource,this.sourceBuffer))return;let{prevRanges:e}=this,t=zo(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 ks=class{constructor(e,t,i,{fetcher:r,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new Ui(0);this.currentLowLatencySegmentLength$=new Ui(0);this.currentSegmentLength$=new Ui(0);this.onLastSegment$=new Ui(!1);this.fullyBuffered$=new Ui(!1);this.playingRepresentation$=new Ui(void 0);this.playingRepresentationInit$=new Ui(void 0);this.error$=new m0;this.gaps=[];this.subscription=new b0;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new J;this.switchAbortController=new J;this.destroyAbortController=new J;this.useSmartRepresentationSwitch=!1;this.bufferLimit=1/0;this.failedDownloads=0;this.baseUrls=[];this.baseUrlsIndex=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.lastDataObtainedTimestampMs=0;this.loadByteRangeSegmentsTimeoutId=0;this.sourceBufferBufferedDiff=null;this.startWith=ai(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);Le(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new LI(this.sourceBuffer),this.sourceBufferBufferedDiff=new Yo(this.mediaSource,this.sourceBuffer),this.subscription.add(Rd(this.sourceBuffer,"updateend").subscribe(()=>{this.maintain()})),this.subscription.add(Rd(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:qi.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,Ar(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=Te(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);Le(i,"No init buffer for starting representation"),Le(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=ai(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);Le(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if(de(s)||de(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),Le(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();si(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=ai(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);Le(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if(de(s)||de(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),Le(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();si(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=ai(this.destroyAbortController.signal,async function*(e){var u;let t=(0,Jo.default)(e,l=>l.representations);if(!this.downloadingRepresentationId||!t.length)return;this.isSeekingLive=!0;for(let l of this.representations.keys()){let c=t.find(p=>p.id===l);c&&this.representations.set(l,c);let d=this.representations.get(l);if(!d||!We(d.segmentReference)){this.isSeekingLive=!1;return}let h=this.getActualLiveStartingSegments(d.segmentReference);this.segments.set(d.id,h)}let i=(u=this.switchingToRepresentationId)!=null?u:this.downloadingRepresentationId,r=this.representations.get(i);Le(r,`Representation not found by id ${i}`);let s=this.segments.get(i);Le(s,"No segments for starting representation");let n=this.initData.get(i);if(Le(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer)){this.isSeekingLive=!1;return}let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(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 J,ai(this.switchAbortController.signal,async function*(i,r=!1){this.switchingToRepresentationId=i;let s=this.representations.get(i);Le(s,`No such representation ${i}`);let n=this.segments.get(i),o=this.initData.get(i);if(de(o)||de(n)?yield this.loadInit(s,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(i),Le(n,"No segments for starting representation"),o=this.initData.get(i),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer||!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();si(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(){!de(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}async abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);return this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new J,this.abortBuffer()}maintain(e=this.getCurrentPosition()){var h;if(de(e)||de(this.downloadingRepresentationId)||de(this.playingRepresentationId)||de(this.sourceBuffer)||!N(this.mediaSource,this.sourceBuffer)||si(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.representations.get(this.playingRepresentationId),r=this.segments.get(this.downloadingRepresentationId),s=this.segments.get(this.playingRepresentationId);if(Le(t,`No such representation ${this.downloadingRepresentationId}`),Le(i,`No such representation ${this.playingRepresentationId}`),de(r)||de(s))return;let n=r.find(p=>e>=p.time.from&&e<p.time.to);si(n)&&isFinite(n.time.from)&&isFinite(n.time.to)&&this.currentSegmentLength$.next((n==null?void 0:n.time.to)-n.time.from);let o=e,u=100;if(this.playingRepresentationId!==this.downloadingRepresentationId){let p=this.getForwardBufferDuration(e),f=Ps(i),m=Ps(t),g=this.useSmartRepresentationSwitch&&this.tuning.dash.useNewRepresentationSwitch&&this.tuning.dash.useSmartRepresentationSwitch&&si(f)&&si(m)&&h0(f.quality,m.quality),b=this.useSmartRepresentationSwitch&&this.tuning.dash.useNewRepresentationSwitch&&this.tuning.dash.useDelayedRepresentationSwitch;if(g||b?o+=Math.min(p,this.tuning.dash.representationSwitchForwardBufferGap):n&&n.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&p>=n.time.to-e+u&&(o=n?n.time.to+u:-1/0),this.tuning.dash.useNewRepresentationSwitch){let T=(h=[...this.segments.entries()].map(([y,E])=>{let A=E.find(k=>e>=k.time.from&&e<k.time.to);return{representationId:y,status:A==null?void 0:A.status}}).find(y=>y.status==="fed"))==null?void 0:h.representationId;T&&(this.playingRepresentationId=T,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)))}}if(isFinite(this.bufferLimit)&&Ar(this.sourceBuffer.buffered)>=this.bufferLimit){let p=Te(this.sourceBuffer.buffered,e),f=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,p<f).catch(m=>{this.handleAsyncError(m,"pruneBuffer")});return}let c=null;if(!this.activeSegments.size&&(c=this.selectForwardBufferSegments(r,t.segmentReference.type,o),c!=null&&c.length)){let p="auto";if(this.tuning.dash.useFetchPriorityHints&&n)if((0,Xo.default)(c,n))p="high";else{let f=(0,Hi.default)(c,0);f&&f.time.from-n.time.to>=this.forwardBufferTarget/2&&(p="low")}this.loadSegments(c,t,p).catch(f=>{this.handleAsyncError(f,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&n&&n.status==="fed"&&!(c!=null&&c.length)&&Te(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let d=(0,Hi.default)(r,-1);!this.isLive&&d&&(this.fullyBuffered$.next(d.time.to-e-Te(this.sourceBuffer.buffered,e)<u),this.onLastSegment$.next(e-d.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;si(t.duration)&&t.duration-i>0&&!this.isLive&&this.gaps.push({representation:t.id,from:i,to:t.duration,persistent:!0})}getActualLiveStartingSegments(e){let t=e.segments,i=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,r=[],s=0,n=t.length-1;do r.unshift(t[n]),s+=t[n].time.to-t[n].time.from,n--;while(s<i&&n>=0);return this.liveInitialAdditionalOffset=s-i,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){let t=e==null?void 0:e.streams[this.kind];if(!t)return;let i=(0,Jo.default)(t,s=>s.representations).find(s=>s.id===this.downloadingRepresentationId);if(!i)return;let r=this.segments.get(i.id);if(r!=null&&r.length)return{from:r[0].time.from,to:r[r.length-1].time.to}}updateLive(e){var i,r,s,n;if(!e||[...this.segments.values()].every(o=>!o.length))return;let t=(i=(0,Jo.default)(e.streams[this.kind],o=>o.representations))!=null?i:[];for(let o of t){if(!o||!We(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,Hi.default)(c,-1))==null?void 0:s.time.to)!=null?n:0,h=u==null?void 0:u.findIndex(p=>d>=p.time.from+l&&d<=p.time.to+l);if(h===-1){this.liveUpdateSegmentIndex=0;let p=this.getActualLiveStartingSegments(o.segmentReference);this.segments.set(o.id,p)}else{let p=u.slice(h+1);this.segments.set(o.id,[...c,...p])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;Le(e);let t=this.segments.get(e);if(t!=null&&t.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}setSmartRepresentationSwitch(e){this.useSmartRepresentationSwitch=e}updateLowLatencyLiveIfNeeded(e){let t=0;for(let i of this.representations.values()){let r=i.segmentReference;if(!We(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=ut(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:h,time:{from:p,to:f}},m)=>{let g=p<=i&&f>=i,b=p>i||g||m===0&&i===0,v=Math.min(this.forwardBufferTarget,this.bufferLimit),T=this.preloadOnly&&p<=i+v||r<v&&f-p>=v||f<=i+v;return(h==="none"||h==="partially_ejected"&&b&&T&&this.sourceBuffer&&N(this.mediaSource,this.sourceBuffer)&&!(Ie(this.sourceBuffer.buffered,p)&&Ie(this.sourceBuffer.buffered,f)))&&b&&T});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 h=s;h<n.length&&(o<=c||u<=d);h++){let p=n[h];if(o+=p.byte.to+1-p.byte.from,u+=p.time.to+1-p.time.from,p.status==="none"||p.status==="partially_ejected")l.push(p);else break}return l}async loadSegments(e,t,i="auto"){We(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 ai(o,async function*(){let c=Pd(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=Ko(),!c)return;let d=new DataView(c),h=Tt(t.mime);if(!isFinite(r.segment.time.to)){let m=t.segmentReference.timescale;r.segment.time.to=h.getChunkEndTime(d,m)}u&&r.feedingBytes&&l?await Promise.all(l):await this.sourceBufferTaskQueue.append(d,o);let{serverDataReceivedTimestamp:p,serverDataPreparedTime:f}=h.getServerLatencyTimestamps(d);p&&f&&this.currentLiveSegmentServerLatency$.next(f-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())We(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 ai(n,async function*(){let u=Pd(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),Rd(window,"online").pipe(f0()).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=Ko(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),It(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(We(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:(0,Hi.default)(e,0).byte.from,to:(0,Hi.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=Ko(),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:qi.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!We(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=Ko();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:qi.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,Xo.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,h=d-c+1,p=c<r,f=d<=r;if(p){if(l.status==="downloading"&&f){l.status="downloaded";let m=new DataView(e.buffer,e.byteOffset+c,h);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(h,r-c),u.loadedBytes>u.feedingBytes)){let m=new DataView(e.buffer,e.byteOffset+c+u.feedingBytes,u.loadedBytes-u.feedingBytes),g=u.loadedBytes===h?m:Tt(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===h&&this.onSegmentFullyAppended(u,t)):await n())}}}}onSegmentFullyAppended(e,t){if(!(de(this.sourceBuffer)||!N(this.mediaSource,this.sourceBuffer))){!this.isLive&&_.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:qi.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",Ad(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=wr(()=>(0,VI.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?ai(this.destroyAbortController.signal,async function*(){let o=Pd(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 h=c;this.isLive&&We(e.segmentReference)&&(h=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,h),u&&this.parsedInitData.set(e.id,u)}).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:qi.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||de(e))return!1;this.checkEjectedSegments();let r=[],s=0,n=o=>{var l;if(s>=t)return;r.push({...o.time});let u=Ad(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 h of d)(0,Xo.default)(["none","partially_ejected"],h.status)&&Math.round(h.time.from)<=Math.round(u)&&Math.round(h.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=CI(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||de(e)?0:Te(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!this.sourceBuffer||!N(this.mediaSource,this.sourceBuffer))return;let{buffered:i}=this.sourceBuffer,r={representation:e,from:t.time.from,to:t.time.to,persistent:!1};for(let s=0;s<i.length;s++){let n=i.start(s)*1e3,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))return;let{buffered:i}=this.sourceBuffer;this.gaps=this.gaps.filter(r=>{if(r.persistent)return!0;let s=Math.round(r.from),n=Math.round(r.to);for(let o=0;o<i.length;o++)if(s>=Math.round(i.start(o)*1e3)&&n<=Math.round(i.end(o)*1e3))return!1;return!0}),this.gapDetectionIdleCallback=wr(()=>{try{this.detectGaps(e,t)}catch(r){this.error$.next({id:"GapDetection",category:qi.WTF,message:"detectGaps threw",thrown:r})}finally{this.gapDetectionIdleCallback=null}})}checkEjectedSegments(){if(de(this.sourceBuffer)||!N(this.mediaSource,this.sourceBuffer)||de(this.playingRepresentationId)||this.sourceBufferBufferedDiff&&!this.sourceBufferBufferedDiff.wasUpdated())return;let e=zo(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],h=e[c+1];u||(u=d-t<=n&&h+t>=o),(n>=d&&n<h-t||o>d+t&&o<=h)&&(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:qi.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,Hi.default)(e,-1))==null?void 0:t.time.to:0)||0}};import{abortable as Ls,assertNever as _I,fromEvent as OI,merge as g0,now as $s,Subject as Nr,ValueSubject as kd,flattenObject as qr,ErrorCategory as Ms,SubscriptionRemovable as S0}from"@vkontakte/videoplayer-shared/es2018";var eu=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:s=!1}){this.manifestRequested=new Nr;this.manifestReceived=new Nr;this.firstBytesRequested=new Nr;this.firstBytesReceived=new Nr;this.lastConnectionType$=new kd(void 0);this.lastConnectionReused$=new kd(void 0);this.lastRequestFirstBytes$=new kd(void 0);this.recoverableError$=new Nr;this.error$=new Nr;this.abortAllController=new J;this.subscription=new S0;this.fetchManifest=Ls(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=ti(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=Po(i)),this.manifestRequested.next();let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(Zo);return r?(t.log("success",qr({url:i,message:"Request successfully executed"})),t.end(),this.manifestReceived.next(),this.onHeadersReceived(r.headers),r.text()):(t.error("error",qr({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=Ls(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 O,Q,H;let c=e,d=new Headers,h=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{d.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let I=new URL(c,location.href);I.searchParams.append("bytes",`${i.from}-${i.to}`),c=I.toString();break}default:_I(t)}this.requestQuic&&(c=ti(c));let p=this.abortAllController.signal,f;if(n){let I=new J;if(f=g0(OI(this.abortAllController.signal,"abort"),OI(n,"abort")).subscribe(()=>{try{I.abort()}catch(P){Zo(P)}}),this.subscription.add(f),this.abortAllController.signal.aborted||n.aborted)try{I.abort()}catch(P){Zo(P)}p=I.signal}let m=0,g=$s();h.log("startRequest",qr({url:c,priority:s,rangeMethod:t,range:i,isLowLatency:u,requestStartedAt:g})),this.firstBytesRequested.next();let b=yield this.doFetch(c,{priority:s,headers:d,signal:p}),v=$s();if(!b)return h.error("error",{message:"No response in request"}),h.end(),this.unsubscribeAbortSubscription(f),null;if((O=this.throughputEstimator)==null||O.addRawRtt(v-g),!b.ok||!b.body){this.unsubscribeAbortSubscription(f);let I=`Fetch error ${b.status}: ${b.statusText}`;return h.error("error",{message:I}),h.end(),Promise.reject(new Error(`Fetch error ${b.status}: ${b.statusText}`))}if(this.onHeadersReceived(b.headers),!r&&!o){this.unsubscribeAbortSubscription(f);let I=$s(),P={requestStartedAt:g,requestEndedAt:I,duration:I-g};return h.log("endRequest",qr(P)),h.end(),b.arrayBuffer()}let T=b.body;if(o){let I;[T,I]=b.body.tee(),(Q=this.throughputEstimator)==null||Q.trackStream(I,u)}let y=T.getReader(),E,A=parseInt((H=b.headers.get("content-length"))!=null?H:"",10);Number.isFinite(A)&&(E=A),!E&&i&&(E=i.to-i.from+1);let k=E?new Uint8Array(E):new Uint8Array(0),L=!1,D=I=>{this.unsubscribeAbortSubscription(f),L=!0,Zo(I)},R=Ls(p,async function*({done:I,value:P}){if(m===0&&(this.lastRequestFirstBytes$.next($s()-g),this.firstBytesReceived.next()),p.aborted){this.unsubscribeAbortSubscription(f);return}if(!I&&P){if(l&&E)k.set(P,m),m+=P.byteLength;else{let x=new Uint8Array(k.length+P.length);x.set(k),x.set(P,k.length),k=x,m+=P.byteLength}r==null||r(new DataView(k.buffer),m),yield y==null?void 0:y.read().then(R,D)}}.bind(this));yield y==null?void 0:y.read().then(R,D),this.unsubscribeAbortSubscription(f);let B=$s(),M={failed:L,requestStartedAt:g,requestEndedAt:B,duration:B-g};return L?(h.error("endRequest",qr(M)),h.end(),null):(h.log("endRequest",qr(M)),h.end(),k.buffer)}.bind(this));this.fetchByteRangeRepresentation=Ls(this.abortAllController.signal,async function*(e,t,i){var b;if(e.type!=="byteRange")return null;let{from:r,to:s}=e.initRange,n=r,o=s,u=!1,l,c;e.indexRange&&(l=e.indexRange.from,c=e.indexRange.to,u=s+1===l,u&&(n=Math.min(l,r),o=Math.max(c,s))),n=Math.min(n,0);let d=yield this.fetch(e.url,{range:{from:n,to:o},priority:i,measureThroughput:!1});if(!d)return null;let h=new DataView(d,r-n,s-n+1);if(!t.validateData(h))throw new Error("Invalid media file");let p=t.parseInit(h),f=(b=e.indexRange)!=null?b:t.getIndexRange(p);if(!f)throw new ReferenceError("No way to load representation index");let m;if(u)m=new DataView(d,f.from-n,f.to-f.from+1);else{let v=yield this.fetch(e.url,{range:f,priority:i,measureThroughput:!1});if(!v)return null;m=new DataView(v)}let g=t.parseSegments(m,p,f);return{init:p,dataView:new DataView(d),segments:g}}.bind(this));this.fetchTemplateRepresentation=Ls(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}=Ro(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 Xe(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:Ms.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:Ms.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:Ms.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:Ms.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${s})`,category:Ms.FATAL})}}unsubscribeAbortSubscription(e){e&&(e.unsubscribe(),this.subscription.remove(e))}},Zo=a=>{if(!It(a))throw a};import{isNullable as v0,ValueSubject as y0}from"@vkontakte/videoplayer-shared/es2018";var Ds=class a{constructor(e,t){this.currentRepresentation$=new y0(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(!v0(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&&We(t.segmentReference))}};var A0=["progress","play","seeked","stalled","waiting"],R0=["timeupdate","progress","loadeddata","playing","seeked"];var iu=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.bufferManagers=[];this.subscription=new Cd;this.subscriptionRemovable=new x0;this.representationSubscription=new Cd;this.state$=new U("none");this.currentVideoRepresentation$=new re(void 0);this.currentVideoRepresentationInit$=new re(void 0);this.currentAudioRepresentation$=new re(void 0);this.currentVideoSegmentLength$=new re(0);this.currentAudioSegmentLength$=new re(0);this.error$=new ni;this.manifestRequested=new ni;this.manifestReceived=new ni;this.firstBytesRequested=new ni;this.firstBytesReceived=new ni;this.lastConnectionType$=new re(void 0);this.lastConnectionReused$=new re(void 0);this.lastRequestFirstBytes$=new re(void 0);this.currentLiveTextRepresentation$=new re(null);this.isLive$=new re(!1);this.isActiveLive$=new re(!1);this.isLowLatency$=new re(!1);this.liveDuration$=new re(0);this.liveSeekableDuration$=new re(0);this.liveAvailabilityStartTime$=new re(0);this.liveStreamStatus$=new re(void 0);this.bufferLength$=new re(0);this.liveLatency$=new re(void 0);this.liveLoadBufferLength$=new re(0);this.livePositionFromPlayer$=new re(0);this.currentStallDuration$=new re(0);this.videoLastDataObtainedTimestamp$=new re(0);this.fetcherRecoverableError$=new ni;this.fetcherError$=new ni;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new ni;this.gapWatchdogActive=!1;this.destroyController=new J;this.initManifest=$d(this.destroyController.signal,async function*(e,t,i){var r;this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=ne(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=$d(this.destroyController.signal,async function*(){var u,l;this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(c=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:lt.NETWORK,message:"Failed to load manifest",thrown:c})});if(!e)return null;let t=null;try{t=Eo(e!=null?e:"",this.manifestUrlString)}catch(c){let d=(u=To(e))!=null?u:{id:"ManifestParsing",category:lt.PARSER,message:"Failed to parse MPD manifest",thrown:c};this.error$.next(d)}if(!t)return null;let i=(c,d,h)=>{var p,f,m,g;return!!((f=(p=this.element)==null?void 0:p.canPlayType)!=null&&f.call(p,d)&&((g=(m=He())==null?void 0:m.isTypeSupported)!=null&&g.call(m,`${d}; codecs="${h}"`))||c==="text")};if(t.live){this.isLive$.next(!!t.live);let{availabilityStartTime:c,latestSegmentPublishTime:d,streamIsUnpublished:h,streamIsAlive:p}=t.live,f=((l=t.duration)!=null?l:0)/1e3;this.liveSeekableDuration$.next(-1*f),this.liveDuration$.next((d-c)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let m="active";p||(m=h?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(m)}let r={text:t.streams.text,video:[],audio:[]},s,n;for(let c of["video","audio"]){let h=t.streams[c].filter(({mime:f,codecs:m})=>i(c,f,m));r[c]=h;let p;if(this.tuning.dash.codecsPrioritizeEnabled){let f=h.map(({codecs:m})=>m);c==="audio"&&(n=Fo(f),p=n[0]),c==="video"&&(s=Oo(f),this.forceVideoCodec&&(0,UI.default)(s,this.forceVideoCodec)?p=this.forceVideoCodec:p=s[0]),p&&(r[c]=h.filter(({codecs:m})=>Cr(m)===p))}else{let f=new Set(h.map(({codecs:m})=>m));p=_o(f),p&&(r[c]=h.filter(({codecs:m})=>m.startsWith(p)))}if(c==="video"){let f=this.tuning.preferHDR,m=r.video.some(b=>b.hdr),g=r.video.some(b=>!b.hdr);_.display.isHDR&&f&&m?r.video=r.video.filter(b=>b.hdr):g&&(r.video=r.video.filter(b=>!b.hdr))}}let o={...t,streams:r};return this.tuning.dash.codecsPrioritizeEnabled&&(o.codecs={video:s,audio:n}),this.tracer.log("updateManifestEnd",Bs(o)),o}.bind(this));this.initRepresentations=$d(this.destroyController.signal,async function*(e,t,i){var h;this.tracer.log("initRepresentationsStart",Bs({initialVideo:e,initialAudio:t,sourceHls:i})),Ur(this.manifest),Ur(this.element),this.representationSubscription.unsubscribe(),this.representationSubscription=new Cd,this.state$.startTransitionTo("representations_ready");let r=p=>{this.representationSubscription.add(Et(p,"error").pipe(tu(f=>{var m;return!!((m=this.element)!=null&&m.played.length)})).subscribe(f=>{this.error$.next({id:"VideoSource",category:lt.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:f})}))};this.source=Kn();let s=document.createElement("source");if(r(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),br())if(i){let p=document.createElement("source");r(p),p.type="application/x-mpegurl",p.src=i.url,this.element.appendChild(p)}else this.element.disableRemotePlayback=!0;this.isActiveLive$.next(this.isLive$.getValue());let n={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),manifest:this.manifest},o=this.manifest.streams.video.reduce((p,f)=>[...p,...f.representations],[]);if(this.videoBufferManager=new ks("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],Vs(t)){let p=this.manifest.streams.audio.reduce((f,m)=>[...f,...m.representations],[]);this.audioBufferManager=new ks("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.manifestRequested.subscribe(this.manifestRequested)),this.representationSubscription.add(this.fetcher.manifestReceived.subscribe(this.manifestReceived)),this.representationSubscription.add(this.fetcher.firstBytesRequested.subscribe(this.firstBytesRequested)),this.representationSubscription.add(this.fetcher.firstBytesReceived.subscribe(this.firstBytesReceived)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$));let u=()=>{var p;(p=this.stallWatchdogSubscription)==null||p.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add(ji(...R0.map(p=>Et(this.element,p))).pipe(jr(p=>this.element?Te(this.element.buffered,this.element.currentTime*1e3):0),Cs(),w0(p=>{p>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add(ji(Et(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe(Cs()).subscribe(f=>this.liveStreamEndTimestamp=Dd())),this.subscription.add(Et(this.element,"pause").subscribe(()=>{this.livePauseWatchdogSubscription=Md(1e3).subscribe(f=>{let m=zt(this.manifestUrlString,2);this.manifestUrlString=ne(this.manifestUrlString,m+1e3,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add(Et(this.element,"play").subscribe(f=>{var m;return(m=this.livePauseWatchdogSubscription)==null?void 0:m.unsubscribe()})),this.representationSubscription.add(Hr({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(jr(({isActiveLive:f,isLowLatency:m})=>f&&m),Cs()).subscribe(f=>{this.isManualDecreasePlaybackInLive()||Dr(this.element,1)})),this.representationSubscription.add(Hr({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(tu(({bufferLength:f,isActiveLive:m,isLowLatency:g})=>m&&g&&!!f)).subscribe(({bufferLength:f})=>this.liveBuffer.next(f))),this.representationSubscription.add(this.videoBufferManager.currentLowLatencySegmentLength$.subscribe(f=>{if(!this.isActiveLive$.getValue()&&!this.isLowLatency$.getValue()&&!f)return;let m=this.liveSeekableDuration$.getValue()-f/1e3;this.liveSeekableDuration$.next(Math.max(m,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+f/1e3)})),this.representationSubscription.add(Hr({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(tu(({isLive:f})=>f),Cs((f,m)=>m.bufferLength<f.bufferLength),jr(({rtt:f,bufferLength:m,segmentServerLatency:g})=>{let b=zt(this.manifestUrlString,2);return(f/2+m+g+b)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(Hr({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:f,isActiveLive:m,isLowLatency:g})=>{if(!g||!m)return;let b=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,v=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,T=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,y=f-b;if(this.isManualDecreasePlaybackInLive())return;let E=1;Math.abs(y)>v&&(E=1+Math.sign(y)*T),Dr(this.element,E)})),this.representationSubscription.add(this.bufferLength$.subscribe(f=>{var g,b;let m=0;if(f){let v=((b=(g=this.element)==null?void 0:g.currentTime)!=null?b:0)*1e3;m=Math.min(...this.bufferManagers.map(y=>{var E,A;return(A=(E=y.getLiveSegmentsToLoadState(this.manifest))==null?void 0:E.to)!=null?A:v}))-v}this.liveLoadBufferLength$.getValue()!==m&&this.liveLoadBufferLength$.next(m)}));let p=0;this.representationSubscription.add(Hr({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(qI(1e3)).subscribe(async({liveLoadBufferLength:f,bufferLength:m})=>{if(!this.element||this.isUpdatingLive)return;let g=this.element.playbackRate,b=zt(this.manifestUrlString,2),v=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,T=Math.min(v,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*g),y=this.tuning.dashCmafLive.normalizedActualBufferOffset*g,E=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*g,A=isFinite(f)?f:m,k=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),L=v<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(L);let D="none";if(k?D="active_low_latency":this.isLowLatency$.getValue()&&L?(this.bufferManagers.forEach(R=>R.proceedLowLatencyLive()),D="active_low_latency"):b!==0&&A<T?D="live_forward_buffering":A<T+E&&(D="live_with_target_offset"),isFinite(f)&&(p=f>p?f:p),D==="live_forward_buffering"||D==="live_with_target_offset"){let R=p-(T+y),B=this.normolizeLiveOffset(Math.trunc(b+R/g)),M=Math.abs(B-b),O=0;!f||M<=this.tuning.dashCmafLive.offsetCalculationError?O=b:B>0&&M>this.tuning.dashCmafLive.offsetCalculationError&&(O=B),this.manifestUrlString=ne(this.manifestUrlString,O,2)}(D==="live_with_target_offset"||D==="live_forward_buffering")&&(p=0,await this.updateLive())},f=>{this.error$.next({id:"updateLive",category:lt.VIDEO_PIPELINE,thrown:f,message:"Failed to update live with subscription"})}))}let l=ji(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe(jr(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),c=ji(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe(jr(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue()))),d=Hr({allBuffersFull:l,someBufferEnded:c}).pipe(Cs(),jr(({allBuffersFull:p,someBufferEnded:f})=>p&&f),tu(p=>p));if(this.representationSubscription.add(ji(this.forceEnded$,d).subscribe(()=>{var p;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(f=>!f.updating))try{(p=this.source)==null||p.endOfStream()}catch(f){this.error$.next({id:"EndOfStream",category:lt.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:f})}})),this.representationSubscription.add(ji(...this.bufferManagers.map(p=>p.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.representationSubscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.representationSubscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.liveTextManager&&this.representationSubscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$)),this.source.readyState!=="open"){let p=this.tuning.dash.sourceOpenTimeout>=0;yield new Promise(f=>{var m;p&&(this.timeoutSourceOpenId=setTimeout(()=>{var g;if(((g=this.source)==null?void 0:g.readyState)==="open"){f();return}this.error$.next({id:"OpenOfStream",category: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),f()},{once:!0})})}if(!this.isLive$.getValue()){let p=[(h=this.manifest.duration)!=null?h:0,...(0,Bd.default)((0,Bd.default)([...this.manifest.streams.audio,...this.manifest.streams.video],f=>f.representations),f=>{let m=[];return f.duration&&m.push(f.duration),We(f.segmentReference)&&f.segmentReference.totalSegmentsDurationMs&&m.push(f.segmentReference.totalSegmentsDurationMs),m})];this.source.duration=Math.max(...p)/1e3}this.audioBufferManager&&Vs(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=Md(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.forceVideoCodec=e.forceVideoCodec,this.fetcher=new eu({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()}setSmartRepresentationSwitch(e){this.bufferManagers.forEach(t=>t.setSmartRepresentationSwitch(e))}async seekLive(e){var r,s,n;Ur(this.element);let t=this.liveStreamStatus$.getValue()!=="active"?Dd()-this.liveStreamEndTimestamp:0,i=this.normolizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=ne(this.manifestUrlString,i,2),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await((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(){Ur(this.element),this.state$.setState("running");let e=Et(this.element,"timeupdate");this.tuning.dash.timeupdateEventTickThrottle&&(e=e.pipe(qI(this.tuning.dash.timeupdateEventTickThrottle))),this.subscription.add(ji(...A0.map(t=>Et(this.element,t)),Et(window,"online"),e).subscribe(()=>this.tick(),t=>{this.error$.next({id:"DashVKPlayer",category:lt.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(()=>{this.tuning.dash.useVideoElementWaitingCurrentTimeReassign&&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 p,f,m,g,b,v,T,y,E,A,k;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=Dd(),n=100,o=(m=(f=this.videoBufferManager)==null?void 0:f.lastDataObtainedTimestamp)!=null?m:0;this.videoLastDataObtainedTimestamp$.next(o);let u=(b=(g=this.audioBufferManager)==null?void 0:g.lastDataObtainedTimestamp)!=null?b:0,l=(T=(v=this.videoBufferManager)==null?void 0:v.getForwardBufferDuration())!=null?T:0,c=(E=(y=this.audioBufferManager)==null?void 0:y.getForwardBufferDuration())!=null?E:0,d=l<n&&s-o>this.tuning.dash.crashOnStallTWithoutDataTimeout,h=this.audioBufferManager&&c<n&&s-u>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((d||h)&&i>this.tuning.dash.crashOnStallTWithoutDataTimeout||i>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${i} ms`);if(this.isLive$.getValue()&&i%2e3===0){let L=this.normolizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(L).catch(D=>{this.error$.next({id:"stallIntervalCallback",category:lt.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:D})}),r.liveLastOffset=L}else{let L=this.element.currentTime*1e3;(A=this.videoBufferManager)==null||A.maintain(L),(k=this.audioBufferManager)==null||k.maintain(L),r.position=L}this.tracer.log("stallIntervalCallback",Bs(r))};this.stallWatchdogSubscription&&(this.stallWatchdogSubscription.unsubscribe(),this.subscriptionRemovable.remove(this.stallWatchdogSubscription)),this.stallWatchdogSubscription=Md(50).subscribe(t,i=>{this.error$.next({id:"StallWatchdogCallback",category:lt.NETWORK,message:"Can't restore DASH after stall.",thrown:i})}),this.subscriptionRemovable.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,i=!1){let r={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return this.tuning.useNewSwitchTo?this.currentStallDuration$.getValue()>0?r==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;Ur(this.element),Ur(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",Bs({requestedPosition:e,forcePrecise:t,position:i})))}warmUpMediaSourceIfNeeded(e=(t=>(t=this.element)==null?void 0:t.currentTime)()){var i;Vs(this.element)&&Vs(this.source)&&Vs(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}getCodecs(){var e;return(e=this.manifest)==null?void 0:e.codecs}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){var e;this.subscription.unsubscribe(),this.subscriptionRemovable.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=E0(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;this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&(this.bufferManagers.forEach(t=>t.updateLive(this.manifest)),(e=this.liveTextManager)==null||e.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",Bs({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 k0,observeElementSize as L0,Subscription as $0,ValueSubject as Vd,noop as M0}from"@vkontakte/videoplayer-shared/es2018";var ru=class{constructor(){this.subscription=new $0;this.pipSize$=new Vd(void 0);this.videoSize$=new Vd(void 0);this.elementSize$=new Vd(void 0);this.pictureInPictureWindowRemoveEventListener=M0}connect({observableVideo:e,video:t}){let i=r=>{let s=r.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add(L0(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(k0(({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 Wi=class{constructor(e){this.subscription=new N0;this.videoState=new U("stopped");this.observableVideo=null;this.droppedFramesManager=new Er;this.stallsManager=new Wo;this.elementSizeManager=new ru;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 C0(e)}}};this.init3DScene=e=>{var i,r,s;if(this.scene3D)return;this.scene3D=new Or(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 Ye(e.source.url),this.params=e,this.video=Ce(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(ye(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 iu({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer,forceVideoCodec:this.params.forceVideoCodec}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params;F0(this.observableVideo)&&(this.observableVideo=_e(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:HI.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(_d(d=>!!d.length),WI()).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(Os(d=>d.to.state!=="none"),_s());this.stallsManager.init({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$,videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,tuning:this.params.tuning.stallsManager,abrParams:this.params.tuning.autoTrackSelection,isBuffering$:i.isBuffering$,looped$:i.looped$,playing$:i.playing$,duration:this.video.duration}),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(this.player.error$,e.error$),s(this.player.fetcherRecoverableError$,e.fetcherRecoverableError$),s(this.player.fetcherError$,e.fetcherError$),s(this.player.lastConnectionType$,e.httpConnectionType$),s(this.player.lastConnectionReused$,e.httpConnectionReused$),s(this.player.isLive$,e.isLive$),s(this.player.lastRequestFirstBytes$.pipe(_d(jI),WI()),e.firstBytesEvent$),s(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),s(this.videoState.stateChangeEnded$.pipe(Os(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(Ve(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(ze(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),s(Ke(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),$(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.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(i.ended$.subscribe(()=>{this.videoState.setState("paused"),$(t.playbackState,"paused")})),this.subscription.add(this.player.manifestRequested.subscribe(this.params.output.manifestRequested$)).add(this.player.manifestReceived.subscribe(this.params.output.manifestReceived$)).add(this.player.firstBytesRequested.subscribe(this.params.output.firstBytesRequested$)).add(this.player.firstBytesReceived.subscribe(this.params.output.firstBytesReceived$)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:d})=>{if(d==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let h=this.player.getStreams(),p=this.player.getCodecs();if(B0(h,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let m=[];for(let g of h.audio){m.push(xd(g));let b=[];for(let v of g.representations){let T=$I(v);b.push(T),this.audioTracksMap.set(T,{stream:g,representation:v})}this.audioStreamsMap.set(g,b)}this.params.output.availableAudioStreams$.next(m)}let f=[];for(let m of h.video){f.push(wd(m));let g=[];for(let b of m.representations){let v=Ps({...b,streamId:m.id});v&&(g.push(v),this.videoTracksMap.set(v,{stream:m,representation:b}))}this.videoStreamsMap.set(m,g)}this.params.output.availableVideoStreams$.next(f);for(let m of h.text)for(let g of m.representations){let b=MI(m,g);this.textTracksMap.set(b,{stream:m,representation:g})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),p!=null&&p.video&&this.params.output.availableVideoCodecs$.next(p.video),p!=null&&p.audio&&this.params.output.availableAudioCodecs$.next(p.audio),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&&BI(o)||null;this.subscription.add(Fs(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$,O0(this.video,"progress")).pipe(_d(()=>this.videoTracksMap.size>0)).subscribe(async()=>{let d=this.player.state$.getState(),h=this.player.state$.getTransition();if(d!=="manifest_ready"&&d!=="running"||h||d==="running"&&u&&!u())return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState()),this.selectVideoAudioRepresentations();let{video:p,audio:f}=this.selectedRepresentations;if(!p)return;let m=Ni(this.videoTracksMap.keys(),b=>{var v;return((v=this.videoTracksMap.get(b))==null?void 0:v.representation.id)===p.id});jI(m)&&(this.stallsManager.lastVideoTrackSelected=m);let g=this.params.desiredState.autoVideoTrackLimits.getTransition();if(g&&this.params.output.autoVideoTrackLimits$.next(g.to),d==="manifest_ready")await this.player.initRepresentations(p.id,f==null?void 0:f.id,this.params.sourceHls);else if(await this.player.switchRepresentation("video",p.id),f){let b=!!t.audioStream.getTransition();await this.player.switchRepresentation("audio",f.id,b)}},r)),this.subscription.add(V0({videoState:this.videoState.stateChangeEnded$,autoVideoTrackState:Fs(au([t.autoVideoTrackSwitching.getState()]),t.autoVideoTrackSwitching.stateChangeEnded$.pipe(Os(d=>d.to)))}).pipe(Os(({videoState:d,autoVideoTrackState:h})=>d.to!=="stopped"&&h),_s()).subscribe(d=>this.player.setSmartRepresentationSwitch(d))),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(_s()).subscribe(d=>{let h=Ni(this.videoTracksMap.entries(),([,{representation:b}])=>b.id===d);if(!h){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[p,{stream:f}]=h,m=this.params.desiredState.videoStream.getTransition();m&&m.to&&m.to.id===f.id&&this.params.desiredState.videoStream.setState(m.to),e.currentVideoTrack$.next(p),e.currentVideoStream$.next(wd(f));let g=this.player.calculateDurationFromSegments();g&&this.params.output.duration$.next(g/1e3)},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(_s()).subscribe(d=>{let h=Ni(this.audioTracksMap.entries(),([,{representation:g}])=>g.id===d);if(!h){e.currentAudioStream$.next(void 0);return}let[p,{stream:f}]=h,m=this.params.desiredState.audioStream.getTransition();m&&m.to&&m.to.id===f.id&&this.params.desiredState.audioStream.setState(m.to),e.currentAudioStream$.next(xd(f))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(d=>{var h,p;if(d!=null&&d.is3dVideo&&((h=this.params.tuning.spherical)!=null&&h.enabled))try{this.init3DScene(d),e.is3DVideo$.next(!0)}catch(f){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${f}`})}else this.destroy3DScene(),(p=this.params.tuning.spherical)!=null&&p.enabled&&e.is3DVideo$.next(!1)},r)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,r)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,r)),this.textTracksManager.connect(this.video,t,e);let l=t.playbackState.stateChangeStarted$.pipe(Os(({to:d})=>d==="ready"),_s());this.subscription.add(Fs(l,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,au(["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(Fs(l,this.player.state$.stateChangeEnded$,au(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let c=Fs(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,au(["init"])).pipe(_0(0));this.subscription.add(c.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){var L,D,R,B,M,O,Q,H,I,P,x,w;if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?La:ka,t=this.params.tuning.useNewAutoSelectVideoTrack?fo:ho,i=this.params.tuning.useNewAutoSelectVideoTrack?vt:po,{desiredState:r,output:s}=this.params,n=r.autoVideoTrackSwitching.getState(),o=(L=r.videoTrack.getState())==null?void 0:L.id,u=Ni(this.videoTracksMap.keys(),V=>V.id===o),l=s.currentVideoTrack$.getValue(),c=((B=(R=r.videoStream.getState())!=null?R:u&&((D=this.videoTracksMap.get(u))==null?void 0:D.stream))!=null?B:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!c)return;let d=Ni(this.videoStreamsMap.keys(),V=>V.id===c.id),h=d&&this.videoStreamsMap.get(d);if(!h)return;let p=Te(this.video.buffered,this.video.currentTime*1e3),f;this.player.isActiveLive$.getValue()?f=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?f=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:f=n?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let m=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,g=Math.min(p/Math.min(f,m||1/0),1),b=(M=r.audioStream.getState())!=null?M:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,v=(b==null?void 0:b.id)&&Ni(this.audioStreamsMap.keys(),V=>V.id===b.id)||this.audioStreamsMap.keys().next().value,T=0;if(v){if(u&&!n){let V=e(u,h,(O=this.audioStreamsMap.get(v))!=null?O:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);T=Math.max(T,(Q=V==null?void 0:V.bitrate)!=null?Q:-1/0)}if(l){let V=e(l,h,(H=this.audioStreamsMap.get(v))!=null?H:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);T=Math.max(T,(I=V==null?void 0:V.bitrate)!=null?I:-1/0)}}let y=u;(n||!y)&&(y=i(h,{container:this.elementSizeManager.getValue(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.stallsManager.abrTuningParams,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:T,forwardBufferHealth:g,current:l,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,stallsVideoMaxQualityLimit:this.stallsManager.videoMaxQualityLimit,stallsPredictedThroughput:this.stallsManager.predictedThroughput,abrLogger:this.params.dependencies.abrLogger}));let E=v&&t(y,h,(P=this.audioStreamsMap.get(v))!=null?P:[],{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}),A=(x=this.videoTracksMap.get(y))==null?void 0:x.representation,k=E&&((w=this.audioTracksMap.get(E))==null?void 0:w.representation);A&&k?(this.selectedRepresentations.video=A,this.selectedRepresentations.audio=k):A&&!k&&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(){Oe(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:HI.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.stallsManager.destroy(),this.elementSizeManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),this.params.output.currentVideoStream$.next(void 0),Be(this.video),this.tracer.end()}};var Ns=class extends Wi{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 Od,merge as QI,filter as GI,filterChanged as zI,isNullable as Fd,map as YI,ValueSubject as Nd,isNonNullable as q0}from"@vkontakte/videoplayer-shared/es2018";var qs=class extends Wi{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 Nd(1);n(r.playbackRateState$,o),this.params.tuning.dashCmafLive.catchupLiveForMutedInactiveTab&&this.subscription.add(i.elementVisible$.pipe(zI()).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(YI(u=>u.to)).subscribe(this.player.isLowLatency$)).add(Od({liveBufferTime:i.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(YI(({liveBufferTime:u,liveAvailabilityStartTime:l})=>u&&l?u+l:void 0)).subscribe(i.liveTime$)).add(this.player.liveStreamStatus$.pipe(GI(u=>q0(u))).subscribe(u=>i.isLiveEnded$.next(u!=="active"&&i.position$.getValue()===0))).add(Od({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:QI(r.playbackRateState$,new Nd(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:h}=this.params.tuning.dashCmafLive.lowLatency;d||l<1-h||this.video.paused||Fd(c)||(t=u-c)})).add(Od({time:i.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:QI(r.playbackRateState$,new Nd(1))}).pipe(zI((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:h}=this.params.tuning.dashCmafLive.lowLatency;if(!d&&!this.video.paused&&c>=1-h||Fd(u)||Fd(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=DI(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 KI="X-Playback-Duration",qd=async a=>{var r;let e=await Xe(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(KI)?parseInt(e.headers.get(KI),10):void 0};import{assertNever as J0,combine as Z0,debounce as eV,ErrorCategory as ou,filter as tV,filterChanged as iV,isNonNullable as ZI,isNullable as uu,map as eE,merge as rV,observableFrom as aV,Subscription as sV,ValueSubject as jd,VideoQuality as nV}from"@vkontakte/videoplayer-shared/es2018";var Hd=F(kl(),1);import{videoSizeToQuality as U0,getExponentialDelay as H0}from"@vkontakte/videoplayer-shared/es2018";var j0=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=U0({width:t,height:i})}return e!=null?e:null},W0=(a,e)=>{var s,n;let t=a.split(`
|
|
179
|
-
`),i=[],r=[];for(let o=0;o<t.length;o++){let u=t[o],
|
|
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(),h=new Date(i.programDateTime).valueOf();i.segmentStartTime=h-d}break}case o.startsWith("#EXT-X-TARGETDURATION:"):i.targetDuration=Number(this.extractPlaylistRowValue("#EXT-X-TARGETDURATION:",o));break;case o.startsWith("#EXT-X-MEDIA-SEQUENCE:"):i.mediaSequence=Number(this.extractPlaylistRowValue("#EXT-X-MEDIA-SEQUENCE:",o));break;case o.startsWith("#EXT-X-VK-PLAYBACK-DURATION:"):i.vkPlaybackDuration=Number(this.extractPlaylistRowValue("#EXT-X-VK-PLAYBACK-DURATION:",o));break;case o.startsWith("#EXT-X-PROGRAM-DATE-TIME:"):{let u=this.extractPlaylistRowValue("#EXT-X-PROGRAM-DATE-TIME:",o);i.programDateTime=u;let l=new Date(u);l.setMilliseconds(0),s=l.valueOf();break}case o.startsWith("#EXT-X-VK-START-TIME:"):i.vkStartTime=this.extractPlaylistRowValue("#EXT-X-VK-START-TIME:",o);break}}return i}extractPlaylistRowValue(e,t){switch(e){case"#EXTINF:":return t.substring(e.length,t.length-1);default:return t.substring(e.length)}}processLiveTime(e){if(G0(e)&&this.currentTextTrackData){let{segments:t}=this.currentTextTrackData.playlist,{from:i}=t[0].time,{to:r}=t[t.length-1].time;if(e<i||e>r)return;r-e<this.params.downloadThreshold&&this.fetchNextManifestData();for(let n of t)if(n.time.from<=e&&n.time.to>=e){this.availableTextTracks$.next([{...this.currentTextTrackData.textTrack,url:n.url,isAuto:!0}]);break}}}async fetchNextManifestData(){try{if(this.abortControllers.nextManifest)return;this.abortControllers.nextManifest=new J;let{textTracks:e}=await this.fetchManifestData(),t=await this.parseTextTracks(e,this.params.sourceUrl);this.currentTextTrackData&&t&&(this.currentTextTrackData.playlist.segments=t.playlist.segments)}catch(e){this.error("fetchNextManifestData",e)}finally{this.abortControllers.nextManifest=null}}async fetchManifestData(){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:X0.WTF,thrown:t,message:e})}};var Us=class{constructor(e){this.subscription=new sV;this.videoState=new U("stopped");this.textTracksManager=null;this.liveTextManager=null;this.manifests$=new jd([]);this.liveOffset=new Li;this.manifestStartTime$=new jd(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 J0(t)}};var i;this.params=e,this.video=Ce(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:nV.INVARIANT,url:this.params.source.url};let t=(r,s)=>su(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 nu(this.params.output.liveTime$,this.video,t,this.params.source.url,this.params.tuning.hlsLiveNewTextManagerDownloadThreshold):this.textTracksManager=new Ye(e.source.url),t(this.generateLiveUrl()).then(({qualityManifests:r,textTracks:s})=>{var n;r.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:ou.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:ou.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(ye(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new jd((i=e.source.maxSeekBackTime)!=null?i:1/0),this.subscribe()}selectManifest(){var u,l,c,d;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),s=(d=(c=(u=r==null?void 0:r.to)==null?void 0:u.id)!=null?c:(l=t.getState())==null?void 0:l.id)!=null?d:"master",n=this.manifests$.getValue();if(!n.length)return;let o=i?"master":s;return i&&!r&&t.startTransitionTo(this.masterManifest),n.find(h=>h.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsLiveProvider",category:ou.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},r=_e(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(Ve(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(ze(this.video,t.playbackRate,r.playbackRateState$,i)),s(Ke(this.video),e.elementVisible$),this.liveTextManager?(s(this.liveTextManager.getCurrentTime$,this.params.output.getCurrentTime$),s(this.liveTextManager.error$,this.params.output.error$)):this.textTracksManager&&this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),$(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(iV(),eE(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&&ZI(l.to)){let d=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let h=this.manifests$.getValue().find(p=>p.id===d);h&&(this.params.output.currentVideoTrack$.next(h),this.params.output.hostname$.next(ye(h.url)))}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o&&o.state==="requested"&&this.seek(o.position)},i)),this.subscription.add(r.loadedData$.subscribe(()=>{var u,l,c;let o=(c=(l=(u=this.video)==null?void 0:u.getStartDate)==null?void 0:l.call(u))==null?void 0:c.getTime();this.manifestStartTime$.next(o||void 0)},i)),this.subscription.add(Z0({startTime:this.manifestStartTime$.pipe(tV(ZI)),currentTime:r.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),i)),this.subscription.add(this.manifests$.pipe(eE(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:h})=>({id:u,quality:l,size:c,fps:h,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,i));let n=rV(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,aV(["init"])).pipe(eV(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),Be(this.video)}prepare(){var o,u,l;let e=this.selectManifest();if(uu(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:c,min:d}=(u=(o=t==null?void 0:t.to)!=null?o:i)!=null?u:{};for(let[h,p]of[[c,"mq"],[d,"lq"]]){let f=String(parseFloat(h||""));p&&h&&r.searchParams.set(p,f)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,n=ne(r.toString(),this.liveOffset.getTotalOffset(),s);(l=this.liveTextManager)==null||l.prepare(n),this.video.setAttribute("src",n),this.video.load(),qd(n).then(c=>{var d;if(!uu(c))this.maxSeekBackTime$.next(c);else{let h=(d=this.params.source.maxSeekBackTime)!=null?d:this.maxSeekBackTime$.getValue();(uu(h)||!isFinite(h))&&Xe(n).then(p=>p.text()).then(p=>{var m;let f=(m=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(p))==null?void 0:m[1];if(f){let g=new URL(f,n).toString();qd(g).then(b=>{uu(b)||this.maxSeekBackTime$.next(b)})}}).catch(()=>{})}})}playIfAllowed(){Oe(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:ou.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3),this.params.output.seekedEvent$.next()}generateLiveUrl(){let e=ne(this.params.source.url);if(this.params.tuning.useHlsLiveNewTextManager){let t=new URL(e);t.searchParams.set("enable-subtitles","yes"),e=t.toString()}return e}};import{assertNever as oV,debounce as uV,ErrorCategory as Wd,fromEvent as Qd,isNonNullable as lV,isNullable as cV,map as tE,merge as iE,observableFrom as rE,Subscription as dV,ValueSubject as aE,VideoQuality as pV}from"@vkontakte/videoplayer-shared/es2018";var Hs=class{constructor(e){this.subscription=new dV;this.videoState=new U("stopped");this.manifests$=new aE([]);this.unmuteAfterBrowserResetsHappened=new aE(!1);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),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 oV(t)}};this.textTracksManager=new Ye(e.source.url),this.params=e,this.video=Ce(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:pV.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(ye(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.manifestRequested$.next(),su(ne(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:t,textTracks:i})=>{this.params.output.manifestReceived$.next(),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:Wd.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){var u,l,c,d;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),s=(d=(c=(u=r==null?void 0:r.to)==null?void 0:u.id)!=null?c:(l=t.getState())==null?void 0:l.id)!=null?d:"master",n=this.manifests$.getValue();if(!n.length)return;let o=i?"master":s;return i&&(!r||!r.from)&&t.startTransitionTo(this.masterManifest),n.find(h=>h.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsProvider",category:Wd.WTF,message:"HlsProvider internal logic error",thrown:o})},r=_e(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(tE(o=>o.to)),this.params.output.playbackState$),this.subscription.add(bt(this.video,t.isLooped,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(ze(this.video,t.playbackRate,r.playbackRateState$,i)),Fr({subscription:this.subscription,desiredState:t,videoElement$:this.params.output.element$,observableVideo:r}),this.subscription.add(Ve(this.video,t.volume,r.volumeState$,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&&lV(l.to)){let f=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let m=this.manifests$.getValue().find(g=>g.id===f);m&&(this.params.output.currentVideoTrack$.next(m),this.params.output.hostname$.next(ye(m.url)))}let d=this.params.desiredState.playbackRate.getState(),h=(p=this.params.output.element$.getValue())==null?void 0:p.playbackRate;if(d!==h){let f=this.params.output.element$.getValue();f&&(this.params.desiredState.playbackRate.setState(d),f.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.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(r.ended$.subscribe(()=>{this.videoState.setState("paused"),$(t.playbackState,"paused")})),this.subscription.add(this.manifests$.pipe(tE(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:h})=>({id:u,quality:l,size:c,fps:h,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,i)),!_.device.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(iE(Qd(o,"addtrack"),Qd(o,"removetrack"),Qd(o,"change"),rE(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},i))}let n=iE(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,rE(["init"])).pipe(uV(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Be(this.video)}prepare(){var s,n;let e=this.selectManifest();if(cV(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(){Oe(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:Wd.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var oE=F(nr(),1),Gd=F(Ii(),1),uE=F(nt(),1);import{assertNever as hV,assertNonNullable as sE,debounce as fV,ErrorCategory as nE,isHigherOrEqual as mV,isLowerOrEqual as bV,isNonNullable as gV,merge as SV,observableFrom as vV,Subscription as yV,map as TV}from"@vkontakte/videoplayer-shared/es2018";var js=class{constructor(e){this.subscription=new yV;this.videoState=new U("stopped");this.trackUrls={};this.textTracksManager=new Ye;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),$(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 hV(e)}};this.params=e,this.video=Ce(e.container,e.tuning),this.params.output.element$.next(this.video),(0,oE.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,Gd.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:nE.WTF,message:"MpegProvider internal logic error",thrown:o})},r=_e(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(TV(o=>o.to)),this.params.output.playbackState$),this.subscription.add(bt(this.video,t.isLooped,i)),Fr({subscription:this.subscription,desiredState:t,videoElement$:this.params.output.element$,observableVideo:r}),this.subscription.add(Ve(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(ze(this.video,t.playbackRate,r.playbackRateState$,i)),s(Ke(this.video),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),$(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&&gV(o.to)){this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to.id].track);let c=this.params.desiredState.playbackRate.getState(),d=(l=this.params.output.element$.getValue())==null?void 0:l.playbackRate;if(c!==d){let h=this.params.output.element$.getValue();h&&(this.params.desiredState.playbackRate.setState(c),h.playbackRate=c)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(r.ended$.subscribe(()=>{this.videoState.setState("paused"),$(t.playbackState,"paused")})),this.textTracksManager.connect(this.video,t,e);let n=SV(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,vV(["init"])).pipe(fV(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),Be(this.video)}prepare(){var i;let e=(i=this.params.desiredState.videoTrack.getState())==null?void 0:i.id;sE(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];sE(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=ti(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(ye(t))}playIfAllowed(){Oe(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:nE.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){var l,c;this.params.output.autoVideoTrackLimits$.next(e);let t=d=>{this.params.output.currentVideoTrack$.next(d),this.params.desiredState.videoTrack.startTransitionTo(d)},i=d=>{let h=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(h)},r=(l=this.params.output.currentVideoTrack$.getValue())==null?void 0:l.quality,s=!!(e.max||e.min),n=(0,Gd.default)(this.trackUrls).map(d=>d.track);if(!r||!s||vr(e,n[0].quality,(c=(0,uE.default)(n,-1))==null?void 0:c.quality)){i();return}let o=e.max?bV(r,e.max):!0,u=e.min?mV(r,e.min):!0;o&&u||i(e)}};import{assertNever as cE,debounce as wV,merge as dE,observableFrom as AV,Subscription as RV,map as pE,ValueSubject as PV,ErrorCategory as Yd,VideoQuality as kV}from"@vkontakte/videoplayer-shared/es2018";import{ErrorCategory as IV}from"@vkontakte/videoplayer-shared/es2018";var lE=["stun:videostun.mycdn.me:80"],EV=1e3,xV=3,zd=()=>null,lu=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=zd;this.externalStopCallback=zd;this.externalErrorCallback=zd;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:lE}]};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:IV.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),EV)}normalizeOptions(e={}){let t={stunServerList:lE,maxRetryNumber:xV,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var Ws=class{constructor(e){this.videoState=new U("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 cE(e)}};this.subscription=new RV,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=Ce(e.container,e.tuning),this.liveStreamClient=new lu(this.params.source.url,{maxRetryNumber:this.params.tuning.webrtc.connectionRetryMaxNumber,errorChanel:this.params.output.error$}),this.liveStreamClient.onStart(this.onLiveStreamStart.bind(this)),this.liveStreamClient.onStop(this.onLiveStreamStop.bind(this)),this.liveStreamClient.onError(this.onLiveStreamError.bind(this)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),Be(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,i=n=>{e.error$.next({id:"WebRTCLiveProvider",category:Yd.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};this.subscription.add(dE(this.videoState.stateChangeStarted$.pipe(pE(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(pE(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})}));let r=_e(this.video);this.subscription.add(()=>r.destroy());let 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(Ke(this.video),this.params.output.elementVisible$),this.subscription.add(r.durationChange$.subscribe(n=>{e.duration$.next(n===1/0?0:n)})).add(r.canplay$.subscribe(()=>{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(Ve(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 cE(n.to)}},i)).add(dE(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,AV(["init"])).pipe(wV(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(ye(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:kV.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:Yd.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){Oe(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:Yd.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var Wr=class{constructor(e){this.length=e.length,this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next(),this.index=this.index===void 0?0:this.index+1}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return!!this.current.done}isLast(){return this.index===this.length-1}};import{assertNever as Gs,assertNonNullable as oi,ErrorCategory as cu,filter as SE,isNonNullable as vE,isNullable as VV,map as _V,merge as OV,once as FV,Subject as oe,Subscription as yE,ValueSubject as q,flattenObject as Kd}from"@vkontakte/videoplayer-shared/es2018";import{Observable as LV,map as hE,Subscription as $V,Subject as MV}from"@vkontakte/videoplayer-shared/es2018";var fE=a=>new LV(e=>{let t=new $V,i=a.desiredPlaybackState$.stateChangeStarted$.pipe(hE(({from:l,to:c})=>`${l}-${c}`)),r=a.desiredPlaybackState$.stateChangeEnded$,s=a.providerChanged$.pipe(hE(({type:l})=>l!==void 0)),n=new MV,o=0,u="unknown";return t.add(i.subscribe(l=>{o&&window.clearTimeout(o),u=l,o=window.setTimeout(()=>n.next(l),a.maxTransitionInterval)})),t.add(r.subscribe(()=>{window.clearTimeout(o),u="unknown",o=0})),t.add(s.subscribe(l=>{o&&(window.clearTimeout(o),o=0,l&&(o=window.setTimeout(()=>n.next(u),a.maxTransitionInterval)))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});import{ErrorCategory as DV,Subscription as CV,combine as BV,filter as bE,once as gE}from"@vkontakte/videoplayer-shared/es2018";function mE(){return new(window.AudioContext||window.webkitAudioContext)}var Qs=class Qs{constructor(e,t,i,r){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=i;this.volumeMultiplier=r;this.destroyController=new J;this.subscriptions=new CV;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe(bE(s=>!!s.type),gE()).subscribe(({type:s})=>this.subscribe(s)))}subscribe(e){_.browser.isSafari&&e!=="MPEG"||this.subscriptions.add(BV({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(bE(({playbackState:t,video:i,volume:{muted:r,volume:s}})=>t==="playing"&&!!i&&!r&&!!s),gE()).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=mE();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:Qs.errorId,category:DV.VIDEO_PIPELINE,message:(t=e==null?void 0:e.message)!=null?t:`${Qs.errorId} exception`,thrown:e})}};Qs.errorId="VolumeMultiplierManager";var Qr=Qs;var NV={chunkDuration:5e3,maxParallelRequests:5},zs=class{constructor(e){this.current$=new q({type:void 0});this.providerError$=new oe;this.noAvailableProvidersError$=new oe;this.volumeMultiplierError$=new oe;this.providerOutput={position$:new q(0),duration$:new q(1/0),volume$:new q({muted:!1,volume:1}),availableVideoStreams$:new q([]),currentVideoStream$:new q(void 0),availableVideoTracks$:new q([]),currentVideoTrack$:new q(void 0),availableVideoCodecs$:new q([]),availableAudioStreams$:new q([]),currentAudioStream$:new q(void 0),availableAudioTracks$:new q([]),availableAudioCodecs$:new q([]),currentVideoSegmentLength$:new q(0),currentAudioSegmentLength$:new q(0),isAudioAvailable$:new q(!0),autoVideoTrackLimitingAvailable$:new q(!1),autoVideoTrackLimits$:new q(void 0),currentBuffer$:new q(void 0),isBuffering$:new q(!0),error$:new oe,fetcherError$:new oe,fetcherRecoverableError$:new oe,warning$:new oe,willSeekEvent$:new oe,soundProhibitedEvent$:new oe,seekedEvent$:new oe,loopedEvent$:new oe,endedEvent$:new oe,manifestRequested$:new oe,manifestReceived$:new oe,firstBytesRequested$:new oe,firstBytesReceived$:new oe,firstBytesEvent$:new oe,loadedMetadataEvent$:new oe,firstFrameEvent$:new oe,canplay$:new oe,isLive$:new q(void 0),isLiveEnded$:new q(null),canPlayLiveTailBuffer$:new q(!1),isLowLatency$:new q(!1),canChangePlaybackSpeed$:new q(!0),liveTime$:new q(void 0),liveBufferTime$:new q(void 0),liveLatency$:new q(void 0),severeStallOccurred$:new oe,availableTextTracks$:new q([]),currentTextTrack$:new q(void 0),hostname$:new q(void 0),httpConnectionType$:new q(void 0),httpConnectionReused$:new q(void 0),inPiP$:new q(!1),inFullscreen$:new q(!1),element$:new q(void 0),elementVisible$:new q(!0),availableSources$:new q(void 0),is3DVideo$:new q(!1),playbackState$:new q(""),getCurrentTime$:new q(null)};this.subscription=new yE;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=bc([...cI(this.params.tuning),...lI(this.params.tuning)]).filter(l=>vE(e.sources[l])),{forceFormat:i,formatsToAvoid:r}=this.params.tuning,s=[];i?s=[i]:r.length?s=[...t.filter(l=>!(0,Xd.default)(r,l)),...t.filter(l=>(0,Xd.default)(r,l))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",Kd(s)),this.screenFormatsIterator=new Wr(s);let n=[...ud(!0),...ud(!1)];this.chromecastFormatsIterator=new Wr(n.filter(l=>vE(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:o=1,tuning:{useVolumeMultiplier:u}}=this.params;u&&o!==1&&Qr.isSupported()&&(this.volumeMultiplierManager=new Qr(this.providerOutput,this.current$,this.volumeMultiplierError$,o))}init(){this.subscription.add(this.initProviderErrorHandling()).add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()})).add(this.providerOutput.availableVideoCodecs$.subscribe(e=>{!this.videoCodecsIterator&&e.length>1&&(this.videoCodecsIterator=new Wr(e))}))}destroy(){var e;this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe(),(e=this.volumeMultiplierManager)==null||e.destroy(),this.volumeMultiplierManager=null,this.tracer.end()}initProvider(){let e=this.chooseDestination(),t=this.chooseFormat(e);if(VV(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:cu.WTF,message:"Failed to create provider",thrown:r})}i?this.current$.next({type:t,provider:i,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.tracer.log("reinitProvider"),this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.tracer.log("switchToNextProvider",{destination:e}),this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}switchToNextVideoCodec(){this.params.tuning.dash.codecsPrioritizeEnabled&&!this.videoCodecsIterator.isLast()&&(this.tracer.log("switchToNextVideoCodec"),this.destroyProvider(),this.videoCodecsIterator.next(),this.initProvider())}destroyProvider(){let e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"}),this.tracer.log("destroyProvider"),e.destroy();let t=this.providerOutput.position$.getValue()*1e3,i=this.params.desiredState.seekState.getState(),r=i.state!=="none";if(this.params.desiredState.seekState.setState({state:"requested",position:r?i.position:t,forcePrecise:r?i.forcePrecise:!1}),e.scene3D){let n=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:n.x,y:n.y})}let s=this.providerOutput.isBuffering$;s.getValue()||s.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),this.tracer.log("createProvider",{destination:e,format:t}),e){case"SCREEN":return this.createScreenProvider(t);case"CHROMECAST":return this.createChromecastProvider(t);default:return Gs(e)}}createScreenProvider(e){var u,l;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 c=this.applyFailoverHost(t[e]),d=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return oi(c),this.params.tuning.useNewDashProvider?new Ns({...o,source:c,sourceHls:d,forceVideoCodec:(u=this.videoCodecsIterator)==null?void 0:u.getValue()}):new As({...o,source:c,sourceHls:d,forceVideoCodec:(l=this.videoCodecsIterator)==null?void 0:l.getValue()})}case"DASH_LIVE_CMAF":{let c=this.applyFailoverHost(t[e]);return oi(c),this.params.tuning.useNewDashProvider?new qs({...o,source:c}):new Rs({...o,source:c})}case"HLS":case"HLS_ONDEMAND":case"HLS_FMP4":{let c=this.applyFailoverHost(t[e]);return oi(c),new Hs({...o,source:c})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let c=this.applyFailoverHost(t[e]);return oi(c),new Us({...o,source:c,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let c=this.applyFailoverHost(t[e]);return oi(c),new js({...o,source:c})}case"DASH_LIVE":{let c=this.applyFailoverHost(t[e]);return oi(c),new ry({...o,source:c,config:{...NV,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let c=this.applyFailoverHost(t[e]);return oi(c),new Ws({container:i,source:c,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 Gs(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 oi(o),new xa({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 Gs(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return Gs(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 Gs(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,IE.default)((0,TE.default)(e).map(([r,s])=>[r,i(s)]))}initProviderErrorHandling(){let e=new yE,t=!1,i=0;return e.add(OV(this.providerOutput.error$.pipe(SE(r=>!this.params.tuning.ignoreAudioRendererError||!r.message||!/AUDIO_RENDERER_ERROR/ig.test(r.message))),fE({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(_V(r=>({id:`ProviderHangup:${r}`,category:cu.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"),FV()).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===cu.NETWORK,u=r.category===cu.FATAL,l=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),c=i<this.params.tuning.providerErrorLimit&&!u,d=this.videoCodecsIterator&&!this.videoCodecsIterator.isLast()&&this.params.tuning.dash.codecsPrioritizeEnabled,h=l&&!u&&(o&&t||!c);n={...n,isNetworkError:o,isFatalError:u,haveFailoverHost:l,tryFailover:h,canReinitProvider:c},c?(i++,this.reinitProvider()):h?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):d?this.switchToNextVideoCodec():(i=0,this.switchToNextProvider(s!=null?s:"SCREEN"))}r.traceAsLog?this.tracer.log("providerInfo",Kd(n)):this.tracer.error("providerError",Kd(n))})),e}};import{fromEvent as du,once as qV,combine as UV,Subscription as EE,ValueSubject as Jd,map as HV,filter as jV,isNonNullable as pu,now as Qe,safeStorage as Zd}from"@vkontakte/videoplayer-shared/es2018";var WV=5e3,xE="one_video_throughput",wE="one_video_rtt",Vt=window.navigator.connection,AE=()=>{let a=Vt==null?void 0:Vt.downlink;if(pu(a)&&a!==10)return a*1e3},RE=()=>{let a=Vt==null?void 0:Vt.rtt;if(pu(a)&&a!==3e3)return a},PE=(a,e,t)=>{let i=t*8,r=i/a;return i/(r+e)},ep=class a{constructor(e){this.subscription=new EE;this.concurrentDownloads=new Set;var r,s;this.tuningConfig=e;let t=a.load(xE)||(e.useBrowserEstimation?AE():void 0)||WV,i=(s=(r=a.load(wE))!=null?r:e.useBrowserEstimation?RE():void 0)!=null?s:0;if(this.throughput$=new Jd(t),this.rtt$=new Jd(i),this.rttAdjustedThroughput$=new Jd(PE(t,i,e.rttPenaltyRequestSize)),this.throughput=Ct.getSmoothedValue(t,-1,e),this.rtt=Ct.getSmoothedValue(i,1,e),e.useBrowserEstimation){let n=()=>{let u=AE();u&&this.throughput.next(u);let l=RE();pu(l)&&this.rtt.next(l)};Vt&&"onchange"in Vt&&this.subscription.add(du(Vt,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{Zd.set(xE,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{Zd.set(wE,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(UV({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(HV(({throughput:n,rtt:o})=>PE(n,o,e.rttPenaltyRequestSize)),jV(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=Qe(),r=new EE;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add(du(e,"progress").pipe(qV()).subscribe(s=>{t=s.loaded,i=Qe()}));break;case 1:case 0:r.add(du(e,"loadstart").subscribe(()=>{t=0,i=Qe()}));break}r.add(du(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=Qe(),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=Qe(),n=0,o=Qe(),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,Qe()-s,1),this.concurrentDownloads.delete(e);else if(d){if(t){let h=Qe();if(h-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||h-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let f=o-s;f&&this.addRawSpeed(n,f,1,t),n=d.byteLength,s=Qe()}else n+=d.byteLength;o=Qe()}else r+=d.byteLength,n+=d.byteLength,n>=this.tuningConfig.streamMinSampleSize&&Qe()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,Qe()-o,this.concurrentDownloads.size),n=0,o=Qe());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(pu(t))return(i=parseInt(t,10))!=null?i:void 0}},kE=ep;import{fillWithDefault as QV,VideoQuality as hu}from"@vkontakte/videoplayer-shared/es2018";var LE={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:hu.Q_4320P,activeVideoAreaThreshold:.1,highQualityLimit:hu.Q_720P,trafficSavingLimit:hu.Q_480P},stallsManager:{enabled:!0,ignoreDynamicAbrForShortVideo:!1,stallDurationNoDataBeforeQualityDecrease:500,stallDurationToBeCount:100,stallCountBeforeQualityDecrease:3,resetQualityRestrictionTimeout:1e4,ignoreStallsOnSeek:!0,stallsMetricsHistoryLength:20,maxPossibleStallDuration:3e4,minTvtToBeCounted:120,maxTvtToBeCounted:10800,significantTvt:600,targetStallsDurationPerTvt:1,deviationStallsDurationPerTvt:.5,criticalStallsDurationPerTvt:6,abrAdjustingSpeed:.1,emaAlpha:.6,useTotalStallsDurationPerTvt:!0,useAverageStallsDurationPerTvt:!0,useEmaStallsDurationPerTvt:!0},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:hu.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,seekBiasInTheEnd:2e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:15e3,crashOnStallTimeout:25e3,crashOnStallTWithoutDataTimeout:5e3,enableSubSegmentBufferFeeding:!0,bufferEmptinessTolerance:100,useNewRepresentationSwitch:!1,useDelayedRepresentationSwitch:!1,useSmartRepresentationSwitch:!1,useFetchPriorityHints:!0,enableBaseUrlSupport:!0,maxSegmentRetryCount:5,sourceOpenTimeout:1e3,vktvAbrThrottle:0,timeupdateEventTickThrottle:300,fetcherBufferOptimisation:!0,codecsPrioritizeEnabled:!1,usePersistentGaps:!1,abrThrottle:0,useVideoElementWaitingCurrentTimeReassign:!0,stallWatchdogInterval:100,liveUpdateInterval:1e3,liveStallReinitInterval:3e3},dashCmafLive:{externalStopControl:!1,keepSilentStallWatchdogWhenNotActive:!1,maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,maxLiveDuration:7200,catchupLiveForMutedInactiveTab:!0,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:250,playbackCatchupSpeedup:.05,isActiveOnDefault:!1,bufferEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:"07A4434E",useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"dash",iosPreferredFormat:"hls",preferCMAF:!1,preferWebRTC:!1,preferMultiStream:!1,preferHDR:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,seekNearDurationBias:1,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useHlsJs:!1,useNativeHLSTextTracks:!1,useNewSwitchTo:!1,useNewDashProvider:!1,useNewAutoSelectVideoTrack:!1,useSafariEndlessRequestBugfix:!0,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,audioVideoSyncRate:20,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50},useVolumeMultiplier:!1,ignoreAudioRendererError:!1,useEnableSubtitlesParam:!1,useHlsLiveNewTextManager:!1,exposeInternalsToGlobal:!1,hlsLiveNewTextManagerDownloadThreshold:4e3,disableYandexPiP:!1,asyncResolveClientChecker:!1,autostartOnlyIfVisible:!1,changePlaybackStateToPausedWhenEnded:!1,suppressExceptionsInObservables:!0},$E=a=>{var e;return{...QV(a,LE),configName:[...(e=a.configName)!=null?e:[],...LE.configName]}};import{assertNonNullable as ip,combine as _t,ErrorCategory as fu,filter as pe,filterChanged as K,fromEvent as rp,isNonNullable as BE,isNullable as ZV,Logger as e_,map as z,mapTo as VE,merge as ui,now as mu,once as Ee,Subject as W,Subscription as _E,tap as ap,ValueSubject as C,isHigher as t_,isInvariantQuality as OE,flattenObject as li,throttle as sp,getTraceSubscriptionMethod as FE,TracerFactory as i_,InternalsExposure as r_,getPlayerId as a_}from"@vkontakte/videoplayer-shared/es2018";import{merge as GV,map as zV,filter as ME,isNonNullable as YV}from"@vkontakte/videoplayer-shared/es2018";var tp=({seekState:a,position$:e})=>GV(a.stateChangeEnded$.pipe(zV(({to:t})=>{var i;return t.state==="none"?void 0:((i=t.position)!=null?i:NaN)/1e3}),ME(YV)),e.pipe(ME(()=>a.getState().state==="none")));import{assertNonNullable as KV}from"@vkontakte/videoplayer-shared/es2018";var DE=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 XV,once as JV}from"@vkontakte/videoplayer-shared/es2018";var CE=(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(XV(r=>r.length>0),JV()).subscribe(r=>{r.find(i)&&e.startTransitionTo(a)}):(a===void 0||t!=null&&t.getValue().find(i))&&e.startTransitionTo(a)};var bu=class{constructor(e={configName:[]},t=i_.createRootTracer(!1),i){this.subscription=new _E;this.logger=new e_;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 U("stopped"),seekState:new U({state:"none"}),volume:new U({volume:1,muted:!1}),videoTrack:new U(void 0),videoStream:new U(void 0),audioStream:new U(void 0),autoVideoTrackSwitching:new U(!0),autoVideoTrackLimits:new U({}),isLooped:new U(!1),isLowLatency:new U(!1),playbackRate:new U(1),externalTextTracks:new U([]),internalTextTracks:new U([]),currentTextTrack:new U(void 0),textTrackCuesSettings:new U({}),cameraOrientation:new U({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 W,ready$:new W,started$:new W,playing$:new W,paused$:new W,stopped$:new W,willReady$:new W,willStart$:new W,willResume$:new W,willPause$:new W,willStop$:new W,willDestruct$:new W,watchCoverageRecord$:new W,watchCoverageLive$:new W,managedError$:new W,fatalError$:new W,fetcherRecoverableError$:new W,ended$:new W,looped$:new W,seeked$:new W,willSeek$:new W,autoplaySoundProhibited$:new W,manifestRequested$:new W,manifestReceived$:new W,firstBytesRequested$:new W,firstBytesReceived$:new W,firstBytes$:new W,loadedMetadata$:new W,firstFrame$:new W,canplay$:new W,log$:new W,fetcherError$:new W,severeStallOccured$:new W};this.experimental={element$:new C(void 0),tuningConfigName$:new C([]),enableDebugTelemetry$:new C(!1),dumpTelemetry:Pv,getCurrentTime$:new C(null)};if(this.initLogs(),this.tuning=$E(e),this.tracer=t,this.tuning.suppressExceptionsInObservables&&((0,np.default)(this.info).forEach(r=>r.setSuppressErrors(!0)),(0,np.default)(this.events).forEach(r=>r.setSuppressErrors(!0))),this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new yn({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new kE(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new r_("core",a_(i==null?void 0:i.playerId)),this.internalsExposure.expose({player:this})),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(r,s,n)=>{let o=Reflect.get(r,s,n);return typeof o!="function"?o:(...u)=>{try{return o.apply(r,u)}catch(l){let c=u.map(p=>JSON.stringify(p,(f,m)=>{let g=typeof m;return(0,NE.default)(["number","string","boolean"],g)?m:m===null?null:`<${g}>`})),d=`Player.${String(s)}`,h=`Exception calling ${d} (${c.join(", ")})`;throw this.events.fatalError$.next({id:d,category:fu.WTF,message:h,thrown:l}),l}}}})}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",li(o)),this.domContainer=DE(e),this.chromecastInitializer.contentId=(u=e.meta)==null?void 0:u.videoId,this.providerContainer=new zs({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?_.isInited$.pipe(pe(n=>!!n),Ee()).subscribe(()=>{console.log("Core SDK async start"),i()}):i()};return this.isNotActiveTabCase()?(this.tracer.log("request play from hidden tab"),rp(document,"visibilitychange").pipe(Ee()).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()}waitInit(e){this.playerInited.getValue()?e():this.subscription.add(this.playerInited.pipe(pe(t=>!!t),Ee()).subscribe(e))}prepare(){return this.waitInit(()=>{let e=this.desiredState.playbackState;this.tracer.log("prepare",{currentPlayBackState:e.getState()}),e.getState()==="stopped"&&e.startTransitionTo("ready")}),this}play(){return this.waitInit(()=>{let e=this.desiredState.playbackState;this.tracer.log("play",{currentPlayBackState:e.getState()}),e.getState()!=="playing"&&e.startTransitionTo("playing")}),this}pause(){return this.waitInit(()=>{let e=this.desiredState.playbackState;this.tracer.log("pause",{currentPlayBackState:e.getState()}),e.getState()!=="paused"&&e.startTransitionTo("paused")}),this}stop(){return this.waitInit(()=>{let e=this.desiredState.playbackState;this.tracer.log("stop",{currentPlayBackState:e.getState()}),e.getState()!=="stopped"&&e.startTransitionTo("stopped")}),this}seekTime(e,t=!0){return this.waitInit(()=>{let i=this.info.duration$.getValue(),r=this.info.isLive$.getValue(),s=e;e>=i&&!r&&(s=i-this.tuning.seekNearDurationBias),this.tracer.log("seekTime",{duration:i,isLive:r,time:e,calculatedTime:s,forcePrecise:t}),Number.isFinite(s)&&(this.events.willSeek$.next({from:this.getExactTime(),to:s}),this.desiredState.seekState.setState({state:"requested",position:s*1e3,forcePrecise:t}))}),this}seekPercent(e){return this.waitInit(()=>{let t=this.info.duration$.getValue();this.tracer.log("seekPercent",{percent:e,duration:t}),isFinite(t)&&this.seekTime(Math.abs(t)*e,!1)}),this}setVolume(e,t){return this.waitInit(()=>{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.waitInit(()=>{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.waitInit(()=>{this.desiredState.videoStream.startTransitionTo(e)}),this}setAudioStream(e){return this.waitInit(()=>{this.desiredState.audioStream.startTransitionTo(e)}),this}setQuality(e){return this.waitInit(()=>{ip(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(pe(i=>i.length>0),Ee()).subscribe(i=>{this.setVideoTrackIdByQuality(i,e)}):this.explicitInitialQuality=e:t.length>0&&this.setVideoTrackIdByQuality(t,e)}),this}setAutoQuality(e){return this.waitInit(()=>{this.tracer.log("setAutoQuality",{enable:e}),this.desiredState.autoVideoTrackSwitching.startTransitionTo(e)}),this}setAutoQualityLimits(e){return this.waitInit(()=>{this.tracer.log("setAutoQualityLimits",li(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e)}),this}setPredefinedQualityLimits(e){return this.waitInit(()=>{if(this.info.predefinedQualityLimitType$.getValue()===e)return this;let{highQualityLimit:t,trafficSavingLimit:i}=this.tuning.autoTrackSelection,r;switch(e){case"high_quality":r={min:t,max:void 0};break;case"traffic_saving":r={max:i,min:void 0};break;default:r={max:void 0,min:void 0}}this.setAutoQualityLimits(r)}),this}setPlaybackRate(e){return this.waitInit(()=>{this.tracer.log("setPlaybackRate",{playbackRate:e}),this.desiredState.playbackRate.startTransitionTo(e)}),this}setExternalTextTracks(e){return this.waitInit(()=>{e.length&&this.tracer.log("setExternalTextTracks",li(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t})))}),this}selectTextTrack(e){return this.waitInit(()=>{var t;CE(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.waitInit(()=>{this.tracer.log("setTextTrackCueSettings",{...e}),this.desiredState.textTrackCuesSettings.startTransitionTo(e)}),this}setLiveLowLatency(e){let t=this.info.isLive$.getValue(),i=this.desiredState.isLowLatency.getState();return!t||i===e?this:(this.tracer.log("live switch to low latency "+e),this.desiredState.isLowLatency.setState(e),this.seekTime(0))}setLooped(e){return this.waitInit(()=>{this.tracer.log("setLooped",{isLooped:e}),this.desiredState.isLooped.startTransitionTo(e)}),this}toggleChromecast(){this.tracer.log("toggleChromecast"),this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){return this.waitInit(()=>{let i=this.getScene3D();this.tracer.log("startCameraManualRotation",{isScene3DAvailable:!!i,mx:e,my:t}),i&&i.startCameraManualRotation(e,t)}),this}stopCameraManualRotation(e=!1){return this.waitInit(()=>{let t=this.getScene3D();this.tracer.log("stopCameraManualRotation",{isScene3DAvailable:!!t,immediate:e}),t&&t.stopCameraManualRotation(e)}),this}moveCameraFocusPX(e,t){return this.waitInit(()=>{let i=this.getScene3D();if(this.tracer.log("moveCameraFocusPX",{isScene3DAvailable:!!i,dxpx:e,dypx:t}),i){let r=i.getCameraRotation(),s=i.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:r.x+s.x,y:r.y+s.y})}}),this}holdCamera(){return this.waitInit(()=>{let e=this.getScene3D();e&&e.holdCamera()}),this}releaseCamera(){return this.waitInit(()=>{let e=this.getScene3D();e&&e.releaseCamera()}),this}getExactTime(){if(!this.providerContainer)return 0;let e=this.providerContainer.providerOutput.element$.getValue();if(ZV(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),i=t.state==="none"?void 0:t.position;return BE(i)?i/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){var t,i;let e=(t=this.providerContainer)==null?void 0:t.current$.getValue();if((i=e==null?void 0:e.provider)!=null&&i.scene3D)return e.provider.scene3D}setIntrinsicVideoSize(...e){let t={width:e.reduce((i,{width:r})=>i||r||0,0),height:e.reduce((i,{height:r})=>i||r||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(ui(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(z(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(z(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(z(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(z(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(z(e=>e.to)).subscribe(e=>{this.info.autoQualityLimits$.next(e);let{highQualityLimit:t,trafficSavingLimit:i}=this.tuning.autoTrackSelection;this.info.predefinedQualityLimitType$.next(Lv(e,t,i))})),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(pe(({from:e})=>e==="stopped"),Ee()).subscribe(()=>{this.initedAt=mu(),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",li(n)),n.state==="requested"?this.desiredState.seekState.setState({...n,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:fu.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe(Ee()).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",li(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(_t({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)=>OE(u)?1:OE(l)?-1:t_(l,u)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(n=>{let o={};for(let u of n)u.fps&&(o[u.quality]=u.fps);this.info.availableQualitiesFps$.next(o)})).add(e.providerOutput.availableAudioStreams$.subscribe(this.info.availableAudioStreams$)).add(e.providerOutput.currentVideoStream$.subscribe(this.info.currentVideoStream$)).add(e.providerOutput.currentAudioStream$.subscribe(this.info.currentAudioStream$)).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.pipe(K()).subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.pipe(pe(n=>BE(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(ap(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:ui(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(_t({atLiveEdge:_t({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:tp({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(),ap(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(z(({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(z(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),K(),ap(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(tp({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(e.providerOutput.seekedEvent$.subscribe(()=>{this.info.isEnded$.getValue()&&this.tuning.changePlaybackStateToPausedWhenEnded&&this.play()})).add(ui(e.providerOutput.endedEvent$.pipe(VE(!0)),e.providerOutput.seekedEvent$.pipe(VE(!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:fu.VIDEO_PIPELINE,message:n?`${n} was forced but failed or not available`:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.getCurrentTime$.subscribe(this.experimental.getCurrentTime$)).add(e.providerOutput.manifestRequested$.pipe(Ee()).subscribe(this.events.manifestRequested$)).add(e.providerOutput.manifestReceived$.pipe(Ee()).subscribe(this.events.manifestReceived$)).add(e.providerOutput.firstBytesRequested$.pipe(Ee()).subscribe(this.events.firstBytesRequested$)).add(e.providerOutput.firstBytesReceived$.pipe(Ee()).subscribe(this.events.firstBytesReceived$)).add(e.providerOutput.firstBytesEvent$.pipe(Ee(),z(n=>n!=null?n:mu()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(Ee(),z(()=>mu()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(Ee(),z(()=>mu()-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(pe(({to:n})=>n==="playing"),Ee()).subscribe(()=>i.next(!1)));let r=0,s=ui(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(ui(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{let n=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n==null?void 0:n.videoWidth,height:n==null?void 0:n.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{var u,l;let o=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:(u=n==null?void 0:n.size)==null?void 0:u.width,height:(l=n==null?void 0:n.size)==null?void 0:l.height},{width:o==null?void 0:o.videoWidth,height:o==null?void 0:o.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add(ui(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,e.providerOutput.elementVisible$,this.chromecastInitializer.castState$).subscribe(()=>{let n=e.providerOutput.inPiP$.getValue(),o=e.providerOutput.inFullscreen$.getValue(),u=e.providerOutput.element$.getValue(),l=e.providerOutput.elementVisible$.getValue(),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(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 _E;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(pe(i=>i.length>0),Ee()).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(ui(this.desiredState.videoTrack.stateChangeStarted$.pipe(z(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(z(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(z(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(z(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(z(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(z(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(z(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(z(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(z(e=>({component:"desiredState",message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`}))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){var t;let e=(t=this.providerContainer)==null?void 0:t.providerOutput;ip(this.providerContainer),ip(e),Rv(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(i=>Av(i)),this.providerContainer.current$.subscribe(({type:i})=>Pa("provider",i)),e.duration$.subscribe(i=>Pa("duration",i)),e.availableVideoTracks$.pipe(pe(i=>!!i.length),Ee()).subscribe(i=>Pa("tracks",i)),this.events.fatalError$.subscribe(new Re("fatalError")),this.events.managedError$.subscribe(new Re("managedError")),e.position$.subscribe(new Re("position")),e.currentVideoTrack$.pipe(z(i=>i==null?void 0:i.quality)).subscribe(new Re("quality")),this.info.currentBuffer$.subscribe(new Re("buffer")),e.isBuffering$.subscribe(new Re("isBuffering"))].forEach(i=>this.subscription.add(i)),Pa("codecs",_.video.supportedCodecs)}initTracerSubscription(){let e=FE(this.tracer.log.bind(this.tracer)),t=FE(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(_t({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe(pe(({currentQuality:i,videoBitrate:r})=>!!i&&!!r),K((i,r)=>i.currentQuality===r.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe(pe(i=>i>0),K()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe(pe(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(_t({currentBuffer:this.info.currentBuffer$.pipe(pe(i=>i.end>0),K((i,r)=>i.end===r.end&&i.start===r.start)),position:this.info.position$.pipe(K())}).pipe(sp(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(_t({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(pe(({liveTime:i,liveBufferTime:r})=>!!i&&!!r),sp(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(K(),pe(i=>i===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(K(),pe(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(),pe(i=>i===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add(_t({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(pe(({throughputEstimation:i,rtt:r})=>!!i&&!!r),sp(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(K(),pe(i=>i===!0)).subscribe(e("is3DVideo"))).add(this.info.surface$.subscribe(e("surface"))).add(this.events.ended$.subscribe(e("ended"))).add(this.events.looped$.subscribe(e("looped"))).add(this.events.managedError$.subscribe(t("managedError"))).add(this.events.fatalError$.subscribe(t("fatalError"))).add(this.events.firstBytes$.subscribe(e("firstBytes"))).add(this.events.firstFrame$.subscribe(e("firstFrame"))).add(this.events.canplay$.subscribe(e("canplay")))}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e,t=()=>{e==null||e.release(),e=void 0},i=async()=>{t(),e=await window.navigator.wakeLock.request("screen").catch(r=>{r instanceof DOMException&&r.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:fu.DOM,message:String(r)})})};this.subscription.add(ui(rp(document,"visibilitychange"),rp(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",li({quality:t,availableTracks:li(e),track:li(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&&!Ba()}};import{Subscription as B7,Observable as V7,Subject as _7,ValueSubject as O7,VideoQuality as F7}from"@vkontakte/videoplayer-shared/es2018";var N7=`@vkontakte/videoplayer-core@${Qp}`;export{cn as ChromecastState,Iu as HttpConnectionType,V7 as Observable,$e as PlaybackState,bu as Player,dn as PredefinedQualityLimits,N7 as SDK_VERSION,_7 as Subject,B7 as Subscription,Eu as Surface,Qp as VERSION,O7 as ValueSubject,At as VideoFormat,F7 as VideoQuality,z$ as areValidLiveRecordSources,_ as clientChecker,Ea as isMobile};
|
|
178
|
+
`;var Fr=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 Zo(this.params.fov,this.params.orientation),this.cameraRotationManager=new eu(this.camera,{rotationSpeed:this.params.rotationSpeed,maxYawAngle:this.params.maxYawAngle,rotationSpeedCorrection:this.params.rotationSpeedCorrection,degreeToPixelCorrection:this.params.degreeToPixelCorrection,speedFadeTime:this.params.speedFadeTime,speedFadeThreshold:this.params.speedFadeThreshold}),this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.textureMappingBuffer=this.createTextureMappingBuffer(),this.updateTextureMappingBuffer(),this.program=this.createProgram(),this.videoTexture=this.createTexture(),this.gl.useProgram(this.program),this.videoElementDataLoadedFn=this.onDataLoadedHandler.bind(this),this.renderFn=this.render.bind(this)}play(){this.active||(this.videoInitialized?this.doPlay():this.sourceVideoElement.readyState>=2?(this.videoInitialized=!0,this.doPlay()):this.sourceVideoElement.addEventListener("loadeddata",this.videoElementDataLoadedFn))}stop(){this.active=!1}startCameraManualRotation(e,t){this.cameraRotationManager.setRotationSpeed(e*this.params.rotationSpeed,t*this.params.rotationSpeed,0),this.cameraRotationManager.startRotation()}stopCameraManualRotation(e=!1){this.cameraRotationManager.stopRotation(e)}turnCamera(e,t){this.cameraRotationManager.turnCamera(e,t)}pointCameraTo(e,t){this.cameraRotationManager.pointCameraTo(e,t)}pixelToDegree(e){return{x:this.params.degreeToPixelCorrection*this.params.fov.x*-e.x/this.viewportWidth,y:this.params.degreeToPixelCorrection*this.params.fov.y*e.y/this.viewportHeight}}getCameraRotation(){return this.camera.orientation}holdCamera(){this.cameraRotationManager.stopRotation(!0)}releaseCamera(){this.cameraRotationManager.onCameraRelease()}destroy(){this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),this.stop(),this.canvas.remove()}setViewportSize(e,t){this.viewportWidth=e,this.viewportHeight=t,this.canvas.width=this.viewportWidth,this.canvas.height=this.viewportHeight,this.gl.viewport(0,0,this.canvas.width,this.canvas.height)}onDataLoadedHandler(){this.videoInitialized=!0,this.doPlay()}doPlay(){this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.active=!0,this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),requestAnimationFrame(this.renderFn)}render(e){this.cameraRotationManager.tick(e),this.updateTexture(),this.updateTextureMappingBuffer();let t=this.gl.getAttribLocation(this.program,"a_vertex"),i=this.gl.getAttribLocation(this.program,"a_texel"),r=this.gl.getUniformLocation(this.program,"u_texture"),a=this.gl.getUniformLocation(this.program,"u_focus");this.gl.enableVertexAttribArray(t),this.gl.enableVertexAttribArray(i),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.vertexBuffer),this.gl.vertexAttribPointer(t,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.vertexAttribPointer(i,2,this.gl.FLOAT,!1,0,0),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.uniform1i(r,0),this.gl.uniform2f(a,-this.camera.orientation.x,-this.camera.orientation.y),this.gl.drawArrays(this.gl.TRIANGLE_FAN,0,4),this.gl.bindTexture(this.gl.TEXTURE_2D,null),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),this.gl.disableVertexAttribArray(t),this.gl.disableVertexAttribArray(i),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){let i=this.gl.createShader(t);if(!i)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(i,e),this.gl.compileShader(i),!this.gl.getShaderParameter(i,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(i));return i}createProgram(){let e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");let t=this.createShader(DI,this.gl.VERTEX_SHADER),i=this.createShader(BI,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,i),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){let e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,i=1,r=this.frameHeight/(this.frameWidth/this.viewportWidth);return r>this.viewportHeight?t=this.viewportHeight/r:i=r/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-i,t,-i,t,i,-t,i]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){let e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,i=this.camera.fov.x/360/2,r=this.camera.fov.y/180/2,a=e-i,n=t-r,o=e+i,u=t-r,c=e+i,d=t+r,l=e-i,h=t+r;return[a,n,o,u,c,d,l,h]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){let e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}};import{isNullable as x0,now as ka,once as w0,Subscription as A0,ValueSubject as Ad,isNonNullable as P0,safeStorage as Pd,filterChanged as R0}from"@vkontakte/videoplayer-shared/es2018";var tu="stalls_manager_metrics",Rd="stalls_manager_abr_params",VI="stalls_manager_default_tuning_abr_params",kd=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 A0;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.duration=e.duration,this.resetStoredAbrParamsIfNeeded(),this.subscribe(e)}get videoMaxQualityLimit(){return this.maxQualityLimit}get predictedThroughput(){return this.predictedThroughputWithoutData}get abrTuningParams(){let t=(this.tuning.ignoreDynamicAbrForShortVideo?this.tuning.enabled&&this.duration>this.tuning.minTvtToBeCounted:this.tuning.enabled)?this.getStoredData(Rd):{};return{...this.abrParams,...t}}set lastVideoTrackSelected(e){var t;((t=this.lastUniqueVideoTrackSelected)==null?void 0:t.id)!==e.id&&(this.lastUniqueVideoTrackSelected=e,this.lastUniqueVideoTrackSelectedTimestamp=ka(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe(),this.currentStallDuration$.getValue()!==0&&this.updateStallData();let e=(ka()-this.providerStartWatchingTimestamp-this.sumStallsDuration)/1e3,t=this.sumStallsDuration;this.addStallInfoToHistory(e,t),this.updateStoredAbrParams()}resetStoredAbrParamsIfNeeded(){let{bitrateFactorAtEmptyBuffer:e,bitrateFactorAtFullBuffer:t,containerSizeFactor:i}={...this.getStoredData(VI)},{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:a,containerSizeFactor:n}={...this.abrParams};this.tuning.enabled&&e===r&&t===a&&i===n||(this.removeStoredData(Rd),this.setStoredData(VI,{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:a,containerSizeFactor:n}))}updateStoredAbrParams(){let e=[],t=this.getStoredData(tu,"[]");if(!this.tuning.enabled||t.length<this.tuning.stallsMetricsHistoryLength)return;let i=t.reduce((a,n)=>a+n.tvt,0);if(this.tuning.useTotalStallsDurationPerTvt){let n=t.reduce((o,u)=>o+u.stallsDuration,0)/i;e.push(this.calculateOptimalAbrParams(n,i))}if(this.tuning.useAverageStallsDurationPerTvt){let a=t.reduce((n,o)=>n+o.stallsDurationPerTvt,0)/t.length;e.push(this.calculateOptimalAbrParams(a,i))}this.tuning.useEmaStallsDurationPerTvt&&e.push(this.calculateOptimalAbrParams(t[t.length-1].stallsDurationPerTvtSmoothed,i));let r={bitrateFactorAtEmptyBuffer:Math.max(...e.map(a=>a.bitrateFactorAtEmptyBuffer)),bitrateFactorAtFullBuffer:Math.max(...e.map(a=>a.bitrateFactorAtFullBuffer)),containerSizeFactor:Math.min(...e.map(a=>a.containerSizeFactor))};this.setStoredData(tu,[]),this.setStoredData(Rd,r)}calculateOptimalAbrParams(e,t){let{targetStallsDurationPerTvt:i,deviationStallsDurationPerTvt:r,criticalStallsDurationPerTvt:a,abrAdjustingSpeed:n,significantTvt:o}=this.tuning,u=n*Math.min(t/o,1),c=this.abrTuningParams;return e<i-r?c={bitrateFactorAtEmptyBuffer:Math.max(c.bitrateFactorAtEmptyBuffer-u,this.abrParams.minBitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.max(c.bitrateFactorAtFullBuffer-u,this.abrParams.minBitrateFactorAtFullBuffer),containerSizeFactor:Math.min(c.containerSizeFactor+u,this.abrParams.maxContainerSizeFactor)}:e>i+r&&(c={bitrateFactorAtEmptyBuffer:Math.min(c.bitrateFactorAtEmptyBuffer+u,this.abrParams.maxBitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.min(c.bitrateFactorAtFullBuffer+u,this.abrParams.maxBitrateFactorAtFullBuffer),containerSizeFactor:Math.max(c.containerSizeFactor-u,this.abrParams.minContainerSizeFactor)}),e>a&&(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=Pd.get(e))!=null?i:t)}setStoredData(e,t){Pd.set(e,JSON.stringify(t))}removeStoredData(e){Pd.remove(e)}addStallInfoToHistory(e,t){if(e<this.tuning.minTvtToBeCounted||e>this.tuning.maxTvtToBeCounted||e*1e3<t)return;let i=this.getStoredData(tu,"[]"),r=t/e,a=i.length?Dt(i[i.length-1].stallsDurationPerTvtSmoothed,t/e,this.tuning.emaAlpha):r,n={tvt:e,stallsDuration:t,stallsDurationPerTvt:r,stallsDurationPerTvtSmoothed:a};i.push(n),i.length>this.tuning.stallsMetricsHistoryLength&&i.shift(),this.setStoredData(tu,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(w0()).subscribe(t=>this.providerStartWatchingTimestamp=ka())),this.subscription.add(this.currentStallDuration$.pipe(R0()).subscribe(t=>{let{stallDurationNoDataBeforeQualityDecrease:i,stallCountBeforeQualityDecrease:r,resetQualityRestrictionTimeout:a,ignoreStallsOnSeek:n}=this.tuning;if(x0(this.lastUniqueVideoTrackSelected)||n&&this.isSeeked$.getValue())return;let o=this.rtt$.getValue(),u=this.throughput$.getValue(),c=this.videoLastDataObtainedTimestamp$.getValue(),d=ka(),l=r&&this.currentStallsCount>=r,h=i&&d-this.lastUniqueVideoTrackSelectedTimestamp>=i+o&&d-c>=i+o&&t>=i;(l||h)&&(this.severeStallOccurred$.next(!0),window.clearTimeout(this.qualityRestrictionTimer),this.maxQualityLimit=this.lastUniqueVideoTrackSelected.quality,P0(this.lastUniqueVideoTrackSelected.bitrate)&&u>this.lastUniqueVideoTrackSelected.bitrate&&(this.predictedThroughputWithoutData=this.lastUniqueVideoTrackSelected.bitrate)),!t&&ka()-this.providerStartWatchingTimestamp>this.lastStallDuration&&(this.updateStallData(),this.severeStallOccurred$.next(!1),window.clearTimeout(this.qualityRestrictionTimer),this.qualityRestrictionTimer=window.setTimeout(()=>{this.maxQualityLimit=void 0,this.predictedThroughputWithoutData=0},a)),this.lastStallDuration=t}))}},iu=kd;import{combine as k0,map as $0,observeElementSize as L0,Subscription as M0,ValueSubject as $d,noop as C0}from"@vkontakte/videoplayer-shared/es2018";var ru=class{constructor(){this.subscription=new M0;this.pipSize$=new $d(void 0);this.videoSize$=new $d(void 0);this.elementSize$=new $d(void 0);this.pictureInPictureWindowRemoveEventListener=C0}connect({observableVideo:e,video:t}){let i=r=>{let a=r.target;this.pipSize$.next({width:a.width,height:a.height})};this.subscription.add(L0(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(k0({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe($0(({videoSize:r,inPip:a,pipSize:n})=>a?n:r)).subscribe(this.elementSize$))}getValue(){return this.elementSize$.getValue()}subscribe(e,t){return this.elementSize$.subscribe(e,t)}getObservable(){return this.elementSize$}destroy(){this.pictureInPictureWindowRemoveEventListener(),this.subscription.unsubscribe()}};import{filter as _I,map as D0,once as OI}from"@vkontakte/videoplayer-shared/es2018";var Nr=({subscription:s,desiredState:e,videoElement$:t,observableVideo:i})=>{if(!_.browser.isSafari)return;let r=0,a=!1;s.add(e.volume.stateChangeStarted$.pipe(D0(()=>{let n=e.volume.getTransition(),o=t.getValue();return!o||!n?!1:!n.to.muted&&o.muted}),_I(n=>!!n),OI()).subscribe(()=>{r=performance.now(),a=!0})),s.add(i.playbackRateState$.pipe(_I(()=>a),OI()).subscribe(()=>{let n=t.getValue(),o=e.playbackRate.getState();n&&o!==n.playbackRate&&performance.now()-r<1e3&&(n.playbackRate=o)}))};var Ni=class{constructor(e){this.subscription=new U0;this.videoState=new U("stopped");this.observableVideo=null;this.droppedFramesManager=new xr;this.stallsManager=new iu;this.elementSizeManager=new ru;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Zt;this.audioTrackSwitchHistory=new Zt;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"),k(this.params.desiredState.playbackState,"stopped",!0));return}switch(e){case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();return;case"ready":t==="paused"?(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="ready"&&k(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):t==="playing"&&this.video.paused?this.playIfAllowed():(i==null?void 0:i.to)==="playing"&&k(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&k(this.params.desiredState.playbackState,"paused");return;default:return V0(e)}}};this.init3DScene=e=>{var i,r,a;if(this.scene3D)return;this.scene3D=new Fr(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((i=e.projectionData)==null?void 0:i.pose.yaw)||0,y:((r=e.projectionData)==null?void 0:r.pose.pitch)||0,z:((a=e.projectionData)==null?void 0:a.pose.roll)||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSizeManager.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.textTracksManager=new Ye(e.source.url),this.params=e,this.video=De(e.container,e.tuning),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(ye(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,forceVideoCodec:this.params.forceVideoCodec}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params;q0(this.observableVideo)&&(this.observableVideo=_e(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:FI.WTF,message:`${i} internal logic error`,thrown:n})},a=(n,o)=>this.subscription.add(n.subscribe(o,r));return{output:e,desiredState:t,observableVideo:this.observableVideo,genericErrorListener:r,connect:a}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:a}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(Ld(l=>!!l.length),qI()).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(La(l=>l.to.state!=="none"),$a());this.stallsManager.init({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$,videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,tuning:this.params.tuning.stallsManager,abrParams:this.params.tuning.autoTrackSelection,isBuffering$:i.isBuffering$,looped$:i.looped$,playing$:i.playing$,duration:this.video.duration}),a(i.ended$,e.endedEvent$),a(i.looped$,e.loopedEvent$),a(i.error$,e.error$),a(i.isBuffering$,e.isBuffering$),a(i.currentBuffer$,e.currentBuffer$),a(i.playing$,e.firstFrameEvent$),a(i.canplay$,e.canplay$),a(i.inPiP$,e.inPiP$),a(i.inFullscreen$,e.inFullscreen$),a(i.loadedMetadata$,e.loadedMetadataEvent$),a(this.player.error$,e.error$),a(this.player.fetcherRecoverableError$,e.fetcherRecoverableError$),a(this.player.fetcherError$,e.fetcherError$),a(this.player.lastConnectionType$,e.httpConnectionType$),a(this.player.lastConnectionReused$,e.httpConnectionReused$),a(this.player.isLive$,e.isLive$),a(this.player.lastRequestFirstBytes$.pipe(Ld(NI),qI()),e.firstBytesEvent$),a(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),a(this.videoState.stateChangeEnded$.pipe(La(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(gt(this.video,t.isLooped,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),Nr({subscription:this.subscription,desiredState:t,videoElement$:this.params.output.element$,observableVideo:i}),this.subscription.add(Ve(this.video,t.volume,i.volumeState$,r)),this.subscription.add(ze(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),a(Ke(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),k(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),k(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(i.ended$.subscribe(()=>{this.videoState.setState("paused"),k(t.playbackState,"paused")})),this.subscription.add(this.player.manifestRequested.subscribe(this.params.output.manifestRequested$)).add(this.player.manifestReceived.subscribe(this.params.output.manifestReceived$)).add(this.player.firstBytesRequested.subscribe(this.params.output.firstBytesRequested$)).add(this.player.firstBytesReceived.subscribe(this.params.output.firstBytesReceived$)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:l})=>{if(l==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let h=this.player.getStreams(),p=this.player.getCodecs();if(_0(h,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let m=[];for(let g of h.audio){m.push(hd(g));let b=[];for(let S of g.representations){let T=SI(S);b.push(T),this.audioTracksMap.set(T,{stream:g,representation:S})}this.audioStreamsMap.set(g,b)}this.params.output.availableAudioStreams$.next(m)}let f=[];for(let m of h.video){f.push(fd(m));let g=[];for(let b of m.representations){let S=ya({...b,streamId:m.id});S&&(g.push(S),this.videoTracksMap.set(S,{stream:m,representation:b}))}this.videoStreamsMap.set(m,g)}this.params.output.availableVideoStreams$.next(f);for(let m of h.text)for(let g of m.representations){let b=yI(m,g);this.textTracksMap.set(b,{stream:m,representation:g})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),p!=null&&p.video&&this.params.output.availableVideoCodecs$.next(p.video),p!=null&&p.audio&&this.params.output.availableAudioCodecs$.next(p.audio),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else l==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r));let o=Ma(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$,N0(this.video,"progress")).pipe(Ld(()=>this.videoTracksMap.size>0)),{abrThrottle:u}=this.params.tuning.dash;u&&(o=o.pipe(j0(u))),this.subscription.add(o.subscribe(async()=>{let l=this.player.state$.getState(),h=this.player.state$.getTransition();if(l!=="manifest_ready"&&l!=="running"||h)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let p=this.selectVideoAudioRepresentations();if(!p)return;let[f,m]=p,g=[...this.videoTracksMap.keys()].find(S=>{var T;return((T=this.videoTracksMap.get(S))==null?void 0:T.representation.id)===f.id});NI(g)&&(this.stallsManager.lastVideoTrackSelected=g);let b=this.params.desiredState.autoVideoTrackLimits.getTransition();if(b&&this.params.output.autoVideoTrackLimits$.next(b.to),l==="manifest_ready")await this.player.initRepresentations(f.id,m==null?void 0:m.id,this.params.sourceHls);else if(await this.player.switchRepresentation("video",f.id),m){let S=!!t.audioStream.getTransition();await this.player.switchRepresentation("audio",m.id,S)}},r)),this.subscription.add(O0({videoState:this.videoState.stateChangeEnded$,autoVideoTrackState:Ma(su([t.autoVideoTrackSwitching.getState()]),t.autoVideoTrackSwitching.stateChangeEnded$.pipe(La(l=>l.to)))}).pipe(La(({videoState:l,autoVideoTrackState:h})=>l.to!=="stopped"&&h),$a()).subscribe(l=>this.player.setSmartRepresentationSwitch(l))),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($a()).subscribe(l=>{let h=[...this.videoTracksMap.entries()].find(([,{representation:b}])=>b.id===l);if(!h){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[p,{stream:f}]=h,m=this.params.desiredState.videoStream.getTransition();m&&m.to&&m.to.id===f.id&&this.params.desiredState.videoStream.setState(m.to),e.currentVideoTrack$.next(p),e.currentVideoStream$.next(fd(f));let g=this.player.calculateDurationFromSegments();g&&this.params.output.duration$.next(g/1e3)},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe($a()).subscribe(l=>{let h=[...this.audioTracksMap.entries()].find(([,{representation:g}])=>g.id===l);if(!h){e.currentAudioStream$.next(void 0);return}let[p,{stream:f}]=h,m=this.params.desiredState.audioStream.getTransition();m&&m.to&&m.to.id===f.id&&this.params.desiredState.audioStream.setState(m.to),e.currentAudioStream$.next(hd(f))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(l=>{var h,p;if(l!=null&&l.is3dVideo&&((h=this.params.tuning.spherical)!=null&&h.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(),(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 c=t.playbackState.stateChangeStarted$.pipe(La(({to:l})=>l==="ready"),$a());this.subscription.add(Ma(c,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,su(["init"])).subscribe(()=>{let l=t.autoVideoTrackSwitching.getState(),p=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:l?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(p)})),this.subscription.add(Ma(c,this.player.state$.stateChangeEnded$,su(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let d=Ma(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,su(["init"])).pipe(F0(0));this.subscription.add(d.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){var L,C,P,B,M,F,Q,j,I,R,x,w,V;if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?_s:Vs,t=this.params.tuning.useNewAutoSelectVideoTrack?wo:xo,i=this.params.tuning.useNewAutoSelectVideoTrack?yt:Eo,{desiredState:r,output:a}=this.params,n=r.autoVideoTrackSwitching.getState(),o=(L=r.videoTrack.getState())==null?void 0:L.id,u=[...this.videoTracksMap.keys()].find(({id:G})=>G===o),c=a.currentVideoTrack$.getValue(),d=((B=(P=r.videoStream.getState())!=null?P:u&&((C=this.videoTracksMap.get(u))==null?void 0:C.stream))!=null?B:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!d)return;let l=[...this.videoStreamsMap.keys()].find(({id:G})=>G===d.id),h=l&&this.videoStreamsMap.get(l);if(!h)return;let p=Te(this.video.buffered,this.video.currentTime*1e3),f;this.player.isActiveLive$.getValue()?f=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?f=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:f=n?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let m=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,g=Math.min(p/Math.min(f,m||1/0),1),b=(M=r.audioStream.getState())!=null?M:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,S=(F=[...this.audioStreamsMap.keys()].find(({id:G})=>G===(b==null?void 0:b.id)))!=null?F:this.audioStreamsMap.keys().next().value,T=0;if(S){if(u&&!n){let G=e(u,h,(Q=this.audioStreamsMap.get(S))!=null?Q:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);T=Math.max(T,(j=G==null?void 0:G.bitrate)!=null?j:-1/0)}if(c){let G=e(c,h,(I=this.audioStreamsMap.get(S))!=null?I:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);T=Math.max(T,(R=G==null?void 0:G.bitrate)!=null?R:-1/0)}}let y=u;(n||!y)&&(y=i(h,{container:this.elementSizeManager.getValue(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.stallsManager.abrTuningParams,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:T,forwardBufferHealth:g,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}));let E=S&&t(y,h,(x=this.audioStreamsMap.get(S))!=null?x:[],{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}),A=(w=this.videoTracksMap.get(y))==null?void 0:w.representation,$=E&&((V=this.audioTracksMap.get(E))==null?void 0:V.representation);if(A&&$)return[A,$];if(A&&!$&&this.audioTracksMap.size===0)return[A,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Oe(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:FI.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.stallsManager.destroy(),this.elementSizeManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),this.params.output.currentVideoStream$.next(void 0),Be(this.video),this.tracer.end()}};var Ca=class extends Ni{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};import{combine as Md,merge as UI,filter as jI,filterChanged as HI,isNullable as Cd,map as WI,ValueSubject as Dd,isNonNullable as H0}from"@vkontakte/videoplayer-shared/es2018";var Da=class extends Ni{constructor(e){super(e),this.textTracksManager.destroy()}subscribe(){super.subscribe();let e=!1,t=-1,{output:i,observableVideo:r,desiredState:a,connect:n}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canPlayLiveTailBuffer$.next(!0),n(r.timeUpdate$,i.liveBufferTime$),n(this.player.liveSeekableDuration$,i.duration$),n(this.player.liveLatency$,i.liveLatency$);let o=new Dd(1);n(r.playbackRateState$,o),this.params.tuning.dashCmafLive.catchupLiveForMutedInactiveTab&&this.subscription.add(i.elementVisible$.pipe(HI()).subscribe(u=>{let c=i.position$.getValue(),d=i.volume$.getValue(),l=!d.volume||d.muted;!u&&!c&&l?e=!0:u&&e&&(this.seek(0),e=!1)})),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(a.isLowLatency.stateChangeEnded$.pipe(WI(u=>u.to)).subscribe(this.player.isLowLatency$)).add(Md({liveBufferTime:i.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(WI(({liveBufferTime:u,liveAvailabilityStartTime:c})=>u&&c?u+c:void 0)).subscribe(i.liveTime$)).add(Md({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:UI(r.playbackRateState$,new Dd(1))}).pipe(jI(({liveStreamStatus:u,liveDuration:c})=>u==="active"&&!!c)).subscribe(({liveDuration:u,playbackRate:c})=>{let d=i.liveBufferTime$.getValue(),l=i.position$.getValue(),{playbackCatchupSpeedup:h}=this.params.tuning.dashCmafLive.lowLatency;l||c<1-h||this.video.paused||Cd(d)||(t=u-d)})).add(Md({time:i.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:UI(r.playbackRateState$,new Dd(1))}).pipe(HI((u,c)=>this.player.liveStreamStatus$.getValue()==="active"?u.liveDuration===c.liveDuration:u.time===c.time)).subscribe(({time:u,liveDuration:c,playbackRate:d})=>{let l=i.position$.getValue(),{playbackCatchupSpeedup:h}=this.params.tuning.dashCmafLive.lowLatency;if(!l&&!this.video.paused&&d>=1-h||Cd(u)||Cd(c))return;let p=-1*(c-u-t);i.position$.next(Math.min(p,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(u=>{if(u){let c=TI(u);this.params.output.availableTextTracks$.next([c])}})),this.params.tuning.dashCmafLive.externalStopControl||this.subscription.add(this.player.liveStreamStatus$.pipe(jI(u=>H0(u))).subscribe(u=>i.isLiveEnded$.next(u==="unpublished"&&i.position$.getValue()===0)))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=Math.trunc(t/1e3<=Math.abs(this.params.output.duration$.getValue())?t:0);this.player.seekLive(i).then(()=>{this.params.output.position$.next(e/1e3)})}};import{assertNever as vV,assertNonNullable as SV,combine as yV,debounce as TV,ErrorCategory as uE,filter as Kd,filterChanged as Ha,fromEvent as IV,isNonNullable as cE,isNullable as EV,map as Wa,merge as Qa,observableFrom as mu,once as lE,Subscription as xV}from"@vkontakte/videoplayer-shared/es2018";var oE=O(Ae(),1),zd=O(Ws(),1);import{abortable as Hd,assertNonNullable as jr,combine as Hr,ErrorCategory as ct,filter as pu,filterChanged as qa,flattenObject as Ua,fromEvent as xt,getTraceSubscriptionMethod as oV,interval as Wd,isNonNullable as ja,isNullable as aE,map as Wr,merge as Wi,now as Qd,Subject as ui,Subscription as Gd,SubscriptionRemovable as uV,tap as cV,throttle as nE,ValueSubject as re}from"@vkontakte/videoplayer-shared/es2018";var uu=O(Ae(),1),Hi=O(nt(),1),cu=O(Ws(),1);var tE=O(uo(),1);import{assertNever as W0,ErrorCategory as QI,Subject as GI}from"@vkontakte/videoplayer-shared/es2018";var Q0=18,zI=!1;try{zI=_.browser.isSafari&&!!_.browser.safariVersion&&_.browser.safariVersion<=Q0}catch(s){console.error(s)}var Bd=class{constructor(e){this.bufferFull$=new GI;this.error$=new GI;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:QI.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(i=>{let r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(r=>{let a={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(a),this.pull()})}async abort(e){return new Promise(t=>{let i,r=a=>{this.abortRequested=!1,t(a)};zI&&e?i={operation:"safariAbort",init:e,callback:r}:i={operation:"abort",callback:r};for(let{callback:a}of this.queue)a(!1);this.abortRequested=!0,i&&(this.queue=[i]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){var r;if((this.buffer.updating||this.currentTask||this.destroyed)&&!this.abortRequested)return;let e=this.queue.shift();if(!e)return;if((r=e.signal)!=null&&r.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(a){a instanceof DOMException&&a.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):a instanceof DOMException&&a.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:QI.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:a}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){let{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:W0(t)}}},YI=Bd;import{abortable as ni,assertNonNullable as Me,ErrorCategory as Ui,fromEvent as Nd,getExponentialDelay as qd,isHigher as X0,isNonNullable as oi,isNullable as de,now as ou,once as J0,Subject as Z0,Subscription as eV,ValueSubject as ji}from"@vkontakte/videoplayer-shared/es2018";var Vd=O(nt(),1);import{videoSizeToQuality as G0,throttleFn as z0}from"@vkontakte/videoplayer-shared/es2018";var Ba=({id:s,width:e,height:t,bitrate:i,fps:r,quality:a,streamId:n})=>{var u;let o=(u=a?Jt(a):void 0)!=null?u:G0({width:e,height:t});return o&&{id:s,quality:o,bitrate:i,size:{width:e,height:t},fps:r,streamId:n}},KI=({id:s,bitrate:e})=>({id:s,bitrate:e}),XI=({language:s,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:s,label:e}),JI=({language:s,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:s,label:e}),_d=({id:s,language:e,label:t,codecs:i,isDefault:r})=>({id:s,language:e,label:t,codec:(0,Vd.default)(i.split("."),0),isDefault:r}),Od=({id:s,language:e,label:t,hdr:i,codecs:r})=>({id:s,language:e,hdr:i,label:t,codec:(0,Vd.default)(r.split("."),0)}),Fd=s=>"url"in s,We=s=>s.type==="template";var ZI=s=>{s.sort((t,i)=>t.from-i.from);let e=[s[0]];for(let t=1;t<s.length;t++){let{from:i,to:r}=s[t],a=e[e.length-1];a.to>=i?a.to=Math.max(a.to,r):e.push(s[t])}return e},qi=(s,e)=>{for(let t of s)if(e(t))return t;return null},eE=s=>{let e=!1,t=z0(()=>{e=!0},s);return()=>{try{return t(),e}finally{e=!1}}};import{fromEvent as Y0,Subscription as K0}from"@vkontakte/videoplayer-shared/es2018";var au=s=>{let e=[];for(let t=0;t<s.length;t++){let i=Math.floor(s.start(t)*1e3),r=Math.ceil(s.end(t)*1e3);e.push(i,r)}return e};var nu=class{constructor(e,t){this.lastUpdateTs=0;this.lastCallTs=0;this.prevRanges=[];this.subscription=new K0;this.mediaSource=e,this.sourceBuffer=t,this.subscription.add(Y0(this.sourceBuffer,"updateend").subscribe(()=>this.updateend()))}updateend(){if(!N(this.mediaSource,this.sourceBuffer))return;let{prevRanges:e}=this,t=au(this.sourceBuffer.buffered);this.prevRanges=t,this.isRangesRemoved(e,t)&&(this.lastUpdateTs=Date.now())}isRangesRemoved(e,t){if(e.length!==t.length)return!0;for(let i=0;i<e.length;i+=2){let r=e[i],a=e[i+1],n=t[i],o=t[i+1];if(n>r||o<a)return!0}return!1}wasUpdated(){let{lastCallTs:e,lastUpdateTs:t}=this;return this.lastCallTs=Date.now(),e<=t}destroy(){this.subscription.unsubscribe()}};var Va=class{constructor(e,t,i,{fetcher:r,tuning:a,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:c}){this.currentLiveSegmentServerLatency$=new ji(0);this.currentLowLatencySegmentLength$=new ji(0);this.currentSegmentLength$=new ji(0);this.onLastSegment$=new ji(!1);this.fullyBuffered$=new ji(!1);this.playingRepresentation$=new ji(void 0);this.playingRepresentationInit$=new ji(void 0);this.error$=new Z0;this.gaps=[];this.subscription=new eV;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new J;this.switchAbortController=new J;this.destroyAbortController=new J;this.useSmartRepresentationSwitch=!1;this.bufferLimit=1/0;this.failedDownloads=0;this.baseUrls=[];this.baseUrlsIndex=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.lastDataObtainedTimestampMs=0;this.loadByteRangeSegmentsTimeoutId=0;this.sourceBufferBufferedDiff=null;this.startWith=ni(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);Me(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new YI(this.sourceBuffer),this.sourceBufferBufferedDiff=new nu(this.mediaSource,this.sourceBuffer),this.subscription.add(Nd(this.sourceBuffer,"updateend").subscribe(()=>{this.maintain()})),this.subscription.add(Nd(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:Ui.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,Pr(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let c=Te(this.sourceBuffer.buffered,o),d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,n*2,c<d).catch(l=>{this.handleAsyncError(l,"pruneBuffer")})})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);let i=this.initData.get(t.id),r=this.segments.get(t.id),a=this.parsedInitData.get(t.id);Me(i,"No init buffer for starting representation"),Me(r,"No segments for starting representation"),i instanceof ArrayBuffer&&(this.searchGaps(r,t),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(a))}.bind(this));this.switchTo=ni(this.destroyAbortController.signal,async function*(e,t=!1){if(!N(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);Me(i,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if(de(a)||de(r)?yield this.loadInit(i,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),Me(r,"No segments for starting representation"),a=this.initData.get(e),!(!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer||!N(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(a,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer();else{let n=this.getCurrentPosition();oi(n)&&!this.isLive&&(this.bufferLimit=1/0,await this.pruneBuffer(n,1/0,!0)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}this.maintain()}}.bind(this));this.switchToOld=ni(this.destroyAbortController.signal,async function*(e,t=!1){if(!N(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);Me(i,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if(de(a)||de(r)?yield this.loadInit(i,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),Me(r,"No segments for starting representation"),a=this.initData.get(e),!(!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer||!N(this.mediaSource,this.sourceBuffer)))if(yield this.abort(),yield this.sourceBufferTaskQueue.append(a,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let n=this.getCurrentPosition();oi(n)&&(this.isLive||(this.bufferLimit=1/0,await this.pruneBuffer(n,1/0,!0)),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}}.bind(this));this.seekLive=ni(this.destroyAbortController.signal,async function*(e){var u;let t=(0,cu.default)(e,c=>c.representations);if(!this.downloadingRepresentationId||!t.length)return;this.isSeekingLive=!0;for(let c of this.representations.keys()){let d=t.find(p=>p.id===c);d&&this.representations.set(c,d);let l=this.representations.get(c);if(!l||!We(l.segmentReference)){this.isSeekingLive=!1;return}let h=this.getActualLiveStartingSegments(l.segmentReference);this.segments.set(l.id,h)}let i=(u=this.switchingToRepresentationId)!=null?u:this.downloadingRepresentationId,r=this.representations.get(i);Me(r,`Representation not found by id ${i}`);let a=this.segments.get(i);Me(a,"No segments for starting representation");let n=this.initData.get(i);if(Me(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer)){this.isSeekingLive=!1;return}let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(a,r),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));var d;this.fetcher=r,this.tuning=a,this.compatibilityMode=u,this.forwardBufferTarget=a.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!(c!=null&&c.live),this.baseUrls=(d=c==null?void 0:c.baseUrls)!=null?d:[],this.initData=new Map(i.map(l=>[l.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(l=>[l.id,l])),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 J,ni(this.switchAbortController.signal,async function*(i,r=!1){this.switchingToRepresentationId=i;let a=this.representations.get(i);Me(a,`No such representation ${i}`);let n=this.segments.get(i),o=this.initData.get(i);if(de(o)||de(n)?yield this.loadInit(a,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(i),Me(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();oi(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(){!de(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}async abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);return this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new J,this.abortBuffer()}maintain(e=this.getCurrentPosition()){var h;if(de(e)||de(this.downloadingRepresentationId)||de(this.playingRepresentationId)||de(this.sourceBuffer)||!N(this.mediaSource,this.sourceBuffer)||oi(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.representations.get(this.playingRepresentationId),r=this.segments.get(this.downloadingRepresentationId),a=this.segments.get(this.playingRepresentationId);if(Me(t,`No such representation ${this.downloadingRepresentationId}`),Me(i,`No such representation ${this.playingRepresentationId}`),de(r)||de(a))return;let n=r.find(p=>e>=p.time.from&&e<p.time.to);oi(n)&&isFinite(n.time.from)&&isFinite(n.time.to)&&this.currentSegmentLength$.next((n==null?void 0:n.time.to)-n.time.from);let o=e,u=100;if(this.playingRepresentationId!==this.downloadingRepresentationId){let p=this.getForwardBufferDuration(e),f=Ba(i),m=Ba(t),g=this.useSmartRepresentationSwitch&&this.tuning.dash.useNewRepresentationSwitch&&this.tuning.dash.useSmartRepresentationSwitch&&oi(f)&&oi(m)&&X0(f.quality,m.quality),b=this.useSmartRepresentationSwitch&&this.tuning.dash.useNewRepresentationSwitch&&this.tuning.dash.useDelayedRepresentationSwitch;if(g||b?o+=Math.min(p,this.tuning.dash.representationSwitchForwardBufferGap):n&&n.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&p>=n.time.to-e+u&&(o=n?n.time.to+u:-1/0),this.tuning.dash.useNewRepresentationSwitch){let T=(h=[...this.segments.entries()].map(([y,E])=>{let A=E.find($=>e>=$.time.from&&e<$.time.to);return{representationId:y,status:A==null?void 0:A.status}}).find(y=>y.status==="fed"))==null?void 0:h.representationId;T&&(this.playingRepresentationId=T,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)))}}if(isFinite(this.bufferLimit)&&Pr(this.sourceBuffer.buffered)>=this.bufferLimit){let p=Te(this.sourceBuffer.buffered,e),f=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,p<f).catch(m=>{this.handleAsyncError(m,"pruneBuffer")});return}let d=null;if(!this.activeSegments.size&&(d=this.selectForwardBufferSegments(r,t.segmentReference.type,o),d!=null&&d.length)){let p="auto";if(this.tuning.dash.useFetchPriorityHints&&n)if((0,uu.default)(d,n))p="high";else{let f=(0,Hi.default)(d,0);f&&f.time.from-n.time.to>=this.forwardBufferTarget/2&&(p="low")}this.loadSegments(d,t,p).catch(f=>{this.handleAsyncError(f,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&n&&n.status==="fed"&&!(d!=null&&d.length)&&Te(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let l=(0,Hi.default)(r,-1);!this.isLive&&l&&(this.fullyBuffered$.next(l.time.to-e-Te(this.sourceBuffer.buffered,e)<u),this.onLastSegment$.next(e-l.time.from>0))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let i=0,r=this.isLive?this.liveInitialAdditionalOffset:0;for(let a of e)Math.trunc(a.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:a.time.from+r,persistent:!0}),i=a.time.to;oi(t.duration)&&t.duration-i>0&&!this.isLive&&this.gaps.push({representation:t.id,from:i,to:t.duration,persistent:!0})}getActualLiveStartingSegments(e){let t=e.segments,i=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,r=[],a=0,n=t.length-1;do r.unshift(t[n]),a+=t[n].time.to-t[n].time.from,n--;while(a<i&&n>=0);return this.liveInitialAdditionalOffset=a-i,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){let t=e==null?void 0:e.streams[this.kind];if(!t)return;let i=(0,cu.default)(t,a=>a.representations).find(a=>a.id===this.downloadingRepresentationId);if(!i)return;let r=this.segments.get(i.id);if(r!=null&&r.length)return{from:r[0].time.from,to:r[r.length-1].time.to}}updateLive(e){var i,r,a,n;if(!e||[...this.segments.values()].every(o=>!o.length))return;let t=(i=(0,cu.default)(e.streams[this.kind],o=>o.representations))!=null?i:[];for(let o of t){if(!o||!We(o.segmentReference))return;let u=o.segmentReference.segments.map(p=>({...p,status:"none",size:void 0})),c=100,d=(r=this.segments.get(o.id))!=null?r:[],l=(n=(a=(0,Hi.default)(d,-1))==null?void 0:a.time.to)!=null?n:0,h=u==null?void 0:u.findIndex(p=>l>=p.time.from+c&&l<=p.time.to+c);if(h===-1){this.liveUpdateSegmentIndex=0;let p=this.getActualLiveStartingSegments(o.segmentReference);this.segments.set(o.id,p)}else{let p=u.slice(h+1);this.segments.set(o.id,[...d,...p])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;Me(e);let t=this.segments.get(e);if(t!=null&&t.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}setSmartRepresentationSwitch(e){this.useSmartRepresentationSwitch=e}updateLowLatencyLiveIfNeeded(e){let t=0;for(let i of this.representations.values()){let r=i.segmentReference;if(!We(r))return;let a=this.segments.get(i.id);if(!a)continue;let n=a.find(u=>Math.floor(u.time.from)===Math.floor(e.time.from));if(n&&!isFinite(n.time.to)&&(n.time.to=e.time.to,t=n.time.to-n.time.from),!!!a.find(u=>Math.floor(u.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let u=Math.round(e.time.to*r.timescale/1e3).toString(10),c=ut(r.segmentTemplateUrl,{segmentTime:u});a.push({status:"none",time:{from:e.time.to,to:1/0},url:c})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){var a,n,o;let t=(n=(a=this.switchingToRepresentationId)!=null?a:this.downloadingRepresentationId)!=null?n:this.playingRepresentationId;if(!t)return;let i=this.segments.get(t);if(!i)return;let r=i.find(u=>u.time.from<=e&&u.time.to>=e);return(o=r==null?void 0:r.time.from)!=null?o:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e,t;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)==null||e.destroy(),(t=this.sourceBufferBufferedDiff)==null||t.destroy(),this.gapDetectionIdleCallback&&Tt&&Tt(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&Tt&&Tt(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(i){if(!(i instanceof DOMException&&i.name==="NotFoundError"))throw i}this.sourceBuffer=null,this.downloadAbortController.abort(),this.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,i){return this.checkEjectedSegments(),this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){if(this.playingRepresentationId!==this.downloadingRepresentationId){let i=e.findIndex(r=>t>=r.time.from&&t<r.time.to);this.liveUpdateSegmentIndex=i}return this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):null}selectForwardBufferSegmentsRecord(e,t,i){let r=this.getForwardBufferDuration(i),a=e.findIndex(({status:h,time:{from:p,to:f}},m)=>{let g=p<=i&&f>=i,b=p>i||g||m===0&&i===0,S=Math.min(this.forwardBufferTarget,this.bufferLimit),T=this.preloadOnly&&p<=i+S||r<S&&f-p>=S||f<=i+S;return(h==="none"||h==="partially_ejected"&&b&&T&&this.sourceBuffer&&N(this.mediaSource,this.sourceBuffer)&&!(Ie(this.sourceBuffer.buffered,p)&&Ie(this.sourceBuffer.buffered,f)))&&b&&T});if(a===-1)return null;if(t!=="byteRange")return e.slice(a,a+1);let n=e,o=0,u=0,c=[],d=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,l=this.preloadOnly?this.forwardBufferTarget:0;for(let h=a;h<n.length&&(o<=d||u<=l);h++){let p=n[h];if(o+=p.byte.to+1-p.byte.from,u+=p.time.to+1-p.time.from,p.status==="none"||p.status==="partially_ejected")c.push(p);else break}return c}async loadSegments(e,t,i="auto"){We(t.segmentReference)?await this.loadTemplateSegment(e[0],t,i):await this.loadByteRangeSegments(e,t,i)}async loadTemplateSegment(e,t,i="auto"){e.status="downloading";let r={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(r);let{range:a,url:n,signal:o,onProgress:u,onProgressTasks:c}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await ni(o,async function*(){let d=qd(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>setTimeout(l,d))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let d=await this.fetcher.fetch(n,{range:a,signal:o,onProgress:u,priority:i,isLowLatency:this.isActiveLowLatency(),bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation});if(this.lastDataObtainedTimestampMs=ou(),!d)return;let l=new DataView(d),h=It(t.mime);if(!isFinite(r.segment.time.to)){let m=t.segmentReference.timescale;r.segment.time.to=h.getChunkEndTime(l,m)}u&&r.feedingBytes&&c?await Promise.all(c):await this.sourceBufferTaskQueue.append(l,o);let{serverDataReceivedTimestamp:p,serverDataPreparedTime:f}=h.getServerLatencyTimestamps(l);p&&f&&this.currentLiveSegmentServerLatency$.next(f-p),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(d){this.abortActiveSegments([e]),Et(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())We(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}async loadByteRangeSegments(e,t,i="auto"){if(!e.length)return;for(let u of e)u.status="downloading",this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:r,url:a,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(await ni(n,async function*(){let u=qd(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(c,u),Nd(window,"online").pipe(J0()).subscribe(()=>{c(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(a,{range:r,onProgress:o,signal:n,priority:i,bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation}),this.lastDataObtainedTimestampMs=ou(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),Et(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(We(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:(0,Hi.default)(e,0).byte.from,to:(0,Hi.default)(e,-1).byte.to},{signal:a}=this.downloadAbortController;return{url:i,range:r,signal:a,onProgress:async(o,u)=>{if(!a.aborted)try{this.lastDataObtainedTimestampMs=ou(),await this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:a,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(c){this.error$.next({id:"SegmentFeeding",category:Ui.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}}}}prepareTemplateFetchSegmentParams(e,t){if(!We(t.segmentReference))throw new Error("Representation is not template type");let i=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&i.searchParams.set("low-latency","yes");let r=i.toString(),{signal:a}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(c,d)=>{if(!a.aborted)try{this.lastDataObtainedTimestampMs=ou();let l=this.onSomeTemplateDataLoaded({dataView:c,loaded:d,signal:a,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(l)}catch(l){this.error$.next({id:"SegmentFeeding",category:Ui.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}:void 0;return{url:r,signal:a,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,uu.default)(e,t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:a}){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(a.aborted){r();continue}if(o.loadedBytes=i,o.loadedBytes>o.feedingBytes){let c=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),d=It(n.mime).parseFeedableSegmentChunk(c,this.isLive);d!=null&&d.byteLength&&(u.status="partially_fed",o.feedingBytes+=d.byteLength,await this.sourceBufferTaskQueue.append(d),o.fedBytes+=d.byteLength)}}}}async onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:a,onSegmentAppendFailed:n}){if(!this.activeSegments.size||!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(a.aborted){await n();continue}let{segment:c}=u,d=c.byte.from-i,l=c.byte.to-i,h=l-d+1,p=d<r,f=l<=r;if(p){if(c.status==="downloading"&&f){c.status="downloaded";let m=new DataView(e.buffer,e.byteOffset+d,h);await this.sourceBufferTaskQueue.append(m,a)&&!a.aborted?this.onSegmentFullyAppended(u,t):await n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(c.status==="downloading"||c.status==="partially_fed")&&(u.loadedBytes=Math.min(h,r-d),u.loadedBytes>u.feedingBytes)){let m=new DataView(e.buffer,e.byteOffset+d+u.feedingBytes,u.loadedBytes-u.feedingBytes),g=u.loadedBytes===h?m:It(o.mime).parseFeedableSegmentChunk(m);g!=null&&g.byteLength&&(c.status="partially_fed",u.feedingBytes+=g.byteLength,await this.sourceBufferTaskQueue.append(g,a)&&!a.aborted?(u.fedBytes+=g.byteLength,u.fedBytes===h&&this.onSegmentFullyAppended(u,t)):await n())}}}}onSegmentFullyAppended(e,t){if(!(de(this.sourceBuffer)||!N(this.mediaSource,this.sourceBuffer))){!this.isLive&&_.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:Ui.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",Fd(e.segment)&&(e.segment.size=e.fedBytes);for(let i of this.representations.values()){if(i.id===t)continue;let r=this.segments.get(i.id);if(r)for(let a of r)a.status==="fed"&&Math.round(a.time.from)===Math.round(e.segment.time.from)&&Math.round(a.time.to)===Math.round(e.segment.time.to)&&(a.status="none")}this.isActiveLowLatency()&&this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,e.segment)}}abortSegment(e){e.status==="partially_fed"?e.status="partially_ejected":e.status!=="partially_ejected"&&(e.status="none");for(let t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[r,a]of this.initData.entries()){let n=a instanceof Promise;t||(t=n),a===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let i=this.representations.get(e);i&&(this.initLoadIdleCallback=Ar(()=>(0,tE.default)(this.loadInit(i,"low",!1),()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",i=!1){let r=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!i&&this.failedDownloads>0?ni(this.destroyAbortController.signal,async function*(){let o=qd(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,It(e.mime),r)).then(o=>{if(!o)return;let{init:u,dataView:c,segments:d}=o,l=c.buffer.slice(c.byteOffset,c.byteOffset+c.byteLength);this.initData.set(e.id,l);let h=d;this.isLive&&We(e.segmentReference)&&(h=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,h),u&&this.parsedInitData.set(e.id,u)}).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:Ui.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||de(e))return!1;this.checkEjectedSegments();let r=[],a=0,n=o=>{var c;if(a>=t)return;r.push({...o.time});let u=Fd(o)?(c=o.size)!=null?c:0:o.byte.to-o.byte.from;a+=u};for(let o of this.segments.values())for(let u of o){let c=u.time.to<=e-this.tuning.dash.bufferPruningSafeZone,d=u.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(c||d)&&u.status==="fed"&&n(u)}for(let o=0;o<this.sourceBuffer.buffered.length;o++){let u=this.sourceBuffer.buffered.start(o)*1e3,c=this.sourceBuffer.buffered.end(o)*1e3,d=0;for(let l of this.segments.values())for(let h of l)(0,uu.default)(["none","partially_ejected"],h.status)&&Math.round(h.time.from)<=Math.round(u)&&Math.round(h.time.to)>=Math.round(c)&&d++;if(d===this.segments.size){let l={time:{from:u,to:c},url:"",status:"none"};n(l)}}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 c of u)c.time.from>=e+o&&c.status==="fed"&&n(c)}return r.length?(r=ZI(r),(await Promise.all(r.map(u=>this.sourceBufferTaskQueue.remove(u.from,u.to)))).reduce((u,c)=>u||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)}}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||de(e)?0:Te(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!this.sourceBuffer||!N(this.mediaSource,this.sourceBuffer))return;let{buffered:i}=this.sourceBuffer,r={representation:e,from:t.time.from,to:t.time.to,persistent:!1};for(let a=0;a<i.length;a++){let n=i.start(a)*1e3,o=i.end(a)*1e3;if(!(o<=t.time.from||n>=t.time.to)){if(n<=t.time.from&&o>=t.time.to){r=void 0;break}o>t.time.from&&o<t.time.to&&(r.from=o),n<t.time.to&&n>t.time.from&&(r.to=n)}}r&&r.to-r.from>1&&!this.gaps.some(a=>r&&a.from===r.from&&a.to===r.to)&&this.gaps.push(r)}detectGapsWhenIdle(e,t){if(this.gapDetectionIdleCallback||!this.sourceBuffer||!N(this.mediaSource,this.sourceBuffer))return;let{buffered:i}=this.sourceBuffer;this.gaps=this.gaps.filter(r=>{if(r.persistent)return!0;let a=Math.round(r.from),n=Math.round(r.to);for(let o=0;o<i.length;o++)if(a>=Math.round(i.start(o)*1e3)&&n<=Math.round(i.end(o)*1e3))return!1;return!0}),this.gapDetectionIdleCallback=Ar(()=>{try{this.detectGaps(e,t)}catch(r){this.error$.next({id:"GapDetection",category:Ui.WTF,message:"detectGaps threw",thrown:r})}finally{this.gapDetectionIdleCallback=null}})}checkEjectedSegments(){if(de(this.sourceBuffer)||!N(this.mediaSource,this.sourceBuffer)||de(this.playingRepresentationId)||this.sourceBufferBufferedDiff&&!this.sourceBufferBufferedDiff.wasUpdated())return;let e=au(this.sourceBuffer.buffered),t=100;for(let i of this.segments.values())for(let r of i){let{status:a}=r;if(a!=="fed"&&a!=="partially_ejected")continue;let n=Math.floor(r.time.from),o=Math.ceil(r.time.to),u=!1,c=0;for(let d=0;d<e.length;d+=2){let l=e[d],h=e[d+1];u||(u=l-t<=n&&h+t>=o),(n>=l&&n<h-t||o>l+t&&o<=h)&&(c+=1)}u||(c===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:Ui.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,Hi.default)(e,-1))==null?void 0:t.time.to:0)||0}};import{abortable as _a,assertNever as iE,fromEvent as rE,merge as tV,now as Oa,Subject as qr,ValueSubject as Ud,flattenObject as Ur,ErrorCategory as Fa,SubscriptionRemovable as iV}from"@vkontakte/videoplayer-shared/es2018";var du=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:a=!1}){this.manifestRequested=new qr;this.manifestReceived=new qr;this.firstBytesRequested=new qr;this.firstBytesReceived=new qr;this.lastConnectionType$=new Ud(void 0);this.lastConnectionReused$=new Ud(void 0);this.lastRequestFirstBytes$=new Ud(void 0);this.recoverableError$=new qr;this.error$=new qr;this.abortAllController=new J;this.subscription=new iV;this.fetchManifest=_a(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=ri(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=Fo(i)),this.manifestRequested.next();let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(lu);return r?(t.log("success",Ur({url:i,message:"Request successfully executed"})),t.end(),this.manifestReceived.next(),this.onHeadersReceived(r.headers),r.text()):(t.error("error",Ur({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=_a(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:a="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1,bufferOptimisation:c=!1}={}){var F,Q,j;let d=e,l=new Headers,h=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{l.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let I=new URL(d,location.href);I.searchParams.append("bytes",`${i.from}-${i.to}`),d=I.toString();break}default:iE(t)}this.requestQuic&&(d=ri(d));let p=this.abortAllController.signal,f;if(n){let I=new J;if(f=tV(rE(this.abortAllController.signal,"abort"),rE(n,"abort")).subscribe(()=>{try{I.abort()}catch(R){lu(R)}}),this.subscription.add(f),this.abortAllController.signal.aborted||n.aborted)try{I.abort()}catch(R){lu(R)}p=I.signal}let m=0,g=Oa();h.log("startRequest",Ur({url:d,priority:a,rangeMethod:t,range:i,isLowLatency:u,requestStartedAt:g})),this.firstBytesRequested.next();let b=yield this.doFetch(d,{priority:a,headers:l,signal:p}),S=Oa();if(!b)return h.error("error",{message:"No response in request"}),h.end(),this.unsubscribeAbortSubscription(f),null;if((F=this.throughputEstimator)==null||F.addRawRtt(S-g),!b.ok||!b.body){this.unsubscribeAbortSubscription(f);let I=`Fetch error ${b.status}: ${b.statusText}`;return h.error("error",{message:I}),h.end(),Promise.reject(new Error(`Fetch error ${b.status}: ${b.statusText}`))}if(this.onHeadersReceived(b.headers),!r&&!o){this.unsubscribeAbortSubscription(f);let I=Oa(),R={requestStartedAt:g,requestEndedAt:I,duration:I-g};return h.log("endRequest",Ur(R)),h.end(),b.arrayBuffer()}let T=b.body;if(o){let I;[T,I]=b.body.tee(),(Q=this.throughputEstimator)==null||Q.trackStream(I,u)}let y=T.getReader(),E,A=parseInt((j=b.headers.get("content-length"))!=null?j:"",10);Number.isFinite(A)&&(E=A),!E&&i&&(E=i.to-i.from+1);let $=E?new Uint8Array(E):new Uint8Array(0),L=!1,C=I=>{this.unsubscribeAbortSubscription(f),L=!0,lu(I)},P=_a(p,async function*({done:I,value:R}){if(m===0&&(this.lastRequestFirstBytes$.next(Oa()-g),this.firstBytesReceived.next()),p.aborted){this.unsubscribeAbortSubscription(f);return}if(!I&&R){if(c&&E)$.set(R,m),m+=R.byteLength;else{let x=new Uint8Array($.length+R.length);x.set($),x.set(R,$.length),$=x,m+=R.byteLength}r==null||r(new DataView($.buffer),m),yield y==null?void 0:y.read().then(P,C)}}.bind(this));yield y==null?void 0:y.read().then(P,C),this.unsubscribeAbortSubscription(f);let B=Oa(),M={failed:L,requestStartedAt:g,requestEndedAt:B,duration:B-g};return L?(h.error("endRequest",Ur(M)),h.end(),null):(h.log("endRequest",Ur(M)),h.end(),$.buffer)}.bind(this));this.fetchByteRangeRepresentation=_a(this.abortAllController.signal,async function*(e,t,i){var b;if(e.type!=="byteRange")return null;let{from:r,to:a}=e.initRange,n=r,o=a,u=!1,c,d;e.indexRange&&(c=e.indexRange.from,d=e.indexRange.to,u=a+1===c,u&&(n=Math.min(c,r),o=Math.max(d,a))),n=Math.min(n,0);let l=yield this.fetch(e.url,{range:{from:n,to:o},priority:i,measureThroughput:!1});if(!l)return null;let h=new DataView(l,r-n,a-n+1);if(!t.validateData(h))throw new Error("Invalid media file");let p=t.parseInit(h),f=(b=e.indexRange)!=null?b:t.getIndexRange(p);if(!f)throw new ReferenceError("No way to load representation index");let m;if(u)m=new DataView(l,f.from-n,f.to-f.from+1);else{let S=yield this.fetch(e.url,{range:f,priority:i,measureThroughput:!1});if(!S)return null;m=new DataView(S)}let g=t.parseSegments(m,p,f);return{init:p,dataView:new DataView(l),segments:g}}.bind(this));this.fetchTemplateRepresentation=_a(this.abortAllController.signal,async function*(e,t){if(e.type!=="template")return null;let i=new URL(e.initUrl,e.baseUrl).toString(),r=yield this.fetch(i,{priority:t,measureThroughput:!1});return r?{init:null,segments:e.segments.map(n=>({...n,status:"none",size:void 0})),dataView:new DataView(r)}:null}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=r,this.tracer=i.createComponentTracer("Fetcher"),this.useEnableSubtitlesParam=a}onHeadersReceived(e){let{type:t,reused:i}=Oo(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,t,i="auto"){var a,n;let{type:r}=e;switch(r){case"byteRange":return(a=await this.fetchByteRangeRepresentation(e,t,i))!=null?a:null;case"template":return(n=await this.fetchTemplateRepresentation(e,i))!=null?n:null;default:iE(r)}}destroy(){this.abortAllController.abort(),this.tracer.end(),this.subscription.unsubscribe()}async doFetch(e,t){let i=await Xe(e,t);if(i.ok)return i;let r=await i.text(),a=parseInt(r);if(!isNaN(a))switch(a){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:Fa.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:Fa.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:Fa.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:Fa.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${a})`,category:Fa.FATAL})}}unsubscribeAbortSubscription(e){e&&(e.unsubscribe(),this.subscription.remove(e))}},lu=s=>{if(!Et(s))throw s};import{isNullable as rV,ValueSubject as sV}from"@vkontakte/videoplayer-shared/es2018";var Na=class s{constructor(e,t){this.currentRepresentation$=new sV(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(!rV(e))for(let i of this.representations)for(let r of i){let a=r.segmentReference,n=a.segments.length,o=a.segments[0].time.from,u=a.segments[n-1].time.to;if(e<o||e>u)continue;let c=a.segments.find(d=>d.time.from<=e&&d.time.to>=e);!c||((t=this.currentSegment)==null?void 0:t.time.from)===c.time.from&&this.currentSegment.time.to===c.time.to||(this.currentSegment=c,this.currentRepresentation$.next({...r,label:"Live Text",language:"ru",isAuto:!0,url:new URL(c.url,a.baseUrl).toString()}))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e!=null?e:[]){let i=s.filterRepresentations(t.representations);if(i){this.representations[this.representationsCursor]=i,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!(e!=null&&e.some(t=>s.filterRepresentations(t.representations)))}static filterRepresentations(e){return e==null?void 0:e.filter(t=>t.kind==="text"&&"segmentReference"in t&&We(t.segmentReference))}};var lV=["progress","play","seeked","stalled","waiting"],dV=["timeupdate","progress","loadeddata","playing","seeked"];var hu=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.bufferManagers=[];this.subscription=new Gd;this.subscriptionRemovable=new uV;this.representationSubscription=new Gd;this.state$=new U("none");this.currentVideoRepresentation$=new re(void 0);this.currentVideoRepresentationInit$=new re(void 0);this.currentAudioRepresentation$=new re(void 0);this.currentVideoSegmentLength$=new re(0);this.currentAudioSegmentLength$=new re(0);this.error$=new ui;this.manifestRequested=new ui;this.manifestReceived=new ui;this.firstBytesRequested=new ui;this.firstBytesReceived=new ui;this.lastConnectionType$=new re(void 0);this.lastConnectionReused$=new re(void 0);this.lastRequestFirstBytes$=new re(void 0);this.currentLiveTextRepresentation$=new re(null);this.isLive$=new re(!1);this.isActiveLive$=new re(!1);this.isLowLatency$=new re(!1);this.liveDuration$=new re(0);this.liveSeekableDuration$=new re(0);this.liveAvailabilityStartTime$=new re(0);this.liveStreamStatus$=new re(void 0);this.bufferLength$=new re(0);this.liveLatency$=new re(void 0);this.liveLoadBufferLength$=new re(0);this.livePositionFromPlayer$=new re(0);this.currentStallDuration$=new re(0);this.videoLastDataObtainedTimestamp$=new re(0);this.fetcherRecoverableError$=new ui;this.fetcherError$=new ui;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new ui;this.gapWatchdogActive=!1;this.destroyController=new J;this.initManifest=Hd(this.destroyController.signal,async function*(e,t,i){var r;this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=ne(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=Hd(this.destroyController.signal,async function*(){var u,c;this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(d=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:ct.NETWORK,message:"Failed to load manifest",thrown:d})});if(!e)return null;let t=null;try{t=Do(e!=null?e:"",this.manifestUrlString)}catch(d){let l=(u=Mo(e))!=null?u:{id:"ManifestParsing",category:ct.PARSER,message:"Failed to parse MPD manifest",thrown:d};this.error$.next(l)}if(!t)return null;let i=(d,l,h)=>{var p,f,m,g;return!!((f=(p=this.element)==null?void 0:p.canPlayType)!=null&&f.call(p,l)&&((g=(m=Ue())==null?void 0:m.isTypeSupported)!=null&&g.call(m,`${l}; codecs="${h}"`))||d==="text")};if(t.live){this.isLive$.next(!!t.live);let{availabilityStartTime:d,latestSegmentPublishTime:l,streamIsUnpublished:h,streamIsAlive:p}=t.live,f=((c=t.duration)!=null?c:0)/1e3;this.liveSeekableDuration$.next(-1*f),this.liveDuration$.next((l-d)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let m="active";p||(m=h?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(m)}let r={text:t.streams.text,video:[],audio:[]},a,n;for(let d of["video","audio"]){let h=t.streams[d].filter(({mime:f,codecs:m})=>i(d,f,m));r[d]=h;let p;if(this.tuning.dash.codecsPrioritizeEnabled){let f=h.map(({codecs:m})=>m);d==="audio"&&(n=Ko(f),p=n[0]),d==="video"&&(a=Yo(f),this.forceVideoCodec&&(0,oE.default)(a,this.forceVideoCodec)?p=this.forceVideoCodec:p=a[0]),p&&(r[d]=h.filter(({codecs:m})=>Br(m)===p))}else{let f=new Set(h.map(({codecs:m})=>m));p=zo(f),p&&(r[d]=h.filter(({codecs:m})=>m.startsWith(p)))}if(d==="video"){let f=this.tuning.preferHDR,m=r.video.some(b=>b.hdr),g=r.video.some(b=>!b.hdr);_.display.isHDR&&f&&m?r.video=r.video.filter(b=>b.hdr):g&&(r.video=r.video.filter(b=>!b.hdr))}}let o={...t,streams:r};return this.tuning.dash.codecsPrioritizeEnabled&&(o.codecs={video:a,audio:n}),this.tracer.log("updateManifestEnd",Ua(o)),o}.bind(this));this.initRepresentations=Hd(this.destroyController.signal,async function*(e,t,i){var h;this.tracer.log("initRepresentationsStart",Ua({initialVideo:e,initialAudio:t,sourceHls:i})),jr(this.manifest),jr(this.element),this.representationSubscription.unsubscribe(),this.representationSubscription=new Gd,this.state$.startTransitionTo("representations_ready");let r=p=>{this.representationSubscription.add(xt(p,"error").pipe(pu(f=>{var m;return!!((m=this.element)!=null&&m.played.length)})).subscribe(f=>{this.error$.next({id:"VideoSource",category:ct.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:f})}))};this.source=Cn();let a=document.createElement("source");if(r(a),a.src=URL.createObjectURL(this.source),this.element.appendChild(a),or())if(i){let p=document.createElement("source");r(p),p.type="application/x-mpegurl",p.src=i.url,this.element.appendChild(p)}else this.element.disableRemotePlayback=!0;this.isActiveLive$.next(this.isLive$.getValue());let n={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),manifest:this.manifest},o=this.manifest.streams.video.reduce((p,f)=>[...p,...f.representations],[]);if(this.videoBufferManager=new Va("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],ja(t)){let p=this.manifest.streams.audio.reduce((f,m)=>[...f,...m.representations],[]);this.audioBufferManager=new Va("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}Na.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new Na(this.manifest.streams.text,n)),this.representationSubscription.add(this.fetcher.manifestRequested.subscribe(this.manifestRequested)),this.representationSubscription.add(this.fetcher.manifestReceived.subscribe(this.manifestReceived)),this.representationSubscription.add(this.fetcher.firstBytesRequested.subscribe(this.firstBytesRequested)),this.representationSubscription.add(this.fetcher.firstBytesReceived.subscribe(this.firstBytesReceived)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$));let u=()=>{var p;(p=this.stallWatchdogSubscription)==null||p.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add(Wi(...dV.map(p=>xt(this.element,p))).pipe(Wr(p=>this.element?Te(this.element.buffered,this.element.currentTime*1e3):0),qa(),cV(p=>{p>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add(Wi(xt(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe(qa()).subscribe(f=>this.liveStreamEndTimestamp=Qd())),this.subscription.add(xt(this.element,"pause").subscribe(()=>{this.livePauseWatchdogSubscription=Wd(1e3).subscribe(f=>{let m=Yt(this.manifestUrlString,2);this.manifestUrlString=ne(this.manifestUrlString,m+1e3,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add(xt(this.element,"play").subscribe(f=>{var m;return(m=this.livePauseWatchdogSubscription)==null?void 0:m.unsubscribe()})),this.representationSubscription.add(Hr({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(Wr(({isActiveLive:f,isLowLatency:m})=>f&&m),qa()).subscribe(f=>{this.isManualDecreasePlaybackInLive()||Dr(this.element,1)})),this.representationSubscription.add(Hr({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(pu(({bufferLength:f,isActiveLive:m,isLowLatency:g})=>m&&g&&!!f)).subscribe(({bufferLength:f})=>this.liveBuffer.next(f))),this.representationSubscription.add(this.videoBufferManager.currentLowLatencySegmentLength$.subscribe(f=>{if(!this.isActiveLive$.getValue()&&!this.isLowLatency$.getValue()&&!f)return;let m=this.liveSeekableDuration$.getValue()-f/1e3;this.liveSeekableDuration$.next(Math.max(m,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+f/1e3)})),this.representationSubscription.add(Hr({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(pu(({isLive:f})=>f),qa((f,m)=>m.bufferLength<f.bufferLength),Wr(({rtt:f,bufferLength:m,segmentServerLatency:g})=>{let b=Yt(this.manifestUrlString,2);return(f/2+m+g+b)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(Hr({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:f,isActiveLive:m,isLowLatency:g})=>{if(!g||!m)return;let b=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,S=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,T=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,y=f-b;if(this.isManualDecreasePlaybackInLive())return;let E=1;Math.abs(y)>S&&(E=1+Math.sign(y)*T),Dr(this.element,E)})),this.representationSubscription.add(this.bufferLength$.subscribe(f=>{var g,b;let m=0;if(f){let S=((b=(g=this.element)==null?void 0:g.currentTime)!=null?b:0)*1e3;m=Math.min(...this.bufferManagers.map(y=>{var E,A;return(A=(E=y.getLiveSegmentsToLoadState(this.manifest))==null?void 0:E.to)!=null?A:S}))-S}this.liveLoadBufferLength$.getValue()!==m&&this.liveLoadBufferLength$.next(m)}));let p=0;this.representationSubscription.add(Hr({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(nE(1e3)).subscribe(async({liveLoadBufferLength:f,bufferLength:m})=>{if(!this.element||this.isUpdatingLive)return;let g=this.element.playbackRate,b=Yt(this.manifestUrlString,2),S=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,T=Math.min(S,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*g),y=this.tuning.dashCmafLive.normalizedActualBufferOffset*g,E=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*g,A=isFinite(f)?f:m,$=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),L=S<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(L);let C="none";if($?C="active_low_latency":this.isLowLatency$.getValue()&&L?(this.bufferManagers.forEach(P=>P.proceedLowLatencyLive()),C="active_low_latency"):b!==0&&A<T?C="live_forward_buffering":A<T+E&&(C="live_with_target_offset"),isFinite(f)&&(p=f>p?f:p),C==="live_forward_buffering"||C==="live_with_target_offset"){let P=p-(T+y),B=this.normolizeLiveOffset(Math.trunc(b+P/g)),M=Math.abs(B-b),F=0;!f||M<=this.tuning.dashCmafLive.offsetCalculationError?F=b:B>0&&M>this.tuning.dashCmafLive.offsetCalculationError&&(F=B),this.manifestUrlString=ne(this.manifestUrlString,F,2)}(C==="live_with_target_offset"||C==="live_forward_buffering")&&(p=0,await this.updateLive())},f=>{this.error$.next({id:"updateLive",category:ct.VIDEO_PIPELINE,thrown:f,message:"Failed to update live with subscription"})}))}let c=Wi(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe(Wr(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),d=Wi(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe(Wr(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue()))),l=Hr({allBuffersFull:c,someBufferEnded:d}).pipe(qa(),Wr(({allBuffersFull:p,someBufferEnded:f})=>p&&f),pu(p=>p));if(this.representationSubscription.add(Wi(this.forceEnded$,l).subscribe(()=>{var p;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(f=>!f.updating))try{(p=this.source)==null||p.endOfStream()}catch(f){this.error$.next({id:"EndOfStream",category:ct.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:f})}})),this.representationSubscription.add(Wi(...this.bufferManagers.map(p=>p.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.representationSubscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.representationSubscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.liveTextManager&&this.representationSubscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$)),this.source.readyState!=="open"){let p=this.tuning.dash.sourceOpenTimeout>=0;yield new Promise(f=>{var m;p&&(this.timeoutSourceOpenId=setTimeout(()=>{var g;if(((g=this.source)==null?void 0:g.readyState)==="open"){f();return}this.error$.next({id:"OpenOfStream",category: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),f()},{once:!0})})}if(!this.isLive$.getValue()){let p=[(h=this.manifest.duration)!=null?h:0,...(0,zd.default)((0,zd.default)([...this.manifest.streams.audio,...this.manifest.streams.video],f=>f.representations),f=>{let m=[];return f.duration&&m.push(f.duration),We(f.segmentReference)&&f.segmentReference.totalSegmentsDurationMs&&m.push(f.segmentReference.totalSegmentsDurationMs),m})];this.source.duration=Math.max(...p)/1e3}this.audioBufferManager&&ja(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")}.bind(this));this.tick=()=>{var t,i,r,a;if(!this.element||!this.videoBufferManager||((t=this.source)==null?void 0:t.readyState)!=="open")return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),(i=this.audioBufferManager)==null||i.maintain(e),(r=this.liveTextManager)==null||r.maintain(e),(this.videoBufferManager.gaps.length||(a=this.audioBufferManager)!=null&&a.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=Wd(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.forceVideoCodec=e.forceVideoCodec,this.fetcher=new du({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=Bt.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator}),this.initTracerSubscription()}setSmartRepresentationSwitch(e){this.bufferManagers.forEach(t=>t.setSmartRepresentationSwitch(e))}async seekLive(e){var r,a,n;jr(this.element);let t=this.liveStreamStatus$.getValue()!=="active"?Qd()-this.liveStreamEndTimestamp:0,i=this.normolizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=ne(this.manifestUrlString,i,2),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await((r=this.videoBufferManager)==null?void 0:r.seekLive(this.manifest.streams.video)),await((a=this.audioBufferManager)==null?void 0:a.seekLive(this.manifest.streams.audio)),(n=this.liveTextManager)==null||n.seekLive(this.manifest.streams.text))}initBuffer(){jr(this.element),this.state$.setState("running");let e=xt(this.element,"timeupdate");this.tuning.dash.timeupdateEventTickThrottle&&(e=e.pipe(nE(this.tuning.dash.timeupdateEventTickThrottle))),this.subscription.add(Wi(...lV.map(t=>xt(this.element,t)),xt(window,"online"),e).subscribe(()=>this.tick(),t=>{this.error$.next({id:"DashVKPlayer",category:ct.WTF,message:"Internal logic error",thrown:t})})),this.subscription.add(xt(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(xt(this.element,"waiting").subscribe(()=>{this.tuning.dash.useVideoElementWaitingCurrentTimeReassign&&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 p,f,m,g,b,S,T,y,E,A,$;if(!this.element||((p=this.source)==null?void 0:p.readyState)!=="open")return;let i=this.currentStallDuration$.getValue();i+=50,this.currentStallDuration$.next(i);let r={timeInWaiting:i},a=Qd(),n=100,o=(m=(f=this.videoBufferManager)==null?void 0:f.lastDataObtainedTimestamp)!=null?m:0;this.videoLastDataObtainedTimestamp$.next(o);let u=(b=(g=this.audioBufferManager)==null?void 0:g.lastDataObtainedTimestamp)!=null?b:0,c=(T=(S=this.videoBufferManager)==null?void 0:S.getForwardBufferDuration())!=null?T:0,d=(E=(y=this.audioBufferManager)==null?void 0:y.getForwardBufferDuration())!=null?E:0,l=c<n&&a-o>this.tuning.dash.crashOnStallTWithoutDataTimeout,h=this.audioBufferManager&&d<n&&a-u>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((l||h)&&i>this.tuning.dash.crashOnStallTWithoutDataTimeout||i>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${i} ms`);if(this.isLive$.getValue()&&i%2e3===0){let L=this.normolizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(L).catch(C=>{this.error$.next({id:"stallIntervalCallback",category:ct.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:C})}),r.liveLastOffset=L}else{let L=this.element.currentTime*1e3;(A=this.videoBufferManager)==null||A.maintain(L),($=this.audioBufferManager)==null||$.maintain(L),r.position=L}this.tracer.log("stallIntervalCallback",Ua(r))};this.stallWatchdogSubscription&&(this.stallWatchdogSubscription.unsubscribe(),this.subscriptionRemovable.remove(this.stallWatchdogSubscription)),this.stallWatchdogSubscription=Wd(50).subscribe(t,i=>{this.error$.next({id:"StallWatchdogCallback",category:ct.NETWORK,message:"Can't restore DASH after stall.",thrown:i})}),this.subscriptionRemovable.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,i=!1){let r={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return this.tuning.useNewSwitchTo?this.currentStallDuration$.getValue()>0?r==null?void 0:r.switchToWithPreviousAbort(t,i):r==null?void 0:r.switchTo(t,i):r==null?void 0:r.switchToOld(t,i)}async seek(e,t){var r,a,n,o,u;jr(this.element),jr(this.videoBufferManager);let i;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?i=e:i=Math.max((r=this.videoBufferManager.findSegmentStartTime(e))!=null?r:e,(n=(a=this.audioBufferManager)==null?void 0:a.findSegmentStartTime(e))!=null?n:e),this.warmUpMediaSourceIfNeeded(i),Ie(this.element.buffered,i)||await Promise.all([this.videoBufferManager.abort(),(o=this.audioBufferManager)==null?void 0:o.abort()]),!(aE(this.element)||aE(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),(u=this.audioBufferManager)==null||u.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",Ua({requestedPosition:e,forcePrecise:t,position:i})))}warmUpMediaSourceIfNeeded(e=(t=>(t=this.element)==null?void 0:t.currentTime)()){var i;ja(this.element)&&ja(this.source)&&ja(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}getCodecs(){var e;return(e=this.manifest)==null?void 0:e.codecs}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){var e;this.subscription.unsubscribe(),this.subscriptionRemovable.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=oV(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;this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&(this.bufferManagers.forEach(t=>t.updateLive(this.manifest)),(e=this.liveTextManager)==null||e.updateLive(this.manifest)),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getBufferedTo();if(e===null)return;let t=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),i=this.isJumpGapAfterSeekLive,r=this.element.currentTime;this.isJumpGapAfterSeekLive&&!t&&this.element.currentTime>e&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let a=this.element.currentTime*1e3,n=null,o=this.element.readyState===HTMLMediaElement.HAVE_METADATA?this.tuning.endGapTolerance:0;for(let u of this.bufferManagers)for(let c of u.gaps)(c.persistent||u.playingRepresentation$.getValue()===c.representation)&&c.from-o<=a&&c.to+o>a&&(this.element.duration*1e3-c.to<this.tuning.endGapTolerance?n=1/0:(n===null||c.to>n)&&(n=c.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",Ua({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 pV,map as hV,observeElementSize as fV,Subscription as mV,ValueSubject as Yd,noop as bV}from"@vkontakte/videoplayer-shared/es2018";var fu=class{constructor(){this.subscription=new mV;this.pipSize$=new Yd(void 0);this.videoSize$=new Yd(void 0);this.elementSize$=new Yd(void 0);this.pictureInPictureWindowRemoveEventListener=bV}connect({observableVideo:e,video:t}){let i=r=>{let a=r.target;this.pipSize$.next({width:a.width,height:a.height})};this.subscription.add(fV(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(pV({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(hV(({videoSize:r,inPip:a,pipSize:n})=>a?n:r)).subscribe(this.elementSize$))}getValue(){return this.elementSize$.getValue()}subscribe(e,t){return this.elementSize$.subscribe(e,t)}getObservable(){return this.elementSize$}destroy(){this.pictureInPictureWindowRemoveEventListener(),this.subscription.unsubscribe()}};var Qi=class{constructor(e){this.subscription=new xV;this.videoState=new U("stopped");this.observableVideo=null;this.droppedFramesManager=new xr;this.stallsManager=new iu;this.elementSizeManager=new fu;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Zt;this.audioTrackSwitchHistory=new Zt;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"),k(this.params.desiredState.playbackState,"stopped",!0));return}switch(e){case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();return;case"ready":t==="paused"?(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="ready"&&k(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):t==="playing"&&this.video.paused?this.playIfAllowed():(i==null?void 0:i.to)==="playing"&&k(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&k(this.params.desiredState.playbackState,"paused");return;default:return vV(e)}}};this.init3DScene=e=>{var i,r,a;if(this.scene3D)return;this.scene3D=new Fr(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((i=e.projectionData)==null?void 0:i.pose.yaw)||0,y:((r=e.projectionData)==null?void 0:r.pose.pitch)||0,z:((a=e.projectionData)==null?void 0:a.pose.roll)||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSizeManager.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.textTracksManager=new Ye(e.source.url),this.params=e,this.video=De(e.container,e.tuning),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(ye(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 hu({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer,forceVideoCodec:this.params.forceVideoCodec}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params;EV(this.observableVideo)&&(this.observableVideo=_e(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:uE.WTF,message:`${i} internal logic error`,thrown:n})},a=(n,o)=>this.subscription.add(n.subscribe(o,r));return{output:e,desiredState:t,observableVideo:this.observableVideo,genericErrorListener:r,connect:a}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:a}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(Kd(l=>!!l.length),lE()).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(Wa(l=>l.to.state!=="none"),Ha());this.stallsManager.init({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$,videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,tuning:this.params.tuning.stallsManager,abrParams:this.params.tuning.autoTrackSelection,isBuffering$:i.isBuffering$,looped$:i.looped$,playing$:i.playing$,duration:this.video.duration}),a(i.ended$,e.endedEvent$),a(i.looped$,e.loopedEvent$),a(i.error$,e.error$),a(i.isBuffering$,e.isBuffering$),a(i.currentBuffer$,e.currentBuffer$),a(i.playing$,e.firstFrameEvent$),a(i.canplay$,e.canplay$),a(i.inPiP$,e.inPiP$),a(i.inFullscreen$,e.inFullscreen$),a(i.loadedMetadata$,e.loadedMetadataEvent$),a(this.player.error$,e.error$),a(this.player.fetcherRecoverableError$,e.fetcherRecoverableError$),a(this.player.fetcherError$,e.fetcherError$),a(this.player.lastConnectionType$,e.httpConnectionType$),a(this.player.lastConnectionReused$,e.httpConnectionReused$),a(this.player.isLive$,e.isLive$),a(this.player.lastRequestFirstBytes$.pipe(Kd(cE),lE()),e.firstBytesEvent$),a(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),a(this.videoState.stateChangeEnded$.pipe(Wa(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(gt(this.video,t.isLooped,r)),this.subscription.add(Ve(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(ze(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),a(Ke(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),k(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),k(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(i.ended$.subscribe(()=>{this.videoState.setState("paused"),k(t.playbackState,"paused")})),this.subscription.add(this.player.manifestRequested.subscribe(this.params.output.manifestRequested$)).add(this.player.manifestReceived.subscribe(this.params.output.manifestReceived$)).add(this.player.firstBytesRequested.subscribe(this.params.output.firstBytesRequested$)).add(this.player.firstBytesReceived.subscribe(this.params.output.firstBytesReceived$)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:l})=>{if(l==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let h=this.player.getStreams(),p=this.player.getCodecs();if(SV(h,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let m=[];for(let g of h.audio){m.push(_d(g));let b=[];for(let S of g.representations){let T=KI(S);b.push(T),this.audioTracksMap.set(T,{stream:g,representation:S})}this.audioStreamsMap.set(g,b)}this.params.output.availableAudioStreams$.next(m)}let f=[];for(let m of h.video){f.push(Od(m));let g=[];for(let b of m.representations){let S=Ba({...b,streamId:m.id});S&&(g.push(S),this.videoTracksMap.set(S,{stream:m,representation:b}))}this.videoStreamsMap.set(m,g)}this.params.output.availableVideoStreams$.next(f);for(let m of h.text)for(let g of m.representations){let b=XI(m,g);this.textTracksMap.set(b,{stream:m,representation:g})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),p!=null&&p.video&&this.params.output.availableVideoCodecs$.next(p.video),p!=null&&p.audio&&this.params.output.availableAudioCodecs$.next(p.audio),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else l==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r));let{vktvAbrThrottle:o}=this.params.tuning.dash,u=o&&eE(o)||null;this.subscription.add(Qa(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$,IV(this.video,"progress")).pipe(Kd(()=>this.videoTracksMap.size>0)).subscribe(async()=>{let l=this.player.state$.getState(),h=this.player.state$.getTransition();if(l!=="manifest_ready"&&l!=="running"||h||l==="running"&&u&&!u())return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState()),this.selectVideoAudioRepresentations();let{video:p,audio:f}=this.selectedRepresentations;if(!p)return;let m=qi(this.videoTracksMap.keys(),b=>{var S;return((S=this.videoTracksMap.get(b))==null?void 0:S.representation.id)===p.id});cE(m)&&(this.stallsManager.lastVideoTrackSelected=m);let g=this.params.desiredState.autoVideoTrackLimits.getTransition();if(g&&this.params.output.autoVideoTrackLimits$.next(g.to),l==="manifest_ready")await this.player.initRepresentations(p.id,f==null?void 0:f.id,this.params.sourceHls);else if(await this.player.switchRepresentation("video",p.id),f){let b=!!t.audioStream.getTransition();await this.player.switchRepresentation("audio",f.id,b)}},r)),this.subscription.add(yV({videoState:this.videoState.stateChangeEnded$,autoVideoTrackState:Qa(mu([t.autoVideoTrackSwitching.getState()]),t.autoVideoTrackSwitching.stateChangeEnded$.pipe(Wa(l=>l.to)))}).pipe(Wa(({videoState:l,autoVideoTrackState:h})=>l.to!=="stopped"&&h),Ha()).subscribe(l=>this.player.setSmartRepresentationSwitch(l))),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(Ha()).subscribe(l=>{let h=qi(this.videoTracksMap.entries(),([,{representation:b}])=>b.id===l);if(!h){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[p,{stream:f}]=h,m=this.params.desiredState.videoStream.getTransition();m&&m.to&&m.to.id===f.id&&this.params.desiredState.videoStream.setState(m.to),e.currentVideoTrack$.next(p),e.currentVideoStream$.next(Od(f));let g=this.player.calculateDurationFromSegments();g&&this.params.output.duration$.next(g/1e3)},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(Ha()).subscribe(l=>{let h=qi(this.audioTracksMap.entries(),([,{representation:g}])=>g.id===l);if(!h){e.currentAudioStream$.next(void 0);return}let[p,{stream:f}]=h,m=this.params.desiredState.audioStream.getTransition();m&&m.to&&m.to.id===f.id&&this.params.desiredState.audioStream.setState(m.to),e.currentAudioStream$.next(_d(f))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(l=>{var h,p;if(l!=null&&l.is3dVideo&&((h=this.params.tuning.spherical)!=null&&h.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(),(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 c=t.playbackState.stateChangeStarted$.pipe(Wa(({to:l})=>l==="ready"),Ha());this.subscription.add(Qa(c,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,mu(["init"])).subscribe(()=>{let l=t.autoVideoTrackSwitching.getState(),p=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:l?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(p)})),this.subscription.add(Qa(c,this.player.state$.stateChangeEnded$,mu(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let d=Qa(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,mu(["init"])).pipe(TV(0));this.subscription.add(d.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){var L,C,P,B,M,F,Q,j,I,R,x,w;if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?_s:Vs,t=this.params.tuning.useNewAutoSelectVideoTrack?wo:xo,i=this.params.tuning.useNewAutoSelectVideoTrack?yt:Eo,{desiredState:r,output:a}=this.params,n=r.autoVideoTrackSwitching.getState(),o=(L=r.videoTrack.getState())==null?void 0:L.id,u=qi(this.videoTracksMap.keys(),V=>V.id===o),c=a.currentVideoTrack$.getValue(),d=((B=(P=r.videoStream.getState())!=null?P:u&&((C=this.videoTracksMap.get(u))==null?void 0:C.stream))!=null?B:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!d)return;let l=qi(this.videoStreamsMap.keys(),V=>V.id===d.id),h=l&&this.videoStreamsMap.get(l);if(!h)return;let p=Te(this.video.buffered,this.video.currentTime*1e3),f;this.player.isActiveLive$.getValue()?f=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?f=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:f=n?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let m=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,g=Math.min(p/Math.min(f,m||1/0),1),b=(M=r.audioStream.getState())!=null?M:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,S=(b==null?void 0:b.id)&&qi(this.audioStreamsMap.keys(),V=>V.id===b.id)||this.audioStreamsMap.keys().next().value,T=0;if(S){if(u&&!n){let V=e(u,h,(F=this.audioStreamsMap.get(S))!=null?F:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);T=Math.max(T,(Q=V==null?void 0:V.bitrate)!=null?Q:-1/0)}if(c){let V=e(c,h,(j=this.audioStreamsMap.get(S))!=null?j:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);T=Math.max(T,(I=V==null?void 0:V.bitrate)!=null?I:-1/0)}}let y=u;(n||!y)&&(y=i(h,{container:this.elementSizeManager.getValue(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.stallsManager.abrTuningParams,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:T,forwardBufferHealth:g,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}));let E=S&&t(y,h,(R=this.audioStreamsMap.get(S))!=null?R:[],{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}),A=(x=this.videoTracksMap.get(y))==null?void 0:x.representation,$=E&&((w=this.audioTracksMap.get(E))==null?void 0:w.representation);A&&$?(this.selectedRepresentations.video=A,this.selectedRepresentations.audio=$):A&&!$&&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(){Oe(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:uE.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.stallsManager.destroy(),this.elementSizeManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),this.params.output.currentVideoStream$.next(void 0),Be(this.video),this.tracer.end()}};var Ga=class extends Qi{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 Xd,merge as dE,filter as pE,filterChanged as hE,isNullable as Jd,map as fE,ValueSubject as Zd,isNonNullable as wV}from"@vkontakte/videoplayer-shared/es2018";var za=class extends Qi{constructor(e){super(e),this.textTracksManager.destroy()}subscribe(){super.subscribe();let e=!1,t=-1,{output:i,observableVideo:r,desiredState:a,connect:n}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canPlayLiveTailBuffer$.next(!0),n(r.timeUpdate$,i.liveBufferTime$),n(this.player.liveSeekableDuration$,i.duration$),n(this.player.liveLatency$,i.liveLatency$);let o=new Zd(1);n(r.playbackRateState$,o),this.params.tuning.dashCmafLive.catchupLiveForMutedInactiveTab&&this.subscription.add(i.elementVisible$.pipe(hE()).subscribe(u=>{let c=i.position$.getValue(),d=i.volume$.getValue(),l=!d.volume||d.muted;!u&&!c&&l?e=!0:u&&e&&(this.seek(0),e=!1)})),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(a.isLowLatency.stateChangeEnded$.pipe(fE(u=>u.to)).subscribe(this.player.isLowLatency$)).add(Xd({liveBufferTime:i.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(fE(({liveBufferTime:u,liveAvailabilityStartTime:c})=>u&&c?u+c:void 0)).subscribe(i.liveTime$)).add(this.player.liveStreamStatus$.pipe(pE(u=>wV(u))).subscribe(u=>i.isLiveEnded$.next(u!=="active"&&i.position$.getValue()===0))).add(Xd({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:dE(r.playbackRateState$,new Zd(1))}).pipe(pE(({liveStreamStatus:u,liveDuration:c})=>u==="active"&&!!c)).subscribe(({liveDuration:u,playbackRate:c})=>{let d=i.liveBufferTime$.getValue(),l=i.position$.getValue(),{playbackCatchupSpeedup:h}=this.params.tuning.dashCmafLive.lowLatency;l||c<1-h||this.video.paused||Jd(d)||(t=u-d)})).add(Xd({time:i.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:dE(r.playbackRateState$,new Zd(1))}).pipe(hE((u,c)=>this.player.liveStreamStatus$.getValue()==="active"?u.liveDuration===c.liveDuration:u.time===c.time)).subscribe(({time:u,liveDuration:c,playbackRate:d})=>{let l=i.position$.getValue(),{playbackCatchupSpeedup:h}=this.params.tuning.dashCmafLive.lowLatency;if(!l&&!this.video.paused&&d>=1-h||Jd(u)||Jd(c))return;let p=-1*(c-u-t);i.position$.next(Math.min(p,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(u=>{if(u){let c=JI(u);this.params.output.availableTextTracks$.next([c])}}))}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 mE="X-Playback-Duration",ep=async s=>{var r;let e=await Xe(s),t=await e.text(),i=(r=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t))==null?void 0:r[1];return i?parseInt(i,10):e.headers.has(mE)?parseInt(e.headers.get(mE),10):void 0};import{assertNever as VV,combine as _V,debounce as OV,ErrorCategory as vu,filter as FV,filterChanged as NV,isNonNullable as vE,isNullable as Su,map as SE,merge as qV,observableFrom as UV,Subscription as jV,ValueSubject as rp,VideoQuality as HV}from"@vkontakte/videoplayer-shared/es2018";var ip=O(Wc(),1);import{videoSizeToQuality as AV,getExponentialDelay as PV}from"@vkontakte/videoplayer-shared/es2018";var RV=s=>{let e=null;if(s.QUALITY&&(e=Jt(s.QUALITY)),!e&&s.RESOLUTION){let[t,i]=s.RESOLUTION.split("x").map(r=>parseInt(r,10));e=AV({width:t,height:i})}return e!=null?e:null},kV=(s,e)=>{var a,n;let t=s.split(`
|
|
179
|
+
`),i=[],r=[];for(let o=0;o<t.length;o++){let u=t[o],c=u.match(/^#EXT-X-STREAM-INF:(.+)/),d=u.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!c&&!d)){if(c){let l=(0,ip.default)(c[1].split(",").map(S=>S.split("="))),h=(a=l.QUALITY)!=null?a:`stream-${l.BANDWIDTH}`,p=RV(l),f;l.BANDWIDTH&&(f=parseInt(l.BANDWIDTH,10)/1e3||void 0),!f&&l["AVERAGE-BANDWIDTH"]&&(f=parseInt(l["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let m=l["FRAME-RATE"]?parseFloat(l["FRAME-RATE"]):void 0,g;if(l.RESOLUTION){let[S,T]=l.RESOLUTION.split("x").map(y=>parseInt(y,10));S&&T&&(g={width:S,height:T})}let b=new URL(t[++o],e).toString();p&&i.push({id:h,quality:p,url:b,bandwidth:f,size:g,fps:m})}if(d){let l=(0,ip.default)(d[1].split(",").map(m=>{let g=m.indexOf("=");return[m.substring(0,g),m.substring(g+1)]}).map(([m,g])=>[m,g.replace(/^"|"$/g,"")])),h=(n=l.URI)==null?void 0:n.replace(/playlist$/,"subtitles.vtt"),p=l.LANGUAGE,f=l.NAME;h&&p&&r.push({type:"internal",id:p,label:f,language:p,url:h,isAuto:!1})}}}if(!i.length)throw new Error("Empty manifest");return{qualityManifests:i,textTracks:r}},$V=s=>new Promise(e=>{setTimeout(()=>{e()},s)}),tp=0,bE=async(s,e=s,t,i)=>{let a=await(await Xe(s,i)).text();tp+=1;try{let{qualityManifests:n,textTracks:o}=kV(a,e);return{qualityManifests:n,textTracks:o}}catch(n){if(tp<=t.manifestRetryMaxCount)return await $V(PV(tp-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),bE(s,e,t)}return{qualityManifests:[],textTracks:[]}},bu=bE;import{isNonNullable as LV,Subscription as MV,throttle as CV,ValueSubject as gE,Subject as DV,ErrorCategory as BV}from"@vkontakte/videoplayer-shared/es2018";var gu=class{constructor(e,t,i,r,a){this.subscription=new MV;this.abortControllers={destroy:new J,nextManifest:null};this.prepareUrl=void 0;this.currentTextTrackData=null;this.availableTextTracks$=new gE(null);this.getCurrentTime$=new gE(null);this.error$=new DV;this.params={fetchManifestData:i,sourceUrl:r,downloadThreshold:a},this.subscription.add(e.pipe(CV(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 Xe(r,{signal:this.abortControllers.destroy.signal})).text(),o=this.parsePlaylist(n,r);return{textTrack:i,playlist:o}}}parsePlaylist(e,t){let i={mediaSequence:0,programDateTime:"",segments:[],targetDuration:0,vkPlaybackDuration:0,segmentStartTime:0,vkStartTime:""},r=e.split(`
|
|
180
|
+
`),a=0;for(let n=0;n<r.length;++n){let o=r[n];switch(!0){case o.startsWith("#EXTINF:"):{let u=r[++n],c=new URL(u,t).toString(),d=Number(this.extractPlaylistRowValue("#EXTINF:",o))*1e3;if(i.segments.push({time:{from:a,to:a+d},url:c}),a=a+d,!i.segmentStartTime){let l=new Date(i.vkStartTime).valueOf(),h=new Date(i.programDateTime).valueOf();i.segmentStartTime=h-l}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 c=new Date(u);c.setMilliseconds(0),a=c.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(LV(e)&&this.currentTextTrackData){let{segments:t}=this.currentTextTrackData.playlist,{from:i}=t[0].time,{to:r}=t[t.length-1].time;if(e<i||e>r)return;r-e<this.params.downloadThreshold&&this.fetchNextManifestData();for(let n of t)if(n.time.from<=e&&n.time.to>=e){this.availableTextTracks$.next([{...this.currentTextTrackData.textTrack,url:n.url,isAuto:!0}]);break}}}async fetchNextManifestData(){try{if(this.abortControllers.nextManifest)return;this.abortControllers.nextManifest=new J;let{textTracks:e}=await this.fetchManifestData(),t=await this.parseTextTracks(e,this.params.sourceUrl);this.currentTextTrackData&&t&&(this.currentTextTrackData.playlist.segments=t.playlist.segments)}catch(e){this.error("fetchNextManifestData",e)}finally{this.abortControllers.nextManifest=null}}async fetchManifestData(){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:BV.WTF,thrown:t,message:e})}};var Ya=class{constructor(e){this.subscription=new jV;this.videoState=new U("stopped");this.textTracksManager=null;this.liveTextManager=null;this.manifests$=new rp([]);this.liveOffset=new Li;this.manifestStartTime$=new rp(void 0);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),k(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let c=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(a||n||o){let d=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(d),this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),c.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((r==null?void 0:r.to)!=="paused"&&c.state==="requested"){this.videoState.startTransitionTo("ready"),this.seek(c.position&&c.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":i==="ready"?k(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),k(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&k(this.params.desiredState.playbackState,"playing");return;case"paused":if(i==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let 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"&&(k(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return VV(t)}};var i;this.params=e,this.video=De(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:HV.INVARIANT,url:this.params.source.url};let t=(r,a)=>bu(r,this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},a);this.params.tuning.useHlsLiveNewTextManager?this.liveTextManager=new gu(this.params.output.liveTime$,this.video,t,this.params.source.url,this.params.tuning.hlsLiveNewTextManagerDownloadThreshold):this.textTracksManager=new Ye(e.source.url),t(this.generateLiveUrl()).then(({qualityManifests:r,textTracks:a})=>{var n;r.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:vu.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),(n=this.liveTextManager)==null||n.processTextTracks(a,this.params.source.url),this.manifests$.next([this.masterManifest,...r])}).catch(r=>{this.params.output.error$.next({id:"ExtractHlsQualities",category:vu.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(ye(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new rp((i=e.source.maxSeekBackTime)!=null?i:1/0),this.subscribe()}selectManifest(){var u,c,d,l;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),a=(l=(d=(u=r==null?void 0:r.to)==null?void 0:u.id)!=null?d:(c=t.getState())==null?void 0:c.id)!=null?l:"master",n=this.manifests$.getValue();if(!n.length)return;let o=i?"master":a;return i&&!r&&t.startTransitionTo(this.masterManifest),n.find(h=>h.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsLiveProvider",category:vu.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},r=_e(this.video);this.subscription.add(()=>r.destroy());let a=(o,u)=>this.subscription.add(o.subscribe(u,i));a(r.ended$,e.endedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.loadedMetadata$,e.loadedMetadataEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(Ve(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(ze(this.video,t.playbackRate,r.playbackRateState$,i)),a(Ke(this.video),e.elementVisible$),this.liveTextManager?(a(this.liveTextManager.getCurrentTime$,this.params.output.getCurrentTime$),a(this.liveTextManager.error$,this.params.output.error$)):this.textTracksManager&&this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),k(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),k(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(NV(),SE(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(),c=this.params.desiredState.videoTrack.getTransition(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(c&&vE(c.to)){let l=c.to.id;this.params.desiredState.videoTrack.setState(c.to);let h=this.manifests$.getValue().find(p=>p.id===l);h&&(this.params.output.currentVideoTrack$.next(h),this.params.output.hostname$.next(ye(h.url)))}d&&this.params.desiredState.autoVideoTrackSwitching.setState(d.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o&&o.state==="requested"&&this.seek(o.position)},i)),this.subscription.add(r.loadedData$.subscribe(()=>{var u,c,d;let o=(d=(c=(u=this.video)==null?void 0:u.getStartDate)==null?void 0:c.call(u))==null?void 0:d.getTime();this.manifestStartTime$.next(o||void 0)},i)),this.subscription.add(_V({startTime:this.manifestStartTime$.pipe(FV(vE)),currentTime:r.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),i)),this.subscription.add(this.manifests$.pipe(SE(o=>o.map(({id:u,quality:c,size:d,bandwidth:l,fps:h})=>({id:u,quality:c,size:d,fps:h,bitrate:l})))).subscribe(this.params.output.availableVideoTracks$,i));let n=qV(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,UV(["init"])).pipe(OV(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),Be(this.video)}prepare(){var o,u,c;let e=this.selectManifest();if(Su(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:l}=(u=(o=t==null?void 0:t.to)!=null?o:i)!=null?u:{};for(let[h,p]of[[d,"mq"],[l,"lq"]]){let f=String(parseFloat(h||""));p&&h&&r.searchParams.set(p,f)}}let a=this.params.format==="HLS_LIVE_CMAF"?2:0,n=ne(r.toString(),this.liveOffset.getTotalOffset(),a);(c=this.liveTextManager)==null||c.prepare(n),this.video.setAttribute("src",n),this.video.load(),ep(n).then(d=>{var l;if(!Su(d))this.maxSeekBackTime$.next(d);else{let h=(l=this.params.source.maxSeekBackTime)!=null?l:this.maxSeekBackTime$.getValue();(Su(h)||!isFinite(h))&&Xe(n).then(p=>p.text()).then(p=>{var m;let f=(m=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(p))==null?void 0:m[1];if(f){let g=new URL(f,n).toString();ep(g).then(b=>{Su(b)||this.maxSeekBackTime$.next(b)})}}).catch(()=>{})}})}playIfAllowed(){Oe(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),k(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:vu.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3),this.params.output.seekedEvent$.next()}generateLiveUrl(){let e=ne(this.params.source.url);if(this.params.tuning.useHlsLiveNewTextManager){let t=new URL(e);t.searchParams.set("enable-subtitles","yes"),e=t.toString()}return e}};import{assertNever as WV,debounce as QV,ErrorCategory as sp,fromEvent as ap,isNonNullable as GV,isNullable as zV,map as yE,merge as TE,observableFrom as IE,Subscription as YV,ValueSubject as EE,VideoQuality as KV}from"@vkontakte/videoplayer-shared/es2018";var Ka=class{constructor(e){this.subscription=new YV;this.videoState=new U("stopped");this.manifests$=new EE([]);this.unmuteAfterBrowserResetsHappened=new EE(!1);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),k(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let c=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(a||n||o){let d=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(d);let{currentTime:l}=this.video;this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),c.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:l*1e3,forcePrecise:!0});return}switch((r==null?void 0:r.to)!=="paused"&&c.state==="requested"&&this.seek(c.position),t){case"ready":i==="ready"?k(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&k(this.params.desiredState.playbackState,"playing");return;case"paused":i==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&k(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return WV(t)}};this.textTracksManager=new Ye(e.source.url),this.params=e,this.video=De(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:KV.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(ye(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.manifestRequested$.next(),bu(ne(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:t,textTracks:i})=>{this.params.output.manifestReceived$.next(),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:sp.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){var u,c,d,l;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),a=(l=(d=(u=r==null?void 0:r.to)==null?void 0:u.id)!=null?d:(c=t.getState())==null?void 0:c.id)!=null?l:"master",n=this.manifests$.getValue();if(!n.length)return;let o=i?"master":a;return i&&(!r||!r.from)&&t.startTransitionTo(this.masterManifest),n.find(h=>h.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsProvider",category:sp.WTF,message:"HlsProvider internal logic error",thrown:o})},r=_e(this.video);this.subscription.add(()=>r.destroy());let a=(o,u)=>this.subscription.add(o.subscribe(u));if(a(r.timeUpdate$,e.position$),a(r.durationChange$,e.duration$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.loadedMetadata$,e.loadedMetadataEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.seeked$,e.seekedEvent$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),a(this.videoState.stateChangeEnded$.pipe(yE(o=>o.to)),this.params.output.playbackState$),this.subscription.add(gt(this.video,t.isLooped,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(ze(this.video,t.playbackRate,r.playbackRateState$,i)),Nr({subscription:this.subscription,desiredState:t,videoElement$:this.params.output.element$,observableVideo:r}),this.subscription.add(Ve(this.video,t.volume,r.volumeState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),k(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),k(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{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(),c=this.params.desiredState.videoTrack.getTransition(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(c&&GV(c.to)){let f=c.to.id;this.params.desiredState.videoTrack.setState(c.to);let m=this.manifests$.getValue().find(g=>g.id===f);m&&(this.params.output.currentVideoTrack$.next(m),this.params.output.hostname$.next(ye(m.url)))}let l=this.params.desiredState.playbackRate.getState(),h=(p=this.params.output.element$.getValue())==null?void 0:p.playbackRate;if(l!==h){let f=this.params.output.element$.getValue();f&&(this.params.desiredState.playbackRate.setState(l),f.playbackRate=l)}d&&this.params.desiredState.autoVideoTrackSwitching.setState(d.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o.state==="requested"&&this.seek(o.position)},i))),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(r.ended$.subscribe(()=>{this.videoState.setState("paused"),k(t.playbackState,"paused")})),this.subscription.add(this.manifests$.pipe(yE(o=>o.map(({id:u,quality:c,size:d,bandwidth:l,fps:h})=>({id:u,quality:c,size:d,fps:h,bitrate:l})))).subscribe(this.params.output.availableVideoTracks$,i)),!_.device.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(TE(ap(o,"addtrack"),ap(o,"removetrack"),ap(o,"change"),IE(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},i))}let n=TE(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,IE(["init"])).pipe(QV(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Be(this.video)}prepare(){var a,n;let e=this.selectManifest();if(zV(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:o,min:u}=(n=(a=t==null?void 0:t.to)!=null?a:i)!=null?n:{};for(let[c,d]of[[o,"mq"],[u,"lq"]]){let l=String(parseFloat(c||""));d&&c&&r.searchParams.set(d,l)}}this.video.setAttribute("src",r.toString()),this.video.load()}playIfAllowed(){Oe(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:sp.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var AE=O(cr(),1),np=O(Ei(),1),PE=O(nt(),1);import{assertNever as XV,assertNonNullable as xE,debounce as JV,ErrorCategory as wE,isHigherOrEqual as ZV,isLowerOrEqual as e_,isNonNullable as t_,merge as i_,observableFrom as r_,Subscription as s_,map as a_}from"@vkontakte/videoplayer-shared/es2018";var Xa=class{constructor(e){this.subscription=new s_;this.videoState=new U("stopped");this.trackUrls={};this.textTracksManager=new Ye;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),k(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let a=this.params.desiredState.autoVideoTrackLimits.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.seekState.getState();if(a&&e!=="ready"&&!n){this.handleQualityLimitTransition(a.to);return}if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(n){let{currentTime:u}=this.video;this.prepare(),o.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:u*1e3,forcePrecise:!0});return}switch((i==null?void 0:i.to)!=="paused"&&o.state==="requested"&&this.seek(o.position),e){case"ready":t==="ready"?k(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(i==null?void 0:i.to)==="playing"&&k(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&k(this.params.desiredState.playbackState,"paused");return;default:return XV(e)}};this.params=e,this.video=De(e.container,e.tuning),this.params.output.element$.next(this.video),(0,AE.default)(this.params.source).reverse().forEach(([t,i],r)=>{let a=r.toString(10);this.trackUrls[a]={track:{quality:t,id:a},url:i}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next((0,np.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:wE.WTF,message:"MpegProvider internal logic error",thrown:o})},r=_e(this.video);this.subscription.add(()=>r.destroy());let a=(o,u)=>this.subscription.add(o.subscribe(u,i));a(r.timeUpdate$,e.position$),a(r.durationChange$,e.duration$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.loadedMetadata$,e.loadedMetadataEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.seeked$,e.seekedEvent$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),a(this.videoState.stateChangeEnded$.pipe(a_(o=>o.to)),this.params.output.playbackState$),this.subscription.add(gt(this.video,t.isLooped,i)),Nr({subscription:this.subscription,desiredState:t,videoElement$:this.params.output.element$,observableVideo:r}),this.subscription.add(Ve(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(ze(this.video,t.playbackRate,r.playbackRateState$,i)),a(Ke(this.video),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),k(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),k(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var u,c;((u=this.videoState.getTransition())==null?void 0:u.to)==="ready"&&this.videoState.setState("ready");let o=this.params.desiredState.videoTrack.getTransition();if(o&&t_(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(),l=(c=this.params.output.element$.getValue())==null?void 0:c.playbackRate;if(d!==l){let h=this.params.output.element$.getValue();h&&(this.params.desiredState.playbackRate.setState(d),h.playbackRate=d)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(r.ended$.subscribe(()=>{this.videoState.setState("paused"),k(t.playbackState,"paused")})),this.textTracksManager.connect(this.video,t,e);let n=i_(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,r_(["init"])).pipe(JV(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),Be(this.video)}prepare(){var i;let e=(i=this.params.desiredState.videoTrack.getState())==null?void 0:i.id;xE(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];xE(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=ri(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(ye(t))}playIfAllowed(){Oe(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:wE.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){var c,d;this.params.output.autoVideoTrackLimits$.next(e);let t=l=>{this.params.output.currentVideoTrack$.next(l),this.params.desiredState.videoTrack.startTransitionTo(l)},i=l=>{let h=yt(n,{container:this.video.getBoundingClientRect(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,limits:l,abrLogger:this.params.dependencies.abrLogger});t(h)},r=(c=this.params.output.currentVideoTrack$.getValue())==null?void 0:c.quality,a=!!(e.max||e.min),n=(0,np.default)(this.trackUrls).map(l=>l.track);if(!r||!a||yr(e,n[0].quality,(d=(0,PE.default)(n,-1))==null?void 0:d.quality)){i();return}let o=e.max?e_(r,e.max):!0,u=e.min?ZV(r,e.min):!0;o&&u||i(e)}};import{assertNever as kE,debounce as c_,merge as $E,observableFrom as l_,Subscription as d_,map as LE,ValueSubject as p_,ErrorCategory as up,VideoQuality as h_}from"@vkontakte/videoplayer-shared/es2018";import{ErrorCategory as n_}from"@vkontakte/videoplayer-shared/es2018";var RE=["stun:videostun.mycdn.me:80"],o_=1e3,u_=3,op=()=>null,yu=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=op;this.externalStopCallback=op;this.externalErrorCallback=op;this.options=this.normalizeOptions(t);let i=e.split("/");this.serverUrl=i.slice(0,i.length-1).join("/"),this.streamKey=i[i.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{let t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}async handleUpdateMessage(e){try{let t=await this.createOffer();this.peerConnection&&await this.peerConnection.setLocalDescription(t),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}}async handleLogin(){try{let e={iceServers:[{urls:RE}]};this.peerConnection=new RTCPeerConnection(e),this.peerConnection.ontrack=this.onPeerConnectionStream.bind(this),this.peerConnection.onicecandidate=this.onPeerConnectionIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onPeerConnectionIceConnectionStateChange.bind(this);let t=await this.createOffer();await this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}}async handleAnswer(e){try{this.peerConnection&&await this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e}))}catch(t){this.handleRTCError(t)}}async handleCandidate(e){if(e)try{this.peerConnection&&await this.peerConnection.addIceCandidate(e)}catch(t){this.handleRTCError(t)}}handleUnpublished(){try{this.closeConnections(),this.externalStopCallback()}catch(e){this.handleRTCError(e)}}handleSystemError(e){this.options.errorChanel&&this.options.errorChanel.next({id:"webrtc-provider-error",category:n_.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),o_)}normalizeOptions(e={}){let t={stunServerList:RE,maxRetryNumber:u_,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var Ja=class{constructor(e){this.videoState=new U("stopped");this.maxSeekBackTime$=new p_(0);this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.pause(),this.video.srcObject=null,this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),k(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let a=this.params.desiredState.videoTrack.getTransition();if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(a){this.prepare();return}switch(e){case"ready":t==="paused"?(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(i==null?void 0:i.to)==="playing"&&k(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&k(this.params.desiredState.playbackState,"paused");return;default:return kE(e)}};this.subscription=new d_,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=De(e.container,e.tuning),this.liveStreamClient=new yu(this.params.source.url,{maxRetryNumber:this.params.tuning.webrtc.connectionRetryMaxNumber,errorChanel:this.params.output.error$}),this.liveStreamClient.onStart(this.onLiveStreamStart.bind(this)),this.liveStreamClient.onStop(this.onLiveStreamStop.bind(this)),this.liveStreamClient.onError(this.onLiveStreamError.bind(this)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),Be(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,i=n=>{e.error$.next({id:"WebRTCLiveProvider",category:up.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};this.subscription.add($E(this.videoState.stateChangeStarted$.pipe(LE(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(LE(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})}));let r=_e(this.video);this.subscription.add(()=>r.destroy());let a=(n,o)=>this.subscription.add(n.subscribe(o,i));a(r.timeUpdate$,e.liveTime$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(Ke(this.video),this.params.output.elementVisible$),this.subscription.add(r.durationChange$.subscribe(n=>{e.duration$.next(n===1/0?0:n)})).add(r.canplay$.subscribe(()=>{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(Ve(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 kE(n.to)}},i)).add($E(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,l_(["init"])).pipe(c_(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(ye(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:h_.INVARIANT}),this.video.srcObject=e,k(this.params.desiredState.playbackState,"playing")}onLiveStreamStop(){this.videoState.startTransitionTo("stopped"),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.params.output.endedEvent$.next()}onLiveStreamError(e){this.onLiveStreamStop(),this.params.output.error$.next({id:"WebRTC stream runtime error",category:up.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){Oe(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:up.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var Qr=class{constructor(e){this.length=e.length,this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next(),this.index=this.index===void 0?0:this.index+1}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return!!this.current.done}isLast(){return this.index===this.length-1}};import{assertNever as en,assertNonNullable as _t,ErrorCategory as Tu,filter as _E,isNonNullable as OE,isNullable as y_,map as T_,merge as I_,once as E_,Subject as oe,Subscription as FE,ValueSubject as q,flattenObject as cp}from"@vkontakte/videoplayer-shared/es2018";import{Observable as f_,map as ME,Subscription as m_,Subject as b_}from"@vkontakte/videoplayer-shared/es2018";var CE=s=>new f_(e=>{let t=new m_,i=s.desiredPlaybackState$.stateChangeStarted$.pipe(ME(({from:c,to:d})=>`${c}-${d}`)),r=s.desiredPlaybackState$.stateChangeEnded$,a=s.providerChanged$.pipe(ME(({type:c})=>c!==void 0)),n=new b_,o=0,u="unknown";return t.add(i.subscribe(c=>{o&&window.clearTimeout(o),u=c,o=window.setTimeout(()=>n.next(c),s.maxTransitionInterval)})),t.add(r.subscribe(()=>{window.clearTimeout(o),u="unknown",o=0})),t.add(a.subscribe(c=>{o&&(window.clearTimeout(o),o=0,c&&(o=window.setTimeout(()=>n.next(u),s.maxTransitionInterval)))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});import{ErrorCategory as g_,Subscription as v_,combine as S_,filter as BE,once as VE}from"@vkontakte/videoplayer-shared/es2018";function DE(){return new(window.AudioContext||window.webkitAudioContext)}var Za=class Za{constructor(e,t,i,r){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=i;this.volumeMultiplier=r;this.destroyController=new J;this.subscriptions=new v_;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe(BE(a=>!!a.type),VE()).subscribe(({type:a})=>this.subscribe(a)))}subscribe(e){_.browser.isSafari&&e!=="MPEG"||this.subscriptions.add(S_({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(BE(({playbackState:t,video:i,volume:{muted:r,volume:a}})=>t==="playing"&&!!i&&!r&&!!a),VE()).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=DE();this.audioContext=i;let r=i.createGain();if(this.gainNode=r,r.gain.value=t,r.connect(i.destination),i.state==="suspended"&&(await i.resume(),this.destroyController.signal.aborted))return!1;let a=i.createMediaElementSource(e);return this.mediaElementSource=a,a.connect(r),!0}cleanup(){this.mediaElementSource&&(this.mediaElementSource.disconnect(),this.mediaElementSource=null),this.gainNode&&(this.gainNode.disconnect(),this.gainNode=null),this.audioContext&&(this.audioContext.state!=="closed"&&this.audioContext.close(),this.audioContext=null)}destroy(){this.destroyController.abort(),this.subscriptions.unsubscribe(),this.cleanup()}handleError(e){var t;this.volumeMultiplierError$.next({id:Za.errorId,category:g_.VIDEO_PIPELINE,message:(t=e==null?void 0:e.message)!=null?t:`${Za.errorId} exception`,thrown:e})}};Za.errorId="VolumeMultiplierManager";var Gr=Za;var x_={chunkDuration:5e3,maxParallelRequests:5},tn=class{constructor(e){this.current$=new q({type:void 0});this.providerError$=new oe;this.noAvailableProvidersError$=new oe;this.volumeMultiplierError$=new oe;this.providerOutput={position$:new q(0),duration$:new q(1/0),volume$:new q({muted:!1,volume:1}),availableVideoStreams$:new q([]),currentVideoStream$:new q(void 0),availableVideoTracks$:new q([]),currentVideoTrack$:new q(void 0),availableVideoCodecs$:new q([]),availableAudioStreams$:new q([]),currentAudioStream$:new q(void 0),availableAudioTracks$:new q([]),availableAudioCodecs$:new q([]),currentVideoSegmentLength$:new q(0),currentAudioSegmentLength$:new q(0),isAudioAvailable$:new q(!0),autoVideoTrackLimitingAvailable$:new q(!1),autoVideoTrackLimits$:new q(void 0),currentBuffer$:new q(void 0),isBuffering$:new q(!0),error$:new oe,fetcherError$:new oe,fetcherRecoverableError$:new oe,warning$:new oe,willSeekEvent$:new oe,soundProhibitedEvent$:new oe,seekedEvent$:new oe,loopedEvent$:new oe,endedEvent$:new oe,manifestRequested$:new oe,manifestReceived$:new oe,firstBytesRequested$:new oe,firstBytesReceived$:new oe,firstBytesEvent$:new oe,loadedMetadataEvent$:new oe,firstFrameEvent$:new oe,canplay$:new oe,isLive$:new q(void 0),isLiveEnded$:new q(null),canPlayLiveTailBuffer$:new q(!1),isLowLatency$:new q(!1),canChangePlaybackSpeed$:new q(!0),liveTime$:new q(void 0),liveBufferTime$:new q(void 0),liveLatency$:new q(void 0),severeStallOccurred$:new oe,availableTextTracks$:new q([]),currentTextTrack$:new q(void 0),hostname$:new q(void 0),httpConnectionType$:new q(void 0),httpConnectionReused$:new q(void 0),inPiP$:new q(!1),inFullscreen$:new q(!1),element$:new q(void 0),elementVisible$:new q(!0),availableSources$:new q(void 0),is3DVideo$:new q(!1),playbackState$:new q(""),getCurrentTime$:new q(null)};this.subscription=new FE;this.volumeMultiplierManager=null;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer"),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name);let t=yc([...kI(this.params.tuning),...RI(this.params.tuning)]).filter(c=>OE(e.sources[c])),{forceFormat:i,formatsToAvoid:r}=this.params.tuning,a=[];i?a=[i]:r.length?a=[...t.filter(c=>!(0,lp.default)(r,c)),...t.filter(c=>(0,lp.default)(r,c))]:a=t,this.log({message:`Selected formats: ${a.join(" > ")}`}),this.tracer.log("Selected formats",cp(a)),this.screenFormatsIterator=new Qr(a);let n=[...Td(!0),...Td(!1)];this.chromecastFormatsIterator=new Qr(n.filter(c=>OE(e.sources[c]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:o=1,tuning:{useVolumeMultiplier:u}}=this.params;u&&o!==1&&Gr.isSupported()&&(this.volumeMultiplierManager=new Gr(this.providerOutput,this.current$,this.volumeMultiplierError$,o))}init(){this.subscription.add(this.initProviderErrorHandling()).add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()})).add(this.providerOutput.availableVideoCodecs$.subscribe(e=>{!this.videoCodecsIterator&&e.length>1&&(this.videoCodecsIterator=new Qr(e))}))}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(y_(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:Tu.WTF,message:"Failed to create provider",thrown:r})}i?this.current$.next({type:t,provider:i,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.tracer.log("reinitProvider"),this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.tracer.log("switchToNextProvider",{destination:e}),this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}switchToNextVideoCodec(){this.params.tuning.dash.codecsPrioritizeEnabled&&!this.videoCodecsIterator.isLast()&&(this.tracer.log("switchToNextVideoCodec"),this.destroyProvider(),this.videoCodecsIterator.next(),this.initProvider())}destroyProvider(){let e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"}),this.tracer.log("destroyProvider"),e.destroy();let t=this.providerOutput.position$.getValue()*1e3,i=this.params.desiredState.seekState.getState(),r=i.state!=="none";if(this.params.desiredState.seekState.setState({state:"requested",position:r?i.position:t,forcePrecise:r?i.forcePrecise:!1}),e.scene3D){let n=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:n.x,y:n.y})}let a=this.providerOutput.isBuffering$;a.getValue()||a.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),this.tracer.log("createProvider",{destination:e,format:t}),e){case"SCREEN":return this.createScreenProvider(t);case"CHROMECAST":return this.createChromecastProvider(t);default:return en(e)}}createScreenProvider(e){var u,c;let{sources:t,container:i,desiredState:r,panelSize:a}=this.params,n=this.providerOutput,o={container:i,source:null,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning,panelSize:a};switch(e){case"DASH_SEP":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_ONDEMAND":case"DASH_STREAMS":{let d=this.applyFailoverHost(t[e]),l=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return _t(d),this.params.tuning.useNewDashProvider?new Ga({...o,source:d,sourceHls:l,forceVideoCodec:(u=this.videoCodecsIterator)==null?void 0:u.getValue()}):new Ca({...o,source:d,sourceHls:l,forceVideoCodec:(c=this.videoCodecsIterator)==null?void 0:c.getValue()})}case"DASH_LIVE_CMAF":{let d=this.applyFailoverHost(t[e]);return _t(d),this.params.tuning.useNewDashProvider?new za({...o,source:d}):new Da({...o,source:d})}case"HLS":case"HLS_ONDEMAND":case"HLS_FMP4":{let d=this.applyFailoverHost(t[e]);return _t(d),new Ka({...o,source:d})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let d=this.applyFailoverHost(t[e]);return _t(d),new Ya({...o,source:d,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let d=this.applyFailoverHost(t[e]);return _t(d),new Xa({...o,source:d})}case"DASH_LIVE":{let d=this.applyFailoverHost(t[e]);return _t(d),new Iy({...o,source:d,config:{...x_,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let d=this.applyFailoverHost(t[e]);return _t(d),new Ja({container:i,source:d,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 en(e)}}createChromecastProvider(e){let{sources:t,container:i,desiredState:r,meta:a}=this.params,n=this.providerOutput,o={meta:a,container:i,source:t,format:e,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning};if(this.params.tuning.chromecastNewProvider&&this.params.dependencies.chromecastInitializer instanceof kt){let{chromecastConnector:c}=this.params.dependencies.chromecastInitializer;return _t(c),new ms({...o,chromecastConnector:c})}let u=this.params.dependencies.chromecastInitializer.connection$.getValue();return _t(u),new Ls({...o,connection:u})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?"CHROMECAST":"SCREEN"}chooseFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case"CHROMECAST":return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return en(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return en(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 en(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;let t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;let i=r=>{let a=new URL(r);return a.host=t,a.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return{...e,url:i(e.url)}}return(0,qE.default)((0,NE.default)(e).map(([r,a])=>[r,i(a)]))}initProviderErrorHandling(){let e=new FE,t=!1,i=0;return e.add(I_(this.providerOutput.error$.pipe(_E(r=>!this.params.tuning.ignoreAudioRendererError||!r.message||!/AUDIO_RENDERER_ERROR/ig.test(r.message))),CE({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(T_(r=>({id:`ProviderHangup:${r}`,category:Tu.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(_E(({to:a})=>a==="playing"),E_()).subscribe(()=>t=!0);e.add(r)})),e.add(this.providerError$.subscribe(r=>{console.error(r);let a=this.current$.getValue().destination,n={error:r,currentDestination:a};if(a==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("CHROMECAST"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let o=r.category===Tu.NETWORK,u=r.category===Tu.FATAL,c=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),d=i<this.params.tuning.providerErrorLimit&&!u,l=this.videoCodecsIterator&&!this.videoCodecsIterator.isLast()&&this.params.tuning.dash.codecsPrioritizeEnabled,h=c&&!u&&(o&&t||!d);n={...n,isNetworkError:o,isFatalError:u,haveFailoverHost:c,tryFailover:h,canReinitProvider:d},d?(i++,this.reinitProvider()):h?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):l?this.switchToNextVideoCodec():(i=0,this.switchToNextProvider(a!=null?a:"SCREEN"))}r.traceAsLog?this.tracer.log("providerInfo",cp(n)):this.tracer.error("providerError",cp(n))})),e}};import{fromEvent as Iu,once as w_,combine as A_,Subscription as UE,ValueSubject as dp,map as P_,filter as R_,isNonNullable as Eu,now as Qe,safeStorage as pp}from"@vkontakte/videoplayer-shared/es2018";var k_=5e3,jE="one_video_throughput",HE="one_video_rtt",Ot=window.navigator.connection,WE=()=>{let s=Ot==null?void 0:Ot.downlink;if(Eu(s)&&s!==10)return s*1e3},QE=()=>{let s=Ot==null?void 0:Ot.rtt;if(Eu(s)&&s!==3e3)return s},GE=(s,e,t)=>{let i=t*8,r=i/s;return i/(r+e)},hp=class s{constructor(e){this.subscription=new UE;this.concurrentDownloads=new Set;var r,a;this.tuningConfig=e;let t=s.load(jE)||(e.useBrowserEstimation?WE():void 0)||k_,i=(a=(r=s.load(HE))!=null?r:e.useBrowserEstimation?QE():void 0)!=null?a:0;if(this.throughput$=new dp(t),this.rtt$=new dp(i),this.rttAdjustedThroughput$=new dp(GE(t,i,e.rttPenaltyRequestSize)),this.throughput=Bt.getSmoothedValue(t,-1,e),this.rtt=Bt.getSmoothedValue(i,1,e),e.useBrowserEstimation){let n=()=>{let u=WE();u&&this.throughput.next(u);let c=QE();Eu(c)&&this.rtt.next(c)};Ot&&"onchange"in Ot&&this.subscription.add(Iu(Ot,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{pp.set(jE,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{pp.set(HE,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(A_({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(P_(({throughput:n,rtt:o})=>GE(n,o,e.rttPenaltyRequestSize)),R_(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=Qe(),r=new UE;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add(Iu(e,"progress").pipe(w_()).subscribe(a=>{t=a.loaded,i=Qe()}));break;case 1:case 0:r.add(Iu(e,"loadstart").subscribe(()=>{t=0,i=Qe()}));break}r.add(Iu(e,"loadend").subscribe(a=>{if(e.status===200){let n=a.loaded,o=Qe(),u=n-t,c=o-i;this.addRawSpeed(u,c,1)}this.concurrentDownloads.delete(e),r.unsubscribe()}))}trackStream(e,t=!1){let i=e.getReader();if(!i){e.cancel("Could not get reader");return}let r=0,a=Qe(),n=0,o=Qe(),u=d=>{this.concurrentDownloads.delete(e),i.releaseLock(),e.cancel(`Throughput Estimator error: ${d}`).catch(()=>{})},c=async({done:d,value:l})=>{if(d)!t&&this.addRawSpeed(r,Qe()-a,1),this.concurrentDownloads.delete(e);else if(l){if(t){let h=Qe();if(h-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||h-a>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let f=o-a;f&&this.addRawSpeed(n,f,1,t),n=l.byteLength,a=Qe()}else n+=l.byteLength;o=Qe()}else r+=l.byteLength,n+=l.byteLength,n>=this.tuningConfig.streamMinSampleSize&&Qe()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,Qe()-o,this.concurrentDownloads.size),n=0,o=Qe());await(i==null?void 0:i.read().then(c,u))}};this.concurrentDownloads.add(e),i==null||i.read().then(c,u)}addRawSpeed(e,t,i=1,r=!1){if(s.sanityCheck(e,t,r)){let a=e*8/t;this.throughput.next(a*i)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,i=!1){let r=e*8/t;return!(!r||!isFinite(r)||r>1e6||r<30||i&&e<1e4||!i&&e<10*1024||!i&&t<=20)}static load(e){var i;let t=pp.get(e);if(Eu(t))return(i=parseInt(t,10))!=null?i:void 0}},zE=hp;import{fillWithDefault as $_,VideoQuality as xu}from"@vkontakte/videoplayer-shared/es2018";var YE={configName:["core"],throughputEstimator:{type:"EmaAndMa",emaAlphaSlow:.2,emaAlphaFast:.7,emaAlpha:.45,basisTrendChangeCount:10,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1*1024*1024,streamMinSampleSize:10*1024,streamMinSampleTime:300,deviationDepth:20,deviationFactor:.5,lowLatency:{continuesByteSequenceInterval:50,maxLastEvaluationTimeout:300}},autoTrackSelection:{maxBitrateFactorAtEmptyBuffer:4,bitrateFactorAtEmptyBuffer:2.8,minBitrateFactorAtEmptyBuffer:1.5,bitrateAudioFactorAtEmptyBuffer:10,maxBitrateFactorAtFullBuffer:3,bitrateFactorAtFullBuffer:2,minBitrateFactorAtFullBuffer:1,bitrateAudioFactorAtFullBuffer:7,minVideoAudioRatio:5,minAvailableThroughputAudioRatio:5,usePixelRatio:!0,pixelRatioMultiplier:void 0,pixelRatioLogBase:3,pixelRatioLogCoefficients:[1,0,1],limitByContainer:!0,maxContainerSizeFactor:2,containerSizeFactor:1.3,minContainerSizeFactor:1,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldownIncreaseQuality:15e3,trackCooldownDecreaseQuality:3e3,backgroundVideoQualityLimit:xu.Q_4320P,activeVideoAreaThreshold:.1,highQualityLimit:xu.Q_720P,trafficSavingLimit:xu.Q_480P},stallsManager:{enabled:!0,ignoreDynamicAbrForShortVideo:!1,stallDurationNoDataBeforeQualityDecrease:500,stallDurationToBeCount:100,stallCountBeforeQualityDecrease:3,resetQualityRestrictionTimeout:1e4,ignoreStallsOnSeek:!0,stallsMetricsHistoryLength:20,maxPossibleStallDuration:3e4,minTvtToBeCounted:120,maxTvtToBeCounted:10800,significantTvt:600,targetStallsDurationPerTvt:1,deviationStallsDurationPerTvt:.5,criticalStallsDurationPerTvt:6,abrAdjustingSpeed:.1,emaAlpha:.6,useTotalStallsDurationPerTvt:!0,useAverageStallsDurationPerTvt:!0,useEmaStallsDurationPerTvt:!0},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:xu.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,seekBiasInTheEnd:2e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:15e3,crashOnStallTimeout:25e3,crashOnStallTWithoutDataTimeout:5e3,enableSubSegmentBufferFeeding:!0,bufferEmptinessTolerance:100,useNewRepresentationSwitch:!1,useDelayedRepresentationSwitch:!1,useSmartRepresentationSwitch:!1,useFetchPriorityHints:!0,enableBaseUrlSupport:!0,maxSegmentRetryCount:5,sourceOpenTimeout:1e3,vktvAbrThrottle:0,timeupdateEventTickThrottle:300,fetcherBufferOptimisation:!0,codecsPrioritizeEnabled:!1,usePersistentGaps:!1,abrThrottle:0,useVideoElementWaitingCurrentTimeReassign:!0,stallWatchdogInterval:100,liveUpdateInterval:1e3,liveStallReinitInterval:3e3},dashCmafLive:{externalStopControl:!1,keepSilentStallWatchdogWhenNotActive:!1,maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,maxLiveDuration:7200,catchupLiveForMutedInactiveTab:!0,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:250,playbackCatchupSpeedup:.05,isActiveOnDefault:!1,bufferEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:"07A4434E",chromecastNewProvider:!1,useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"dash",iosPreferredFormat:"hls",preferCMAF:!1,preferWebRTC:!1,preferMultiStream:!1,preferHDR:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,seekNearDurationBias:1,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useHlsJs:!1,useNativeHLSTextTracks:!1,useNewSwitchTo:!1,useNewDashProvider:!1,useNewAutoSelectVideoTrack:!1,useSafariEndlessRequestBugfix:!0,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,audioVideoSyncRate:20,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50},useVolumeMultiplier:!1,ignoreAudioRendererError:!1,useEnableSubtitlesParam:!1,useHlsLiveNewTextManager:!1,exposeInternalsToGlobal:!1,hlsLiveNewTextManagerDownloadThreshold:4e3,disableYandexPiP:!1,asyncResolveClientChecker:!1,autostartOnlyIfVisible:!1,changePlaybackStateToPausedWhenEnded:!1,suppressExceptionsInObservables:!0},KE=s=>{var e;return{...$_(s,YE),configName:[...(e=s.configName)!=null?e:[],...YE.configName]}};import{assertNonNullable as mp,combine as Ft,ErrorCategory as wu,filter as pe,filterChanged as K,fromEvent as bp,isNonNullable as ex,isNullable as __,Logger as O_,map as z,mapTo as tx,merge as ci,now as Au,once as Ee,Subject as W,Subscription as ix,tap as gp,ValueSubject as D,isHigher as F_,isInvariantQuality as rx,flattenObject as li,throttle as vp,getTraceSubscriptionMethod as sx,TracerFactory as N_,InternalsExposure as q_,getPlayerId as U_}from"@vkontakte/videoplayer-shared/es2018";import{merge as L_,map as M_,filter as XE,isNonNullable as C_}from"@vkontakte/videoplayer-shared/es2018";var fp=({seekState:s,position$:e})=>L_(s.stateChangeEnded$.pipe(M_(({to:t})=>{var i;return t.state==="none"?void 0:((i=t.position)!=null?i:NaN)/1e3}),XE(C_)),e.pipe(XE(()=>s.getState().state==="none")));import{assertNonNullable as D_}from"@vkontakte/videoplayer-shared/es2018";var JE=s=>{let e=typeof s.container=="string"?document.getElementById(s.container):s.container;return D_(e,`Wrong container or containerId {${s.container}}`),e};import{filter as B_,once as V_}from"@vkontakte/videoplayer-shared/es2018";var ZE=(s,e,t,i)=>{s!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&(t==null?void 0:t.getValue().length)===0?t.pipe(B_(r=>r.length>0),V_()).subscribe(r=>{r.find(i)&&e.startTransitionTo(s)}):(s===void 0||t!=null&&t.getValue().find(i))&&e.startTransitionTo(s)};var Pu=class{constructor(e={configName:[]},t=N_.createRootTracer(!1),i){this.subscription=new ix;this.logger=new O_;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 U("stopped"),seekState:new U({state:"none"}),volume:new U({volume:1,muted:!1}),videoTrack:new U(void 0),videoStream:new U(void 0),audioStream:new U(void 0),autoVideoTrackSwitching:new U(!0),autoVideoTrackLimits:new U({}),isLooped:new U(!1),isLowLatency:new U(!1),playbackRate:new U(1),externalTextTracks:new U([]),internalTextTracks:new U([]),currentTextTrack:new U(void 0),textTrackCuesSettings:new U({}),cameraOrientation:new U({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),canPlayLiveTailBuffer$:new D(!1),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 W,ready$:new W,started$:new W,playing$:new W,paused$:new W,stopped$:new W,willReady$:new W,willStart$:new W,willResume$:new W,willPause$:new W,willStop$:new W,willDestruct$:new W,watchCoverageRecord$:new W,watchCoverageLive$:new W,managedError$:new W,fatalError$:new W,fetcherRecoverableError$:new W,ended$:new W,looped$:new W,seeked$:new W,willSeek$:new W,autoplaySoundProhibited$:new W,manifestRequested$:new W,manifestReceived$:new W,firstBytesRequested$:new W,firstBytesReceived$:new W,firstBytes$:new W,loadedMetadata$:new W,firstFrame$:new W,canplay$:new W,log$:new W,fetcherError$:new W,severeStallOccured$:new W};this.experimental={element$:new D(void 0),tuningConfigName$:new D([]),enableDebugTelemetry$:new D(!1),dumpTelemetry:GS,getCurrentTime$:new D(null)};this.initLogs(),this.tuning=KE(e),this.tracer=t,this.tuning.suppressExceptionsInObservables&&((0,Sp.default)(this.info).forEach(a=>a.setSuppressErrors(!0)),(0,Sp.default)(this.events).forEach(a=>a.setSuppressErrors(!0))),this.experimental.tuningConfigName$.next(this.tuning.configName);let r={receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}};if(this.chromecastInitializer=this.tuning.chromecastNewProvider?new kt(r):new An(r),this.throughputEstimator=new zE(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new q_("core",U_(i==null?void 0:i.playerId)),this.internalsExposure.expose({player:this})),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(a,n,o)=>{let u=Reflect.get(a,n,o);return typeof u!="function"?u:(...c)=>{try{return u.apply(a,c)}catch(d){let l=c.map(f=>JSON.stringify(f,(m,g)=>{let b=typeof g;return(0,ax.default)(["number","string","boolean"],b)?g:g===null?null:`<${b}>`})),h=`Player.${String(n)}`,p=`Exception calling ${h} (${l.join(", ")})`;throw this.events.fatalError$.next({id:h,category:wu.WTF,message:p,thrown:d}),d}}}})}initVideo(e){var a;this.config=e,(a=this.internalsExposure)==null||a.expose({config:e,logger:this.logger,tuning:this.tuning}),this.setMuted(this.tuning.isAudioDisabled);let t=()=>{var u,c,d;let{container:n,...o}=e;this.tracer.log("initVideo",li(o)),this.domContainer=JE(e),this.chromecastInitializer.contentId=(u=e.meta)==null?void 0:u.videoId,this.providerContainer=new tn({sources:e.sources,meta:(c=e.meta)!=null?c:{},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?_.isInited$.pipe(pe(n=>!!n),Ee()).subscribe(()=>{console.log("Core SDK async start"),i()}):i()};return this.isNotActiveTabCase()?(this.tracer.log("request play from hidden tab"),bp(document,"visibilitychange").pipe(Ee()).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()}waitInit(e){this.playerInited.getValue()?e():this.subscription.add(this.playerInited.pipe(pe(t=>!!t),Ee()).subscribe(e))}prepare(){return this.waitInit(()=>{let e=this.desiredState.playbackState;this.tracer.log("prepare",{currentPlayBackState:e.getState()}),e.getState()==="stopped"&&e.startTransitionTo("ready")}),this}play(){return this.waitInit(()=>{let e=this.desiredState.playbackState;this.tracer.log("play",{currentPlayBackState:e.getState()}),e.getState()!=="playing"&&e.startTransitionTo("playing")}),this}pause(){return this.waitInit(()=>{let e=this.desiredState.playbackState;this.tracer.log("pause",{currentPlayBackState:e.getState()}),e.getState()!=="paused"&&e.startTransitionTo("paused")}),this}stop(){return this.waitInit(()=>{let e=this.desiredState.playbackState;this.tracer.log("stop",{currentPlayBackState:e.getState()}),e.getState()!=="stopped"&&e.startTransitionTo("stopped")}),this}seekTime(e,t=!0){return this.waitInit(()=>{let i=this.info.duration$.getValue(),r=this.info.isLive$.getValue(),a=e;e>=i&&!r&&(a=i-this.tuning.seekNearDurationBias),this.tracer.log("seekTime",{duration:i,isLive:r,time:e,calculatedTime:a,forcePrecise:t}),Number.isFinite(a)&&(this.events.willSeek$.next({from:this.getExactTime(),to:a}),this.desiredState.seekState.setState({state:"requested",position:a*1e3,forcePrecise:t}))}),this}seekPercent(e){return this.waitInit(()=>{let t=this.info.duration$.getValue();this.tracer.log("seekPercent",{percent:e,duration:t}),isFinite(t)&&this.seekTime(Math.abs(t)*e,!1)}),this}setVolume(e,t){return this.waitInit(()=>{var o;let i=this.desiredState.volume,r=i.getTransition(),a=(o=r==null?void 0:r.to.muted)!=null?o:this.info.muted$.getValue(),n=t!=null?t:this.tuning.isAudioDisabled||a;this.tracer.log("setVolume",{volume:e,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:n}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"&&!(this.chromecastInitializer instanceof kt)?this.chromecastInitializer.setVolume(e):i.startTransitionTo({volume:e,muted:n})}),this}setMuted(e,t=!1){return this.waitInit(()=>{var o;let i=this.desiredState.volume,r=this.tuning.isAudioDisabled&&!t||e,a=i.getTransition(),n=(o=a==null?void 0:a.to.volume)!=null?o:this.info.volume$.getValue();this.tracer.log("setMuted",{isMuted:e,nextMuted:r,volume:n,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue()}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"&&!(this.chromecastInitializer instanceof kt)?this.chromecastInitializer.setMuted(r):i.startTransitionTo({volume:n,muted:r})}),this}setVideoStream(e){return this.waitInit(()=>{this.desiredState.videoStream.startTransitionTo(e)}),this}setAudioStream(e){return this.waitInit(()=>{this.desiredState.audioStream.startTransitionTo(e)}),this}setQuality(e){return this.waitInit(()=>{mp(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(pe(i=>i.length>0),Ee()).subscribe(i=>{this.setVideoTrackIdByQuality(i,e)}):this.explicitInitialQuality=e:t.length>0&&this.setVideoTrackIdByQuality(t,e)}),this}setAutoQuality(e){return this.waitInit(()=>{this.tracer.log("setAutoQuality",{enable:e}),this.desiredState.autoVideoTrackSwitching.startTransitionTo(e)}),this}setAutoQualityLimits(e){return this.waitInit(()=>{this.tracer.log("setAutoQualityLimits",li(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e)}),this}setPredefinedQualityLimits(e){return this.waitInit(()=>{if(this.info.predefinedQualityLimitType$.getValue()===e)return this;let{highQualityLimit:t,trafficSavingLimit:i}=this.tuning.autoTrackSelection,r;switch(e){case"high_quality":r={min:t,max:void 0};break;case"traffic_saving":r={max:i,min:void 0};break;default:r={max:void 0,min:void 0}}this.setAutoQualityLimits(r)}),this}setPlaybackRate(e){return this.waitInit(()=>{this.tracer.log("setPlaybackRate",{playbackRate:e}),this.desiredState.playbackRate.startTransitionTo(e)}),this}setExternalTextTracks(e){return this.waitInit(()=>{e.length&&this.tracer.log("setExternalTextTracks",li(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t})))}),this}selectTextTrack(e){return this.waitInit(()=>{var t;ZE(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.waitInit(()=>{this.tracer.log("setTextTrackCueSettings",{...e}),this.desiredState.textTrackCuesSettings.startTransitionTo(e)}),this}setLiveLowLatency(e){let t=this.info.isLive$.getValue(),i=this.desiredState.isLowLatency.getState();return!t||i===e?this:(this.tracer.log("live switch to low latency "+e),this.desiredState.isLowLatency.setState(e),this.seekTime(0))}setLooped(e){return this.waitInit(()=>{this.tracer.log("setLooped",{isLooped:e}),this.desiredState.isLooped.startTransitionTo(e)}),this}toggleChromecast(){this.tracer.log("toggleChromecast"),this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){return this.waitInit(()=>{let i=this.getScene3D();this.tracer.log("startCameraManualRotation",{isScene3DAvailable:!!i,mx:e,my:t}),i&&i.startCameraManualRotation(e,t)}),this}stopCameraManualRotation(e=!1){return this.waitInit(()=>{let t=this.getScene3D();this.tracer.log("stopCameraManualRotation",{isScene3DAvailable:!!t,immediate:e}),t&&t.stopCameraManualRotation(e)}),this}moveCameraFocusPX(e,t){return this.waitInit(()=>{let i=this.getScene3D();if(this.tracer.log("moveCameraFocusPX",{isScene3DAvailable:!!i,dxpx:e,dypx:t}),i){let r=i.getCameraRotation(),a=i.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:r.x+a.x,y:r.y+a.y})}}),this}holdCamera(){return this.waitInit(()=>{let e=this.getScene3D();e&&e.holdCamera()}),this}releaseCamera(){return this.waitInit(()=>{let e=this.getScene3D();e&&e.releaseCamera()}),this}getExactTime(){if(!this.providerContainer)return 0;let e=this.providerContainer.providerOutput.element$.getValue();if(__(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),i=t.state==="none"?void 0:t.position;return ex(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(ci(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(YS(e,t,i))})),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(pe(({from:e})=>e==="stopped"),Ee()).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",li(n)),n.state==="requested"?this.desiredState.seekState.setState({...n,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:wu.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe(Ee()).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",li(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(Ft({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,c)=>rx(u)?1:rx(c)?-1:F_(c,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(pe(n=>ex(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(gp(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(Ft({hasLiveOffsetByPaused:ci(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(Ft({atLiveEdge:Ft({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:fp({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(z(({isLive:n,position:o,isLowLatency:u})=>{let c=this.getActiveLiveDelay(u);return n&&Math.abs(o)<c/1e3}),K(),gp(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(z(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add(Ft({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(),gp(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(fp({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(e.providerOutput.seekedEvent$.subscribe(()=>{this.info.isEnded$.getValue()&&this.tuning.changePlaybackStateToPausedWhenEnded&&this.play()})).add(ci(e.providerOutput.endedEvent$.pipe(tx(!0)),e.providerOutput.seekedEvent$.pipe(tx(!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:wu.VIDEO_PIPELINE,message:n?`${n} was forced but failed or not available`:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.getCurrentTime$.subscribe(this.experimental.getCurrentTime$)).add(e.providerOutput.manifestRequested$.pipe(Ee()).subscribe(this.events.manifestRequested$)).add(e.providerOutput.manifestReceived$.pipe(Ee()).subscribe(this.events.manifestReceived$)).add(e.providerOutput.firstBytesRequested$.pipe(Ee()).subscribe(this.events.firstBytesRequested$)).add(e.providerOutput.firstBytesReceived$.pipe(Ee()).subscribe(this.events.firstBytesReceived$)).add(e.providerOutput.firstBytesEvent$.pipe(Ee(),z(n=>n!=null?n:Au()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(Ee(),z(()=>Au()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(Ee(),z(()=>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 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(pe(({to:n})=>n==="playing"),Ee()).subscribe(()=>i.next(!1)));let r=0,a=ci(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(a.subscribe(n=>{n?r=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(r),this.info.isStalled$.next(!1))})),this.subscription.add(ci(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,c;let o=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:(u=n==null?void 0:n.size)==null?void 0:u.width,height:(c=n==null?void 0:n.size)==null?void 0:c.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(ci(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(),c=e.providerOutput.elementVisible$.getValue(),d=this.chromecastInitializer.castState$.getValue(),l;d==="CONNECTED"?l="second_screen":u?c?n?l="pip":o?l="fullscreen":l="inline":l="invisible":l="none",this.info.surface$.getValue()!==l&&this.info.surface$.next(l)}))}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 ix;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(pe(i=>i.length>0),Ee()).subscribe(i=>{this.setStartingVideoTrack(i)}))}))}setStartingVideoTrack(e){var r;let t;this.wasSetStartedQuality=!0;let i=(r=this.explicitInitialQuality)!=null?r:this.info.currentQuality$.getValue();i&&(t=e.find(({quality:a})=>a===i),t||this.setAutoQuality(!0)),t||(t=yt(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(ci(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;mp(this.providerContainer),mp(e),QS(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(i=>WS(i)),this.providerContainer.current$.subscribe(({type:i})=>Bs("provider",i)),e.duration$.subscribe(i=>Bs("duration",i)),e.availableVideoTracks$.pipe(pe(i=>!!i.length),Ee()).subscribe(i=>Bs("tracks",i)),this.events.fatalError$.subscribe(new ke("fatalError")),this.events.managedError$.subscribe(new ke("managedError")),e.position$.subscribe(new ke("position")),e.currentVideoTrack$.pipe(z(i=>i==null?void 0:i.quality)).subscribe(new ke("quality")),this.info.currentBuffer$.subscribe(new ke("buffer")),e.isBuffering$.subscribe(new ke("isBuffering"))].forEach(i=>this.subscription.add(i)),Bs("codecs",_.video.supportedCodecs)}initTracerSubscription(){let e=sx(this.tracer.log.bind(this.tracer)),t=sx(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(Ft({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe(pe(({currentQuality:i,videoBitrate:r})=>!!i&&!!r),K((i,r)=>i.currentQuality===r.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe(pe(i=>i>0),K()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe(pe(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(Ft({currentBuffer:this.info.currentBuffer$.pipe(pe(i=>i.end>0),K((i,r)=>i.end===r.end&&i.start===r.start)),position:this.info.position$.pipe(K())}).pipe(vp(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(Ft({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(pe(({liveTime:i,liveBufferTime:r})=>!!i&&!!r),vp(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(K(),pe(i=>i===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(K(),pe(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(),pe(i=>i===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add(Ft({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(pe(({throughputEstimation:i,rtt:r})=>!!i&&!!r),vp(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(K(),pe(i=>i===!0)).subscribe(e("is3DVideo"))).add(this.info.surface$.subscribe(e("surface"))).add(this.events.ended$.subscribe(e("ended"))).add(this.events.looped$.subscribe(e("looped"))).add(this.events.managedError$.subscribe(t("managedError"))).add(this.events.fatalError$.subscribe(t("fatalError"))).add(this.events.firstBytes$.subscribe(e("firstBytes"))).add(this.events.firstFrame$.subscribe(e("firstFrame"))).add(this.events.canplay$.subscribe(e("canplay")))}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e,t=()=>{e==null||e.release(),e=void 0},i=async()=>{t(),e=await window.navigator.wakeLock.request("screen").catch(r=>{r instanceof DOMException&&r.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:wu.DOM,message:String(r)})})};this.subscription.add(ci(bp(document,"visibilitychange"),bp(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let r=document.visibilityState==="visible",a=this.desiredState.playbackState.getState()==="playing",n=!!e&&!(e!=null&&e.released);r&&a?n||i():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let i=e.find(r=>r.quality===t);this.tracer.log("setVideoTrackIdByQuality",li({quality:t,availableTracks:li(e),track:li(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&&!Us()}};import{Subscription as nZ,Observable as oZ,Subject as uZ,ValueSubject as cZ,VideoQuality as lZ}from"@vkontakte/videoplayer-shared/es2018";var dZ=`@vkontakte/videoplayer-core@${ah}`;export{es as ChromecastState,Cu as HttpConnectionType,oZ as Observable,we as PlaybackState,Pu as Player,gn as PredefinedQualityLimits,dZ as SDK_VERSION,uZ as Subject,nZ as Subscription,Du as Surface,ah as VERSION,cZ as ValueSubject,Pt as VideoFormat,lZ as VideoQuality,MP as areValidLiveRecordSources,_ as clientChecker,hs as isMobile};
|