@vkontakte/videoplayer-core 2.0.135-dev.de6f0c74.0 → 2.0.135-dev.ee4a31cc.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 +20 -20
- package/es2015.esm.js +24 -24
- package/es2018.cjs.js +25 -25
- package/es2018.esm.js +18 -18
- package/es2024.cjs.js +26 -26
- package/es2024.esm.js +23 -23
- package/esnext.cjs.js +26 -26
- package/esnext.esm.js +23 -23
- package/evergreen.esm.js +17 -17
- package/package.json +2 -2
- package/types/providers/DashProvider/baseDashProvider.d.ts +2 -0
- package/types/providers/DashProviderNew/baseDashProvider.d.ts +2 -0
package/es2015.esm.js
CHANGED
|
@@ -1,19 +1,19 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @vkontakte/videoplayer-core v2.0.135-dev.
|
|
3
|
-
* Tue,
|
|
2
|
+
* @vkontakte/videoplayer-core v2.0.135-dev.ee4a31cc.0
|
|
3
|
+
* Tue, 01 Jul 2025 11:59:49 GMT
|
|
4
4
|
* https://st.mycdn.me/static/vkontakte-videoplayer/2-0-135/doc/
|
|
5
5
|
*/
|
|
6
|
-
var qE=Object.create;var ql=Object.defineProperty,jE=Object.defineProperties,HE=Object.getOwnPropertyDescriptor,zE=Object.getOwnPropertyDescriptors,QE=Object.getOwnPropertyNames,wo=Object.getOwnPropertySymbols,GE=Object.getPrototypeOf,jl=Object.prototype.hasOwnProperty,Uh=Object.prototype.propertyIsEnumerable;var WE=(s,e)=>(e=Symbol[s])?e:Symbol.for("Symbol."+s);var Ze=Math.pow,Nh=(s,e,t)=>e in s?ql(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,x=(s,e)=>{for(var t in e||(e={}))jl.call(e,t)&&Nh(s,t,e[t]);if(wo)for(var t of wo(e))Uh.call(e,t)&&Nh(s,t,e[t]);return s},B=(s,e)=>jE(s,zE(e));var qh=(s,e)=>{var t={};for(var i in s)jl.call(s,i)&&e.indexOf(i)<0&&(t[i]=s[i]);if(s!=null&&wo)for(var i of wo(s))e.indexOf(i)<0&&Uh.call(s,i)&&(t[i]=s[i]);return t};var b=(s,e)=>()=>(e||s((e={exports:{}}).exports,e),e.exports);var YE=(s,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of QE(e))!jl.call(s,r)&&r!==t&&ql(s,r,{get:()=>e[r],enumerable:!(i=HE(e,r))||i.enumerable});return s};var H=(s,e,t)=>(t=s!=null?qE(GE(s)):{},YE(e||!s||!s.__esModule?ql(t,"default",{value:s,enumerable:!0}):t,s));var E=(s,e,t)=>new Promise((i,r)=>{var a=u=>{try{o(t.next(u))}catch(l){r(l)}},n=u=>{try{o(t.throw(u))}catch(l){r(l)}},o=u=>u.done?i(u.value):Promise.resolve(u.value).then(a,n);o((t=t.apply(s,e)).next())}),Zi=function(s,e){this[0]=s,this[1]=e},X=(s,e,t)=>{var i=(n,o,u,l)=>{try{var d=t[n](o),c=(o=d.value)instanceof Zi,h=d.done;Promise.resolve(c?o[0]:o).then(p=>c?i(n==="return"?n:"next",o[1]?{done:p.done,value:p.value}:p,u,l):u({value:p,done:h})).catch(p=>i("throw",p,u,l))}catch(p){l(p)}},r=n=>a[n]=o=>new Promise((u,l)=>i(n,o,u,l)),a={};return t=t.apply(s,e),a[WE("asyncIterator")]=()=>a,r("next"),r("throw"),r("return"),a};var xe=b((Ql,Hh)=>{"use strict";var na=function(s){return s&&s.Math===Math&&s};Hh.exports=na(typeof globalThis=="object"&&globalThis)||na(typeof window=="object"&&window)||na(typeof self=="object"&&self)||na(typeof global=="object"&&global)||na(typeof Ql=="object"&&Ql)||function(){return this}()||Function("return this")()});var Ue=b((l_,zh)=>{"use strict";zh.exports=function(s){try{return!!s()}catch(e){return!0}}});var oa=b((c_,Qh)=>{"use strict";var KE=Ue();Qh.exports=!KE(function(){var s=function(){}.bind();return typeof s!="function"||s.hasOwnProperty("prototype")})});var Gl=b((d_,Kh)=>{"use strict";var XE=oa(),Yh=Function.prototype,Gh=Yh.apply,Wh=Yh.call;Kh.exports=typeof Reflect=="object"&&Reflect.apply||(XE?Wh.bind(Gh):function(){return Wh.apply(Gh,arguments)})});var Ce=b((p_,Zh)=>{"use strict";var Xh=oa(),Jh=Function.prototype,Wl=Jh.call,JE=Xh&&Jh.bind.bind(Wl,Wl);Zh.exports=Xh?JE:function(s){return function(){return Wl.apply(s,arguments)}}});var er=b((h_,tf)=>{"use strict";var ef=Ce(),ZE=ef({}.toString),ew=ef("".slice);tf.exports=function(s){return ew(ZE(s),8,-1)}});var Yl=b((f_,rf)=>{"use strict";var tw=er(),iw=Ce();rf.exports=function(s){if(tw(s)==="Function")return iw(s)}});var Te=b((m_,sf)=>{"use strict";var Kl=typeof document=="object"&&document.all;sf.exports=typeof Kl=="undefined"&&Kl!==void 0?function(s){return typeof s=="function"||s===Kl}:function(s){return typeof s=="function"}});var vt=b((b_,af)=>{"use strict";var rw=Ue();af.exports=!rw(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var yt=b((g_,nf)=>{"use strict";var sw=oa(),Ro=Function.prototype.call;nf.exports=sw?Ro.bind(Ro):function(){return Ro.apply(Ro,arguments)}});var Xl=b(lf=>{"use strict";var of={}.propertyIsEnumerable,uf=Object.getOwnPropertyDescriptor,aw=uf&&!of.call({1:2},1);lf.f=aw?function(e){var t=uf(this,e);return!!t&&t.enumerable}:of});var ua=b((v_,cf)=>{"use strict";cf.exports=function(s,e){return{enumerable:!(s&1),configurable:!(s&2),writable:!(s&4),value:e}}});var pf=b((y_,df)=>{"use strict";var nw=Ce(),ow=Ue(),uw=er(),Jl=Object,lw=nw("".split);df.exports=ow(function(){return!Jl("z").propertyIsEnumerable(0)})?function(s){return uw(s)==="String"?lw(s,""):Jl(s)}:Jl});var Pr=b((T_,hf)=>{"use strict";hf.exports=function(s){return s==null}});var Bi=b((I_,ff)=>{"use strict";var cw=Pr(),dw=TypeError;ff.exports=function(s){if(cw(s))throw new dw("Can't call method on "+s);return s}});var tr=b((x_,mf)=>{"use strict";var pw=pf(),hw=Bi();mf.exports=function(s){return pw(hw(s))}});var Tt=b((E_,bf)=>{"use strict";var fw=Te();bf.exports=function(s){return typeof s=="object"?s!==null:fw(s)}});var Rr=b((w_,gf)=>{"use strict";gf.exports={}});var gi=b((A_,vf)=>{"use strict";var Zl=Rr(),ec=xe(),mw=Te(),Sf=function(s){return mw(s)?s:void 0};vf.exports=function(s,e){return arguments.length<2?Sf(Zl[s])||Sf(ec[s]):Zl[s]&&Zl[s][e]||ec[s]&&ec[s][e]}});var la=b((P_,yf)=>{"use strict";var bw=Ce();yf.exports=bw({}.isPrototypeOf)});var ir=b((R_,xf)=>{"use strict";var gw=xe(),Tf=gw.navigator,If=Tf&&Tf.userAgent;xf.exports=If?String(If):""});var ic=b((k_,kf)=>{"use strict";var Rf=xe(),tc=ir(),Ef=Rf.process,wf=Rf.Deno,Af=Ef&&Ef.versions||wf&&wf.version,Pf=Af&&Af.v8,_t,ko;Pf&&(_t=Pf.split("."),ko=_t[0]>0&&_t[0]<4?1:+(_t[0]+_t[1]));!ko&&tc&&(_t=tc.match(/Edge\/(\d+)/),(!_t||_t[1]>=74)&&(_t=tc.match(/Chrome\/(\d+)/),_t&&(ko=+_t[1])));kf.exports=ko});var rc=b((M_,Lf)=>{"use strict";var Mf=ic(),Sw=Ue(),vw=xe(),yw=vw.String;Lf.exports=!!Object.getOwnPropertySymbols&&!Sw(function(){var s=Symbol("symbol detection");return!yw(s)||!(Object(s)instanceof Symbol)||!Symbol.sham&&Mf&&Mf<41})});var sc=b((L_,Bf)=>{"use strict";var Tw=rc();Bf.exports=Tw&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var ac=b((B_,$f)=>{"use strict";var Iw=gi(),xw=Te(),Ew=la(),ww=sc(),Aw=Object;$f.exports=ww?function(s){return typeof s=="symbol"}:function(s){var e=Iw("Symbol");return xw(e)&&Ew(e.prototype,Aw(s))}});var ca=b(($_,Df)=>{"use strict";var Pw=String;Df.exports=function(s){try{return Pw(s)}catch(e){return"Object"}}});var Wt=b((D_,Cf)=>{"use strict";var Rw=Te(),kw=ca(),Mw=TypeError;Cf.exports=function(s){if(Rw(s))return s;throw new Mw(kw(s)+" is not a function")}});var da=b((C_,Vf)=>{"use strict";var Lw=Wt(),Bw=Pr();Vf.exports=function(s,e){var t=s[e];return Bw(t)?void 0:Lw(t)}});var _f=b((V_,Of)=>{"use strict";var nc=yt(),oc=Te(),uc=Tt(),$w=TypeError;Of.exports=function(s,e){var t,i;if(e==="string"&&oc(t=s.toString)&&!uc(i=nc(t,s))||oc(t=s.valueOf)&&!uc(i=nc(t,s))||e!=="string"&&oc(t=s.toString)&&!uc(i=nc(t,s)))return i;throw new $w("Can't convert object to primitive value")}});var Ft=b((O_,Ff)=>{"use strict";Ff.exports=!0});var qf=b((__,Uf)=>{"use strict";var Nf=xe(),Dw=Object.defineProperty;Uf.exports=function(s,e){try{Dw(Nf,s,{value:e,configurable:!0,writable:!0})}catch(t){Nf[s]=e}return e}});var pa=b((F_,zf)=>{"use strict";var Cw=Ft(),Vw=xe(),Ow=qf(),jf="__core-js_shared__",Hf=zf.exports=Vw[jf]||Ow(jf,{});(Hf.versions||(Hf.versions=[])).push({version:"3.38.0",mode:Cw?"pure":"global",copyright:"\xA9 2014-2024 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.38.0/LICENSE",source:"https://github.com/zloirock/core-js"})});var lc=b((N_,Gf)=>{"use strict";var Qf=pa();Gf.exports=function(s,e){return Qf[s]||(Qf[s]=e||{})}});var kr=b((U_,Wf)=>{"use strict";var _w=Bi(),Fw=Object;Wf.exports=function(s){return Fw(_w(s))}});var Nt=b((q_,Yf)=>{"use strict";var Nw=Ce(),Uw=kr(),qw=Nw({}.hasOwnProperty);Yf.exports=Object.hasOwn||function(e,t){return qw(Uw(e),t)}});var cc=b((j_,Kf)=>{"use strict";var jw=Ce(),Hw=0,zw=Math.random(),Qw=jw(1 .toString);Kf.exports=function(s){return"Symbol("+(s===void 0?"":s)+")_"+Qw(++Hw+zw,36)}});var qe=b((H_,Jf)=>{"use strict";var Gw=xe(),Ww=lc(),Xf=Nt(),Yw=cc(),Kw=rc(),Xw=sc(),Mr=Gw.Symbol,dc=Ww("wks"),Jw=Xw?Mr.for||Mr:Mr&&Mr.withoutSetter||Yw;Jf.exports=function(s){return Xf(dc,s)||(dc[s]=Kw&&Xf(Mr,s)?Mr[s]:Jw("Symbol."+s)),dc[s]}});var im=b((z_,tm)=>{"use strict";var Zw=yt(),Zf=Tt(),em=ac(),eA=da(),tA=_f(),iA=qe(),rA=TypeError,sA=iA("toPrimitive");tm.exports=function(s,e){if(!Zf(s)||em(s))return s;var t=eA(s,sA),i;if(t){if(e===void 0&&(e="default"),i=Zw(t,s,e),!Zf(i)||em(i))return i;throw new rA("Can't convert object to primitive value")}return e===void 0&&(e="number"),tA(s,e)}});var pc=b((Q_,rm)=>{"use strict";var aA=im(),nA=ac();rm.exports=function(s){var e=aA(s,"string");return nA(e)?e:e+""}});var Mo=b((G_,am)=>{"use strict";var oA=xe(),sm=Tt(),hc=oA.document,uA=sm(hc)&&sm(hc.createElement);am.exports=function(s){return uA?hc.createElement(s):{}}});var fc=b((W_,nm)=>{"use strict";var lA=vt(),cA=Ue(),dA=Mo();nm.exports=!lA&&!cA(function(){return Object.defineProperty(dA("div"),"a",{get:function(){return 7}}).a!==7})});var lm=b(um=>{"use strict";var pA=vt(),hA=yt(),fA=Xl(),mA=ua(),bA=tr(),gA=pc(),SA=Nt(),vA=fc(),om=Object.getOwnPropertyDescriptor;um.f=pA?om:function(e,t){if(e=bA(e),t=gA(t),vA)try{return om(e,t)}catch(i){}if(SA(e,t))return mA(!hA(fA.f,e,t),e[t])}});var mc=b((K_,cm)=>{"use strict";var yA=Ue(),TA=Te(),IA=/#|\.prototype\./,ha=function(s,e){var t=EA[xA(s)];return t===AA?!0:t===wA?!1:TA(e)?yA(e):!!e},xA=ha.normalize=function(s){return String(s).replace(IA,".").toLowerCase()},EA=ha.data={},wA=ha.NATIVE="N",AA=ha.POLYFILL="P";cm.exports=ha});var Lr=b((X_,pm)=>{"use strict";var dm=Yl(),PA=Wt(),RA=oa(),kA=dm(dm.bind);pm.exports=function(s,e){return PA(s),e===void 0?s:RA?kA(s,e):function(){return s.apply(e,arguments)}}});var bc=b((J_,hm)=>{"use strict";var MA=vt(),LA=Ue();hm.exports=MA&&LA(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var Yt=b((Z_,fm)=>{"use strict";var BA=Tt(),$A=String,DA=TypeError;fm.exports=function(s){if(BA(s))return s;throw new DA($A(s)+" is not an object")}});var rr=b(bm=>{"use strict";var CA=vt(),VA=fc(),OA=bc(),Lo=Yt(),mm=pc(),_A=TypeError,gc=Object.defineProperty,FA=Object.getOwnPropertyDescriptor,Sc="enumerable",vc="configurable",yc="writable";bm.f=CA?OA?function(e,t,i){if(Lo(e),t=mm(t),Lo(i),typeof e=="function"&&t==="prototype"&&"value"in i&&yc in i&&!i[yc]){var r=FA(e,t);r&&r[yc]&&(e[t]=i.value,i={configurable:vc in i?i[vc]:r[vc],enumerable:Sc in i?i[Sc]:r[Sc],writable:!1})}return gc(e,t,i)}:gc:function(e,t,i){if(Lo(e),t=mm(t),Lo(i),VA)try{return gc(e,t,i)}catch(r){}if("get"in i||"set"in i)throw new _A("Accessors not supported");return"value"in i&&(e[t]=i.value),e}});var Br=b((tF,gm)=>{"use strict";var NA=vt(),UA=rr(),qA=ua();gm.exports=NA?function(s,e,t){return UA.f(s,e,qA(1,t))}:function(s,e,t){return s[e]=t,s}});var Re=b((iF,vm)=>{"use strict";var fa=xe(),jA=Gl(),HA=Yl(),zA=Te(),QA=lm().f,GA=mc(),$r=Rr(),WA=Lr(),Dr=Br(),Sm=Nt();pa();var YA=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 jA(s,this,arguments)};return e.prototype=s.prototype,e};vm.exports=function(s,e){var t=s.target,i=s.global,r=s.stat,a=s.proto,n=i?fa:r?fa[t]:fa[t]&&fa[t].prototype,o=i?$r:$r[t]||Dr($r,t,{})[t],u=o.prototype,l,d,c,h,p,f,m,g,S;for(h in e)l=GA(i?h:t+(r?".":"#")+h,s.forced),d=!l&&n&&Sm(n,h),f=o[h],d&&(s.dontCallGetSet?(S=QA(n,h),m=S&&S.value):m=n[h]),p=d&&m?m:e[h],!(!l&&!a&&typeof f==typeof p)&&(s.bind&&d?g=WA(p,fa):s.wrap&&d?g=YA(p):a&&zA(p)?g=HA(p):g=p,(s.sham||p&&p.sham||f&&f.sham)&&Dr(g,"sham",!0),Dr(o,h,g),a&&(c=t+"Prototype",Sm($r,c)||Dr($r,c,{}),Dr($r[c],h,p),s.real&&u&&(l||!u[h])&&Dr(u,h,p)))}});var Tm=b((rF,ym)=>{"use strict";var KA=Math.ceil,XA=Math.floor;ym.exports=Math.trunc||function(e){var t=+e;return(t>0?XA:KA)(t)}});var ma=b((sF,Im)=>{"use strict";var JA=Tm();Im.exports=function(s){var e=+s;return e!==e||e===0?0:JA(e)}});var Em=b((aF,xm)=>{"use strict";var ZA=ma(),eP=Math.max,tP=Math.min;xm.exports=function(s,e){var t=ZA(s);return t<0?eP(t+e,0):tP(t,e)}});var Tc=b((nF,wm)=>{"use strict";var iP=ma(),rP=Math.min;wm.exports=function(s){var e=iP(s);return e>0?rP(e,9007199254740991):0}});var Cr=b((oF,Am)=>{"use strict";var sP=Tc();Am.exports=function(s){return sP(s.length)}});var Ic=b((uF,Rm)=>{"use strict";var aP=tr(),nP=Em(),oP=Cr(),Pm=function(s){return function(e,t,i){var r=aP(e),a=oP(r);if(a===0)return!s&&-1;var n=nP(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}};Rm.exports={includes:Pm(!0),indexOf:Pm(!1)}});var ba=b((lF,km)=>{"use strict";km.exports=function(){}});var Mm=b(()=>{"use strict";var uP=Re(),lP=Ic().includes,cP=Ue(),dP=ba(),pP=cP(function(){return!Array(1).includes()});uP({target:"Array",proto:!0,forced:pP},{includes:function(e){return lP(this,e,arguments.length>1?arguments[1]:void 0)}});dP("includes")});var $i=b((pF,Lm)=>{"use strict";var hP=gi();Lm.exports=hP});var $m=b((hF,Bm)=>{"use strict";Mm();var fP=$i();Bm.exports=fP("Array","includes")});var Cm=b((fF,Dm)=>{"use strict";var mP=$m();Dm.exports=mP});var It=b((mF,Vm)=>{"use strict";var bP=Cm();Vm.exports=bP});var Do=b((PF,Hm)=>{"use strict";var EP=lc(),wP=cc(),jm=EP("keys");Hm.exports=function(s){return jm[s]||(jm[s]=wP(s))}});var Qm=b((RF,zm)=>{"use strict";var AP=Ue();zm.exports=!AP(function(){function s(){}return s.prototype.constructor=null,Object.getPrototypeOf(new s)!==s.prototype})});var Co=b((kF,Wm)=>{"use strict";var PP=Nt(),RP=Te(),kP=kr(),MP=Do(),LP=Qm(),Gm=MP("IE_PROTO"),wc=Object,BP=wc.prototype;Wm.exports=LP?wc.getPrototypeOf:function(s){var e=kP(s);if(PP(e,Gm))return e[Gm];var t=e.constructor;return RP(t)&&e instanceof t?t.prototype:e instanceof wc?BP:null}});var Vo=b((MF,Ym)=>{"use strict";Ym.exports={}});var Jm=b((LF,Xm)=>{"use strict";var $P=Ce(),Ac=Nt(),DP=tr(),CP=Ic().indexOf,VP=Vo(),Km=$P([].push);Xm.exports=function(s,e){var t=DP(s),i=0,r=[],a;for(a in t)!Ac(VP,a)&&Ac(t,a)&&Km(r,a);for(;e.length>i;)Ac(t,a=e[i++])&&(~CP(r,a)||Km(r,a));return r}});var Pc=b((BF,Zm)=>{"use strict";Zm.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var Rc=b(($F,eb)=>{"use strict";var OP=Jm(),_P=Pc();eb.exports=Object.keys||function(e){return OP(e,_P)}});var kc=b((DF,ab)=>{"use strict";var ib=vt(),FP=Ue(),rb=Ce(),NP=Co(),UP=Rc(),qP=tr(),jP=Xl().f,sb=rb(jP),HP=rb([].push),zP=ib&&FP(function(){var s=Object.create(null);return s[2]=2,!sb(s,2)}),tb=function(s){return function(e){for(var t=qP(e),i=UP(t),r=zP&&NP(t)===null,a=i.length,n=0,o=[],u;a>n;)u=i[n++],(!ib||(r?u in t:sb(t,u)))&&HP(o,s?[u,t[u]]:t[u]);return o}};ab.exports={entries:tb(!0),values:tb(!1)}});var nb=b(()=>{"use strict";var QP=Re(),GP=kc().entries;QP({target:"Object",stat:!0},{entries:function(e){return GP(e)}})});var ub=b((OF,ob)=>{"use strict";nb();var WP=Rr();ob.exports=WP.Object.entries});var cb=b((_F,lb)=>{"use strict";var YP=ub();lb.exports=YP});var sr=b((FF,db)=>{"use strict";var KP=cb();db.exports=KP});var ar=b((NF,pb)=>{"use strict";pb.exports={}});var mb=b((UF,fb)=>{"use strict";var XP=xe(),JP=Te(),hb=XP.WeakMap;fb.exports=JP(hb)&&/native code/.test(String(hb))});var $c=b((qF,Sb)=>{"use strict";var ZP=mb(),gb=xe(),eR=Tt(),tR=Br(),Mc=Nt(),Lc=pa(),iR=Do(),rR=Vo(),bb="Object already initialized",Bc=gb.TypeError,sR=gb.WeakMap,Oo,ga,_o,aR=function(s){return _o(s)?ga(s):Oo(s,{})},nR=function(s){return function(e){var t;if(!eR(e)||(t=ga(e)).type!==s)throw new Bc("Incompatible receiver, "+s+" required");return t}};ZP||Lc.state?(Ut=Lc.state||(Lc.state=new sR),Ut.get=Ut.get,Ut.has=Ut.has,Ut.set=Ut.set,Oo=function(s,e){if(Ut.has(s))throw new Bc(bb);return e.facade=s,Ut.set(s,e),e},ga=function(s){return Ut.get(s)||{}},_o=function(s){return Ut.has(s)}):(nr=iR("state"),rR[nr]=!0,Oo=function(s,e){if(Mc(s,nr))throw new Bc(bb);return e.facade=s,tR(s,nr,e),e},ga=function(s){return Mc(s,nr)?s[nr]:{}},_o=function(s){return Mc(s,nr)});var Ut,nr;Sb.exports={set:Oo,get:ga,has:_o,enforce:aR,getterFor:nR}});var Vc=b((jF,yb)=>{"use strict";var Dc=vt(),oR=Nt(),vb=Function.prototype,uR=Dc&&Object.getOwnPropertyDescriptor,Cc=oR(vb,"name"),lR=Cc&&function(){}.name==="something",cR=Cc&&(!Dc||Dc&&uR(vb,"name").configurable);yb.exports={EXISTS:Cc,PROPER:lR,CONFIGURABLE:cR}});var Ib=b(Tb=>{"use strict";var dR=vt(),pR=bc(),hR=rr(),fR=Yt(),mR=tr(),bR=Rc();Tb.f=dR&&!pR?Object.defineProperties:function(e,t){fR(e);for(var i=mR(t),r=bR(t),a=r.length,n=0,o;a>n;)hR.f(e,o=r[n++],i[o]);return e}});var Oc=b((zF,xb)=>{"use strict";var gR=gi();xb.exports=gR("document","documentElement")});var Uc=b((QF,Mb)=>{"use strict";var SR=Yt(),vR=Ib(),Eb=Pc(),yR=Vo(),TR=Oc(),IR=Mo(),xR=Do(),wb=">",Ab="<",Fc="prototype",Nc="script",Rb=xR("IE_PROTO"),_c=function(){},kb=function(s){return Ab+Nc+wb+s+Ab+"/"+Nc+wb},Pb=function(s){s.write(kb("")),s.close();var e=s.parentWindow.Object;return s=null,e},ER=function(){var s=IR("iframe"),e="java"+Nc+":",t;return s.style.display="none",TR.appendChild(s),s.src=String(e),t=s.contentWindow.document,t.open(),t.write(kb("document.F=Object")),t.close(),t.F},Fo,No=function(){try{Fo=new ActiveXObject("htmlfile")}catch(e){}No=typeof document!="undefined"?document.domain&&Fo?Pb(Fo):ER():Pb(Fo);for(var s=Eb.length;s--;)delete No[Fc][Eb[s]];return No()};yR[Rb]=!0;Mb.exports=Object.create||function(e,t){var i;return e!==null?(_c[Fc]=SR(e),i=new _c,_c[Fc]=null,i[Rb]=e):i=No(),t===void 0?i:vR.f(i,t)}});var Vr=b((GF,Lb)=>{"use strict";var wR=Br();Lb.exports=function(s,e,t,i){return i&&i.enumerable?s[e]=t:wR(s,e,t),s}});var zc=b((WF,Db)=>{"use strict";var AR=Ue(),PR=Te(),RR=Tt(),kR=Uc(),Bb=Co(),MR=Vr(),LR=qe(),BR=Ft(),Hc=LR("iterator"),$b=!1,Si,qc,jc;[].keys&&(jc=[].keys(),"next"in jc?(qc=Bb(Bb(jc)),qc!==Object.prototype&&(Si=qc)):$b=!0);var $R=!RR(Si)||AR(function(){var s={};return Si[Hc].call(s)!==s});$R?Si={}:BR&&(Si=kR(Si));PR(Si[Hc])||MR(Si,Hc,function(){return this});Db.exports={IteratorPrototype:Si,BUGGY_SAFARI_ITERATORS:$b}});var Uo=b((YF,Vb)=>{"use strict";var DR=qe(),CR=DR("toStringTag"),Cb={};Cb[CR]="z";Vb.exports=String(Cb)==="[object z]"});var Sa=b((KF,Ob)=>{"use strict";var VR=Uo(),OR=Te(),qo=er(),_R=qe(),FR=_R("toStringTag"),NR=Object,UR=qo(function(){return arguments}())==="Arguments",qR=function(s,e){try{return s[e]}catch(t){}};Ob.exports=VR?qo:function(s){var e,t,i;return s===void 0?"Undefined":s===null?"Null":typeof(t=qR(e=NR(s),FR))=="string"?t:UR?qo(e):(i=qo(e))==="Object"&&OR(e.callee)?"Arguments":i}});var Fb=b((XF,_b)=>{"use strict";var jR=Uo(),HR=Sa();_b.exports=jR?{}.toString:function(){return"[object "+HR(this)+"]"}});var va=b((JF,Ub)=>{"use strict";var zR=Uo(),QR=rr().f,GR=Br(),WR=Nt(),YR=Fb(),KR=qe(),Nb=KR("toStringTag");Ub.exports=function(s,e,t,i){var r=t?s:s&&s.prototype;r&&(WR(r,Nb)||QR(r,Nb,{configurable:!0,value:e}),i&&!zR&&GR(r,"toString",YR))}});var jb=b((ZF,qb)=>{"use strict";var XR=zc().IteratorPrototype,JR=Uc(),ZR=ua(),ek=va(),tk=ar(),ik=function(){return this};qb.exports=function(s,e,t,i){var r=e+" Iterator";return s.prototype=JR(XR,{next:ZR(+!i,t)}),ek(s,r,!1,!0),tk[r]=ik,s}});var zb=b((eN,Hb)=>{"use strict";var rk=Ce(),sk=Wt();Hb.exports=function(s,e,t){try{return rk(sk(Object.getOwnPropertyDescriptor(s,e)[t]))}catch(i){}}});var Gb=b((tN,Qb)=>{"use strict";var ak=Tt();Qb.exports=function(s){return ak(s)||s===null}});var Yb=b((iN,Wb)=>{"use strict";var nk=Gb(),ok=String,uk=TypeError;Wb.exports=function(s){if(nk(s))return s;throw new uk("Can't set "+ok(s)+" as a prototype")}});var Qc=b((rN,Kb)=>{"use strict";var lk=zb(),ck=Tt(),dk=Bi(),pk=Yb();Kb.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 dk(r),pk(a),ck(r)&&(s?t(r,a):r.__proto__=a),r}}():void 0)});var og=b((sN,ng)=>{"use strict";var hk=Re(),fk=yt(),jo=Ft(),sg=Vc(),mk=Te(),bk=jb(),Xb=Co(),Jb=Qc(),gk=va(),Sk=Br(),Gc=Vr(),vk=qe(),Zb=ar(),ag=zc(),yk=sg.PROPER,Tk=sg.CONFIGURABLE,eg=ag.IteratorPrototype,Ho=ag.BUGGY_SAFARI_ITERATORS,ya=vk("iterator"),tg="keys",Ta="values",ig="entries",rg=function(){return this};ng.exports=function(s,e,t,i,r,a,n){bk(t,e,i);var o=function(S){if(S===r&&h)return h;if(!Ho&&S&&S in d)return d[S];switch(S){case tg:return function(){return new t(this,S)};case Ta:return function(){return new t(this,S)};case ig:return function(){return new t(this,S)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,d=s.prototype,c=d[ya]||d["@@iterator"]||r&&d[r],h=!Ho&&c||o(r),p=e==="Array"&&d.entries||c,f,m,g;if(p&&(f=Xb(p.call(new s)),f!==Object.prototype&&f.next&&(!jo&&Xb(f)!==eg&&(Jb?Jb(f,eg):mk(f[ya])||Gc(f,ya,rg)),gk(f,u,!0,!0),jo&&(Zb[u]=rg))),yk&&r===Ta&&c&&c.name!==Ta&&(!jo&&Tk?Sk(d,"name",Ta):(l=!0,h=function(){return fk(c,this)})),r)if(m={values:o(Ta),keys:a?h:o(tg),entries:o(ig)},n)for(g in m)(Ho||l||!(g in d))&&Gc(d,g,m[g]);else hk({target:e,proto:!0,forced:Ho||l},m);return(!jo||n)&&d[ya]!==h&&Gc(d,ya,h,{name:r}),Zb[e]=h,m}});var lg=b((aN,ug)=>{"use strict";ug.exports=function(s,e){return{value:s,done:e}}});var Yc=b((nN,fg)=>{"use strict";var Ik=tr(),Wc=ba(),cg=ar(),pg=$c(),xk=rr().f,Ek=og(),zo=lg(),wk=Ft(),Ak=vt(),hg="Array Iterator",Pk=pg.set,Rk=pg.getterFor(hg);fg.exports=Ek(Array,"Array",function(s,e){Pk(this,{type:hg,target:Ik(s),index:0,kind:e})},function(){var s=Rk(this),e=s.target,t=s.index++;if(!e||t>=e.length)return s.target=void 0,zo(void 0,!0);switch(s.kind){case"keys":return zo(t,!1);case"values":return zo(e[t],!1)}return zo([t,e[t]],!1)},"values");var dg=cg.Arguments=cg.Array;Wc("keys");Wc("values");Wc("entries");if(!wk&&Ak&&dg.name!=="values")try{xk(dg,"name",{value:"values"})}catch(s){}});var bg=b((oN,mg)=>{"use strict";var kk=qe(),Mk=ar(),Lk=kk("iterator"),Bk=Array.prototype;mg.exports=function(s){return s!==void 0&&(Mk.Array===s||Bk[Lk]===s)}});var Kc=b((uN,Sg)=>{"use strict";var $k=Sa(),gg=da(),Dk=Pr(),Ck=ar(),Vk=qe(),Ok=Vk("iterator");Sg.exports=function(s){if(!Dk(s))return gg(s,Ok)||gg(s,"@@iterator")||Ck[$k(s)]}});var yg=b((lN,vg)=>{"use strict";var _k=yt(),Fk=Wt(),Nk=Yt(),Uk=ca(),qk=Kc(),jk=TypeError;vg.exports=function(s,e){var t=arguments.length<2?qk(s):e;if(Fk(t))return Nk(_k(t,s));throw new jk(Uk(s)+" is not iterable")}});var xg=b((cN,Ig)=>{"use strict";var Hk=yt(),Tg=Yt(),zk=da();Ig.exports=function(s,e,t){var i,r;Tg(s);try{if(i=zk(s,"return"),!i){if(e==="throw")throw t;return t}i=Hk(i,s)}catch(a){r=!0,i=a}if(e==="throw")throw t;if(r)throw i;return Tg(i),t}});var Go=b((dN,Pg)=>{"use strict";var Qk=Lr(),Gk=yt(),Wk=Yt(),Yk=ca(),Kk=bg(),Xk=Cr(),Eg=la(),Jk=yg(),Zk=Kc(),wg=xg(),eM=TypeError,Qo=function(s,e){this.stopped=s,this.result=e},Ag=Qo.prototype;Pg.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=Qk(e,i),l,d,c,h,p,f,m,g=function(v){return l&&wg(l,"normal",v),new Qo(!0,v)},S=function(v){return r?(Wk(v),o?u(v[0],v[1],g):u(v[0],v[1])):o?u(v,g):u(v)};if(a)l=s.iterator;else if(n)l=s;else{if(d=Zk(s),!d)throw new eM(Yk(s)+" is not iterable");if(Kk(d)){for(c=0,h=Xk(s);h>c;c++)if(p=S(s[c]),p&&Eg(Ag,p))return p;return new Qo(!1)}l=Jk(s,d)}for(f=a?s.next:l.next;!(m=Gk(f,l)).done;){try{p=S(m.value)}catch(v){wg(l,"throw",v)}if(typeof p=="object"&&p&&Eg(Ag,p))return p}return new Qo(!1)}});var kg=b((pN,Rg)=>{"use strict";var tM=vt(),iM=rr(),rM=ua();Rg.exports=function(s,e,t){tM?iM.f(s,e,rM(0,t)):s[e]=t}});var Mg=b(()=>{"use strict";var sM=Re(),aM=Go(),nM=kg();sM({target:"Object",stat:!0},{fromEntries:function(e){var t={};return aM(e,function(i,r){nM(t,i,r)},{AS_ENTRIES:!0}),t}})});var Bg=b((mN,Lg)=>{"use strict";Yc();Mg();var oM=Rr();Lg.exports=oM.Object.fromEntries});var Dg=b((bN,$g)=>{"use strict";$g.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 Vg=b(()=>{"use strict";Yc();var uM=Dg(),lM=xe(),cM=va(),Cg=ar();for(Wo in uM)cM(lM[Wo],Wo),Cg[Wo]=Cg.Array;var Wo});var _g=b((vN,Og)=>{"use strict";var dM=Bg();Vg();Og.exports=dM});var Xc=b((yN,Fg)=>{"use strict";var pM=_g();Fg.exports=pM});var Ng=b(()=>{"use strict"});var Jc=b((xN,Ug)=>{"use strict";var Ia=xe(),hM=ir(),fM=er(),Yo=function(s){return hM.slice(0,s.length)===s};Ug.exports=function(){return Yo("Bun/")?"BUN":Yo("Cloudflare-Workers")?"CLOUDFLARE":Yo("Deno/")?"DENO":Yo("Node.js/")?"NODE":Ia.Bun&&typeof Bun.version=="string"?"BUN":Ia.Deno&&typeof Deno.version=="object"?"DENO":fM(Ia.process)==="process"?"NODE":Ia.window&&Ia.document?"BROWSER":"REST"}()});var Ko=b((EN,qg)=>{"use strict";var mM=Jc();qg.exports=mM==="NODE"});var Hg=b((wN,jg)=>{"use strict";var bM=rr();jg.exports=function(s,e,t){return bM.f(s,e,t)}});var Gg=b((AN,Qg)=>{"use strict";var gM=gi(),SM=Hg(),vM=qe(),yM=vt(),zg=vM("species");Qg.exports=function(s){var e=gM(s);yM&&e&&!e[zg]&&SM(e,zg,{configurable:!0,get:function(){return this}})}});var Yg=b((PN,Wg)=>{"use strict";var TM=la(),IM=TypeError;Wg.exports=function(s,e){if(TM(e,s))return s;throw new IM("Incorrect invocation")}});var ed=b((RN,Kg)=>{"use strict";var xM=Ce(),EM=Te(),Zc=pa(),wM=xM(Function.toString);EM(Zc.inspectSource)||(Zc.inspectSource=function(s){return wM(s)});Kg.exports=Zc.inspectSource});var id=b((kN,tS)=>{"use strict";var AM=Ce(),PM=Ue(),Xg=Te(),RM=Sa(),kM=gi(),MM=ed(),Jg=function(){},Zg=kM("Reflect","construct"),td=/^\s*(?:class|function)\b/,LM=AM(td.exec),BM=!td.test(Jg),xa=function(e){if(!Xg(e))return!1;try{return Zg(Jg,[],e),!0}catch(t){return!1}},eS=function(e){if(!Xg(e))return!1;switch(RM(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return BM||!!LM(td,MM(e))}catch(t){return!0}};eS.sham=!0;tS.exports=!Zg||PM(function(){var s;return xa(xa.call)||!xa(Object)||!xa(function(){s=!0})||s})?eS:xa});var rS=b((MN,iS)=>{"use strict";var $M=id(),DM=ca(),CM=TypeError;iS.exports=function(s){if($M(s))return s;throw new CM(DM(s)+" is not a constructor")}});var rd=b((LN,aS)=>{"use strict";var sS=Yt(),VM=rS(),OM=Pr(),_M=qe(),FM=_M("species");aS.exports=function(s,e){var t=sS(s).constructor,i;return t===void 0||OM(i=sS(t)[FM])?e:VM(i)}});var oS=b((BN,nS)=>{"use strict";var NM=Ce();nS.exports=NM([].slice)});var lS=b(($N,uS)=>{"use strict";var UM=TypeError;uS.exports=function(s,e){if(s<e)throw new UM("Not enough arguments");return s}});var sd=b((DN,cS)=>{"use strict";var qM=ir();cS.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(qM)});var hd=b((CN,vS)=>{"use strict";var xt=xe(),jM=Gl(),HM=Lr(),dS=Te(),zM=Nt(),SS=Ue(),pS=Oc(),QM=oS(),hS=Mo(),GM=lS(),WM=sd(),YM=Ko(),cd=xt.setImmediate,dd=xt.clearImmediate,KM=xt.process,ad=xt.Dispatch,XM=xt.Function,fS=xt.MessageChannel,JM=xt.String,nd=0,Ea={},mS="onreadystatechange",wa,or,od,ud;SS(function(){wa=xt.location});var pd=function(s){if(zM(Ea,s)){var e=Ea[s];delete Ea[s],e()}},ld=function(s){return function(){pd(s)}},bS=function(s){pd(s.data)},gS=function(s){xt.postMessage(JM(s),wa.protocol+"//"+wa.host)};(!cd||!dd)&&(cd=function(e){GM(arguments.length,1);var t=dS(e)?e:XM(e),i=QM(arguments,1);return Ea[++nd]=function(){jM(t,void 0,i)},or(nd),nd},dd=function(e){delete Ea[e]},YM?or=function(s){KM.nextTick(ld(s))}:ad&&ad.now?or=function(s){ad.now(ld(s))}:fS&&!WM?(od=new fS,ud=od.port2,od.port1.onmessage=bS,or=HM(ud.postMessage,ud)):xt.addEventListener&&dS(xt.postMessage)&&!xt.importScripts&&wa&&wa.protocol!=="file:"&&!SS(gS)?(or=gS,xt.addEventListener("message",bS,!1)):mS in hS("script")?or=function(s){pS.appendChild(hS("script"))[mS]=function(){pS.removeChild(this),pd(s)}}:or=function(s){setTimeout(ld(s),0)});vS.exports={set:cd,clear:dd}});var IS=b((VN,TS)=>{"use strict";var yS=xe(),ZM=vt(),eL=Object.getOwnPropertyDescriptor;TS.exports=function(s){if(!ZM)return yS[s];var e=eL(yS,s);return e&&e.value}});var fd=b((ON,ES)=>{"use strict";var xS=function(){this.head=null,this.tail=null};xS.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}}};ES.exports=xS});var AS=b((_N,wS)=>{"use strict";var tL=ir();wS.exports=/ipad|iphone|ipod/i.test(tL)&&typeof Pebble!="undefined"});var RS=b((FN,PS)=>{"use strict";var iL=ir();PS.exports=/web0s(?!.*chrome)/i.test(iL)});var CS=b((NN,DS)=>{"use strict";var _r=xe(),rL=IS(),kS=Lr(),md=hd().set,sL=fd(),aL=sd(),nL=AS(),oL=RS(),bd=Ko(),MS=_r.MutationObserver||_r.WebKitMutationObserver,LS=_r.document,BS=_r.process,Xo=_r.Promise,vd=rL("queueMicrotask"),Or,gd,Sd,Jo,$S;vd||(Aa=new sL,Pa=function(){var s,e;for(bd&&(s=BS.domain)&&s.exit();e=Aa.get();)try{e()}catch(t){throw Aa.head&&Or(),t}s&&s.enter()},!aL&&!bd&&!oL&&MS&&LS?(gd=!0,Sd=LS.createTextNode(""),new MS(Pa).observe(Sd,{characterData:!0}),Or=function(){Sd.data=gd=!gd}):!nL&&Xo&&Xo.resolve?(Jo=Xo.resolve(void 0),Jo.constructor=Xo,$S=kS(Jo.then,Jo),Or=function(){$S(Pa)}):bd?Or=function(){BS.nextTick(Pa)}:(md=kS(md,_r),Or=function(){md(Pa)}),vd=function(s){Aa.head||Or(),Aa.add(s)});var Aa,Pa;DS.exports=vd});var OS=b((UN,VS)=>{"use strict";VS.exports=function(s,e){try{arguments.length===1?console.error(s):console.error(s,e)}catch(t){}}});var Zo=b((qN,_S)=>{"use strict";_S.exports=function(s){try{return{error:!1,value:s()}}catch(e){return{error:!0,value:e}}}});var ur=b((jN,FS)=>{"use strict";var uL=xe();FS.exports=uL.Promise});var Fr=b((HN,jS)=>{"use strict";var lL=xe(),Ra=ur(),cL=Te(),dL=mc(),pL=ed(),hL=qe(),NS=Jc(),fL=Ft(),yd=ic(),US=Ra&&Ra.prototype,mL=hL("species"),Td=!1,qS=cL(lL.PromiseRejectionEvent),bL=dL("Promise",function(){var s=pL(Ra),e=s!==String(Ra);if(!e&&yd===66||fL&&!(US.catch&&US.finally))return!0;if(!yd||yd<51||!/native code/.test(s)){var t=new Ra(function(a){a(1)}),i=function(a){a(function(){},function(){})},r=t.constructor={};if(r[mL]=i,Td=t.then(function(){})instanceof i,!Td)return!0}return!e&&(NS==="BROWSER"||NS==="DENO")&&!qS});jS.exports={CONSTRUCTOR:bL,REJECTION_EVENT:qS,SUBCLASSING:Td}});var Nr=b((zN,zS)=>{"use strict";var HS=Wt(),gL=TypeError,SL=function(s){var e,t;this.promise=new s(function(i,r){if(e!==void 0||t!==void 0)throw new gL("Bad Promise constructor");e=i,t=r}),this.resolve=HS(e),this.reject=HS(t)};zS.exports.f=function(s){return new SL(s)}});var cv=b(()=>{"use strict";var vL=Re(),yL=Ft(),ru=Ko(),Di=xe(),Hr=yt(),QS=Vr(),GS=Qc(),TL=va(),IL=Gg(),xL=Wt(),iu=Te(),EL=Tt(),wL=Yg(),AL=rd(),JS=hd().set,Ad=CS(),PL=OS(),RL=Zo(),kL=fd(),ZS=$c(),su=ur(),Pd=Fr(),ev=Nr(),au="Promise",tv=Pd.CONSTRUCTOR,ML=Pd.REJECTION_EVENT,LL=Pd.SUBCLASSING,Id=ZS.getterFor(au),BL=ZS.set,Ur=su&&su.prototype,lr=su,eu=Ur,iv=Di.TypeError,xd=Di.document,Rd=Di.process,Ed=ev.f,$L=Ed,DL=!!(xd&&xd.createEvent&&Di.dispatchEvent),rv="unhandledrejection",CL="rejectionhandled",WS=0,sv=1,VL=2,kd=1,av=2,tu,YS,OL,KS,nv=function(s){var e;return EL(s)&&iu(e=s.then)?e:!1},ov=function(s,e){var t=e.value,i=e.state===sv,r=i?s.ok:s.fail,a=s.resolve,n=s.reject,o=s.domain,u,l,d;try{r?(i||(e.rejection===av&&FL(e),e.rejection=kd),r===!0?u=t:(o&&o.enter(),u=r(t),o&&(o.exit(),d=!0)),u===s.promise?n(new iv("Promise-chain cycle")):(l=nv(u))?Hr(l,u,a,n):a(u)):n(t)}catch(c){o&&!d&&o.exit(),n(c)}},uv=function(s,e){s.notified||(s.notified=!0,Ad(function(){for(var t=s.reactions,i;i=t.get();)ov(i,s);s.notified=!1,e&&!s.rejection&&_L(s)}))},lv=function(s,e,t){var i,r;DL?(i=xd.createEvent("Event"),i.promise=e,i.reason=t,i.initEvent(s,!1,!0),Di.dispatchEvent(i)):i={promise:e,reason:t},!ML&&(r=Di["on"+s])?r(i):s===rv&&PL("Unhandled promise rejection",t)},_L=function(s){Hr(JS,Di,function(){var e=s.facade,t=s.value,i=XS(s),r;if(i&&(r=RL(function(){ru?Rd.emit("unhandledRejection",t,e):lv(rv,e,t)}),s.rejection=ru||XS(s)?av:kd,r.error))throw r.value})},XS=function(s){return s.rejection!==kd&&!s.parent},FL=function(s){Hr(JS,Di,function(){var e=s.facade;ru?Rd.emit("rejectionHandled",e):lv(CL,e,s.value)})},qr=function(s,e,t){return function(i){s(e,i,t)}},jr=function(s,e,t){s.done||(s.done=!0,t&&(s=t),s.value=e,s.state=VL,uv(s,!0))},wd=function(s,e,t){if(!s.done){s.done=!0,t&&(s=t);try{if(s.facade===e)throw new iv("Promise can't be resolved itself");var i=nv(e);i?Ad(function(){var r={done:!1};try{Hr(i,e,qr(wd,r,s),qr(jr,r,s))}catch(a){jr(r,a,s)}}):(s.value=e,s.state=sv,uv(s,!1))}catch(r){jr({done:!1},r,s)}}};if(tv&&(lr=function(e){wL(this,eu),xL(e),Hr(tu,this);var t=Id(this);try{e(qr(wd,t),qr(jr,t))}catch(i){jr(t,i)}},eu=lr.prototype,tu=function(e){BL(this,{type:au,done:!1,notified:!1,parent:!1,reactions:new kL,rejection:!1,state:WS,value:void 0})},tu.prototype=QS(eu,"then",function(e,t){var i=Id(this),r=Ed(AL(this,lr));return i.parent=!0,r.ok=iu(e)?e:!0,r.fail=iu(t)&&t,r.domain=ru?Rd.domain:void 0,i.state===WS?i.reactions.add(r):Ad(function(){ov(r,i)}),r.promise}),YS=function(){var s=new tu,e=Id(s);this.promise=s,this.resolve=qr(wd,e),this.reject=qr(jr,e)},ev.f=Ed=function(s){return s===lr||s===OL?new YS(s):$L(s)},!yL&&iu(su)&&Ur!==Object.prototype)){KS=Ur.then,LL||QS(Ur,"then",function(e,t){var i=this;return new lr(function(r,a){Hr(KS,i,r,a)}).then(e,t)},{unsafe:!0});try{delete Ur.constructor}catch(s){}GS&&GS(Ur,eu)}vL({global:!0,constructor:!0,wrap:!0,forced:tv},{Promise:lr});TL(lr,au,!1,!0);IL(au)});var mv=b((WN,fv)=>{"use strict";var NL=qe(),pv=NL("iterator"),hv=!1;try{dv=0,Md={next:function(){return{done:!!dv++}},return:function(){hv=!0}},Md[pv]=function(){return this},Array.from(Md,function(){throw 2})}catch(s){}var dv,Md;fv.exports=function(s,e){try{if(!e&&!hv)return!1}catch(r){return!1}var t=!1;try{var i={};i[pv]=function(){return{next:function(){return{done:t=!0}}}},s(i)}catch(r){}return t}});var Ld=b((YN,bv)=>{"use strict";var UL=ur(),qL=mv(),jL=Fr().CONSTRUCTOR;bv.exports=jL||!qL(function(s){UL.all(s).then(void 0,function(){})})});var gv=b(()=>{"use strict";var HL=Re(),zL=yt(),QL=Wt(),GL=Nr(),WL=Zo(),YL=Go(),KL=Ld();HL({target:"Promise",stat:!0,forced:KL},{all:function(e){var t=this,i=GL.f(t),r=i.resolve,a=i.reject,n=WL(function(){var o=QL(t.resolve),u=[],l=0,d=1;YL(e,function(c){var h=l++,p=!1;d++,zL(o,t,c).then(function(f){p||(p=!0,u[h]=f,--d||r(u))},a)}),--d||r(u)});return n.error&&a(n.value),i.promise}})});var vv=b(()=>{"use strict";var XL=Re(),JL=Ft(),ZL=Fr().CONSTRUCTOR,$d=ur(),eB=gi(),tB=Te(),iB=Vr(),Sv=$d&&$d.prototype;XL({target:"Promise",proto:!0,forced:ZL,real:!0},{catch:function(s){return this.then(void 0,s)}});!JL&&tB($d)&&(Bd=eB("Promise").prototype.catch,Sv.catch!==Bd&&iB(Sv,"catch",Bd,{unsafe:!0}));var Bd});var yv=b(()=>{"use strict";var rB=Re(),sB=yt(),aB=Wt(),nB=Nr(),oB=Zo(),uB=Go(),lB=Ld();rB({target:"Promise",stat:!0,forced:lB},{race:function(e){var t=this,i=nB.f(t),r=i.reject,a=oB(function(){var n=aB(t.resolve);uB(e,function(o){sB(n,t,o).then(i.resolve,r)})});return a.error&&r(a.value),i.promise}})});var Tv=b(()=>{"use strict";var cB=Re(),dB=Nr(),pB=Fr().CONSTRUCTOR;cB({target:"Promise",stat:!0,forced:pB},{reject:function(e){var t=dB.f(this),i=t.reject;return i(e),t.promise}})});var Dd=b((sU,Iv)=>{"use strict";var hB=Yt(),fB=Tt(),mB=Nr();Iv.exports=function(s,e){if(hB(s),fB(e)&&e.constructor===s)return e;var t=mB.f(s),i=t.resolve;return i(e),t.promise}});var wv=b(()=>{"use strict";var bB=Re(),gB=gi(),xv=Ft(),SB=ur(),Ev=Fr().CONSTRUCTOR,vB=Dd(),yB=gB("Promise"),TB=xv&&!Ev;bB({target:"Promise",stat:!0,forced:xv||Ev},{resolve:function(e){return vB(TB&&this===yB?SB:this,e)}})});var Av=b(()=>{"use strict";cv();gv();vv();yv();Tv();wv()});var Mv=b(()=>{"use strict";var IB=Re(),xB=Ft(),nu=ur(),EB=Ue(),Rv=gi(),kv=Te(),wB=rd(),Pv=Dd(),AB=Vr(),Vd=nu&&nu.prototype,PB=!!nu&&EB(function(){Vd.finally.call({then:function(){}},function(){})});IB({target:"Promise",proto:!0,real:!0,forced:PB},{finally:function(s){var e=wB(this,Rv("Promise")),t=kv(s);return this.then(t?function(i){return Pv(e,s()).then(function(){return i})}:s,t?function(i){return Pv(e,s()).then(function(){throw i})}:s)}});!xB&&kv(nu)&&(Cd=Rv("Promise").prototype.finally,Vd.finally!==Cd&&AB(Vd,"finally",Cd,{unsafe:!0}));var Cd});var Bv=b((dU,Lv)=>{"use strict";Ng();Av();Mv();var RB=$i();Lv.exports=RB("Promise","finally")});var Dv=b((pU,$v)=>{"use strict";var kB=Bv();$v.exports=kB});var ou=b((hU,Cv)=>{"use strict";var MB=Dv();Cv.exports=MB});var Wv=b(()=>{"use strict";var HB=Re(),zB=kc().values;HB({target:"Object",stat:!0},{values:function(e){return zB(e)}})});var Kv=b((XU,Yv)=>{"use strict";Wv();var QB=Rr();Yv.exports=QB.Object.values});var Jv=b((JU,Xv)=>{"use strict";var GB=Kv();Xv.exports=GB});var pr=b((ZU,Zv)=>{"use strict";var WB=Jv();Zv.exports=WB});var by=b(()=>{"use strict";var g$=Re(),S$=kr(),v$=Cr(),y$=ma(),T$=ba();g$({target:"Array",proto:!0},{at:function(e){var t=S$(this),i=v$(t),r=y$(e),a=r>=0?r:i+r;return a<0||a>=i?void 0:t[a]}});T$("at")});var Sy=b((dq,gy)=>{"use strict";by();var I$=$i();gy.exports=I$("Array","at")});var yy=b((pq,vy)=>{"use strict";var x$=Sy();vy.exports=x$});var qt=b((hq,Ty)=>{"use strict";var E$=yy();Ty.exports=E$});var ap=b((iH,eT)=>{"use strict";var sD=er();eT.exports=Array.isArray||function(e){return sD(e)==="Array"}});var iT=b((rH,tT)=>{"use strict";var aD=TypeError,nD=9007199254740991;tT.exports=function(s){if(s>nD)throw aD("Maximum allowed index exceeded");return s}});var aT=b((sH,sT)=>{"use strict";var oD=ap(),uD=Cr(),lD=iT(),cD=Lr(),rT=function(s,e,t,i,r,a,n,o){for(var u=r,l=0,d=n?cD(n,o):!1,c,h;l<i;)l in t&&(c=d?d(t[l],l,e):t[l],a>0&&oD(c)?(h=uD(c),u=rT(s,e,c,h,u,a-1)-1):(lD(u+1),s[u]=c),u++),l++;return u};sT.exports=rT});var lT=b((aH,uT)=>{"use strict";var nT=ap(),dD=id(),pD=Tt(),hD=qe(),fD=hD("species"),oT=Array;uT.exports=function(s){var e;return nT(s)&&(e=s.constructor,dD(e)&&(e===oT||nT(e.prototype))?e=void 0:pD(e)&&(e=e[fD],e===null&&(e=void 0))),e===void 0?oT:e}});var dT=b((nH,cT)=>{"use strict";var mD=lT();cT.exports=function(s,e){return new(mD(s))(e===0?0:e)}});var pT=b(()=>{"use strict";var bD=Re(),gD=aT(),SD=Wt(),vD=kr(),yD=Cr(),TD=dT();bD({target:"Array",proto:!0},{flatMap:function(e){var t=vD(this),i=yD(t),r;return SD(e),r=TD(t,0),r.length=gD(r,t,t,i,0,1,e,arguments.length>1?arguments[1]:void 0),r}})});var hT=b(()=>{"use strict";var ID=ba();ID("flatMap")});var mT=b((dH,fT)=>{"use strict";pT();hT();var xD=$i();fT.exports=xD("Array","flatMap")});var gT=b((pH,bT)=>{"use strict";var ED=mT();bT.exports=ED});var za=b((hH,ST)=>{"use strict";var wD=gT();ST.exports=wD});var Qa=b((fH,vT)=>{"use strict";var AD=Sa(),PD=String;vT.exports=function(s){if(AD(s)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return PD(s)}});var np=b((mH,yT)=>{"use strict";yT.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 xT=b((bH,IT)=>{"use strict";var RD=Ce(),kD=Bi(),MD=Qa(),up=np(),TT=RD("".replace),LD=RegExp("^["+up+"]+"),BD=RegExp("(^|[^"+up+"])["+up+"]+$"),op=function(s){return function(e){var t=MD(kD(e));return s&1&&(t=TT(t,LD,"")),s&2&&(t=TT(t,BD,"$1")),t}};IT.exports={start:op(1),end:op(2),trim:op(3)}});var PT=b((gH,AT)=>{"use strict";var $D=Vc().PROPER,DD=Ue(),ET=np(),wT="\u200B\x85\u180E";AT.exports=function(s){return DD(function(){return!!ET[s]()||wT[s]()!==wT||$D&&ET[s].name!==s})}});var lp=b((SH,RT)=>{"use strict";var CD=xT().start,VD=PT();RT.exports=VD("trimStart")?function(){return CD(this)}:"".trimStart});var MT=b(()=>{"use strict";var OD=Re(),kT=lp();OD({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==kT},{trimLeft:kT})});var BT=b(()=>{"use strict";MT();var _D=Re(),LT=lp();_D({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==LT},{trimStart:LT})});var DT=b((xH,$T)=>{"use strict";BT();var FD=$i();$T.exports=FD("String","trimLeft")});var VT=b((EH,CT)=>{"use strict";var ND=DT();CT.exports=ND});var _T=b((wH,OT)=>{"use strict";var UD=VT();OT.exports=UD});var ZT=b(()=>{"use strict"});var eI=b(()=>{"use strict"});var iI=b((uz,tI)=>{"use strict";var c0=Tt(),d0=er(),p0=qe(),h0=p0("match");tI.exports=function(s){var e;return c0(s)&&((e=s[h0])!==void 0?!!e:d0(s)==="RegExp")}});var sI=b((lz,rI)=>{"use strict";var f0=Yt();rI.exports=function(){var s=f0(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 oI=b((cz,nI)=>{"use strict";var m0=yt(),b0=Nt(),g0=la(),S0=sI(),aI=RegExp.prototype;nI.exports=function(s){var e=s.flags;return e===void 0&&!("flags"in aI)&&!b0(s,"flags")&&g0(aI,s)?m0(S0,s):e}});var lI=b((dz,uI)=>{"use strict";var mp=Ce(),v0=kr(),y0=Math.floor,hp=mp("".charAt),T0=mp("".replace),fp=mp("".slice),I0=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,x0=/\$([$&'`]|\d{1,2})/g;uI.exports=function(s,e,t,i,r,a){var n=t+s.length,o=i.length,u=x0;return r!==void 0&&(r=v0(r),u=I0),T0(a,u,function(l,d){var c;switch(hp(d,0)){case"$":return"$";case"&":return s;case"`":return fp(e,0,t);case"'":return fp(e,n);case"<":c=r[fp(d,1,-1)];break;default:var h=+d;if(h===0)return l;if(h>o){var p=y0(h/10);return p===0?l:p<=o?i[p-1]===void 0?hp(d,1):i[p-1]+hp(d,1):l}c=i[h-1]}return c===void 0?"":c})}});var pI=b(()=>{"use strict";var E0=Re(),w0=yt(),gp=Ce(),cI=Bi(),A0=Te(),P0=Pr(),R0=iI(),ss=Qa(),k0=da(),M0=oI(),L0=lI(),B0=qe(),$0=Ft(),D0=B0("replace"),C0=TypeError,bp=gp("".indexOf),V0=gp("".replace),dI=gp("".slice),O0=Math.max;E0({target:"String",proto:!0},{replaceAll:function(e,t){var i=cI(this),r,a,n,o,u,l,d,c,h,p,f=0,m="";if(!P0(e)){if(r=R0(e),r&&(a=ss(cI(M0(e))),!~bp(a,"g")))throw new C0("`.replaceAll` does not allow non-global regexes");if(n=k0(e,D0),n)return w0(n,e,i,t);if($0&&r)return V0(ss(i),e,t)}for(o=ss(i),u=ss(e),l=A0(t),l||(t=ss(t)),d=u.length,c=O0(1,d),h=bp(o,u);h!==-1;)p=l?ss(t(u,h,o)):L0(u,o,h,[],void 0,t),m+=dI(o,f,h)+p,f=h+d,h=h+c>o.length?-1:bp(o,u,h+c);return f<o.length&&(m+=dI(o,f)),m}})});var fI=b((fz,hI)=>{"use strict";ZT();eI();pI();var _0=$i();hI.exports=_0("String","replaceAll")});var bI=b((mz,mI)=>{"use strict";var F0=fI();mI.exports=F0});var Sp=b((bz,gI)=>{"use strict";var N0=bI();gI.exports=N0});var vI=b((gz,SI)=>{"use strict";var U0=ma(),q0=Qa(),j0=Bi(),H0=RangeError;SI.exports=function(e){var t=q0(j0(this)),i="",r=U0(e);if(r<0||r===1/0)throw new H0("Wrong number of repetitions");for(;r>0;(r>>>=1)&&(t+=t))r&1&&(i+=t);return i}});var EI=b((Sz,xI)=>{"use strict";var II=Ce(),z0=Tc(),yI=Qa(),Q0=vI(),G0=Bi(),W0=II(Q0),Y0=II("".slice),K0=Math.ceil,TI=function(s){return function(e,t,i){var r=yI(G0(e)),a=z0(t),n=r.length,o=i===void 0?" ":yI(i),u,l;return a<=n||o===""?r:(u=a-n,l=W0(o,K0(u/o.length)),l.length>u&&(l=Y0(l,0,u)),s?r+l:l+r)}};xI.exports={start:TI(!1),end:TI(!0)}});var AI=b((vz,wI)=>{"use strict";var X0=ir();wI.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(X0)});var PI=b(()=>{"use strict";var J0=Re(),Z0=EI().start,eC=AI();J0({target:"String",proto:!0,forced:eC},{padStart:function(e){return Z0(this,e,arguments.length>1?arguments[1]:void 0)}})});var kI=b((Iz,RI)=>{"use strict";PI();var tC=$i();RI.exports=tC("String","padStart")});var LI=b((xz,MI)=>{"use strict";var iC=kI();MI.exports=iC});var vp=b((Ez,BI)=>{"use strict";var rC=LI();BI.exports=rC});var jh="2.0.135-dev.de6f0c74.0";var at=(r=>(r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused",r))(at||{}),bi=(y=>(y.MPEG="MPEG",y.DASH="DASH",y.DASH_SEP="DASH_SEP",y.DASH_SEP_VK="DASH_SEP",y.DASH_WEBM="DASH_WEBM",y.DASH_WEBM_AV1="DASH_WEBM_AV1",y.DASH_STREAMS="DASH_STREAMS",y.DASH_WEBM_VK="DASH_WEBM",y.DASH_ONDEMAND="DASH_ONDEMAND",y.DASH_ONDEMAND_VK="DASH_ONDEMAND",y.DASH_LIVE="DASH_LIVE",y.DASH_LIVE_CMAF="DASH_LIVE_CMAF",y.DASH_LIVE_WEBM="DASH_LIVE_WEBM",y.HLS="HLS",y.HLS_ONDEMAND="HLS_ONDEMAND",y.HLS_JS="HLS",y.HLS_LIVE="HLS_LIVE",y.HLS_LIVE_CMAF="HLS_LIVE_CMAF",y.WEB_RTC_LIVE="WEB_RTC_LIVE",y))(bi||{});var Ao=(r=>(r.NOT_AVAILABLE="NOT_AVAILABLE",r.AVAILABLE="AVAILABLE",r.CONNECTING="CONNECTING",r.CONNECTED="CONNECTED",r))(Ao||{}),Hl=(i=>(i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic",i))(Hl||{});var zl=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(zl||{}),Po=(i=>(i.TRAFFIC_SAVING="traffic_saving",i.HIGH_QUALITY="high_quality",i.UNKNOWN="unknown",i))(Po||{});var UE=H(It(),1);import{assertNever as qm,assertNonNullable as gP,isNonNullable as Bo,ValueSubject as xc,Subject as SP,Subscription as vP,merge as yP,observableFrom as TP,fromEvent as _m,map as Fm,tap as Nm,filterChanged as IP,isNullable as Ec,ErrorCategory as Um}from"@vkontakte/videoplayer-shared/es2015";var Om=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 $o=class{constructor(e){this.connection$=new xc(void 0);this.castState$=new xc("NOT_AVAILABLE");this.errorEvent$=new SP;this.realCastState$=new xc("NOT_AVAILABLE");this.subscription=new vP;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=Bo((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||Om("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:Um.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(){Bo(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();Ec(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();Ec(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(_m(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 qm(r.sessionState)}})).add(yP(_m(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(Nm(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),Fm(r=>r.castState)),TP([i.getCastState()])).pipe(IP(),Fm(xP),Nm(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{var o,u;let a=r==="CONNECTED",n=Bo(this.connection$.getValue());if(a&&!n){let l=i.getCurrentSession();gP(l);let d=l.getCastDevice(),c=(u=(o=l.getMediaSession())==null?void 0:o.media)==null?void 0:u.contentId;(Ec(c)||c===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:l,castDevice:d}))}else!a&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(r==="CONNECTED"?Bo(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:Um.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:a})}}},xP=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 qm(s)}};var Bh=H(It(),1),IE=H(sr(),1),xE=H(Xc(),1);var zv=H(ou(),1);import{assertNever as Vv}from"@vkontakte/videoplayer-shared/es2015";var Ie=(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:Vv(t)}return s},Ci=(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:Vv(e)}};var D=(s,e,t=!1)=>{let i=s.getTransition();(t||!i||i.to===e)&&s.setState(e)};import{isNonNullable as LB,Subject as uu,merge as Ov}from"@vkontakte/videoplayer-shared/es2015";var Y=class{constructor(e){this.transitionStarted$=new uu;this.transitionEnded$=new uu;this.transitionUpdated$=new uu;this.forceChanged$=new uu;this.stateChangeStarted$=Ov(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=Ov(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||LB(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 BB}from"@vkontakte/videoplayer-shared/es2015";var _v=s=>{switch(s){case"MPEG":case"DASH":case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":case"HLS":case"HLS_ONDEMAND":return!1;case"DASH_LIVE":case"DASH_LIVE_CMAF":case"HLS_LIVE":case"HLS_LIVE_CMAF":case"DASH_LIVE_WEBM":case"WEB_RTC_LIVE":return!0;default:return BB(s)}};import{assertNever as zr,assertNonNullable as cr,debounce as Fv,ErrorCategory as Nv,fromEvent as dr,isNonNullable as Uv,map as qv,merge as jv,observableFrom as $B,Subject as DB,Subscription as Od,timeout as CB,getHighestQuality as VB}from"@vkontakte/videoplayer-shared/es2015";var OB=5,_B=5,FB=500,Hv=7e3,ka=class{constructor(e){this.subscription=new Od;this.loadMediaTimeoutSubscription=new Od;this.videoState=new Y("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:zr(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:zr(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:zr(e)}break}default:zr(i)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(_v(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 Od;this.subscription.add(e),this.subscription.add(jv(this.videoState.stateChangeStarted$.pipe(qv(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe(qv(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 DB;e.add(r.pipe(Fv(FB)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let a=NaN;e.add(dr(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)>OB)&&r.next(o),a=o})),e.add(dr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(dr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(dr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t(dr(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<_B&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),D(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:zr(n)}}),t(dr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t(dr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});let i=jv(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,$B(["init"])).pipe(Fv(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"),D(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),D(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"),D(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"),D(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"&&D(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){var r,a;let t=this.params.output.volume$.getValue(),i={volume:(r=e.volume)!=null?r:t.volume,muted:(a=e.muted)!=null?a:t.muted};(i.volume!==t.volume||i.muted!==i.muted)&&this.params.output.volume$.next(i)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:i}=this.params.connection;t.currentTime=e,i.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){var l;let t=this.params.source,i,r,a;switch(e){case"MPEG":{let d=t[e];cr(d);let c=VB(Object.keys(d));cr(c);let h=d[c];cr(h),i=h,r="video/mp4",a=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let d=t[e];cr(d),i=d.url,r="application/x-mpegurl",a=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":{let d=t[e];cr(d),i=d.url,r="application/dash+xml",a=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let d=t[e];cr(d),i=d.url,r="application/dash+xml",a=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let d=t[e];cr(d),i=Ie(d.url),r="application/x-mpegurl",a=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let d="Unsupported format for Chromecast",c=new Error(d);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:Nv.VIDEO_PIPELINE,message:d,thrown:c}),c}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return zr(e)}let n=new chrome.cast.media.MediaInfo((l=this.params.meta.videoId)!=null?l:i,r);n.contentUrl=i,n.streamType=a,n.metadata=new chrome.cast.media.GenericMediaMetadata;let{title:o,subtitle:u}=this.params.meta;return Uv(o)&&(n.metadata.title=o),Uv(u)&&(n.metadata.subtitle=u),n}createLoadRequest(e){let t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;let i=this.params.desiredState.seekState.getState();return i.state==="applying"||i.state==="requested"?t.currentTime=this.params.output.isLive$.getValue()?0:i.position/1e3:t.currentTime=0,t}loadMedia(e){let t=this.params.connection.session.loadMedia(e),i=new Promise((r,a)=>{this.loadMediaTimeoutSubscription.add(CB(Hv).subscribe(()=>a(`timeout(${Hv})`)))});(0,zv.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:Nv.VIDEO_PIPELINE,message:a,thrown:r})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var rp=H(It(),1);import{clearVideoElement as Gv}from"@vkontakte/videoplayer-shared/es2015";import{clearVideoElement as NB}from"@vkontakte/videoplayer-shared/es2015";var Qv=s=>{try{s.pause(),s.playbackRate=0,NB(s),s.remove()}catch(e){console.error(e)}};import{fromEvent as UB,Subscription as qB}from"@vkontakte/videoplayer-shared/es2015";var _d=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)}},Fd=window.WeakMap?new WeakMap:new _d,Nd=window.WeakMap?new WeakMap:new Map,jB=(s,e=20)=>{let t=0;return UB(s,"ratechange").subscribe(i=>{t++,t>=e&&(s.currentTime=s.currentTime,t=0)})},nt=(s,{audioVideoSyncRate:e,disableYandexPiP:t})=>{let i=s.querySelector("video"),r=!!i;i?Gv(i):(i=document.createElement("video"),s.appendChild(i)),Fd.set(i,r);let a=new qB;return a.add(jB(i,e)),Nd.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},ot=s=>{let e=Nd.get(s);e==null||e.unsubscribe(),Nd.delete(s);let t=Fd.get(s);Fd.delete(s),t?Gv(s):Qv(s)};var qd=H(pr(),1);import{assertNonNullable as La,isNonNullable as Xt,isNullable as XB,fromEvent as Qr,merge as ey,observableFrom as ty,filterChanged as iy,map as Ba,Subject as ry,Subscription as JB,ValueSubject as ZB,ErrorCategory as e$}from"@vkontakte/videoplayer-shared/es2015";import{isNonNullable as Ud,isNullable as YB,Subscription as KB}from"@vkontakte/videoplayer-shared/es2015";var lu=(s,e,t,{equal:i=(n,o)=>n===o,changed$:r,onError:a}={})=>{let n=s.getState(),o=e(),u=YB(r),l=new KB;return r&&l.add(r.subscribe(d=>{let c=s.getState();i(d,c)&&s.setState(d)},a)),i(o,n)||(t(n),u&&s.setState(n)),l.add(s.stateChangeStarted$.subscribe(d=>{t(d.to),u&&s.setState(d.to)},a)),l},Kt=(s,e,t)=>lu(e,()=>s.loop,i=>{Ud(i)&&(s.loop=i)},{onError:t}),ut=(s,e,t,i)=>lu(e,()=>({muted:s.muted,volume:s.volume}),r=>{Ud(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}),Pt=(s,e,t,i)=>lu(e,()=>s.playbackRate,r=>{Ud(r)&&(s.playbackRate=r)},{changed$:t,onError:i}),Ma=lu;var t$=s=>["__",s.language,s.label].join("|"),i$=(s,e)=>{if(s.id===e)return!0;let[t,i,r]=e.split("|");return s.language===i&&s.label===r},jd=class s{constructor(e){this.available$=new ry;this.current$=new ZB(void 0);this.error$=new ry;this.subscription=new JB;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:e$.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(Ma(t.internalTextTracks,()=>(0,qd.default)(this.internalTracks),a=>{Xt(a)&&this.setInternal(a)},{equal:(a,n)=>Xt(a)&&Xt(n)&&a.length===n.length&&a.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(Ba(a=>a.filter(({type:n})=>n==="internal"))),onError:r})),this.subscription.add(Ma(t.externalTextTracks,()=>(0,qd.default)(this.externalTracks),a=>{Xt(a)&&this.setExternal(a)},{equal:(a,n)=>Xt(a)&&Xt(n)&&a.length===n.length&&a.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(Ba(a=>a.filter(({type:n})=>n==="external"))),onError:r})),this.subscription.add(Ma(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(Ma(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let a of this.htmlTextTracksAsArray())this.applyCueSettings(a.cues),this.applyCueSettings(a.activeCues)}))}subscribe(){La(this.video);let{textTracks:e}=this.video;this.subscription.add(Qr(e,"addtrack").subscribe(()=>{let i=this.current$.getValue();i&&this.select(i)})),this.subscription.add(ey(Qr(e,"addtrack"),Qr(e,"removetrack"),ty(["init"])).pipe(Ba(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),iy((i,r)=>i.length===r.length&&i.every(({id:a},n)=>a===r[n].id))).subscribe(this.available$)),this.subscription.add(ey(Qr(e,"change"),ty(["init"])).pipe(Ba(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),Ba(i=>i&&this.htmlTextTrackToITextTrack(i).id),iy()).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(Qr(e,"addtrack").subscribe(i=>{var a,n;(a=i.track)==null||a.addEventListener("cuechange",t);let r=o=>{var l,d,c,h,p;let u=(d=(l=o.target)==null?void 0:l.cues)!=null?d:null;u&&u.length&&(this.applyCueSettings((h=(c=o.target)==null?void 0:c.cues)!=null?h:null),(p=o.target)==null||p.removeEventListener("cuechange",r))};(n=i.track)==null||n.addEventListener("cuechange",r)})),this.subscription.add(Qr(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;Xt(t.align)&&(r.align=t.align),Xt(t.position)&&(r.position=t.position),Xt(t.size)&&(r.size=t.size),Xt(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){La(this.video);let t=[...this.video.textTracks];return e?t:t.filter(s.isHealthyTrack)}htmlTextTrackToITextTrack(e){var o,u,l,d,c;let{language:t,label:i}=e,r=e.id?e.id:t$(e),a=this.externalTracks.has(r),n=(l=a?(o=this.externalTracks.get(r))==null?void 0:o.isAuto:(u=this.internalTracks.get(r))==null?void 0:u.isAuto)!=null?l:r.includes("auto");return a?{id:r,type:"external",isAuto:n,language:t,label:i,url:(d=this.externalTracks.get(r))==null?void 0:d.url}:{id:r,type:"internal",isAuto:n,language:t,label:i,url:(c=this.internalTracks.get(r))==null?void 0:c.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(i=>i.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){let t=[...this.externalTracks];e.filter(({id:i,language:r,isAuto:a})=>!this.internalTracks.has(i)&&!t.some(([,n])=>n.language===r&&n.isAuto===a)).forEach(i=>this.attach(i)),Array.from(this.internalTracks).filter(([i])=>!e.find(r=>r.id===i)).forEach(([,i])=>this.detach(i))}select(e){La(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(XB(e)||!i$(t,e))&&(t.mode="disabled")}destroy(){if(this.subscription.unsubscribe(),this.video)for(let e of Array.from(this.video.getElementsByTagName("track"))){let t=e.getAttribute("id");t&&this.externalTracks.has(t)&&this.video.removeChild(e)}this.externalTracks.clear()}attach(e){La(this.video);let t=document.createElement("track");this.baseURL?t.setAttribute("src",new URL(e.url,this.baseURL).toString()):t.setAttribute("src",e.url),t.setAttribute("id",e.id),e.label&&t.setAttribute("label",e.label),e.language&&t.setAttribute("srclang",e.language),e.type==="external"?this.externalTracks.set(e.id,e):e.type==="internal"&&this.internalTracks.set(e.id,e),this.video.appendChild(t)}detach(e){La(this.video);let t=Array.prototype.find.call(this.video.getElementsByTagName("track"),i=>i.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}},Rt=jd;var hr=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 sy=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},Hd=s=>{let e=sy(s);return!!(e&&e.fullscreenElement&&e.fullscreenElement===s)},ay=s=>{let e=sy(s);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===s)};import{fromEvent as et,map as Jt,merge as bu,filterChanged as hy,isNonNullable as fy,Subject as d$,filter as Qd,mapTo as Gd,combine as p$,once as h$,throttle as f$,ErrorCategory as m$,ValueSubject as my,Subscription as b$}from"@vkontakte/videoplayer-shared/es2015";var r$=3,ny=(s,e,t=r$)=>{let i=0,r=0;for(let a=0;a<s.length;a++){let n=s.start(a),o=s.end(a);if(n<=e&&e<=o){if(i=n,r=o,!t)return{from:i,to:r};for(let u=a-1;u>=0;u--)s.end(u)+t>=i&&(i=s.start(u));for(let u=a+1;u<s.length;u++)s.start(u)-t<=r&&(r=s.end(u))}}return{from:i,to:r}};var cu=class{constructor(){this._isMiuiBrowser=!1}get current(){return this._current}get isChrome(){return this.current==="Chrome"}get isFirefox(){return this.current==="Firefox"}get isSafari(){return this.current==="Safari"}get isOpera(){return this.current==="Opera"}get isEdge(){return this.current==="Edge"}get isYandex(){return this.current==="Yandex"}get isSamsungBrowser(){return this.current==="SamsungBrowser"}get currentVersion(){return this._current_version}get chromeVersion(){return this._chromeVersion}get firefoxVersion(){return this._firefoxVersion}get safariVersion(){return this._safariVersion}get operaVersion(){return this._operaVersion}get edgeVersion(){return this._edgeVersion}get yandexVersion(){return this._yandexVersion}get isMiuiBrowser(){return this._isMiuiBrowser}detect(){let{userAgent:e}=navigator;try{let t=/yabrowser/i.test(e)?"Yandex":void 0,i=/samsungbrowser/i.test(e)?"SamsungBrowser":void 0,r=/chrome|crios/i.test(e)?"Chrome":void 0,a=/chromium/i.test(e)?"Chromium":void 0,n=/firefox|fxios/i.test(e)?"Firefox":void 0,o=/webkit|safari|khtml/i.test(e)?"Safari":void 0,u=/opr\//i.test(e)?"Opera":void 0,l=/edg/i.test(e)?"Edge":void 0;this._isMiuiBrowser=/(XiaoMi)|(MiuiBrowser)/i.test(e),this._current=t||i||n||u||l||r||a||o||"Rest"}catch(t){console.error(t)}this.isChrome&&this.detectChromeVersion(),this.isFirefox&&this.detectFirefoxVersion(),this.isSafari&&this.detectSafariVersion(),this.isOpera&&this.detectOperaVersion(),this.isEdge&&this.detectEdgeVersion(),this.isYandex&&this.detectYandexVersion()}detectVersion(e){try{let{userAgent:t}=window.navigator,i=t.match(e);if(!i)return;let r=i[1],a=parseInt(r,10);if(!isNaN(a))return this._current_version=a,a}catch(t){console.error(t)}}detectChromeVersion(){this._chromeVersion=this.detectVersion(/Chrome\/(\d+\.\d+)/)}detectFirefoxVersion(){this._firefoxVersion=this.detectVersion(/Firefox\/(\d+\.\d+)/)}detectSafariVersion(){this._safariVersion=this.detectVersion(/Version\/(\d+)/)}detectOperaVersion(){this._operaVersion=this.detectVersion(/OPR\/(\d+\.\d+)/)}detectEdgeVersion(){this._edgeVersion=this.detectVersion(/Edg\/(\d+\.\d+)/)}detectYandexVersion(){this._yandexVersion=this.detectVersion(/YaBrowser\/(\d+\.\d+\.\d+)/)}};var oy=H(It(),1);var $a=()=>{var s,e;return/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test((s=navigator.appVersion)!=null?s:navigator.userAgent)||((e=navigator==null?void 0:navigator.userAgentData)==null?void 0:e.mobile)};var du=class{constructor(e){this._highEntropyValues={};this._displayChecker=e}get current(){return this._current}get isIOS(){let e=["iPhone","iPad","iPod"];return this._highEntropyValues.platform==="iOS"||(0,oy.default)(e,this.current)}get isMac(){return this._highEntropyValues.platform==="macOS"||this.current==="Mac"}get isApple(){return this.isIOS||this.isMac}get isIphoneOrOldIpad(){if(!this.isApple||!this._displayChecker.isTouch)return!1;let e=this.current==="iPad"||this._displayChecker.width>700,t=this._iosVersion;return!e||e&&!!t&&t<16}get isAndroid(){return this._highEntropyValues.platform==="Android"||this.current==="Android"}get isMobile(){return this._highEntropyValues.mobile||this._isMobile}get iOSVersion(){return this._iosVersion}detect(){let{userAgent:e}=navigator;try{this._isMobile=$a()}catch(t){console.error(t)}this.detectDevice(e),this.detectHighEntropyValues(),this.isIOS&&this.detectIOSVersion()}detectHighEntropyValues(){return E(this,null,function*(){let{userAgentData:e}=navigator;if(e!=null&&e.getHighEntropyValues){let t=yield e.getHighEntropyValues(["architecture","bitness","brands","mobile","platform","formFactor","model","platformVersion","wow64"]);this._highEntropyValues=t}})}detectDevice(e){try{let t=/android/i.test(e)?"Android":void 0,i=/iphone/i.test(e)?"iPhone":void 0,r=/ipad/i.test(e)?"iPad":void 0,a=/ipod/i.test(e)?"iPod":void 0,n=/mac/i.test(e)?"Mac":void 0,o=/webOS|BlackBerry|IEMobile|Opera Mini/i.test(e)?"RestMobile":void 0;this._current=t||i||r||a||o||n||"Desktop"}catch(t){console.error(t)}}detectIOSVersion(){try{if(this._highEntropyValues.platformVersion){let a=this._highEntropyValues.platformVersion.split(".").slice(0,2).join("."),n=parseFloat(a);this._iosVersion=n;return}let{userAgent:e}=window.navigator,t=e.match(/OS (\d+(_\d+)?)/i);if(!t)return;let i=t[1].replace(/_/g,".");if(!i)return;let r=parseFloat(i);if(isNaN(r))return;this._iosVersion=r}catch(e){console.error(e)}}};var pu=class{get isTouch(){return typeof this._maxTouchPoints=="number"?this._maxTouchPoints>1:"ontouchstart"in window}get maxTouchPoints(){return this._maxTouchPoints}get height(){return this._height}get width(){return this._width}get screenHeight(){return this._screenHeight}get screenWidth(){return this._screenWidth}get pixelRatio(){return this._pixelRatio}get isHDR(){return this._isHdr}get colorDepth(){return this._colorDepth}detect(){var t;let{maxTouchPoints:e}=navigator;try{this._maxTouchPoints=e!=null?e:0,this._isHdr=!!((t=matchMedia("(dynamic-range: high)"))!=null&&t.matches),this._colorDepth=screen.colorDepth}catch(i){console.error(i)}try{this._pixelRatio=window.devicePixelRatio||1,this._height=screen.height,this._width=screen.width,this._height=screen.height,this._screenHeight=this._height*this._pixelRatio,this._screenWidth=this._width*this._pixelRatio}catch(i){console.error(i)}}};var Et=()=>window.ManagedMediaSource||window.MediaSource,Gr=()=>{var s,e;return!!(window.ManagedMediaSource&&((e=(s=window.ManagedSourceBuffer)==null?void 0:s.prototype)!=null&&e.appendBuffer))},uy=()=>{var s,e;return!!(window.MediaSource&&((e=(s=window.SourceBuffer)==null?void 0:s.prototype)!=null&&e.appendBuffer))},hu=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var s$=document.createElement("video"),a$='video/mp4; codecs="avc1.42000a,mp4a.40.2"',n$='video/mp4; codecs="hev1.1.6.L93.B0"',ly='video/webm; codecs="vp09.00.10.08"',cy='video/webm; codecs="av01.0.00M.08"',o$='audio/mp4; codecs="mp4a.40.2"',u$='audio/webm; codecs="opus"',dy,l$=()=>E(void 0,null,function*(){if(!window.navigator.mediaCapabilities)return;let s={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=yield Promise.all([window.navigator.mediaCapabilities.decodingInfo(B(x({},s),{video:B(x({},s.video),{contentType:cy})})),window.navigator.mediaCapabilities.decodingInfo(B(x({},s),{video:B(x({},s.video),{contentType:ly})}))]);dy={DASH_WEBM_AV1:e,DASH_WEBM:t}});l$().catch(s=>{console.log(s$),console.error(s)});var fu=class{constructor(e,t){this._deviceChecker=e,this._browserChecker=t}get protocols(){return this._protocols}get containers(){return this._containers}get codecs(){return this._codecs}get webmDecodingInfo(){return dy}get supportedCodecs(){return Object.keys(this._codecs).filter(e=>this._codecs[e])}get nativeHlsSupported(){return this._nativeHlsSupported}detect(){var e,t,i,r,a,n,o,u,l,d,c,h,p,f,m,g,S,v,y,T;this._video=document.createElement("video");try{this._protocols={mms:Gr(),mse:uy(),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 I=!!((d=(l=Et())==null?void 0:l.isTypeSupported)!=null&&d.call(l,a$)),R=!!((h=(c=Et())==null?void 0:c.isTypeSupported)!=null&&h.call(c,n$)),C=!!((f=(p=Et())==null?void 0:p.isTypeSupported)!=null&&f.call(p,o$));this._codecs={h264:I,h265:R,vp9:!!((g=(m=Et())==null?void 0:m.isTypeSupported)!=null&&g.call(m,ly)),av1:!!((v=(S=Et())==null?void 0:S.isTypeSupported)!=null&&v.call(S,cy)),aac:C,opus:!!((T=(y=Et())==null?void 0:y.isTypeSupported)!=null&&T.call(y,u$)),mpeg:(I||R)&&C},this._nativeHlsSupported=this._protocols.hls&&this._containers.mp4}catch(I){console.error(I)}try{this.destroyVideoElement()}catch(I){console.error("Error destroying video element:",I)}}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 py="audio/mpeg",mu=class{supportMp3(){return this._codecs.mp3&&this._containers.mpeg}detect(){var e,t,i,r;this._audio=document.createElement("audio");try{this._containers={mpeg:!!((t=(e=this._audio).canPlayType)!=null&&t.call(e,py))},this._codecs={mp3:!!((r=(i=Et())==null?void 0:i.isTypeSupported)!=null&&r.call(i,py))}}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 c$}from"@vkontakte/videoplayer-shared/es2015";var zd=class{constructor(){this.isInited$=new c$(!1);this._displayChecker=new pu,this._deviceChecker=new du(this._displayChecker),this._browserChecker=new cu,this._videoChecker=new fu(this._deviceChecker,this._browserChecker),this._audioChecker=new mu,this.detect()}get display(){return this._displayChecker}get device(){return this._deviceChecker}get browser(){return this._browserChecker}get video(){return this._videoChecker}get audio(){return this._audioChecker}detect(){return E(this,null,function*(){this._displayChecker.detect(),this._deviceChecker.detect(),this._browserChecker.detect(),this._videoChecker.detect(),this._audioChecker.detect(),this.isInited$.next(!0)})}},Q=new zd;var lt=s=>{let e=w=>et(s,w).pipe(Gd(void 0)),t=new b$,i=()=>t.unsubscribe(),r=bu(et(s,"progress"),et(s,"timeupdate")).pipe(Jt(()=>ny(s.buffered,s.currentTime))),a=Q.browser.isSafari?p$({play:e("play").pipe(h$()),playing:e("playing")}).pipe(Gd(void 0)):e("playing"),n=et(s,"volumechange").pipe(Jt(()=>({muted:s.muted,volume:s.volume}))),o=et(s,"ratechange").pipe(Jt(()=>s.playbackRate)),u=et(s,"error").pipe(Qd(()=>!!(s.error||s.played.length)),Jt(()=>{var F;let w=s.error;return{id:w?`MediaError#${w.code}`:"HtmlVideoError",category:m$.VIDEO_PIPELINE,message:w?w.message:"Error event from HTML video element",thrown:(F=s.error)!=null?F:void 0}})),l=et(s,"timeupdate").pipe(Jt(()=>s.currentTime)),d=["waiting","seeking","seeked","timeupdate"],c=new d$,h=.3,p;t.add(bu(...d.map(w=>et(s,w))).subscribe(w=>{let F=s.currentTime;s.loop&&fy(p)&&fy(F)&&p>=s.duration-h&&F<=h&&c.next(p),p=F}));let f=e("pause").pipe(Qd(()=>!s.error&&p!==s.duration)),m=et(s,"enterpictureinpicture"),g=et(s,"leavepictureinpicture"),S=new my(ay(s));t.add(m.subscribe(()=>S.next(!0))),t.add(g.subscribe(()=>S.next(!1)));let v=new my(Hd(s)),y=et(s,"fullscreenchange");t.add(y.pipe(Jt(()=>Hd(s))).subscribe(v));let T=.1,I=1e3,R=et(s,"timeupdate").pipe(Jt(w=>s.duration-s.currentTime<T),hy()),C=bu(R.pipe(Qd(w=>!s.loop&&w)),et(s,"ended")).pipe(f$(I),Gd(void 0)),$=bu(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(w=>et(s,w)),R.pipe(Jt(w=>({type:w?"ended":"unknown"})))).pipe(Jt(w=>Q.browser.isFirefox&&w.type==="ended"?s.readyState<2:s.readyState<3),hy());return{playing$:a,pause$:f,canplay$:e("canplay"),ended$:C,looped$:c,error$:u,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:l,durationChange$:et(s,"durationchange").pipe(Jt(()=>s.duration)),isBuffering$:$,currentBuffer$:r,volumeState$:n,playbackRateState$:o,inPiP$:S,inFullscreen$:v,enterPip$:m,leavePip$:g,destroy:i}};import{VideoQuality as Vi}from"@vkontakte/videoplayer-shared/es2015";var Oi=s=>{switch(s){case"mobile":return Vi.Q_144P;case"lowest":return Vi.Q_240P;case"low":return Vi.Q_360P;case"sd":case"medium":return Vi.Q_480P;case"hd":case"high":return Vi.Q_720P;case"fullhd":case"full":return Vi.Q_1080P;case"quadhd":case"quad":return Vi.Q_1440P;case"ultrahd":case"ultra":return Vi.Q_2160P}};var it=H(qt(),1),Kd=H(It(),1),fr=H(sr(),1);import{isNonNullable as oe,isNullable as Tu,now as Ly,isHigher as Iu,isHigherOrEqual as Yr,isInvariantQuality as xu,isLowerOrEqual as Kr,videoSizeToQuality as By,assertNotEmptyArray as Eu,assertNonNullable as $y}from"@vkontakte/videoplayer-shared/es2015";var Wd=!1,yi={},Iy=s=>{Wd=s},xy=()=>{yi={}},Ey=s=>{s(yi)},Da=(s,e)=>{var t;Wd&&(yi.meta=(t=yi.meta)!=null?t:{},yi.meta[s]=e)},tt=class{constructor(e){this.name=e}next(e){var i,r;if(!Wd)return;yi.series=(i=yi.series)!=null?i:{};let t=(r=yi.series[this.name])!=null?r:[];t.push([Date.now(),e]),yi.series[this.name]=t}};import{isHigher as w$,isHigherOrEqual as vq,isLower as wy,isLowerOrEqual as yq,isNonNullable as gu,isNullable as A$,videoHeightToQuality as Su}from"@vkontakte/videoplayer-shared/es2015";function Yd(s,e,t){return!s.max&&s.min===e?"high_quality":!s.min&&s.max===t?"traffic_saving":"unknown"}function vu(s,e,t){return!!s&&Yd(s,e,t)==="high_quality"}function Wr(s,e,t){return A$(s)||gu(s.min)&&gu(s.max)&&wy(s.max,s.min)||gu(s.min)&&e&&w$(s.min,e)||gu(s.max)&&t&&wy(s.max,t)}function Ay({limits:s,highestAvailableHeight:e,lowestAvailableHeight:t}){return Wr({max:s!=null&&s.max?Su(s.max):void 0,min:s!=null&&s.min?Su(s.min):void 0},e?Su(e):void 0,t?Su(t):void 0)}var Dy=new tt("best_bitrate"),wu=(s,e,t)=>(e-t)*Math.pow(2,-10*s)+t;var Xr=s=>(e,t)=>s*(Number(e.bitrate)-Number(t.bitrate)),_i=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=Ly()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},Au='Assertion "ABR Tracks is empty array" failed',yu=new WeakMap,Py=new WeakMap,Ry=new WeakMap,Ca=(s,e,t,i)=>{var u;let r=[...e].sort(Xr(1)),a=[...t].sort(Xr(1)),n=a.filter(l=>oe(l.bitrate)&&oe(s.bitrate)?s.bitrate/l.bitrate>i:!0),o=(u=(0,it.default)(a,Math.round(a.length*r.indexOf(s)/(r.length+1))))!=null?u:(0,it.default)(a,-1);return o&&(0,Kd.default)(n,o)?o:n.length?(0,it.default)(n,-1):(0,it.default)(a,0)},Va=(s,e,t,i)=>{var u;let r=yu.get(e);r||(r=[...e].sort(Xr(1)),yu.set(e,r));let a=yu.get(t);a||(a=[...t].sort(Xr(1)),yu.set(t,a));let n=Ry.get(s);n||(n=a.filter(l=>oe(l.bitrate)&&oe(s.bitrate)?s.bitrate/l.bitrate>i:!0),Ry.set(s,n));let o=(u=(0,it.default)(a,Math.round(a.length*r.indexOf(s)/(r.length+1))))!=null?u:(0,it.default)(a,-1);return o&&(0,Kd.default)(n,o)?o:n.length?(0,it.default)(n,-1):(0,it.default)(a,0)},ky=s=>"quality"in s,Pu=(s,e,t,i)=>{var n;let r=oe((n=i==null?void 0:i.last)==null?void 0:n.bitrate)&&oe(t==null?void 0:t.bitrate)&&i.last.bitrate<t.bitrate?s.trackCooldownIncreaseQuality:s.trackCooldownDecreaseQuality,a=t&&i&&i.history[t.id]&&Ly()-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=ky(o)?"video":"audio",l=ky(o)?o.quality:o.bitrate;return e({message:`
|
|
6
|
+
var qE=Object.create;var ql=Object.defineProperty,jE=Object.defineProperties,HE=Object.getOwnPropertyDescriptor,zE=Object.getOwnPropertyDescriptors,QE=Object.getOwnPropertyNames,wo=Object.getOwnPropertySymbols,GE=Object.getPrototypeOf,jl=Object.prototype.hasOwnProperty,Uh=Object.prototype.propertyIsEnumerable;var WE=(s,e)=>(e=Symbol[s])?e:Symbol.for("Symbol."+s);var Ze=Math.pow,Nh=(s,e,t)=>e in s?ql(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,x=(s,e)=>{for(var t in e||(e={}))jl.call(e,t)&&Nh(s,t,e[t]);if(wo)for(var t of wo(e))Uh.call(e,t)&&Nh(s,t,e[t]);return s},B=(s,e)=>jE(s,zE(e));var qh=(s,e)=>{var t={};for(var i in s)jl.call(s,i)&&e.indexOf(i)<0&&(t[i]=s[i]);if(s!=null&&wo)for(var i of wo(s))e.indexOf(i)<0&&Uh.call(s,i)&&(t[i]=s[i]);return t};var b=(s,e)=>()=>(e||s((e={exports:{}}).exports,e),e.exports);var YE=(s,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of QE(e))!jl.call(s,r)&&r!==t&&ql(s,r,{get:()=>e[r],enumerable:!(i=HE(e,r))||i.enumerable});return s};var H=(s,e,t)=>(t=s!=null?qE(GE(s)):{},YE(e||!s||!s.__esModule?ql(t,"default",{value:s,enumerable:!0}):t,s));var E=(s,e,t)=>new Promise((i,r)=>{var a=u=>{try{o(t.next(u))}catch(l){r(l)}},n=u=>{try{o(t.throw(u))}catch(l){r(l)}},o=u=>u.done?i(u.value):Promise.resolve(u.value).then(a,n);o((t=t.apply(s,e)).next())}),Zi=function(s,e){this[0]=s,this[1]=e},X=(s,e,t)=>{var i=(n,o,u,l)=>{try{var d=t[n](o),c=(o=d.value)instanceof Zi,f=d.done;Promise.resolve(c?o[0]:o).then(p=>c?i(n==="return"?n:"next",o[1]?{done:p.done,value:p.value}:p,u,l):u({value:p,done:f})).catch(p=>i("throw",p,u,l))}catch(p){l(p)}},r=n=>a[n]=o=>new Promise((u,l)=>i(n,o,u,l)),a={};return t=t.apply(s,e),a[WE("asyncIterator")]=()=>a,r("next"),r("throw"),r("return"),a};var xe=b((Ql,Hh)=>{"use strict";var na=function(s){return s&&s.Math===Math&&s};Hh.exports=na(typeof globalThis=="object"&&globalThis)||na(typeof window=="object"&&window)||na(typeof self=="object"&&self)||na(typeof global=="object"&&global)||na(typeof Ql=="object"&&Ql)||function(){return this}()||Function("return this")()});var Ue=b((d_,zh)=>{"use strict";zh.exports=function(s){try{return!!s()}catch(e){return!0}}});var oa=b((p_,Qh)=>{"use strict";var KE=Ue();Qh.exports=!KE(function(){var s=function(){}.bind();return typeof s!="function"||s.hasOwnProperty("prototype")})});var Gl=b((h_,Kh)=>{"use strict";var XE=oa(),Yh=Function.prototype,Gh=Yh.apply,Wh=Yh.call;Kh.exports=typeof Reflect=="object"&&Reflect.apply||(XE?Wh.bind(Gh):function(){return Wh.apply(Gh,arguments)})});var Ce=b((f_,Zh)=>{"use strict";var Xh=oa(),Jh=Function.prototype,Wl=Jh.call,JE=Xh&&Jh.bind.bind(Wl,Wl);Zh.exports=Xh?JE:function(s){return function(){return Wl.apply(s,arguments)}}});var er=b((m_,tf)=>{"use strict";var ef=Ce(),ZE=ef({}.toString),ew=ef("".slice);tf.exports=function(s){return ew(ZE(s),8,-1)}});var Yl=b((b_,rf)=>{"use strict";var tw=er(),iw=Ce();rf.exports=function(s){if(tw(s)==="Function")return iw(s)}});var Te=b((g_,sf)=>{"use strict";var Kl=typeof document=="object"&&document.all;sf.exports=typeof Kl=="undefined"&&Kl!==void 0?function(s){return typeof s=="function"||s===Kl}:function(s){return typeof s=="function"}});var vt=b((S_,af)=>{"use strict";var rw=Ue();af.exports=!rw(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var yt=b((v_,nf)=>{"use strict";var sw=oa(),ko=Function.prototype.call;nf.exports=sw?ko.bind(ko):function(){return ko.apply(ko,arguments)}});var Xl=b(lf=>{"use strict";var of={}.propertyIsEnumerable,uf=Object.getOwnPropertyDescriptor,aw=uf&&!of.call({1:2},1);lf.f=aw?function(e){var t=uf(this,e);return!!t&&t.enumerable}:of});var ua=b((T_,cf)=>{"use strict";cf.exports=function(s,e){return{enumerable:!(s&1),configurable:!(s&2),writable:!(s&4),value:e}}});var pf=b((I_,df)=>{"use strict";var nw=Ce(),ow=Ue(),uw=er(),Jl=Object,lw=nw("".split);df.exports=ow(function(){return!Jl("z").propertyIsEnumerable(0)})?function(s){return uw(s)==="String"?lw(s,""):Jl(s)}:Jl});var Pr=b((x_,hf)=>{"use strict";hf.exports=function(s){return s==null}});var Bi=b((E_,ff)=>{"use strict";var cw=Pr(),dw=TypeError;ff.exports=function(s){if(cw(s))throw new dw("Can't call method on "+s);return s}});var tr=b((w_,mf)=>{"use strict";var pw=pf(),hw=Bi();mf.exports=function(s){return pw(hw(s))}});var Tt=b((A_,bf)=>{"use strict";var fw=Te();bf.exports=function(s){return typeof s=="object"?s!==null:fw(s)}});var kr=b((P_,gf)=>{"use strict";gf.exports={}});var gi=b((k_,vf)=>{"use strict";var Zl=kr(),ec=xe(),mw=Te(),Sf=function(s){return mw(s)?s:void 0};vf.exports=function(s,e){return arguments.length<2?Sf(Zl[s])||Sf(ec[s]):Zl[s]&&Zl[s][e]||ec[s]&&ec[s][e]}});var la=b((R_,yf)=>{"use strict";var bw=Ce();yf.exports=bw({}.isPrototypeOf)});var ir=b((M_,xf)=>{"use strict";var gw=xe(),Tf=gw.navigator,If=Tf&&Tf.userAgent;xf.exports=If?String(If):""});var ic=b((L_,Rf)=>{"use strict";var kf=xe(),tc=ir(),Ef=kf.process,wf=kf.Deno,Af=Ef&&Ef.versions||wf&&wf.version,Pf=Af&&Af.v8,_t,Ro;Pf&&(_t=Pf.split("."),Ro=_t[0]>0&&_t[0]<4?1:+(_t[0]+_t[1]));!Ro&&tc&&(_t=tc.match(/Edge\/(\d+)/),(!_t||_t[1]>=74)&&(_t=tc.match(/Chrome\/(\d+)/),_t&&(Ro=+_t[1])));Rf.exports=Ro});var rc=b((B_,Lf)=>{"use strict";var Mf=ic(),Sw=Ue(),vw=xe(),yw=vw.String;Lf.exports=!!Object.getOwnPropertySymbols&&!Sw(function(){var s=Symbol("symbol detection");return!yw(s)||!(Object(s)instanceof Symbol)||!Symbol.sham&&Mf&&Mf<41})});var sc=b(($_,Bf)=>{"use strict";var Tw=rc();Bf.exports=Tw&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var ac=b((D_,$f)=>{"use strict";var Iw=gi(),xw=Te(),Ew=la(),ww=sc(),Aw=Object;$f.exports=ww?function(s){return typeof s=="symbol"}:function(s){var e=Iw("Symbol");return xw(e)&&Ew(e.prototype,Aw(s))}});var ca=b((C_,Df)=>{"use strict";var Pw=String;Df.exports=function(s){try{return Pw(s)}catch(e){return"Object"}}});var Wt=b((V_,Cf)=>{"use strict";var kw=Te(),Rw=ca(),Mw=TypeError;Cf.exports=function(s){if(kw(s))return s;throw new Mw(Rw(s)+" is not a function")}});var da=b((O_,Vf)=>{"use strict";var Lw=Wt(),Bw=Pr();Vf.exports=function(s,e){var t=s[e];return Bw(t)?void 0:Lw(t)}});var _f=b((__,Of)=>{"use strict";var nc=yt(),oc=Te(),uc=Tt(),$w=TypeError;Of.exports=function(s,e){var t,i;if(e==="string"&&oc(t=s.toString)&&!uc(i=nc(t,s))||oc(t=s.valueOf)&&!uc(i=nc(t,s))||e!=="string"&&oc(t=s.toString)&&!uc(i=nc(t,s)))return i;throw new $w("Can't convert object to primitive value")}});var Ft=b((F_,Ff)=>{"use strict";Ff.exports=!0});var qf=b((N_,Uf)=>{"use strict";var Nf=xe(),Dw=Object.defineProperty;Uf.exports=function(s,e){try{Dw(Nf,s,{value:e,configurable:!0,writable:!0})}catch(t){Nf[s]=e}return e}});var pa=b((U_,zf)=>{"use strict";var Cw=Ft(),Vw=xe(),Ow=qf(),jf="__core-js_shared__",Hf=zf.exports=Vw[jf]||Ow(jf,{});(Hf.versions||(Hf.versions=[])).push({version:"3.38.0",mode:Cw?"pure":"global",copyright:"\xA9 2014-2024 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.38.0/LICENSE",source:"https://github.com/zloirock/core-js"})});var lc=b((q_,Gf)=>{"use strict";var Qf=pa();Gf.exports=function(s,e){return Qf[s]||(Qf[s]=e||{})}});var Rr=b((j_,Wf)=>{"use strict";var _w=Bi(),Fw=Object;Wf.exports=function(s){return Fw(_w(s))}});var Nt=b((H_,Yf)=>{"use strict";var Nw=Ce(),Uw=Rr(),qw=Nw({}.hasOwnProperty);Yf.exports=Object.hasOwn||function(e,t){return qw(Uw(e),t)}});var cc=b((z_,Kf)=>{"use strict";var jw=Ce(),Hw=0,zw=Math.random(),Qw=jw(1 .toString);Kf.exports=function(s){return"Symbol("+(s===void 0?"":s)+")_"+Qw(++Hw+zw,36)}});var qe=b((Q_,Jf)=>{"use strict";var Gw=xe(),Ww=lc(),Xf=Nt(),Yw=cc(),Kw=rc(),Xw=sc(),Mr=Gw.Symbol,dc=Ww("wks"),Jw=Xw?Mr.for||Mr:Mr&&Mr.withoutSetter||Yw;Jf.exports=function(s){return Xf(dc,s)||(dc[s]=Kw&&Xf(Mr,s)?Mr[s]:Jw("Symbol."+s)),dc[s]}});var im=b((G_,tm)=>{"use strict";var Zw=yt(),Zf=Tt(),em=ac(),eA=da(),tA=_f(),iA=qe(),rA=TypeError,sA=iA("toPrimitive");tm.exports=function(s,e){if(!Zf(s)||em(s))return s;var t=eA(s,sA),i;if(t){if(e===void 0&&(e="default"),i=Zw(t,s,e),!Zf(i)||em(i))return i;throw new rA("Can't convert object to primitive value")}return e===void 0&&(e="number"),tA(s,e)}});var pc=b((W_,rm)=>{"use strict";var aA=im(),nA=ac();rm.exports=function(s){var e=aA(s,"string");return nA(e)?e:e+""}});var Mo=b((Y_,am)=>{"use strict";var oA=xe(),sm=Tt(),hc=oA.document,uA=sm(hc)&&sm(hc.createElement);am.exports=function(s){return uA?hc.createElement(s):{}}});var fc=b((K_,nm)=>{"use strict";var lA=vt(),cA=Ue(),dA=Mo();nm.exports=!lA&&!cA(function(){return Object.defineProperty(dA("div"),"a",{get:function(){return 7}}).a!==7})});var lm=b(um=>{"use strict";var pA=vt(),hA=yt(),fA=Xl(),mA=ua(),bA=tr(),gA=pc(),SA=Nt(),vA=fc(),om=Object.getOwnPropertyDescriptor;um.f=pA?om:function(e,t){if(e=bA(e),t=gA(t),vA)try{return om(e,t)}catch(i){}if(SA(e,t))return mA(!hA(fA.f,e,t),e[t])}});var mc=b((J_,cm)=>{"use strict";var yA=Ue(),TA=Te(),IA=/#|\.prototype\./,ha=function(s,e){var t=EA[xA(s)];return t===AA?!0:t===wA?!1:TA(e)?yA(e):!!e},xA=ha.normalize=function(s){return String(s).replace(IA,".").toLowerCase()},EA=ha.data={},wA=ha.NATIVE="N",AA=ha.POLYFILL="P";cm.exports=ha});var Lr=b((Z_,pm)=>{"use strict";var dm=Yl(),PA=Wt(),kA=oa(),RA=dm(dm.bind);pm.exports=function(s,e){return PA(s),e===void 0?s:kA?RA(s,e):function(){return s.apply(e,arguments)}}});var bc=b((eF,hm)=>{"use strict";var MA=vt(),LA=Ue();hm.exports=MA&&LA(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var Yt=b((tF,fm)=>{"use strict";var BA=Tt(),$A=String,DA=TypeError;fm.exports=function(s){if(BA(s))return s;throw new DA($A(s)+" is not an object")}});var rr=b(bm=>{"use strict";var CA=vt(),VA=fc(),OA=bc(),Lo=Yt(),mm=pc(),_A=TypeError,gc=Object.defineProperty,FA=Object.getOwnPropertyDescriptor,Sc="enumerable",vc="configurable",yc="writable";bm.f=CA?OA?function(e,t,i){if(Lo(e),t=mm(t),Lo(i),typeof e=="function"&&t==="prototype"&&"value"in i&&yc in i&&!i[yc]){var r=FA(e,t);r&&r[yc]&&(e[t]=i.value,i={configurable:vc in i?i[vc]:r[vc],enumerable:Sc in i?i[Sc]:r[Sc],writable:!1})}return gc(e,t,i)}:gc:function(e,t,i){if(Lo(e),t=mm(t),Lo(i),VA)try{return gc(e,t,i)}catch(r){}if("get"in i||"set"in i)throw new _A("Accessors not supported");return"value"in i&&(e[t]=i.value),e}});var Br=b((rF,gm)=>{"use strict";var NA=vt(),UA=rr(),qA=ua();gm.exports=NA?function(s,e,t){return UA.f(s,e,qA(1,t))}:function(s,e,t){return s[e]=t,s}});var ke=b((sF,vm)=>{"use strict";var fa=xe(),jA=Gl(),HA=Yl(),zA=Te(),QA=lm().f,GA=mc(),$r=kr(),WA=Lr(),Dr=Br(),Sm=Nt();pa();var YA=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 jA(s,this,arguments)};return e.prototype=s.prototype,e};vm.exports=function(s,e){var t=s.target,i=s.global,r=s.stat,a=s.proto,n=i?fa:r?fa[t]:fa[t]&&fa[t].prototype,o=i?$r:$r[t]||Dr($r,t,{})[t],u=o.prototype,l,d,c,f,p,h,m,g,S;for(f in e)l=GA(i?f:t+(r?".":"#")+f,s.forced),d=!l&&n&&Sm(n,f),h=o[f],d&&(s.dontCallGetSet?(S=QA(n,f),m=S&&S.value):m=n[f]),p=d&&m?m:e[f],!(!l&&!a&&typeof h==typeof p)&&(s.bind&&d?g=WA(p,fa):s.wrap&&d?g=YA(p):a&&zA(p)?g=HA(p):g=p,(s.sham||p&&p.sham||h&&h.sham)&&Dr(g,"sham",!0),Dr(o,f,g),a&&(c=t+"Prototype",Sm($r,c)||Dr($r,c,{}),Dr($r[c],f,p),s.real&&u&&(l||!u[f])&&Dr(u,f,p)))}});var Tm=b((aF,ym)=>{"use strict";var KA=Math.ceil,XA=Math.floor;ym.exports=Math.trunc||function(e){var t=+e;return(t>0?XA:KA)(t)}});var ma=b((nF,Im)=>{"use strict";var JA=Tm();Im.exports=function(s){var e=+s;return e!==e||e===0?0:JA(e)}});var Em=b((oF,xm)=>{"use strict";var ZA=ma(),eP=Math.max,tP=Math.min;xm.exports=function(s,e){var t=ZA(s);return t<0?eP(t+e,0):tP(t,e)}});var Tc=b((uF,wm)=>{"use strict";var iP=ma(),rP=Math.min;wm.exports=function(s){var e=iP(s);return e>0?rP(e,9007199254740991):0}});var Cr=b((lF,Am)=>{"use strict";var sP=Tc();Am.exports=function(s){return sP(s.length)}});var Ic=b((cF,km)=>{"use strict";var aP=tr(),nP=Em(),oP=Cr(),Pm=function(s){return function(e,t,i){var r=aP(e),a=oP(r);if(a===0)return!s&&-1;var n=nP(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}};km.exports={includes:Pm(!0),indexOf:Pm(!1)}});var ba=b((dF,Rm)=>{"use strict";Rm.exports=function(){}});var Mm=b(()=>{"use strict";var uP=ke(),lP=Ic().includes,cP=Ue(),dP=ba(),pP=cP(function(){return!Array(1).includes()});uP({target:"Array",proto:!0,forced:pP},{includes:function(e){return lP(this,e,arguments.length>1?arguments[1]:void 0)}});dP("includes")});var $i=b((fF,Lm)=>{"use strict";var hP=gi();Lm.exports=hP});var $m=b((mF,Bm)=>{"use strict";Mm();var fP=$i();Bm.exports=fP("Array","includes")});var Cm=b((bF,Dm)=>{"use strict";var mP=$m();Dm.exports=mP});var It=b((gF,Vm)=>{"use strict";var bP=Cm();Vm.exports=bP});var Do=b((RF,Hm)=>{"use strict";var EP=lc(),wP=cc(),jm=EP("keys");Hm.exports=function(s){return jm[s]||(jm[s]=wP(s))}});var Qm=b((MF,zm)=>{"use strict";var AP=Ue();zm.exports=!AP(function(){function s(){}return s.prototype.constructor=null,Object.getPrototypeOf(new s)!==s.prototype})});var Co=b((LF,Wm)=>{"use strict";var PP=Nt(),kP=Te(),RP=Rr(),MP=Do(),LP=Qm(),Gm=MP("IE_PROTO"),wc=Object,BP=wc.prototype;Wm.exports=LP?wc.getPrototypeOf:function(s){var e=RP(s);if(PP(e,Gm))return e[Gm];var t=e.constructor;return kP(t)&&e instanceof t?t.prototype:e instanceof wc?BP:null}});var Vo=b((BF,Ym)=>{"use strict";Ym.exports={}});var Jm=b(($F,Xm)=>{"use strict";var $P=Ce(),Ac=Nt(),DP=tr(),CP=Ic().indexOf,VP=Vo(),Km=$P([].push);Xm.exports=function(s,e){var t=DP(s),i=0,r=[],a;for(a in t)!Ac(VP,a)&&Ac(t,a)&&Km(r,a);for(;e.length>i;)Ac(t,a=e[i++])&&(~CP(r,a)||Km(r,a));return r}});var Pc=b((DF,Zm)=>{"use strict";Zm.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var kc=b((CF,eb)=>{"use strict";var OP=Jm(),_P=Pc();eb.exports=Object.keys||function(e){return OP(e,_P)}});var Rc=b((VF,ab)=>{"use strict";var ib=vt(),FP=Ue(),rb=Ce(),NP=Co(),UP=kc(),qP=tr(),jP=Xl().f,sb=rb(jP),HP=rb([].push),zP=ib&&FP(function(){var s=Object.create(null);return s[2]=2,!sb(s,2)}),tb=function(s){return function(e){for(var t=qP(e),i=UP(t),r=zP&&NP(t)===null,a=i.length,n=0,o=[],u;a>n;)u=i[n++],(!ib||(r?u in t:sb(t,u)))&&HP(o,s?[u,t[u]]:t[u]);return o}};ab.exports={entries:tb(!0),values:tb(!1)}});var nb=b(()=>{"use strict";var QP=ke(),GP=Rc().entries;QP({target:"Object",stat:!0},{entries:function(e){return GP(e)}})});var ub=b((FF,ob)=>{"use strict";nb();var WP=kr();ob.exports=WP.Object.entries});var cb=b((NF,lb)=>{"use strict";var YP=ub();lb.exports=YP});var sr=b((UF,db)=>{"use strict";var KP=cb();db.exports=KP});var ar=b((qF,pb)=>{"use strict";pb.exports={}});var mb=b((jF,fb)=>{"use strict";var XP=xe(),JP=Te(),hb=XP.WeakMap;fb.exports=JP(hb)&&/native code/.test(String(hb))});var $c=b((HF,Sb)=>{"use strict";var ZP=mb(),gb=xe(),ek=Tt(),tk=Br(),Mc=Nt(),Lc=pa(),ik=Do(),rk=Vo(),bb="Object already initialized",Bc=gb.TypeError,sk=gb.WeakMap,Oo,ga,_o,ak=function(s){return _o(s)?ga(s):Oo(s,{})},nk=function(s){return function(e){var t;if(!ek(e)||(t=ga(e)).type!==s)throw new Bc("Incompatible receiver, "+s+" required");return t}};ZP||Lc.state?(Ut=Lc.state||(Lc.state=new sk),Ut.get=Ut.get,Ut.has=Ut.has,Ut.set=Ut.set,Oo=function(s,e){if(Ut.has(s))throw new Bc(bb);return e.facade=s,Ut.set(s,e),e},ga=function(s){return Ut.get(s)||{}},_o=function(s){return Ut.has(s)}):(nr=ik("state"),rk[nr]=!0,Oo=function(s,e){if(Mc(s,nr))throw new Bc(bb);return e.facade=s,tk(s,nr,e),e},ga=function(s){return Mc(s,nr)?s[nr]:{}},_o=function(s){return Mc(s,nr)});var Ut,nr;Sb.exports={set:Oo,get:ga,has:_o,enforce:ak,getterFor:nk}});var Vc=b((zF,yb)=>{"use strict";var Dc=vt(),ok=Nt(),vb=Function.prototype,uk=Dc&&Object.getOwnPropertyDescriptor,Cc=ok(vb,"name"),lk=Cc&&function(){}.name==="something",ck=Cc&&(!Dc||Dc&&uk(vb,"name").configurable);yb.exports={EXISTS:Cc,PROPER:lk,CONFIGURABLE:ck}});var Ib=b(Tb=>{"use strict";var dk=vt(),pk=bc(),hk=rr(),fk=Yt(),mk=tr(),bk=kc();Tb.f=dk&&!pk?Object.defineProperties:function(e,t){fk(e);for(var i=mk(t),r=bk(t),a=r.length,n=0,o;a>n;)hk.f(e,o=r[n++],i[o]);return e}});var Oc=b((GF,xb)=>{"use strict";var gk=gi();xb.exports=gk("document","documentElement")});var Uc=b((WF,Mb)=>{"use strict";var Sk=Yt(),vk=Ib(),Eb=Pc(),yk=Vo(),Tk=Oc(),Ik=Mo(),xk=Do(),wb=">",Ab="<",Fc="prototype",Nc="script",kb=xk("IE_PROTO"),_c=function(){},Rb=function(s){return Ab+Nc+wb+s+Ab+"/"+Nc+wb},Pb=function(s){s.write(Rb("")),s.close();var e=s.parentWindow.Object;return s=null,e},Ek=function(){var s=Ik("iframe"),e="java"+Nc+":",t;return s.style.display="none",Tk.appendChild(s),s.src=String(e),t=s.contentWindow.document,t.open(),t.write(Rb("document.F=Object")),t.close(),t.F},Fo,No=function(){try{Fo=new ActiveXObject("htmlfile")}catch(e){}No=typeof document!="undefined"?document.domain&&Fo?Pb(Fo):Ek():Pb(Fo);for(var s=Eb.length;s--;)delete No[Fc][Eb[s]];return No()};yk[kb]=!0;Mb.exports=Object.create||function(e,t){var i;return e!==null?(_c[Fc]=Sk(e),i=new _c,_c[Fc]=null,i[kb]=e):i=No(),t===void 0?i:vk.f(i,t)}});var Vr=b((YF,Lb)=>{"use strict";var wk=Br();Lb.exports=function(s,e,t,i){return i&&i.enumerable?s[e]=t:wk(s,e,t),s}});var zc=b((KF,Db)=>{"use strict";var Ak=Ue(),Pk=Te(),kk=Tt(),Rk=Uc(),Bb=Co(),Mk=Vr(),Lk=qe(),Bk=Ft(),Hc=Lk("iterator"),$b=!1,Si,qc,jc;[].keys&&(jc=[].keys(),"next"in jc?(qc=Bb(Bb(jc)),qc!==Object.prototype&&(Si=qc)):$b=!0);var $k=!kk(Si)||Ak(function(){var s={};return Si[Hc].call(s)!==s});$k?Si={}:Bk&&(Si=Rk(Si));Pk(Si[Hc])||Mk(Si,Hc,function(){return this});Db.exports={IteratorPrototype:Si,BUGGY_SAFARI_ITERATORS:$b}});var Uo=b((XF,Vb)=>{"use strict";var Dk=qe(),Ck=Dk("toStringTag"),Cb={};Cb[Ck]="z";Vb.exports=String(Cb)==="[object z]"});var Sa=b((JF,Ob)=>{"use strict";var Vk=Uo(),Ok=Te(),qo=er(),_k=qe(),Fk=_k("toStringTag"),Nk=Object,Uk=qo(function(){return arguments}())==="Arguments",qk=function(s,e){try{return s[e]}catch(t){}};Ob.exports=Vk?qo:function(s){var e,t,i;return s===void 0?"Undefined":s===null?"Null":typeof(t=qk(e=Nk(s),Fk))=="string"?t:Uk?qo(e):(i=qo(e))==="Object"&&Ok(e.callee)?"Arguments":i}});var Fb=b((ZF,_b)=>{"use strict";var jk=Uo(),Hk=Sa();_b.exports=jk?{}.toString:function(){return"[object "+Hk(this)+"]"}});var va=b((eN,Ub)=>{"use strict";var zk=Uo(),Qk=rr().f,Gk=Br(),Wk=Nt(),Yk=Fb(),Kk=qe(),Nb=Kk("toStringTag");Ub.exports=function(s,e,t,i){var r=t?s:s&&s.prototype;r&&(Wk(r,Nb)||Qk(r,Nb,{configurable:!0,value:e}),i&&!zk&&Gk(r,"toString",Yk))}});var jb=b((tN,qb)=>{"use strict";var Xk=zc().IteratorPrototype,Jk=Uc(),Zk=ua(),eR=va(),tR=ar(),iR=function(){return this};qb.exports=function(s,e,t,i){var r=e+" Iterator";return s.prototype=Jk(Xk,{next:Zk(+!i,t)}),eR(s,r,!1,!0),tR[r]=iR,s}});var zb=b((iN,Hb)=>{"use strict";var rR=Ce(),sR=Wt();Hb.exports=function(s,e,t){try{return rR(sR(Object.getOwnPropertyDescriptor(s,e)[t]))}catch(i){}}});var Gb=b((rN,Qb)=>{"use strict";var aR=Tt();Qb.exports=function(s){return aR(s)||s===null}});var Yb=b((sN,Wb)=>{"use strict";var nR=Gb(),oR=String,uR=TypeError;Wb.exports=function(s){if(nR(s))return s;throw new uR("Can't set "+oR(s)+" as a prototype")}});var Qc=b((aN,Kb)=>{"use strict";var lR=zb(),cR=Tt(),dR=Bi(),pR=Yb();Kb.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var s=!1,e={},t;try{t=lR(Object.prototype,"__proto__","set"),t(e,[]),s=e instanceof Array}catch(i){}return function(r,a){return dR(r),pR(a),cR(r)&&(s?t(r,a):r.__proto__=a),r}}():void 0)});var og=b((nN,ng)=>{"use strict";var hR=ke(),fR=yt(),jo=Ft(),sg=Vc(),mR=Te(),bR=jb(),Xb=Co(),Jb=Qc(),gR=va(),SR=Br(),Gc=Vr(),vR=qe(),Zb=ar(),ag=zc(),yR=sg.PROPER,TR=sg.CONFIGURABLE,eg=ag.IteratorPrototype,Ho=ag.BUGGY_SAFARI_ITERATORS,ya=vR("iterator"),tg="keys",Ta="values",ig="entries",rg=function(){return this};ng.exports=function(s,e,t,i,r,a,n){bR(t,e,i);var o=function(S){if(S===r&&f)return f;if(!Ho&&S&&S in d)return d[S];switch(S){case tg:return function(){return new t(this,S)};case Ta:return function(){return new t(this,S)};case ig:return function(){return new t(this,S)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,d=s.prototype,c=d[ya]||d["@@iterator"]||r&&d[r],f=!Ho&&c||o(r),p=e==="Array"&&d.entries||c,h,m,g;if(p&&(h=Xb(p.call(new s)),h!==Object.prototype&&h.next&&(!jo&&Xb(h)!==eg&&(Jb?Jb(h,eg):mR(h[ya])||Gc(h,ya,rg)),gR(h,u,!0,!0),jo&&(Zb[u]=rg))),yR&&r===Ta&&c&&c.name!==Ta&&(!jo&&TR?SR(d,"name",Ta):(l=!0,f=function(){return fR(c,this)})),r)if(m={values:o(Ta),keys:a?f:o(tg),entries:o(ig)},n)for(g in m)(Ho||l||!(g in d))&&Gc(d,g,m[g]);else hR({target:e,proto:!0,forced:Ho||l},m);return(!jo||n)&&d[ya]!==f&&Gc(d,ya,f,{name:r}),Zb[e]=f,m}});var lg=b((oN,ug)=>{"use strict";ug.exports=function(s,e){return{value:s,done:e}}});var Yc=b((uN,fg)=>{"use strict";var IR=tr(),Wc=ba(),cg=ar(),pg=$c(),xR=rr().f,ER=og(),zo=lg(),wR=Ft(),AR=vt(),hg="Array Iterator",PR=pg.set,kR=pg.getterFor(hg);fg.exports=ER(Array,"Array",function(s,e){PR(this,{type:hg,target:IR(s),index:0,kind:e})},function(){var s=kR(this),e=s.target,t=s.index++;if(!e||t>=e.length)return s.target=void 0,zo(void 0,!0);switch(s.kind){case"keys":return zo(t,!1);case"values":return zo(e[t],!1)}return zo([t,e[t]],!1)},"values");var dg=cg.Arguments=cg.Array;Wc("keys");Wc("values");Wc("entries");if(!wR&&AR&&dg.name!=="values")try{xR(dg,"name",{value:"values"})}catch(s){}});var bg=b((lN,mg)=>{"use strict";var RR=qe(),MR=ar(),LR=RR("iterator"),BR=Array.prototype;mg.exports=function(s){return s!==void 0&&(MR.Array===s||BR[LR]===s)}});var Kc=b((cN,Sg)=>{"use strict";var $R=Sa(),gg=da(),DR=Pr(),CR=ar(),VR=qe(),OR=VR("iterator");Sg.exports=function(s){if(!DR(s))return gg(s,OR)||gg(s,"@@iterator")||CR[$R(s)]}});var yg=b((dN,vg)=>{"use strict";var _R=yt(),FR=Wt(),NR=Yt(),UR=ca(),qR=Kc(),jR=TypeError;vg.exports=function(s,e){var t=arguments.length<2?qR(s):e;if(FR(t))return NR(_R(t,s));throw new jR(UR(s)+" is not iterable")}});var xg=b((pN,Ig)=>{"use strict";var HR=yt(),Tg=Yt(),zR=da();Ig.exports=function(s,e,t){var i,r;Tg(s);try{if(i=zR(s,"return"),!i){if(e==="throw")throw t;return t}i=HR(i,s)}catch(a){r=!0,i=a}if(e==="throw")throw t;if(r)throw i;return Tg(i),t}});var Go=b((hN,Pg)=>{"use strict";var QR=Lr(),GR=yt(),WR=Yt(),YR=ca(),KR=bg(),XR=Cr(),Eg=la(),JR=yg(),ZR=Kc(),wg=xg(),eM=TypeError,Qo=function(s,e){this.stopped=s,this.result=e},Ag=Qo.prototype;Pg.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=QR(e,i),l,d,c,f,p,h,m,g=function(v){return l&&wg(l,"normal",v),new Qo(!0,v)},S=function(v){return r?(WR(v),o?u(v[0],v[1],g):u(v[0],v[1])):o?u(v,g):u(v)};if(a)l=s.iterator;else if(n)l=s;else{if(d=ZR(s),!d)throw new eM(YR(s)+" is not iterable");if(KR(d)){for(c=0,f=XR(s);f>c;c++)if(p=S(s[c]),p&&Eg(Ag,p))return p;return new Qo(!1)}l=JR(s,d)}for(h=a?s.next:l.next;!(m=GR(h,l)).done;){try{p=S(m.value)}catch(v){wg(l,"throw",v)}if(typeof p=="object"&&p&&Eg(Ag,p))return p}return new Qo(!1)}});var Rg=b((fN,kg)=>{"use strict";var tM=vt(),iM=rr(),rM=ua();kg.exports=function(s,e,t){tM?iM.f(s,e,rM(0,t)):s[e]=t}});var Mg=b(()=>{"use strict";var sM=ke(),aM=Go(),nM=Rg();sM({target:"Object",stat:!0},{fromEntries:function(e){var t={};return aM(e,function(i,r){nM(t,i,r)},{AS_ENTRIES:!0}),t}})});var Bg=b((gN,Lg)=>{"use strict";Yc();Mg();var oM=kr();Lg.exports=oM.Object.fromEntries});var Dg=b((SN,$g)=>{"use strict";$g.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 Vg=b(()=>{"use strict";Yc();var uM=Dg(),lM=xe(),cM=va(),Cg=ar();for(Wo in uM)cM(lM[Wo],Wo),Cg[Wo]=Cg.Array;var Wo});var _g=b((TN,Og)=>{"use strict";var dM=Bg();Vg();Og.exports=dM});var Xc=b((IN,Fg)=>{"use strict";var pM=_g();Fg.exports=pM});var Ng=b(()=>{"use strict"});var Jc=b((wN,Ug)=>{"use strict";var Ia=xe(),hM=ir(),fM=er(),Yo=function(s){return hM.slice(0,s.length)===s};Ug.exports=function(){return Yo("Bun/")?"BUN":Yo("Cloudflare-Workers")?"CLOUDFLARE":Yo("Deno/")?"DENO":Yo("Node.js/")?"NODE":Ia.Bun&&typeof Bun.version=="string"?"BUN":Ia.Deno&&typeof Deno.version=="object"?"DENO":fM(Ia.process)==="process"?"NODE":Ia.window&&Ia.document?"BROWSER":"REST"}()});var Ko=b((AN,qg)=>{"use strict";var mM=Jc();qg.exports=mM==="NODE"});var Hg=b((PN,jg)=>{"use strict";var bM=rr();jg.exports=function(s,e,t){return bM.f(s,e,t)}});var Gg=b((kN,Qg)=>{"use strict";var gM=gi(),SM=Hg(),vM=qe(),yM=vt(),zg=vM("species");Qg.exports=function(s){var e=gM(s);yM&&e&&!e[zg]&&SM(e,zg,{configurable:!0,get:function(){return this}})}});var Yg=b((RN,Wg)=>{"use strict";var TM=la(),IM=TypeError;Wg.exports=function(s,e){if(TM(e,s))return s;throw new IM("Incorrect invocation")}});var ed=b((MN,Kg)=>{"use strict";var xM=Ce(),EM=Te(),Zc=pa(),wM=xM(Function.toString);EM(Zc.inspectSource)||(Zc.inspectSource=function(s){return wM(s)});Kg.exports=Zc.inspectSource});var id=b((LN,tS)=>{"use strict";var AM=Ce(),PM=Ue(),Xg=Te(),kM=Sa(),RM=gi(),MM=ed(),Jg=function(){},Zg=RM("Reflect","construct"),td=/^\s*(?:class|function)\b/,LM=AM(td.exec),BM=!td.test(Jg),xa=function(e){if(!Xg(e))return!1;try{return Zg(Jg,[],e),!0}catch(t){return!1}},eS=function(e){if(!Xg(e))return!1;switch(kM(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return BM||!!LM(td,MM(e))}catch(t){return!0}};eS.sham=!0;tS.exports=!Zg||PM(function(){var s;return xa(xa.call)||!xa(Object)||!xa(function(){s=!0})||s})?eS:xa});var rS=b((BN,iS)=>{"use strict";var $M=id(),DM=ca(),CM=TypeError;iS.exports=function(s){if($M(s))return s;throw new CM(DM(s)+" is not a constructor")}});var rd=b(($N,aS)=>{"use strict";var sS=Yt(),VM=rS(),OM=Pr(),_M=qe(),FM=_M("species");aS.exports=function(s,e){var t=sS(s).constructor,i;return t===void 0||OM(i=sS(t)[FM])?e:VM(i)}});var oS=b((DN,nS)=>{"use strict";var NM=Ce();nS.exports=NM([].slice)});var lS=b((CN,uS)=>{"use strict";var UM=TypeError;uS.exports=function(s,e){if(s<e)throw new UM("Not enough arguments");return s}});var sd=b((VN,cS)=>{"use strict";var qM=ir();cS.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(qM)});var hd=b((ON,vS)=>{"use strict";var xt=xe(),jM=Gl(),HM=Lr(),dS=Te(),zM=Nt(),SS=Ue(),pS=Oc(),QM=oS(),hS=Mo(),GM=lS(),WM=sd(),YM=Ko(),cd=xt.setImmediate,dd=xt.clearImmediate,KM=xt.process,ad=xt.Dispatch,XM=xt.Function,fS=xt.MessageChannel,JM=xt.String,nd=0,Ea={},mS="onreadystatechange",wa,or,od,ud;SS(function(){wa=xt.location});var pd=function(s){if(zM(Ea,s)){var e=Ea[s];delete Ea[s],e()}},ld=function(s){return function(){pd(s)}},bS=function(s){pd(s.data)},gS=function(s){xt.postMessage(JM(s),wa.protocol+"//"+wa.host)};(!cd||!dd)&&(cd=function(e){GM(arguments.length,1);var t=dS(e)?e:XM(e),i=QM(arguments,1);return Ea[++nd]=function(){jM(t,void 0,i)},or(nd),nd},dd=function(e){delete Ea[e]},YM?or=function(s){KM.nextTick(ld(s))}:ad&&ad.now?or=function(s){ad.now(ld(s))}:fS&&!WM?(od=new fS,ud=od.port2,od.port1.onmessage=bS,or=HM(ud.postMessage,ud)):xt.addEventListener&&dS(xt.postMessage)&&!xt.importScripts&&wa&&wa.protocol!=="file:"&&!SS(gS)?(or=gS,xt.addEventListener("message",bS,!1)):mS in hS("script")?or=function(s){pS.appendChild(hS("script"))[mS]=function(){pS.removeChild(this),pd(s)}}:or=function(s){setTimeout(ld(s),0)});vS.exports={set:cd,clear:dd}});var IS=b((_N,TS)=>{"use strict";var yS=xe(),ZM=vt(),eL=Object.getOwnPropertyDescriptor;TS.exports=function(s){if(!ZM)return yS[s];var e=eL(yS,s);return e&&e.value}});var fd=b((FN,ES)=>{"use strict";var xS=function(){this.head=null,this.tail=null};xS.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}}};ES.exports=xS});var AS=b((NN,wS)=>{"use strict";var tL=ir();wS.exports=/ipad|iphone|ipod/i.test(tL)&&typeof Pebble!="undefined"});var kS=b((UN,PS)=>{"use strict";var iL=ir();PS.exports=/web0s(?!.*chrome)/i.test(iL)});var CS=b((qN,DS)=>{"use strict";var _r=xe(),rL=IS(),RS=Lr(),md=hd().set,sL=fd(),aL=sd(),nL=AS(),oL=kS(),bd=Ko(),MS=_r.MutationObserver||_r.WebKitMutationObserver,LS=_r.document,BS=_r.process,Xo=_r.Promise,vd=rL("queueMicrotask"),Or,gd,Sd,Jo,$S;vd||(Aa=new sL,Pa=function(){var s,e;for(bd&&(s=BS.domain)&&s.exit();e=Aa.get();)try{e()}catch(t){throw Aa.head&&Or(),t}s&&s.enter()},!aL&&!bd&&!oL&&MS&&LS?(gd=!0,Sd=LS.createTextNode(""),new MS(Pa).observe(Sd,{characterData:!0}),Or=function(){Sd.data=gd=!gd}):!nL&&Xo&&Xo.resolve?(Jo=Xo.resolve(void 0),Jo.constructor=Xo,$S=RS(Jo.then,Jo),Or=function(){$S(Pa)}):bd?Or=function(){BS.nextTick(Pa)}:(md=RS(md,_r),Or=function(){md(Pa)}),vd=function(s){Aa.head||Or(),Aa.add(s)});var Aa,Pa;DS.exports=vd});var OS=b((jN,VS)=>{"use strict";VS.exports=function(s,e){try{arguments.length===1?console.error(s):console.error(s,e)}catch(t){}}});var Zo=b((HN,_S)=>{"use strict";_S.exports=function(s){try{return{error:!1,value:s()}}catch(e){return{error:!0,value:e}}}});var ur=b((zN,FS)=>{"use strict";var uL=xe();FS.exports=uL.Promise});var Fr=b((QN,jS)=>{"use strict";var lL=xe(),ka=ur(),cL=Te(),dL=mc(),pL=ed(),hL=qe(),NS=Jc(),fL=Ft(),yd=ic(),US=ka&&ka.prototype,mL=hL("species"),Td=!1,qS=cL(lL.PromiseRejectionEvent),bL=dL("Promise",function(){var s=pL(ka),e=s!==String(ka);if(!e&&yd===66||fL&&!(US.catch&&US.finally))return!0;if(!yd||yd<51||!/native code/.test(s)){var t=new ka(function(a){a(1)}),i=function(a){a(function(){},function(){})},r=t.constructor={};if(r[mL]=i,Td=t.then(function(){})instanceof i,!Td)return!0}return!e&&(NS==="BROWSER"||NS==="DENO")&&!qS});jS.exports={CONSTRUCTOR:bL,REJECTION_EVENT:qS,SUBCLASSING:Td}});var Nr=b((GN,zS)=>{"use strict";var HS=Wt(),gL=TypeError,SL=function(s){var e,t;this.promise=new s(function(i,r){if(e!==void 0||t!==void 0)throw new gL("Bad Promise constructor");e=i,t=r}),this.resolve=HS(e),this.reject=HS(t)};zS.exports.f=function(s){return new SL(s)}});var cv=b(()=>{"use strict";var vL=ke(),yL=Ft(),ru=Ko(),Di=xe(),Hr=yt(),QS=Vr(),GS=Qc(),TL=va(),IL=Gg(),xL=Wt(),iu=Te(),EL=Tt(),wL=Yg(),AL=rd(),JS=hd().set,Ad=CS(),PL=OS(),kL=Zo(),RL=fd(),ZS=$c(),su=ur(),Pd=Fr(),ev=Nr(),au="Promise",tv=Pd.CONSTRUCTOR,ML=Pd.REJECTION_EVENT,LL=Pd.SUBCLASSING,Id=ZS.getterFor(au),BL=ZS.set,Ur=su&&su.prototype,lr=su,eu=Ur,iv=Di.TypeError,xd=Di.document,kd=Di.process,Ed=ev.f,$L=Ed,DL=!!(xd&&xd.createEvent&&Di.dispatchEvent),rv="unhandledrejection",CL="rejectionhandled",WS=0,sv=1,VL=2,Rd=1,av=2,tu,YS,OL,KS,nv=function(s){var e;return EL(s)&&iu(e=s.then)?e:!1},ov=function(s,e){var t=e.value,i=e.state===sv,r=i?s.ok:s.fail,a=s.resolve,n=s.reject,o=s.domain,u,l,d;try{r?(i||(e.rejection===av&&FL(e),e.rejection=Rd),r===!0?u=t:(o&&o.enter(),u=r(t),o&&(o.exit(),d=!0)),u===s.promise?n(new iv("Promise-chain cycle")):(l=nv(u))?Hr(l,u,a,n):a(u)):n(t)}catch(c){o&&!d&&o.exit(),n(c)}},uv=function(s,e){s.notified||(s.notified=!0,Ad(function(){for(var t=s.reactions,i;i=t.get();)ov(i,s);s.notified=!1,e&&!s.rejection&&_L(s)}))},lv=function(s,e,t){var i,r;DL?(i=xd.createEvent("Event"),i.promise=e,i.reason=t,i.initEvent(s,!1,!0),Di.dispatchEvent(i)):i={promise:e,reason:t},!ML&&(r=Di["on"+s])?r(i):s===rv&&PL("Unhandled promise rejection",t)},_L=function(s){Hr(JS,Di,function(){var e=s.facade,t=s.value,i=XS(s),r;if(i&&(r=kL(function(){ru?kd.emit("unhandledRejection",t,e):lv(rv,e,t)}),s.rejection=ru||XS(s)?av:Rd,r.error))throw r.value})},XS=function(s){return s.rejection!==Rd&&!s.parent},FL=function(s){Hr(JS,Di,function(){var e=s.facade;ru?kd.emit("rejectionHandled",e):lv(CL,e,s.value)})},qr=function(s,e,t){return function(i){s(e,i,t)}},jr=function(s,e,t){s.done||(s.done=!0,t&&(s=t),s.value=e,s.state=VL,uv(s,!0))},wd=function(s,e,t){if(!s.done){s.done=!0,t&&(s=t);try{if(s.facade===e)throw new iv("Promise can't be resolved itself");var i=nv(e);i?Ad(function(){var r={done:!1};try{Hr(i,e,qr(wd,r,s),qr(jr,r,s))}catch(a){jr(r,a,s)}}):(s.value=e,s.state=sv,uv(s,!1))}catch(r){jr({done:!1},r,s)}}};if(tv&&(lr=function(e){wL(this,eu),xL(e),Hr(tu,this);var t=Id(this);try{e(qr(wd,t),qr(jr,t))}catch(i){jr(t,i)}},eu=lr.prototype,tu=function(e){BL(this,{type:au,done:!1,notified:!1,parent:!1,reactions:new RL,rejection:!1,state:WS,value:void 0})},tu.prototype=QS(eu,"then",function(e,t){var i=Id(this),r=Ed(AL(this,lr));return i.parent=!0,r.ok=iu(e)?e:!0,r.fail=iu(t)&&t,r.domain=ru?kd.domain:void 0,i.state===WS?i.reactions.add(r):Ad(function(){ov(r,i)}),r.promise}),YS=function(){var s=new tu,e=Id(s);this.promise=s,this.resolve=qr(wd,e),this.reject=qr(jr,e)},ev.f=Ed=function(s){return s===lr||s===OL?new YS(s):$L(s)},!yL&&iu(su)&&Ur!==Object.prototype)){KS=Ur.then,LL||QS(Ur,"then",function(e,t){var i=this;return new lr(function(r,a){Hr(KS,i,r,a)}).then(e,t)},{unsafe:!0});try{delete Ur.constructor}catch(s){}GS&&GS(Ur,eu)}vL({global:!0,constructor:!0,wrap:!0,forced:tv},{Promise:lr});TL(lr,au,!1,!0);IL(au)});var mv=b((KN,fv)=>{"use strict";var NL=qe(),pv=NL("iterator"),hv=!1;try{dv=0,Md={next:function(){return{done:!!dv++}},return:function(){hv=!0}},Md[pv]=function(){return this},Array.from(Md,function(){throw 2})}catch(s){}var dv,Md;fv.exports=function(s,e){try{if(!e&&!hv)return!1}catch(r){return!1}var t=!1;try{var i={};i[pv]=function(){return{next:function(){return{done:t=!0}}}},s(i)}catch(r){}return t}});var Ld=b((XN,bv)=>{"use strict";var UL=ur(),qL=mv(),jL=Fr().CONSTRUCTOR;bv.exports=jL||!qL(function(s){UL.all(s).then(void 0,function(){})})});var gv=b(()=>{"use strict";var HL=ke(),zL=yt(),QL=Wt(),GL=Nr(),WL=Zo(),YL=Go(),KL=Ld();HL({target:"Promise",stat:!0,forced:KL},{all:function(e){var t=this,i=GL.f(t),r=i.resolve,a=i.reject,n=WL(function(){var o=QL(t.resolve),u=[],l=0,d=1;YL(e,function(c){var f=l++,p=!1;d++,zL(o,t,c).then(function(h){p||(p=!0,u[f]=h,--d||r(u))},a)}),--d||r(u)});return n.error&&a(n.value),i.promise}})});var vv=b(()=>{"use strict";var XL=ke(),JL=Ft(),ZL=Fr().CONSTRUCTOR,$d=ur(),eB=gi(),tB=Te(),iB=Vr(),Sv=$d&&$d.prototype;XL({target:"Promise",proto:!0,forced:ZL,real:!0},{catch:function(s){return this.then(void 0,s)}});!JL&&tB($d)&&(Bd=eB("Promise").prototype.catch,Sv.catch!==Bd&&iB(Sv,"catch",Bd,{unsafe:!0}));var Bd});var yv=b(()=>{"use strict";var rB=ke(),sB=yt(),aB=Wt(),nB=Nr(),oB=Zo(),uB=Go(),lB=Ld();rB({target:"Promise",stat:!0,forced:lB},{race:function(e){var t=this,i=nB.f(t),r=i.reject,a=oB(function(){var n=aB(t.resolve);uB(e,function(o){sB(n,t,o).then(i.resolve,r)})});return a.error&&r(a.value),i.promise}})});var Tv=b(()=>{"use strict";var cB=ke(),dB=Nr(),pB=Fr().CONSTRUCTOR;cB({target:"Promise",stat:!0,forced:pB},{reject:function(e){var t=dB.f(this),i=t.reject;return i(e),t.promise}})});var Dd=b((nU,Iv)=>{"use strict";var hB=Yt(),fB=Tt(),mB=Nr();Iv.exports=function(s,e){if(hB(s),fB(e)&&e.constructor===s)return e;var t=mB.f(s),i=t.resolve;return i(e),t.promise}});var wv=b(()=>{"use strict";var bB=ke(),gB=gi(),xv=Ft(),SB=ur(),Ev=Fr().CONSTRUCTOR,vB=Dd(),yB=gB("Promise"),TB=xv&&!Ev;bB({target:"Promise",stat:!0,forced:xv||Ev},{resolve:function(e){return vB(TB&&this===yB?SB:this,e)}})});var Av=b(()=>{"use strict";cv();gv();vv();yv();Tv();wv()});var Mv=b(()=>{"use strict";var IB=ke(),xB=Ft(),nu=ur(),EB=Ue(),kv=gi(),Rv=Te(),wB=rd(),Pv=Dd(),AB=Vr(),Vd=nu&&nu.prototype,PB=!!nu&&EB(function(){Vd.finally.call({then:function(){}},function(){})});IB({target:"Promise",proto:!0,real:!0,forced:PB},{finally:function(s){var e=wB(this,kv("Promise")),t=Rv(s);return this.then(t?function(i){return Pv(e,s()).then(function(){return i})}:s,t?function(i){return Pv(e,s()).then(function(){throw i})}:s)}});!xB&&Rv(nu)&&(Cd=kv("Promise").prototype.finally,Vd.finally!==Cd&&AB(Vd,"finally",Cd,{unsafe:!0}));var Cd});var Bv=b((hU,Lv)=>{"use strict";Ng();Av();Mv();var kB=$i();Lv.exports=kB("Promise","finally")});var Dv=b((fU,$v)=>{"use strict";var RB=Bv();$v.exports=RB});var ou=b((mU,Cv)=>{"use strict";var MB=Dv();Cv.exports=MB});var Wv=b(()=>{"use strict";var HB=ke(),zB=Rc().values;HB({target:"Object",stat:!0},{values:function(e){return zB(e)}})});var Kv=b((ZU,Yv)=>{"use strict";Wv();var QB=kr();Yv.exports=QB.Object.values});var Jv=b((e1,Xv)=>{"use strict";var GB=Kv();Xv.exports=GB});var pr=b((t1,Zv)=>{"use strict";var WB=Jv();Zv.exports=WB});var by=b(()=>{"use strict";var g$=ke(),S$=Rr(),v$=Cr(),y$=ma(),T$=ba();g$({target:"Array",proto:!0},{at:function(e){var t=S$(this),i=v$(t),r=y$(e),a=r>=0?r:i+r;return a<0||a>=i?void 0:t[a]}});T$("at")});var Sy=b((hq,gy)=>{"use strict";by();var I$=$i();gy.exports=I$("Array","at")});var yy=b((fq,vy)=>{"use strict";var x$=Sy();vy.exports=x$});var qt=b((mq,Ty)=>{"use strict";var E$=yy();Ty.exports=E$});var ap=b((sH,eT)=>{"use strict";var sD=er();eT.exports=Array.isArray||function(e){return sD(e)==="Array"}});var iT=b((aH,tT)=>{"use strict";var aD=TypeError,nD=9007199254740991;tT.exports=function(s){if(s>nD)throw aD("Maximum allowed index exceeded");return s}});var aT=b((nH,sT)=>{"use strict";var oD=ap(),uD=Cr(),lD=iT(),cD=Lr(),rT=function(s,e,t,i,r,a,n,o){for(var u=r,l=0,d=n?cD(n,o):!1,c,f;l<i;)l in t&&(c=d?d(t[l],l,e):t[l],a>0&&oD(c)?(f=uD(c),u=rT(s,e,c,f,u,a-1)-1):(lD(u+1),s[u]=c),u++),l++;return u};sT.exports=rT});var lT=b((oH,uT)=>{"use strict";var nT=ap(),dD=id(),pD=Tt(),hD=qe(),fD=hD("species"),oT=Array;uT.exports=function(s){var e;return nT(s)&&(e=s.constructor,dD(e)&&(e===oT||nT(e.prototype))?e=void 0:pD(e)&&(e=e[fD],e===null&&(e=void 0))),e===void 0?oT:e}});var dT=b((uH,cT)=>{"use strict";var mD=lT();cT.exports=function(s,e){return new(mD(s))(e===0?0:e)}});var pT=b(()=>{"use strict";var bD=ke(),gD=aT(),SD=Wt(),vD=Rr(),yD=Cr(),TD=dT();bD({target:"Array",proto:!0},{flatMap:function(e){var t=vD(this),i=yD(t),r;return SD(e),r=TD(t,0),r.length=gD(r,t,t,i,0,1,e,arguments.length>1?arguments[1]:void 0),r}})});var hT=b(()=>{"use strict";var ID=ba();ID("flatMap")});var mT=b((hH,fT)=>{"use strict";pT();hT();var xD=$i();fT.exports=xD("Array","flatMap")});var gT=b((fH,bT)=>{"use strict";var ED=mT();bT.exports=ED});var za=b((mH,ST)=>{"use strict";var wD=gT();ST.exports=wD});var Qa=b((bH,vT)=>{"use strict";var AD=Sa(),PD=String;vT.exports=function(s){if(AD(s)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return PD(s)}});var np=b((gH,yT)=>{"use strict";yT.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 xT=b((SH,IT)=>{"use strict";var kD=Ce(),RD=Bi(),MD=Qa(),up=np(),TT=kD("".replace),LD=RegExp("^["+up+"]+"),BD=RegExp("(^|[^"+up+"])["+up+"]+$"),op=function(s){return function(e){var t=MD(RD(e));return s&1&&(t=TT(t,LD,"")),s&2&&(t=TT(t,BD,"$1")),t}};IT.exports={start:op(1),end:op(2),trim:op(3)}});var PT=b((vH,AT)=>{"use strict";var $D=Vc().PROPER,DD=Ue(),ET=np(),wT="\u200B\x85\u180E";AT.exports=function(s){return DD(function(){return!!ET[s]()||wT[s]()!==wT||$D&&ET[s].name!==s})}});var lp=b((yH,kT)=>{"use strict";var CD=xT().start,VD=PT();kT.exports=VD("trimStart")?function(){return CD(this)}:"".trimStart});var MT=b(()=>{"use strict";var OD=ke(),RT=lp();OD({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==RT},{trimLeft:RT})});var BT=b(()=>{"use strict";MT();var _D=ke(),LT=lp();_D({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==LT},{trimStart:LT})});var DT=b((wH,$T)=>{"use strict";BT();var FD=$i();$T.exports=FD("String","trimLeft")});var VT=b((AH,CT)=>{"use strict";var ND=DT();CT.exports=ND});var _T=b((PH,OT)=>{"use strict";var UD=VT();OT.exports=UD});var ZT=b(()=>{"use strict"});var eI=b(()=>{"use strict"});var iI=b((cz,tI)=>{"use strict";var c0=Tt(),d0=er(),p0=qe(),h0=p0("match");tI.exports=function(s){var e;return c0(s)&&((e=s[h0])!==void 0?!!e:d0(s)==="RegExp")}});var sI=b((dz,rI)=>{"use strict";var f0=Yt();rI.exports=function(){var s=f0(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 oI=b((pz,nI)=>{"use strict";var m0=yt(),b0=Nt(),g0=la(),S0=sI(),aI=RegExp.prototype;nI.exports=function(s){var e=s.flags;return e===void 0&&!("flags"in aI)&&!b0(s,"flags")&&g0(aI,s)?m0(S0,s):e}});var lI=b((hz,uI)=>{"use strict";var mp=Ce(),v0=Rr(),y0=Math.floor,hp=mp("".charAt),T0=mp("".replace),fp=mp("".slice),I0=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,x0=/\$([$&'`]|\d{1,2})/g;uI.exports=function(s,e,t,i,r,a){var n=t+s.length,o=i.length,u=x0;return r!==void 0&&(r=v0(r),u=I0),T0(a,u,function(l,d){var c;switch(hp(d,0)){case"$":return"$";case"&":return s;case"`":return fp(e,0,t);case"'":return fp(e,n);case"<":c=r[fp(d,1,-1)];break;default:var f=+d;if(f===0)return l;if(f>o){var p=y0(f/10);return p===0?l:p<=o?i[p-1]===void 0?hp(d,1):i[p-1]+hp(d,1):l}c=i[f-1]}return c===void 0?"":c})}});var pI=b(()=>{"use strict";var E0=ke(),w0=yt(),gp=Ce(),cI=Bi(),A0=Te(),P0=Pr(),k0=iI(),ss=Qa(),R0=da(),M0=oI(),L0=lI(),B0=qe(),$0=Ft(),D0=B0("replace"),C0=TypeError,bp=gp("".indexOf),V0=gp("".replace),dI=gp("".slice),O0=Math.max;E0({target:"String",proto:!0},{replaceAll:function(e,t){var i=cI(this),r,a,n,o,u,l,d,c,f,p,h=0,m="";if(!P0(e)){if(r=k0(e),r&&(a=ss(cI(M0(e))),!~bp(a,"g")))throw new C0("`.replaceAll` does not allow non-global regexes");if(n=R0(e,D0),n)return w0(n,e,i,t);if($0&&r)return V0(ss(i),e,t)}for(o=ss(i),u=ss(e),l=A0(t),l||(t=ss(t)),d=u.length,c=O0(1,d),f=bp(o,u);f!==-1;)p=l?ss(t(u,f,o)):L0(u,o,f,[],void 0,t),m+=dI(o,h,f)+p,h=f+d,f=f+c>o.length?-1:bp(o,u,f+c);return h<o.length&&(m+=dI(o,h)),m}})});var fI=b((bz,hI)=>{"use strict";ZT();eI();pI();var _0=$i();hI.exports=_0("String","replaceAll")});var bI=b((gz,mI)=>{"use strict";var F0=fI();mI.exports=F0});var Sp=b((Sz,gI)=>{"use strict";var N0=bI();gI.exports=N0});var vI=b((vz,SI)=>{"use strict";var U0=ma(),q0=Qa(),j0=Bi(),H0=RangeError;SI.exports=function(e){var t=q0(j0(this)),i="",r=U0(e);if(r<0||r===1/0)throw new H0("Wrong number of repetitions");for(;r>0;(r>>>=1)&&(t+=t))r&1&&(i+=t);return i}});var EI=b((yz,xI)=>{"use strict";var II=Ce(),z0=Tc(),yI=Qa(),Q0=vI(),G0=Bi(),W0=II(Q0),Y0=II("".slice),K0=Math.ceil,TI=function(s){return function(e,t,i){var r=yI(G0(e)),a=z0(t),n=r.length,o=i===void 0?" ":yI(i),u,l;return a<=n||o===""?r:(u=a-n,l=W0(o,K0(u/o.length)),l.length>u&&(l=Y0(l,0,u)),s?r+l:l+r)}};xI.exports={start:TI(!1),end:TI(!0)}});var AI=b((Tz,wI)=>{"use strict";var X0=ir();wI.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(X0)});var PI=b(()=>{"use strict";var J0=ke(),Z0=EI().start,eC=AI();J0({target:"String",proto:!0,forced:eC},{padStart:function(e){return Z0(this,e,arguments.length>1?arguments[1]:void 0)}})});var RI=b((Ez,kI)=>{"use strict";PI();var tC=$i();kI.exports=tC("String","padStart")});var LI=b((wz,MI)=>{"use strict";var iC=RI();MI.exports=iC});var vp=b((Az,BI)=>{"use strict";var rC=LI();BI.exports=rC});var jh="2.0.135-dev.ee4a31cc.0";var at=(r=>(r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused",r))(at||{}),bi=(y=>(y.MPEG="MPEG",y.DASH="DASH",y.DASH_SEP="DASH_SEP",y.DASH_SEP_VK="DASH_SEP",y.DASH_WEBM="DASH_WEBM",y.DASH_WEBM_AV1="DASH_WEBM_AV1",y.DASH_STREAMS="DASH_STREAMS",y.DASH_WEBM_VK="DASH_WEBM",y.DASH_ONDEMAND="DASH_ONDEMAND",y.DASH_ONDEMAND_VK="DASH_ONDEMAND",y.DASH_LIVE="DASH_LIVE",y.DASH_LIVE_CMAF="DASH_LIVE_CMAF",y.DASH_LIVE_WEBM="DASH_LIVE_WEBM",y.HLS="HLS",y.HLS_ONDEMAND="HLS_ONDEMAND",y.HLS_JS="HLS",y.HLS_LIVE="HLS_LIVE",y.HLS_LIVE_CMAF="HLS_LIVE_CMAF",y.WEB_RTC_LIVE="WEB_RTC_LIVE",y))(bi||{});var Ao=(r=>(r.NOT_AVAILABLE="NOT_AVAILABLE",r.AVAILABLE="AVAILABLE",r.CONNECTING="CONNECTING",r.CONNECTED="CONNECTED",r))(Ao||{}),Hl=(i=>(i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic",i))(Hl||{});var zl=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(zl||{}),Po=(i=>(i.TRAFFIC_SAVING="traffic_saving",i.HIGH_QUALITY="high_quality",i.UNKNOWN="unknown",i))(Po||{});var UE=H(It(),1);import{assertNever as qm,assertNonNullable as gP,isNonNullable as Bo,ValueSubject as xc,Subject as SP,Subscription as vP,merge as yP,observableFrom as TP,fromEvent as _m,map as Fm,tap as Nm,filterChanged as IP,isNullable as Ec,ErrorCategory as Um}from"@vkontakte/videoplayer-shared/es2015";var Om=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 $o=class{constructor(e){this.connection$=new xc(void 0);this.castState$=new xc("NOT_AVAILABLE");this.errorEvent$=new SP;this.realCastState$=new xc("NOT_AVAILABLE");this.subscription=new vP;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=Bo((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||Om("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:Um.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(){Bo(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();Ec(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();Ec(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(_m(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 qm(r.sessionState)}})).add(yP(_m(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(Nm(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),Fm(r=>r.castState)),TP([i.getCastState()])).pipe(IP(),Fm(xP),Nm(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{var o,u;let a=r==="CONNECTED",n=Bo(this.connection$.getValue());if(a&&!n){let l=i.getCurrentSession();gP(l);let d=l.getCastDevice(),c=(u=(o=l.getMediaSession())==null?void 0:o.media)==null?void 0:u.contentId;(Ec(c)||c===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:l,castDevice:d}))}else!a&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(r==="CONNECTED"?Bo(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:Um.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:a})}}},xP=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 qm(s)}};var Bh=H(It(),1),IE=H(sr(),1),xE=H(Xc(),1);var zv=H(ou(),1);import{assertNever as Vv}from"@vkontakte/videoplayer-shared/es2015";var Ie=(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:Vv(t)}return s},Ci=(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:Vv(e)}};var D=(s,e,t=!1)=>{let i=s.getTransition();(t||!i||i.to===e)&&s.setState(e)};import{isNonNullable as LB,Subject as uu,merge as Ov}from"@vkontakte/videoplayer-shared/es2015";var Y=class{constructor(e){this.transitionStarted$=new uu;this.transitionEnded$=new uu;this.transitionUpdated$=new uu;this.forceChanged$=new uu;this.stateChangeStarted$=Ov(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=Ov(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||LB(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 BB}from"@vkontakte/videoplayer-shared/es2015";var _v=s=>{switch(s){case"MPEG":case"DASH":case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":case"HLS":case"HLS_ONDEMAND":return!1;case"DASH_LIVE":case"DASH_LIVE_CMAF":case"HLS_LIVE":case"HLS_LIVE_CMAF":case"DASH_LIVE_WEBM":case"WEB_RTC_LIVE":return!0;default:return BB(s)}};import{assertNever as zr,assertNonNullable as cr,debounce as Fv,ErrorCategory as Nv,fromEvent as dr,isNonNullable as Uv,map as qv,merge as jv,observableFrom as $B,Subject as DB,Subscription as Od,timeout as CB,getHighestQuality as VB}from"@vkontakte/videoplayer-shared/es2015";var OB=5,_B=5,FB=500,Hv=7e3,Ra=class{constructor(e){this.subscription=new Od;this.loadMediaTimeoutSubscription=new Od;this.videoState=new Y("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:zr(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:zr(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:zr(e)}break}default:zr(i)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(_v(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 Od;this.subscription.add(e),this.subscription.add(jv(this.videoState.stateChangeStarted$.pipe(qv(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe(qv(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 DB;e.add(r.pipe(Fv(FB)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let a=NaN;e.add(dr(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)>OB)&&r.next(o),a=o})),e.add(dr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(dr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(dr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t(dr(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<_B&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),D(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:zr(n)}}),t(dr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t(dr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});let i=jv(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,$B(["init"])).pipe(Fv(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"),D(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),D(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"),D(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"),D(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"&&D(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){var r,a;let t=this.params.output.volume$.getValue(),i={volume:(r=e.volume)!=null?r:t.volume,muted:(a=e.muted)!=null?a:t.muted};(i.volume!==t.volume||i.muted!==i.muted)&&this.params.output.volume$.next(i)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:i}=this.params.connection;t.currentTime=e,i.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){var l;let t=this.params.source,i,r,a;switch(e){case"MPEG":{let d=t[e];cr(d);let c=VB(Object.keys(d));cr(c);let f=d[c];cr(f),i=f,r="video/mp4",a=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let d=t[e];cr(d),i=d.url,r="application/x-mpegurl",a=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":{let d=t[e];cr(d),i=d.url,r="application/dash+xml",a=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let d=t[e];cr(d),i=d.url,r="application/dash+xml",a=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let d=t[e];cr(d),i=Ie(d.url),r="application/x-mpegurl",a=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let d="Unsupported format for Chromecast",c=new Error(d);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:Nv.VIDEO_PIPELINE,message:d,thrown:c}),c}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return zr(e)}let n=new chrome.cast.media.MediaInfo((l=this.params.meta.videoId)!=null?l:i,r);n.contentUrl=i,n.streamType=a,n.metadata=new chrome.cast.media.GenericMediaMetadata;let{title:o,subtitle:u}=this.params.meta;return Uv(o)&&(n.metadata.title=o),Uv(u)&&(n.metadata.subtitle=u),n}createLoadRequest(e){let t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;let i=this.params.desiredState.seekState.getState();return i.state==="applying"||i.state==="requested"?t.currentTime=this.params.output.isLive$.getValue()?0:i.position/1e3:t.currentTime=0,t}loadMedia(e){let t=this.params.connection.session.loadMedia(e),i=new Promise((r,a)=>{this.loadMediaTimeoutSubscription.add(CB(Hv).subscribe(()=>a(`timeout(${Hv})`)))});(0,zv.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:Nv.VIDEO_PIPELINE,message:a,thrown:r})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var rp=H(It(),1);import{clearVideoElement as Gv}from"@vkontakte/videoplayer-shared/es2015";import{clearVideoElement as NB}from"@vkontakte/videoplayer-shared/es2015";var Qv=s=>{try{s.pause(),s.playbackRate=0,NB(s),s.remove()}catch(e){console.error(e)}};import{fromEvent as UB,Subscription as qB}from"@vkontakte/videoplayer-shared/es2015";var _d=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)}},Fd=window.WeakMap?new WeakMap:new _d,Nd=window.WeakMap?new WeakMap:new Map,jB=(s,e=20)=>{let t=0;return UB(s,"ratechange").subscribe(i=>{t++,t>=e&&(s.currentTime=s.currentTime,t=0)})},nt=(s,{audioVideoSyncRate:e,disableYandexPiP:t})=>{let i=s.querySelector("video"),r=!!i;i?Gv(i):(i=document.createElement("video"),s.appendChild(i)),Fd.set(i,r);let a=new qB;return a.add(jB(i,e)),Nd.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},ot=s=>{let e=Nd.get(s);e==null||e.unsubscribe(),Nd.delete(s);let t=Fd.get(s);Fd.delete(s),t?Gv(s):Qv(s)};var qd=H(pr(),1);import{assertNonNullable as La,isNonNullable as Xt,isNullable as XB,fromEvent as Qr,merge as ey,observableFrom as ty,filterChanged as iy,map as Ba,Subject as ry,Subscription as JB,ValueSubject as ZB,ErrorCategory as e$}from"@vkontakte/videoplayer-shared/es2015";import{isNonNullable as Ud,isNullable as YB,Subscription as KB}from"@vkontakte/videoplayer-shared/es2015";var lu=(s,e,t,{equal:i=(n,o)=>n===o,changed$:r,onError:a}={})=>{let n=s.getState(),o=e(),u=YB(r),l=new KB;return r&&l.add(r.subscribe(d=>{let c=s.getState();i(d,c)&&s.setState(d)},a)),i(o,n)||(t(n),u&&s.setState(n)),l.add(s.stateChangeStarted$.subscribe(d=>{t(d.to),u&&s.setState(d.to)},a)),l},Kt=(s,e,t)=>lu(e,()=>s.loop,i=>{Ud(i)&&(s.loop=i)},{onError:t}),ut=(s,e,t,i)=>lu(e,()=>({muted:s.muted,volume:s.volume}),r=>{Ud(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}),Pt=(s,e,t,i)=>lu(e,()=>s.playbackRate,r=>{Ud(r)&&(s.playbackRate=r)},{changed$:t,onError:i}),Ma=lu;var t$=s=>["__",s.language,s.label].join("|"),i$=(s,e)=>{if(s.id===e)return!0;let[t,i,r]=e.split("|");return s.language===i&&s.label===r},jd=class s{constructor(e){this.available$=new ry;this.current$=new ZB(void 0);this.error$=new ry;this.subscription=new JB;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:e$.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(Ma(t.internalTextTracks,()=>(0,qd.default)(this.internalTracks),a=>{Xt(a)&&this.setInternal(a)},{equal:(a,n)=>Xt(a)&&Xt(n)&&a.length===n.length&&a.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(Ba(a=>a.filter(({type:n})=>n==="internal"))),onError:r})),this.subscription.add(Ma(t.externalTextTracks,()=>(0,qd.default)(this.externalTracks),a=>{Xt(a)&&this.setExternal(a)},{equal:(a,n)=>Xt(a)&&Xt(n)&&a.length===n.length&&a.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(Ba(a=>a.filter(({type:n})=>n==="external"))),onError:r})),this.subscription.add(Ma(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(Ma(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let a of this.htmlTextTracksAsArray())this.applyCueSettings(a.cues),this.applyCueSettings(a.activeCues)}))}subscribe(){La(this.video);let{textTracks:e}=this.video;this.subscription.add(Qr(e,"addtrack").subscribe(()=>{let i=this.current$.getValue();i&&this.select(i)})),this.subscription.add(ey(Qr(e,"addtrack"),Qr(e,"removetrack"),ty(["init"])).pipe(Ba(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),iy((i,r)=>i.length===r.length&&i.every(({id:a},n)=>a===r[n].id))).subscribe(this.available$)),this.subscription.add(ey(Qr(e,"change"),ty(["init"])).pipe(Ba(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),Ba(i=>i&&this.htmlTextTrackToITextTrack(i).id),iy()).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(Qr(e,"addtrack").subscribe(i=>{var a,n;(a=i.track)==null||a.addEventListener("cuechange",t);let r=o=>{var l,d,c,f,p;let u=(d=(l=o.target)==null?void 0:l.cues)!=null?d:null;u&&u.length&&(this.applyCueSettings((f=(c=o.target)==null?void 0:c.cues)!=null?f:null),(p=o.target)==null||p.removeEventListener("cuechange",r))};(n=i.track)==null||n.addEventListener("cuechange",r)})),this.subscription.add(Qr(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;Xt(t.align)&&(r.align=t.align),Xt(t.position)&&(r.position=t.position),Xt(t.size)&&(r.size=t.size),Xt(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){La(this.video);let t=[...this.video.textTracks];return e?t:t.filter(s.isHealthyTrack)}htmlTextTrackToITextTrack(e){var o,u,l,d,c;let{language:t,label:i}=e,r=e.id?e.id:t$(e),a=this.externalTracks.has(r),n=(l=a?(o=this.externalTracks.get(r))==null?void 0:o.isAuto:(u=this.internalTracks.get(r))==null?void 0:u.isAuto)!=null?l:r.includes("auto");return a?{id:r,type:"external",isAuto:n,language:t,label:i,url:(d=this.externalTracks.get(r))==null?void 0:d.url}:{id:r,type:"internal",isAuto:n,language:t,label:i,url:(c=this.internalTracks.get(r))==null?void 0:c.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(i=>i.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){let t=[...this.externalTracks];e.filter(({id:i,language:r,isAuto:a})=>!this.internalTracks.has(i)&&!t.some(([,n])=>n.language===r&&n.isAuto===a)).forEach(i=>this.attach(i)),Array.from(this.internalTracks).filter(([i])=>!e.find(r=>r.id===i)).forEach(([,i])=>this.detach(i))}select(e){La(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(XB(e)||!i$(t,e))&&(t.mode="disabled")}destroy(){if(this.subscription.unsubscribe(),this.video)for(let e of Array.from(this.video.getElementsByTagName("track"))){let t=e.getAttribute("id");t&&this.externalTracks.has(t)&&this.video.removeChild(e)}this.externalTracks.clear()}attach(e){La(this.video);let t=document.createElement("track");this.baseURL?t.setAttribute("src",new URL(e.url,this.baseURL).toString()):t.setAttribute("src",e.url),t.setAttribute("id",e.id),e.label&&t.setAttribute("label",e.label),e.language&&t.setAttribute("srclang",e.language),e.type==="external"?this.externalTracks.set(e.id,e):e.type==="internal"&&this.internalTracks.set(e.id,e),this.video.appendChild(t)}detach(e){La(this.video);let t=Array.prototype.find.call(this.video.getElementsByTagName("track"),i=>i.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}},kt=jd;var hr=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 sy=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},Hd=s=>{let e=sy(s);return!!(e&&e.fullscreenElement&&e.fullscreenElement===s)},ay=s=>{let e=sy(s);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===s)};import{fromEvent as et,map as Jt,merge as bu,filterChanged as hy,isNonNullable as fy,Subject as d$,filter as Qd,mapTo as Gd,combine as p$,once as h$,throttle as f$,ErrorCategory as m$,ValueSubject as my,Subscription as b$}from"@vkontakte/videoplayer-shared/es2015";var r$=3,ny=(s,e,t=r$)=>{let i=0,r=0;for(let a=0;a<s.length;a++){let n=s.start(a),o=s.end(a);if(n<=e&&e<=o){if(i=n,r=o,!t)return{from:i,to:r};for(let u=a-1;u>=0;u--)s.end(u)+t>=i&&(i=s.start(u));for(let u=a+1;u<s.length;u++)s.start(u)-t<=r&&(r=s.end(u))}}return{from:i,to:r}};var cu=class{constructor(){this._isMiuiBrowser=!1}get current(){return this._current}get isChrome(){return this.current==="Chrome"}get isFirefox(){return this.current==="Firefox"}get isSafari(){return this.current==="Safari"}get isOpera(){return this.current==="Opera"}get isEdge(){return this.current==="Edge"}get isYandex(){return this.current==="Yandex"}get isSamsungBrowser(){return this.current==="SamsungBrowser"}get currentVersion(){return this._current_version}get chromeVersion(){return this._chromeVersion}get firefoxVersion(){return this._firefoxVersion}get safariVersion(){return this._safariVersion}get operaVersion(){return this._operaVersion}get edgeVersion(){return this._edgeVersion}get yandexVersion(){return this._yandexVersion}get isMiuiBrowser(){return this._isMiuiBrowser}detect(){let{userAgent:e}=navigator;try{let t=/yabrowser/i.test(e)?"Yandex":void 0,i=/samsungbrowser/i.test(e)?"SamsungBrowser":void 0,r=/chrome|crios/i.test(e)?"Chrome":void 0,a=/chromium/i.test(e)?"Chromium":void 0,n=/firefox|fxios/i.test(e)?"Firefox":void 0,o=/webkit|safari|khtml/i.test(e)?"Safari":void 0,u=/opr\//i.test(e)?"Opera":void 0,l=/edg/i.test(e)?"Edge":void 0;this._isMiuiBrowser=/(XiaoMi)|(MiuiBrowser)/i.test(e),this._current=t||i||n||u||l||r||a||o||"Rest"}catch(t){console.error(t)}this.isChrome&&this.detectChromeVersion(),this.isFirefox&&this.detectFirefoxVersion(),this.isSafari&&this.detectSafariVersion(),this.isOpera&&this.detectOperaVersion(),this.isEdge&&this.detectEdgeVersion(),this.isYandex&&this.detectYandexVersion()}detectVersion(e){try{let{userAgent:t}=window.navigator,i=t.match(e);if(!i)return;let r=i[1],a=parseInt(r,10);if(!isNaN(a))return this._current_version=a,a}catch(t){console.error(t)}}detectChromeVersion(){this._chromeVersion=this.detectVersion(/Chrome\/(\d+\.\d+)/)}detectFirefoxVersion(){this._firefoxVersion=this.detectVersion(/Firefox\/(\d+\.\d+)/)}detectSafariVersion(){this._safariVersion=this.detectVersion(/Version\/(\d+)/)}detectOperaVersion(){this._operaVersion=this.detectVersion(/OPR\/(\d+\.\d+)/)}detectEdgeVersion(){this._edgeVersion=this.detectVersion(/Edg\/(\d+\.\d+)/)}detectYandexVersion(){this._yandexVersion=this.detectVersion(/YaBrowser\/(\d+\.\d+\.\d+)/)}};var oy=H(It(),1);var $a=()=>{var s,e;return/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test((s=navigator.appVersion)!=null?s:navigator.userAgent)||((e=navigator==null?void 0:navigator.userAgentData)==null?void 0:e.mobile)};var du=class{constructor(e){this._highEntropyValues={};this._displayChecker=e}get current(){return this._current}get isIOS(){let e=["iPhone","iPad","iPod"];return this._highEntropyValues.platform==="iOS"||(0,oy.default)(e,this.current)}get isMac(){return this._highEntropyValues.platform==="macOS"||this.current==="Mac"}get isApple(){return this.isIOS||this.isMac}get isIphoneOrOldIpad(){if(!this.isApple||!this._displayChecker.isTouch)return!1;let e=this.current==="iPad"||this._displayChecker.width>700,t=this._iosVersion;return!e||e&&!!t&&t<16}get isAndroid(){return this._highEntropyValues.platform==="Android"||this.current==="Android"}get isMobile(){return this._highEntropyValues.mobile||this._isMobile}get iOSVersion(){return this._iosVersion}detect(){let{userAgent:e}=navigator;try{this._isMobile=$a()}catch(t){console.error(t)}this.detectDevice(e),this.detectHighEntropyValues(),this.isIOS&&this.detectIOSVersion()}detectHighEntropyValues(){return E(this,null,function*(){let{userAgentData:e}=navigator;if(e!=null&&e.getHighEntropyValues){let t=yield e.getHighEntropyValues(["architecture","bitness","brands","mobile","platform","formFactor","model","platformVersion","wow64"]);this._highEntropyValues=t}})}detectDevice(e){try{let t=/android/i.test(e)?"Android":void 0,i=/iphone/i.test(e)?"iPhone":void 0,r=/ipad/i.test(e)?"iPad":void 0,a=/ipod/i.test(e)?"iPod":void 0,n=/mac/i.test(e)?"Mac":void 0,o=/webOS|BlackBerry|IEMobile|Opera Mini/i.test(e)?"RestMobile":void 0;this._current=t||i||r||a||o||n||"Desktop"}catch(t){console.error(t)}}detectIOSVersion(){try{if(this._highEntropyValues.platformVersion){let a=this._highEntropyValues.platformVersion.split(".").slice(0,2).join("."),n=parseFloat(a);this._iosVersion=n;return}let{userAgent:e}=window.navigator,t=e.match(/OS (\d+(_\d+)?)/i);if(!t)return;let i=t[1].replace(/_/g,".");if(!i)return;let r=parseFloat(i);if(isNaN(r))return;this._iosVersion=r}catch(e){console.error(e)}}};var pu=class{get isTouch(){return typeof this._maxTouchPoints=="number"?this._maxTouchPoints>1:"ontouchstart"in window}get maxTouchPoints(){return this._maxTouchPoints}get height(){return this._height}get width(){return this._width}get screenHeight(){return this._screenHeight}get screenWidth(){return this._screenWidth}get pixelRatio(){return this._pixelRatio}get isHDR(){return this._isHdr}get colorDepth(){return this._colorDepth}detect(){var t;let{maxTouchPoints:e}=navigator;try{this._maxTouchPoints=e!=null?e:0,this._isHdr=!!((t=matchMedia("(dynamic-range: high)"))!=null&&t.matches),this._colorDepth=screen.colorDepth}catch(i){console.error(i)}try{this._pixelRatio=window.devicePixelRatio||1,this._height=screen.height,this._width=screen.width,this._height=screen.height,this._screenHeight=this._height*this._pixelRatio,this._screenWidth=this._width*this._pixelRatio}catch(i){console.error(i)}}};var Et=()=>window.ManagedMediaSource||window.MediaSource,Gr=()=>{var s,e;return!!(window.ManagedMediaSource&&((e=(s=window.ManagedSourceBuffer)==null?void 0:s.prototype)!=null&&e.appendBuffer))},uy=()=>{var s,e;return!!(window.MediaSource&&((e=(s=window.SourceBuffer)==null?void 0:s.prototype)!=null&&e.appendBuffer))},hu=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var s$=document.createElement("video"),a$='video/mp4; codecs="avc1.42000a,mp4a.40.2"',n$='video/mp4; codecs="hev1.1.6.L93.B0"',ly='video/webm; codecs="vp09.00.10.08"',cy='video/webm; codecs="av01.0.00M.08"',o$='audio/mp4; codecs="mp4a.40.2"',u$='audio/webm; codecs="opus"',dy,l$=()=>E(void 0,null,function*(){if(!window.navigator.mediaCapabilities)return;let s={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=yield Promise.all([window.navigator.mediaCapabilities.decodingInfo(B(x({},s),{video:B(x({},s.video),{contentType:cy})})),window.navigator.mediaCapabilities.decodingInfo(B(x({},s),{video:B(x({},s.video),{contentType:ly})}))]);dy={DASH_WEBM_AV1:e,DASH_WEBM:t}});l$().catch(s=>{console.log(s$),console.error(s)});var fu=class{constructor(e,t){this._deviceChecker=e,this._browserChecker=t}get protocols(){return this._protocols}get containers(){return this._containers}get codecs(){return this._codecs}get webmDecodingInfo(){return dy}get supportedCodecs(){return Object.keys(this._codecs).filter(e=>this._codecs[e])}get nativeHlsSupported(){return this._nativeHlsSupported}detect(){var e,t,i,r,a,n,o,u,l,d,c,f,p,h,m,g,S,v,y,T;this._video=document.createElement("video");try{this._protocols={mms:Gr(),mse:uy(),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 I=!!((d=(l=Et())==null?void 0:l.isTypeSupported)!=null&&d.call(l,a$)),k=!!((f=(c=Et())==null?void 0:c.isTypeSupported)!=null&&f.call(c,n$)),C=!!((h=(p=Et())==null?void 0:p.isTypeSupported)!=null&&h.call(p,o$));this._codecs={h264:I,h265:k,vp9:!!((g=(m=Et())==null?void 0:m.isTypeSupported)!=null&&g.call(m,ly)),av1:!!((v=(S=Et())==null?void 0:S.isTypeSupported)!=null&&v.call(S,cy)),aac:C,opus:!!((T=(y=Et())==null?void 0:y.isTypeSupported)!=null&&T.call(y,u$)),mpeg:(I||k)&&C},this._nativeHlsSupported=this._protocols.hls&&this._containers.mp4}catch(I){console.error(I)}try{this.destroyVideoElement()}catch(I){console.error("Error destroying video element:",I)}}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 py="audio/mpeg",mu=class{supportMp3(){return this._codecs.mp3&&this._containers.mpeg}detect(){var e,t,i,r;this._audio=document.createElement("audio");try{this._containers={mpeg:!!((t=(e=this._audio).canPlayType)!=null&&t.call(e,py))},this._codecs={mp3:!!((r=(i=Et())==null?void 0:i.isTypeSupported)!=null&&r.call(i,py))}}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 c$}from"@vkontakte/videoplayer-shared/es2015";var zd=class{constructor(){this.isInited$=new c$(!1);this._displayChecker=new pu,this._deviceChecker=new du(this._displayChecker),this._browserChecker=new cu,this._videoChecker=new fu(this._deviceChecker,this._browserChecker),this._audioChecker=new mu,this.detect()}get display(){return this._displayChecker}get device(){return this._deviceChecker}get browser(){return this._browserChecker}get video(){return this._videoChecker}get audio(){return this._audioChecker}detect(){return E(this,null,function*(){this._displayChecker.detect(),this._deviceChecker.detect(),this._browserChecker.detect(),this._videoChecker.detect(),this._audioChecker.detect(),this.isInited$.next(!0)})}},Q=new zd;var lt=s=>{let e=w=>et(s,w).pipe(Gd(void 0)),t=new b$,i=()=>t.unsubscribe(),r=bu(et(s,"progress"),et(s,"timeupdate")).pipe(Jt(()=>ny(s.buffered,s.currentTime))),a=Q.browser.isSafari?p$({play:e("play").pipe(h$()),playing:e("playing")}).pipe(Gd(void 0)):e("playing"),n=et(s,"volumechange").pipe(Jt(()=>({muted:s.muted,volume:s.volume}))),o=et(s,"ratechange").pipe(Jt(()=>s.playbackRate)),u=et(s,"error").pipe(Qd(()=>!!(s.error||s.played.length)),Jt(()=>{var F;let w=s.error;return{id:w?`MediaError#${w.code}`:"HtmlVideoError",category:m$.VIDEO_PIPELINE,message:w?w.message:"Error event from HTML video element",thrown:(F=s.error)!=null?F:void 0}})),l=et(s,"timeupdate").pipe(Jt(()=>s.currentTime)),d=["waiting","seeking","seeked","timeupdate"],c=new d$,f=.3,p;t.add(bu(...d.map(w=>et(s,w))).subscribe(w=>{let F=s.currentTime;s.loop&&fy(p)&&fy(F)&&p>=s.duration-f&&F<=f&&c.next(p),p=F}));let h=e("pause").pipe(Qd(()=>!s.error&&p!==s.duration)),m=et(s,"enterpictureinpicture"),g=et(s,"leavepictureinpicture"),S=new my(ay(s));t.add(m.subscribe(()=>S.next(!0))),t.add(g.subscribe(()=>S.next(!1)));let v=new my(Hd(s)),y=et(s,"fullscreenchange");t.add(y.pipe(Jt(()=>Hd(s))).subscribe(v));let T=.1,I=1e3,k=et(s,"timeupdate").pipe(Jt(w=>s.duration-s.currentTime<T),hy()),C=bu(k.pipe(Qd(w=>!s.loop&&w)),et(s,"ended")).pipe(f$(I),Gd(void 0)),$=bu(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(w=>et(s,w)),k.pipe(Jt(w=>({type:w?"ended":"unknown"})))).pipe(Jt(w=>Q.browser.isFirefox&&w.type==="ended"?s.readyState<2:s.readyState<3),hy());return{playing$:a,pause$:h,canplay$:e("canplay"),ended$:C,looped$:c,error$:u,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:l,durationChange$:et(s,"durationchange").pipe(Jt(()=>s.duration)),isBuffering$:$,currentBuffer$:r,volumeState$:n,playbackRateState$:o,inPiP$:S,inFullscreen$:v,enterPip$:m,leavePip$:g,destroy:i}};import{VideoQuality as Vi}from"@vkontakte/videoplayer-shared/es2015";var Oi=s=>{switch(s){case"mobile":return Vi.Q_144P;case"lowest":return Vi.Q_240P;case"low":return Vi.Q_360P;case"sd":case"medium":return Vi.Q_480P;case"hd":case"high":return Vi.Q_720P;case"fullhd":case"full":return Vi.Q_1080P;case"quadhd":case"quad":return Vi.Q_1440P;case"ultrahd":case"ultra":return Vi.Q_2160P}};var it=H(qt(),1),Kd=H(It(),1),fr=H(sr(),1);import{isNonNullable as oe,isNullable as Tu,now as Ly,isHigher as Iu,isHigherOrEqual as Yr,isInvariantQuality as xu,isLowerOrEqual as Kr,videoSizeToQuality as By,assertNotEmptyArray as Eu,assertNonNullable as $y}from"@vkontakte/videoplayer-shared/es2015";var Wd=!1,yi={},Iy=s=>{Wd=s},xy=()=>{yi={}},Ey=s=>{s(yi)},Da=(s,e)=>{var t;Wd&&(yi.meta=(t=yi.meta)!=null?t:{},yi.meta[s]=e)},tt=class{constructor(e){this.name=e}next(e){var i,r;if(!Wd)return;yi.series=(i=yi.series)!=null?i:{};let t=(r=yi.series[this.name])!=null?r:[];t.push([Date.now(),e]),yi.series[this.name]=t}};import{isHigher as w$,isHigherOrEqual as Tq,isLower as wy,isLowerOrEqual as Iq,isNonNullable as gu,isNullable as A$,videoHeightToQuality as Su}from"@vkontakte/videoplayer-shared/es2015";function Yd(s,e,t){return!s.max&&s.min===e?"high_quality":!s.min&&s.max===t?"traffic_saving":"unknown"}function vu(s,e,t){return!!s&&Yd(s,e,t)==="high_quality"}function Wr(s,e,t){return A$(s)||gu(s.min)&&gu(s.max)&&wy(s.max,s.min)||gu(s.min)&&e&&w$(s.min,e)||gu(s.max)&&t&&wy(s.max,t)}function Ay({limits:s,highestAvailableHeight:e,lowestAvailableHeight:t}){return Wr({max:s!=null&&s.max?Su(s.max):void 0,min:s!=null&&s.min?Su(s.min):void 0},e?Su(e):void 0,t?Su(t):void 0)}var Dy=new tt("best_bitrate"),wu=(s,e,t)=>(e-t)*Math.pow(2,-10*s)+t;var Xr=s=>(e,t)=>s*(Number(e.bitrate)-Number(t.bitrate)),_i=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=Ly()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},Au='Assertion "ABR Tracks is empty array" failed',yu=new WeakMap,Py=new WeakMap,ky=new WeakMap,Ca=(s,e,t,i)=>{var u;let r=[...e].sort(Xr(1)),a=[...t].sort(Xr(1)),n=a.filter(l=>oe(l.bitrate)&&oe(s.bitrate)?s.bitrate/l.bitrate>i:!0),o=(u=(0,it.default)(a,Math.round(a.length*r.indexOf(s)/(r.length+1))))!=null?u:(0,it.default)(a,-1);return o&&(0,Kd.default)(n,o)?o:n.length?(0,it.default)(n,-1):(0,it.default)(a,0)},Va=(s,e,t,i)=>{var u;let r=yu.get(e);r||(r=[...e].sort(Xr(1)),yu.set(e,r));let a=yu.get(t);a||(a=[...t].sort(Xr(1)),yu.set(t,a));let n=ky.get(s);n||(n=a.filter(l=>oe(l.bitrate)&&oe(s.bitrate)?s.bitrate/l.bitrate>i:!0),ky.set(s,n));let o=(u=(0,it.default)(a,Math.round(a.length*r.indexOf(s)/(r.length+1))))!=null?u:(0,it.default)(a,-1);return o&&(0,Kd.default)(n,o)?o:n.length?(0,it.default)(n,-1):(0,it.default)(a,0)},Ry=s=>"quality"in s,Pu=(s,e,t,i)=>{var n;let r=oe((n=i==null?void 0:i.last)==null?void 0:n.bitrate)&&oe(t==null?void 0:t.bitrate)&&i.last.bitrate<t.bitrate?s.trackCooldownIncreaseQuality:s.trackCooldownDecreaseQuality,a=t&&i&&i.history[t.id]&&Ly()-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=Ry(o)?"video":"audio",l=Ry(o)?o.quality:o.bitrate;return e({message:`
|
|
8
8
|
[last ${u} selected] ${l}
|
|
9
|
-
`}),o}return i==null||i.recordSwitch(t),t},P$=(s,e)=>Math.log(e)/Math.log(s),Cy=({tuning:s,container:e,limits:t,panelSize:i})=>{let r=s.containerSizeFactor;if(i)return{containerSizeLimit:i,containerSizeFactor:r};if(s.usePixelRatio&&Q.display.pixelRatio){let a=Q.display.pixelRatio;if(s.pixelRatioMultiplier)r*=s.pixelRatioMultiplier*(a-1)+1;else{let n=s.pixelRatioLogBase,[o=0,u=0,l=0]=s.pixelRatioLogCoefficients,d=P$(n,o*a+u)+l;Number.isFinite(d)&&(r*=d)}}return vu(t,s.highQualityLimit,s.trafficSavingLimit)&&(r*=2),{containerSizeLimit:s.limitByContainer&&e&&e.width>0&&e.height>0?{width:e.width*r,height:e.height*r}:void 0,containerSizeFactor:r}},My=new WeakMap,Zt=(s,{container:e,estimatedThroughput:t,tuning:i,limits:r,reserve:a=0,forwardBufferHealth:n,playbackRate:o,current:u,history:l,visible:d,droppedVideoMaxQualityLimit:c,stallsVideoMaxQualityLimit:
|
|
9
|
+
`}),o}return i==null||i.recordSwitch(t),t},P$=(s,e)=>Math.log(e)/Math.log(s),Cy=({tuning:s,container:e,limits:t,panelSize:i})=>{let r=s.containerSizeFactor;if(i)return{containerSizeLimit:i,containerSizeFactor:r};if(s.usePixelRatio&&Q.display.pixelRatio){let a=Q.display.pixelRatio;if(s.pixelRatioMultiplier)r*=s.pixelRatioMultiplier*(a-1)+1;else{let n=s.pixelRatioLogBase,[o=0,u=0,l=0]=s.pixelRatioLogCoefficients,d=P$(n,o*a+u)+l;Number.isFinite(d)&&(r*=d)}}return vu(t,s.highQualityLimit,s.trafficSavingLimit)&&(r*=2),{containerSizeLimit:s.limitByContainer&&e&&e.width>0&&e.height>0?{width:e.width*r,height:e.height*r}:void 0,containerSizeFactor:r}},My=new WeakMap,Zt=(s,{container:e,estimatedThroughput:t,tuning:i,limits:r,reserve:a=0,forwardBufferHealth:n,playbackRate:o,current:u,history:l,visible:d,droppedVideoMaxQualityLimit:c,stallsVideoMaxQualityLimit:f,stallsPredictedThroughput:p,abrLogger:h,panelSize:m})=>{var j,N,K,P,L;Eu(s,Au);let{containerSizeFactor:g,containerSizeLimit:S}=Cy({container:e,tuning:i,limits:r,panelSize:m}),v=i.considerPlaybackRate&&oe(o)?o:1,y=My.get(s);y||(y=s.filter(R=>!xu(R.quality)).sort((R,A)=>Iu(R.quality,A.quality)?-1:1),My.set(s,y));let T=(j=(0,it.default)(y,-1))==null?void 0:j.quality,I=(N=(0,it.default)(y,0))==null?void 0:N.quality,k=Wr(r,I,T),C=v*wu(n!=null?n:.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),V={},$=null;for(let R of y){let A=!0;if(S)if(R.size)A=R.size.width<=S.width&&R.size.height<=S.height;else{let Ne=S&&By(S);A=Ne?Kr(R.quality,Ne):!0}if(!A){V[R.quality]="FitsContainer";continue}let O=p||t,de=oe(O)&&isFinite(O)&&oe(R.bitrate)?O-a>=R.bitrate*C:!0,Fe=vu(r,i.highQualityLimit,i.trafficSavingLimit)&&(r==null?void 0:r.min)===R.quality;if(!de&&!Fe){V[R.quality]="FitsThroughput";continue}if(i.lazyQualitySwitch&&oe(i.minBufferToSwitchUp)&&u&&!xu(u.quality)&&(n!=null?n:0)<i.minBufferToSwitchUp&&Iu(R.quality,u.quality)){V[R.quality]="Buffer";continue}if(!!c&&Yr(R.quality,c)&&!Fe){V[R.quality]="DroppedFramesLimit";continue}if(!!f&&Yr(R.quality,f)&&!Fe){V[R.quality]="StallsLimit";continue}let we=k||(Tu(r==null?void 0:r.max)||Kr(R.quality,r.max))&&(Tu(r==null?void 0:r.min)||Yr(R.quality,r.min)),Ae=oe(d)&&!d?Kr(R.quality,i.backgroundVideoQualityLimit):!0;if(!we||!Ae){V[R.quality]="FitsQualityLimits";continue}$||($=R)}$&&$.bitrate&&Dy.next($.bitrate);let w=(K=$!=null?$:(0,it.default)(y,-1))!=null?K:s[0],F=l==null?void 0:l.last,M=Pu(i,h,w,l);return oe(l)&&M.quality!==(F==null?void 0:F.quality)&&h({message:`
|
|
10
10
|
[VIDEO TRACKS ABR]
|
|
11
11
|
[available video tracks]
|
|
12
|
-
${s.map(
|
|
12
|
+
${s.map(R=>{var A,O;return`{ id: ${R.id}, quality: ${R.quality}, bitrate: ${R.bitrate}, size: ${(A=R.size)==null?void 0:A.width}:${(O=R.size)==null?void 0:O.height} }`}).join(`
|
|
13
13
|
`)}
|
|
14
14
|
|
|
15
15
|
[tuning]
|
|
16
|
-
${(0,fr.default)(i!=null?i:{}).map(([
|
|
16
|
+
${(0,fr.default)(i!=null?i:{}).map(([R,A])=>`${R}: ${A}`).join(`
|
|
17
17
|
`)}
|
|
18
18
|
|
|
19
19
|
[limit params]
|
|
@@ -28,18 +28,18 @@ var qE=Object.create;var ql=Object.defineProperty,jE=Object.defineProperties,HE=
|
|
|
28
28
|
bitrateFactor: ${C},
|
|
29
29
|
minBufferToSwitchUp: ${i.minBufferToSwitchUp},
|
|
30
30
|
droppedVideoMaxQualityLimit: ${c},
|
|
31
|
-
stallsVideoMaxQualityLimit: ${
|
|
32
|
-
limitsAreInvalid: ${
|
|
31
|
+
stallsVideoMaxQualityLimit: ${f},
|
|
32
|
+
limitsAreInvalid: ${k},
|
|
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,fr.default)(V).map(([
|
|
37
|
+
${(0,fr.default)(V).map(([R,A])=>`${R}: ${A}`).join(`
|
|
38
38
|
`)||"All tracks are available"}
|
|
39
39
|
|
|
40
40
|
[best video track] ${$==null?void 0:$.quality}
|
|
41
41
|
[selected video track] ${M==null?void 0:M.quality}
|
|
42
|
-
`}),M},
|
|
42
|
+
`}),M},ku=(s,{container:e,estimatedThroughput:t,tuning:i,limits:r,reserve:a=0,forwardBufferHealth:n,playbackRate:o,current:u,history:l,visible:d,droppedVideoMaxQualityLimit:c,stallsVideoMaxQualityLimit:f,stallsPredictedThroughput:p,abrLogger:h,panelSize:m})=>{var N,K,P,L,R;Eu(s,Au);let{containerSizeFactor:g,containerSizeLimit:S}=Cy({container:e,tuning:i,limits:r,panelSize:m}),v=i.considerPlaybackRate&&oe(o)?o:1,y=s.filter(A=>!xu(A.quality)).sort((A,O)=>Iu(A.quality,O.quality)?-1:1),T=(N=(0,it.default)(y,-1))==null?void 0:N.quality,I=(K=(0,it.default)(y,0))==null?void 0:K.quality,k=Wr(r,I,T),C=v*wu(n!=null?n:.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),V={},w=y.filter(A=>{let O=!0;if(S)if(A.size)O=A.size.width<=S.width&&A.size.height<=S.height;else{let At=S&&By(S);O=At?Kr(A.quality,At):!0}if(!O)return V[A.quality]="FitsContainer",!1;let de=p||t,Fe=oe(de)&&isFinite(de)&&oe(A.bitrate)?de-a>=A.bitrate*C:!0,ue=vu(r,i.highQualityLimit,i.trafficSavingLimit)&&(r==null?void 0:r.min)===A.quality;if(!Fe&&!ue)return V[A.quality]="FitsThroughput",!1;if(i.lazyQualitySwitch&&oe(i.minBufferToSwitchUp)&&u&&!xu(u.quality)&&(n!=null?n:0)<i.minBufferToSwitchUp&&Iu(A.quality,u.quality))return V[A.quality]="Buffer",!1;if(!!c&&Yr(A.quality,c)&&!ue)return V[A.quality]="DroppedFramesLimit",!1;if(!!f&&Yr(A.quality,f)&&!ue)return V[A.quality]="StallsLimit",!1;let Ae=k||(Tu(r==null?void 0:r.max)||Kr(A.quality,r.max))&&(Tu(r==null?void 0:r.min)||Yr(A.quality,r.min)),Ne=oe(d)&&!d?Kr(A.quality,i.backgroundVideoQualityLimit):!0;return!Ae||!Ne?(V[A.quality]="FitsQualityLimits",!1):!0})[0];w&&w.bitrate&&Dy.next(w.bitrate);let F=(P=w!=null?w:(0,it.default)(y,-1))!=null?P:s[0],M=l==null?void 0:l.last,j=Pu(i,h,F,l);return oe(l)&&j.quality!==(M==null?void 0:M.quality)&&h({message:`
|
|
43
43
|
[VIDEO TRACKS ABR]
|
|
44
44
|
[available video tracks]
|
|
45
45
|
${s.map(A=>{var O,de;return`{ id: ${A.id}, quality: ${A.quality}, bitrate: ${A.bitrate}, size: ${(O=A.size)==null?void 0:O.width}:${(de=A.size)==null?void 0:de.height} }`}).join(`
|
|
@@ -51,7 +51,7 @@ var qE=Object.create;var ql=Object.defineProperty,jE=Object.defineProperties,HE=
|
|
|
51
51
|
|
|
52
52
|
[limit params]
|
|
53
53
|
containerSizeFactor: ${g},
|
|
54
|
-
containerSizeLimit: ${(L=S==null?void 0:S.width)!=null?L:0} x ${(
|
|
54
|
+
containerSizeLimit: ${(L=S==null?void 0:S.width)!=null?L:0} x ${(R=S==null?void 0:S.height)!=null?R:0},
|
|
55
55
|
estimatedThroughput: ${t},
|
|
56
56
|
stallsPredictedThroughput: ${p},
|
|
57
57
|
reserve: ${a},
|
|
@@ -61,8 +61,8 @@ var qE=Object.create;var ql=Object.defineProperty,jE=Object.defineProperties,HE=
|
|
|
61
61
|
bitrateFactor: ${C},
|
|
62
62
|
minBufferToSwitchUp: ${i.minBufferToSwitchUp},
|
|
63
63
|
droppedVideoMaxQualityLimit: ${c},
|
|
64
|
-
stallsVideoMaxQualityLimit: ${
|
|
65
|
-
limitsAreInvalid: ${
|
|
64
|
+
stallsVideoMaxQualityLimit: ${f},
|
|
65
|
+
limitsAreInvalid: ${k},
|
|
66
66
|
maxQualityLimit: ${r==null?void 0:r.max},
|
|
67
67
|
minQualityLimit: ${r==null?void 0:r.min},
|
|
68
68
|
|
|
@@ -72,7 +72,7 @@ var qE=Object.create;var ql=Object.defineProperty,jE=Object.defineProperties,HE=
|
|
|
72
72
|
|
|
73
73
|
[best video track] ${w==null?void 0:w.quality}
|
|
74
74
|
[selected video track] ${j==null?void 0:j.quality}
|
|
75
|
-
`}),j},
|
|
75
|
+
`}),j},Ru=(s,e,t,{estimatedThroughput:i,tuning:r,playbackRate:a,forwardBufferHealth:n,history:o,abrLogger:u,stallsPredictedThroughput:l})=>{Eu(t,Au);let d=r.considerPlaybackRate&&oe(a)?a:1,c=[...t].sort(Xr(-1)),f=s.bitrate;$y(f);let p=d*wu(n!=null?n:.5,r.bitrateAudioFactorAtEmptyBuffer,r.bitrateAudioFactorAtFullBuffer),h,m=Ca(s,e,t,r.minVideoAudioRatio),g=l||i;oe(g)&&isFinite(g)&&(h=c.find(y=>oe(y.bitrate)&&oe(m==null?void 0:m.bitrate)?g-f>=y.bitrate*p&&y.bitrate>=m.bitrate:!1)),h||(h=m);let S=o==null?void 0:o.last,v=h&&Pu(r,u,h,o);return oe(o)&&(v==null?void 0:v.bitrate)!==(S==null?void 0:S.bitrate)&&u({message:`
|
|
76
76
|
[AUDIO TRACKS ABR]
|
|
77
77
|
[available audio tracks]
|
|
78
78
|
${t.map(y=>`{ id: ${y.id}, bitrate: ${y.bitrate} }`).join(`
|
|
@@ -85,7 +85,7 @@ var qE=Object.create;var ql=Object.defineProperty,jE=Object.defineProperties,HE=
|
|
|
85
85
|
[limit params]
|
|
86
86
|
estimatedThroughput: ${i},
|
|
87
87
|
stallsPredictedThroughput: ${l},
|
|
88
|
-
reserve: ${
|
|
88
|
+
reserve: ${f},
|
|
89
89
|
playbackRate: ${a},
|
|
90
90
|
playbackRateFactor: ${d},
|
|
91
91
|
forwardBufferHealth: ${n},
|
|
@@ -93,7 +93,7 @@ var qE=Object.create;var ql=Object.defineProperty,jE=Object.defineProperties,HE=
|
|
|
93
93
|
minBufferToSwitchUp: ${r.minBufferToSwitchUp},
|
|
94
94
|
|
|
95
95
|
[selected audio track] ${v==null?void 0:v.id}
|
|
96
|
-
`}),v},Mu=(s,e,t,{estimatedThroughput:i,tuning:r,playbackRate:a,forwardBufferHealth:n,history:o,abrLogger:u,stallsPredictedThroughput:l})=>{Eu(t,Au);let d=r.considerPlaybackRate&&oe(a)?a:1,c=Py.get(t);c||(c=[...t].sort(Xr(-1)),Py.set(t,c));let
|
|
96
|
+
`}),v},Mu=(s,e,t,{estimatedThroughput:i,tuning:r,playbackRate:a,forwardBufferHealth:n,history:o,abrLogger:u,stallsPredictedThroughput:l})=>{Eu(t,Au);let d=r.considerPlaybackRate&&oe(a)?a:1,c=Py.get(t);c||(c=[...t].sort(Xr(-1)),Py.set(t,c));let f=s.bitrate;$y(f);let p=d*wu(n!=null?n:.5,r.bitrateAudioFactorAtEmptyBuffer,r.bitrateAudioFactorAtFullBuffer),h,m=Va(s,e,t,r.minVideoAudioRatio),g=l||i;oe(g)&&isFinite(g)&&(h=c.find(y=>oe(y.bitrate)&&oe(m==null?void 0:m.bitrate)?g-f>=y.bitrate*p&&y.bitrate>=m.bitrate:!1)),h||(h=m);let S=o==null?void 0:o.last,v=h&&Pu(r,u,h,o);return oe(o)&&(v==null?void 0:v.bitrate)!==(S==null?void 0:S.bitrate)&&u({message:`
|
|
97
97
|
[AUDIO TRACKS ABR]
|
|
98
98
|
[available audio tracks]
|
|
99
99
|
${t.map(y=>`{ id: ${y.id}, bitrate: ${y.bitrate} }`).join(`
|
|
@@ -106,7 +106,7 @@ var qE=Object.create;var ql=Object.defineProperty,jE=Object.defineProperties,HE=
|
|
|
106
106
|
[limit params]
|
|
107
107
|
estimatedThroughput: ${i},
|
|
108
108
|
stallsPredictedThroughput: ${l},
|
|
109
|
-
reserve: ${
|
|
109
|
+
reserve: ${f},
|
|
110
110
|
playbackRate: ${a},
|
|
111
111
|
playbackRateFactor: ${d},
|
|
112
112
|
forwardBufferHealth: ${n},
|
|
@@ -114,14 +114,14 @@ var qE=Object.create;var ql=Object.defineProperty,jE=Object.defineProperties,HE=
|
|
|
114
114
|
minBufferToSwitchUp: ${r.minBufferToSwitchUp},
|
|
115
115
|
|
|
116
116
|
[selected audio track] ${v==null?void 0:v.id}
|
|
117
|
-
`}),v};var je=s=>new URL(s).hostname;import{assertNever as Qy,assertNonNullable as Gy,combine as W$,debounce as Y$,ErrorCategory as Wy,filter as Yy,filterChanged as K$,isNonNullable as tp,map as Du,merge as Ky,observableFrom as X$,once as J$,Subscription as Z$,ValueSubject as ip,videoQualityToHeight as Xy,videoSizeToQuality as eD}from"@vkontakte/videoplayer-shared/es2015";var qy=H(qt(),1);var Oy=H(It(),1);var Vy=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"))},ct=(s,e)=>E(void 0,null,function*(){let t=s.muted;try{yield s.play()}catch(i){if(!Vy(i))return!1;if(e&&e(),t)return console.warn(i),!1;s.muted=!0;try{yield s.play()}catch(r){return Vy(r)&&(s.muted=!1,console.warn(r)),!1}}return!0});import{isNonNullable as Bu,isNullable as M$,assertNonNullable as Fa}from"@vkontakte/videoplayer-shared/es2015";var Fy=H(pr(),1);import{isNonNullable as _y,assertNonNullable as Lu,now as R$}from"@vkontakte/videoplayer-shared/es2015";function Ve(){return R$()}function Xd(s){return Ve()-s}function Jd(s){let e=s.split("/"),t=e.slice(0,e.length-1).join("/"),i=/^([a-z]+:)?\/\//i,r=n=>i.test(n);return{resolve:(n,o,u=!1)=>{r(n)||(n.startsWith("/")||(n="/"+n),n=t+n);let l=n.indexOf("?")>-1?"&":"?";return u&&(n+=l+"lowLat=1",l="&"),o&&(n+=l+"_rnd="+Math.floor(999999999*Math.random())),n}}}function Ny(s,e,t){let i=(...r)=>{t.apply(null,r),s.removeEventListener(e,i)};s.addEventListener(e,i)}function Jr(s,e,t,i){let r=window.XMLHttpRequest,a,n,o,u=!1,l=0,d,c,h=!1,p="arraybuffer",f=7e3,m=2e3,g=()=>{if(u)return;Lu(d);let M=Xd(d),j;if(M<m){j=m-M,setTimeout(g,j);return}m*=2,m>f&&(m=f),n&&n.abort(),n=new r,R()},S=M=>(a=M,F),v=M=>(c=M,F),y=()=>(p="json",F),T=()=>{if(!u){if(--l>=0){g(),i&&i();return}u=!0,c&&c(),t&&t()}},I=M=>(h=M,F),R=()=>{d=Ve(),n=new r,n.open("get",s);let M=0,j,N=0,K=()=>(Lu(d),Math.max(d,Math.max(j||0,N||0)));if(a&&n.addEventListener("progress",P=>{let L=Ve();a.updateChunk&&P.loaded>M&&(a.updateChunk(K(),P.loaded-M),M=P.loaded,j=L)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>T())),n.addEventListener("load",()=>{if(u)return;Lu(n);let P=n.status;if(P>=200&&P<300){let{response:L,responseType:k}=n,A=L==null?void 0:L.byteLength;if(typeof A=="number"&&a){let O=A-M;O&&a.updateChunk&&a.updateChunk(K(),O)}k==="json"&&(!L||!(0,Fy.default)(L).length)?T():(c&&c(),e(L))}else T()}),n.addEventListener("error",()=>{T()}),h){let P=()=>{Lu(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(N=Ve(),n.removeEventListener("readystatechange",P))};n.addEventListener("readystatechange",P)}return n.responseType=p,n.send(),F},F={withBitrateReporting:S,withParallel:I,withJSONResponse:y,withRetryCount:M=>(l=M,F),withRetryInterval:(M,j)=>(_y(M)&&(m=M),_y(j)&&(f=j),F),withTimeout:M=>(o=M,F),withFinally:v,send:R,abort:()=>{n&&(n.abort(),n=void 0),u=!0,c&&c()}};return F}var Oa=class{constructor(e){this.intervals=[];this.currentRate=0;this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,i){return{start:e,end:t,bytes:i}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;let e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-500;if(t-e>2e3){let i=0,r=0;for(;this.intervals.length>0;){let a=this.intervals[0];if(a.end<=t)i+=a.end-a.start,r+=a.bytes,this.intervals.splice(0,1);else{if(a.start>=t)break;{let n=t-a.start,o=a.end-a.start;i+=n;let u=a.bytes*n/o;r+=u,a.start=t,a.bytes-=u}}}if(r>0&&i>0){let a=r*8/(i/1e3);return this._updateRate(a),this.logger(`rate updated, new=${Math.round(a/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(r)}/${Math.round(i)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,i){return this.intervals.push(this._createInterval(e,t,i)),this._joinIntervals(),this.intervals.length>100&&(this.logger(`too many intervals (${this.intervals.length}); will merge`,{type:"warn"}),this._doMergeIntervals(this.intervals[1],this.intervals[0]),this.intervals.splice(0,1)),this._flushIntervals()}getBitRate(){return this.currentRate}};var Uy=H(pr(),1);var _a=class{constructor(e,t,i,r,a){this.pendingQueue=[];this.activeRequests={};this.completeRequests={};this.averageSegmentDuration=2e3;this.lastPrefetchStart=0;this.throttleTimeout=null;this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=i,this.MAX_PARALLEL_REQUESTS=r,this.logger=a}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){let t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){let i=Ve(),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=Ve()-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=Jr(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=Ve()}_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=Ve();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,Uy.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 L$}from"@vkontakte/videoplayer-shared/es2015";var $u=1e4,Zd=3;var B$=6e4,$$=10,D$=1,C$=500,Na=class{constructor(e){this.paused=!1;this.autoQuality=!0;this.autoQualityLimits=void 0;this.buffering=!0;this.destroyed=!1;this.videoPlayStarted=!1;this.lowLatency=!1;this.bitrate=0;this.manifest=[];this.sourceBuffer=0;this.bufferStates=[];this.sourceJitter=-1;this.waitingForFirstBufferAfterSrcChange=!1;this.params=e,this.soundProhibitedEvent$=new L$,this.chunkRateEstimator=new Oa(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=Jd(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setAutoQualityLimits(e){this.autoQualityLimits=e}switchByName(e){let t;for(let i=0;i<this.manifest.length;++i)if(t=this.manifest[i],t.name===e){this._switchToQuality(t);return}}catchUp(){if(this.rep&&this.rep.stop(),this.currentManifestEntry){let e=this.params.playbackState.getState();this.paused=e==="paused",this._initPlayerWith(this.currentManifestEntry),this._notifyBuffering(!0)}}stop(){this.params.videoElement.pause(),this.rep&&(this.rep.stop(),this.rep=null)}pause(){this.paused=!0,this.params.videoElement.pause(),this.videoPlayStarted=!1,this._notifyBuffering(!1)}play(){this.paused=!1;let e=this.lowLatency&&this._getBufferSizeSec()>this.sourceJitter+5;this.rep&&!e?(this.bufferStates=[],this.videoPlayStarted=!1,this.shouldPlay()?this._playVideoElement():this._notifyBuffering(!0)):this.catchUp()}startPlay(e,t){this.autoQuality=t,this._initPlayerWith(e)}destroy(){this.destroyed=!0,this.rep&&(this.rep.stop(),this.rep=null),this.manifestRequest&&this.manifestRequest.abort(),this.manifestRefetchTimer&&(clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=void 0)}reinit(e){this.manifestUrl=e,this.urlResolver=Jd(e),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){let e=this.params.videoElement,t=0,i=e.buffered.length;return i!==0&&(t=e.buffered.end(i-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){let{videoElement:e,logger:t}=this.params;e.addEventListener("error",()=>{var r,a;!!e.error&&!this.destroyed&&(t(`Video element error: ${(r=e.error)==null?void 0:r.code}, details: ${(a=e.error)==null?void 0:a.message}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{let i=this._getBufferSizeSec();!this.paused&&i<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(i+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){let{logger:e,videoElement:t}=this.params,i=t.buffered.length,r;i!==0&&!this.waitingForFirstBufferAfterSrcChange&&(r=t.buffered.start(i-1),t.currentTime<r&&(e("Fixup stall"),t.currentTime=r))}_selectQuality(e){let{videoElement:t}=this.params,i,r,a,n=t&&1.62*(Q.display.pixelRatio||1)*t.offsetHeight||520;for(let o=0;o<this.manifest.length;++o){a=this.manifest[o];let{max:u,min:l}=this.autoQualityLimits||{};!Ay({limits:this.autoQualityLimits,highestAvailableHeight:this.manifest[0].video.height,lowestAvailableHeight:(0,qy.default)(this.manifest,-1).video.height})&&(u&&a.video.height>u||l&&a.video.height<l)||(a.bitrate<e&&n>Math.min(a.video.height,a.video.width)?(!r||a.bitrate>r.bitrate)&&(r=a):(!i||i.bitrate>a.bitrate)&&(i=a))}return r||i}shouldPlay(){if(this.paused)return!1;let t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||Bu(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=()=>{Ny(r,"progress",()=>{r.buffered.length?(r.currentTime=r.buffered.start(0),this.waitingForFirstBufferAfterSrcChange=!1,a({name:"playing"})):n()})};this.waitingForFirstBufferAfterSrcChange=!0,n()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new _a(Zd,$u,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:i,playerCallback:r}=this.params,a=!1,n=null,o=null,u=null,l=null,d=!1,c=()=>{let T=a&&(!d||d===this.rep);return T||t("Not running!"),T},h=(T,I,R)=>{u&&u.abort(),u=Jr(this.urlResolver.resolve(T,!1),I,R,()=>this._retryCallback()).withTimeout($u).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Zd).withFinally(()=>{u=null}).send()},p=(T,I,R)=>{Fa(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(T,!1),I,R,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},f=T=>{let I=i.playbackRate;i.playbackRate!==T&&(t(`Playback rate switch: ${I}=>${T}`),i.playbackRate=T)},m=T=>{this.lowLatency=T,t(`lowLatency changed to ${T}`),g()},g=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)f(1);else{let T=this._getBufferSizeSec();if(this.bufferStates.length<5){f(1);return}let R=Ve()-1e4,C=0;for(let $=0;$<this.bufferStates.length;$++){let w=this.bufferStates[$];T=Math.min(T,w.buf),w.ts<R&&C++}this.bufferStates.splice(0,C),t(`update playback rate; minBuffer=${T} drop=${C} jitter=${this.sourceJitter}`);let V=T-D$;this.sourceJitter>=0?V-=this.sourceJitter/2:this.sourceJitter-=1,V>3?f(1.15):V>1?f(1.1):V>.3?f(1.05):f(1)}},S=T=>{let I,R=()=>I&&I.start?I.start.length:0,C=P=>I.start[P]/1e3,V=P=>I.dur[P]/1e3,$=P=>I.fragIndex+P,w=(P,L)=>({chunkIdx:$(P),startTS:C(P),dur:V(P),discontinuity:L}),F=()=>{let P=0;if(I&&I.dur){let L=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,k=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,A=L;this.sourceJitter>1&&(A+=this.sourceJitter-1);let O=I.dur.length-1;for(;O>=0&&(A-=I.dur[O],!(A<=0));--O);P=Math.min(O,I.dur.length-1-k),P=Math.max(P,0)}return w(P,!0)},M=P=>{let L=R();if(!(L<=0)){if(Bu(P)){for(let k=0;k<L;k++)if(C(k)>P)return w(k)}return F()}},j=P=>{let L=R(),k=P?P.chunkIdx+1:0,A=k-I.fragIndex;if(!(L<=0)){if(!P||A<0||A-L>$$)return t(`Resync: offset=${A} bChunks=${L} chunk=`+JSON.stringify(P)),F();if(!(A>=L))return w(k-I.fragIndex,!1)}},N=(P,L,k)=>{l&&l.abort(),l=Jr(this.urlResolver.resolve(P,!0,this.lowLatency),L,k,()=>this._retryCallback()).withTimeout($u).withRetryCount(Zd).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(P,L)=>{N(T,k=>{if(!c())return;I=k;let A=!!I.lowLatency;A!==this.lowLatency&&m(A);let O=0;for(let de=0;de<I.dur.length;++de)O+=I.dur[de];O>0&&(Fa(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(O/I.dur.length)),r({name:"index",zeroTime:I.zeroTime,shiftDuration:I.shiftDuration}),this.sourceJitter=I.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,I.jitter/1e3)):1,P(M(L))},()=>this._handleNetworkError())},nextChunk:j}},v=()=>{a=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),Fa(this.filesFetcher),this.filesFetcher.abortAll()};return d={start:T=>{let{videoElement:I,logger:R}=this.params,C=S(e.jidxUrl),V,$,w,F,M=0,j,N,K,P=()=>{j&&(clearTimeout(j),j=void 0);let ee=Math.max(C$,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),Ee=M+ee,we=Ve(),Ae=Math.min(1e4,Ee-we);M=we;let Ne=()=>{l||c()&&C.seek(()=>{c()&&(M=Ve(),L(),P())})};Ae>0?j=window.setTimeout(()=>{this.paused?P():Ne()},Ae):Ne()},L=()=>{let ee;for(;ee=C.nextChunk(F);)F=ee,Fe(ee);let Ee=C.nextChunk(w);if(Ee){if(w&&Ee.discontinuity){R("Detected discontinuity; restarting playback"),this.paused?P():(v(),this._initPlayerWith(e));return}de(Ee)}else P()},k=(ee,Ee)=>{if(!c()||!this.sourceBuffer)return;let we,Ae,Ne,At=Lt=>{window.setTimeout(()=>{c()&&k(ee,Ee)},Lt)};if(this.sourceBuffer.updating)R("Source buffer is updating; delaying appendBuffer"),At(100);else{let Lt=Ve(),Gt=I.currentTime;!this.paused&&I.buffered.length>1&&N===Gt&&Lt-K>500&&(R("Stall suspected; trying to fix"),this._fixupStall()),N!==Gt&&(N=Gt,K=Lt);let ii=this._getBufferSizeSec();if(ii>30)R(`Buffered ${ii} seconds; delaying appendBuffer`),At(2e3);else try{this.sourceBuffer.appendBuffer(ee),this.videoPlayStarted?(this.bufferStates.push({ts:Lt,buf:ii}),g(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),Ee&&Ee()}catch(Li){if(Li.name==="QuotaExceededError")R("QuotaExceededError; delaying appendBuffer"),Ne=this.sourceBuffer.buffered.length,Ne!==0&&(we=this.sourceBuffer.buffered.start(0),Ae=Gt,Ae-we>4&&this.sourceBuffer.remove(we,Ae-3)),At(1e3);else throw Li}}},A=()=>{$&&V&&(R([`Appending chunk, sz=${$.byteLength}:`,JSON.stringify(w)]),k($,function(){$=null,L()}))},O=ee=>e.fragUrlTemplate.replace("%%id%%",ee.chunkIdx),de=ee=>{c()&&p(O(ee),(Ee,we)=>{if(c()){if(we/=1e3,$=Ee,w=ee,n=ee.startTS,we){let Ae=Math.min(10,ee.dur/we);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*Ae:Ae}A()}},()=>this._handleNetworkError())},Fe=ee=>{c()&&(Fa(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(O(ee),!1)))},ue=ee=>{c()&&(e.cachedHeader=ee,k(ee,()=>{V=!0,A()}))};a=!0,C.seek(ee=>{if(c()){if(M=Ve(),!ee){P();return}F=ee,!M$(T)||ee.startTS>T?de(ee):(w=ee,L())}},T),e.cachedHeader?ue(e.cachedHeader):h(e.headerUrl,ue,()=>this._handleNetworkError())},stop:v,getTimestampSec:()=>n},d}_switchToQuality(e){let{logger:t,playerCallback:i}=this.params,r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),Bu(r)&&(r+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,Fa(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return Bu(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,i=c=>{if(!this.autoQuality)return;let h,p,f;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&c<this.bitrate&&(p=this._getBufferSizeSec(),f=c/this.bitrate,p>10&&f>.8||p>15&&f>.5||p>20&&f>.3)){e(`Not switching: buffer=${Math.floor(p)}; bitrate=${this.bitrate}; newRate=${Math.floor(c)}`);return}h=this._selectQuality(c),h?this._switchToQuality(h):e(`Could not find quality by bitrate ${c}`)},a={updateChunk:(h,p)=>{let f=Ve();if(this.chunkRateEstimator.addInterval(h,f,p)){let g=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:p,duration:f-h,speed:g}),!0}},get:()=>{let h=this.chunkRateEstimator.getBitRate();return h?h*.85:0}},n=-1/0,o,u=!0,l=()=>{let c=a.get();if(c&&o&&this.autoQuality){if(u&&c>o&&Xd(n)<3e4)return;i(c)}u=this.autoQuality};return{updateChunk:(c,h)=>{let p=a.updateChunk(c,h);return p&&l(),p},notifySwitch:c=>{let h=Ve();c<o&&(n=h),o=c}}}_fetchManifest(e,t,i){this.manifestRequest=Jr(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout($u).withRetryCount(this.params.config.manifestRetryMaxCount).withRetryInterval(this.params.config.manifestRetryInterval,this.params.config.manifestRetryMaxInterval).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(){let{videoElement:e}=this.params;ct(e,()=>{this.soundProhibitedEvent$.next()}).then(t=>{t||(this.params.liveOffset.pause(),this.params.videoState.setState("paused"))})}_handleManifestUpdate(e){let{logger:t,playerCallback:i,videoElement:r}=this.params,a=n=>{let o=[];return n!=null&&n.length?(n.forEach((u,l)=>{var d,c;u.video&&r.canPlayType(u.codecs).replace(/no/,"")&&((c=(d=window.MediaSource)==null?void 0:d.isTypeSupported)!=null&&c.call(d,u.codecs))&&(u.index=l,o.push(u))}),o.sort(function(u,l){return u.video&&l.video?l.video.height-u.video.height:l.bitrate-u.bitrate}),o):(i({name:"error",type:"empty_manifest"}),[])};this.manifest=a(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),i({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},B$))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var zy=H(sr(),1);import{debounce as V$,filter as jy,fromEvent as O$,interval as _$,isHigher as F$,isInvariantQuality as N$,isLower as U$,merge as q$,Subject as Hy,Subscription as j$}from"@vkontakte/videoplayer-shared/es2015";var ep=class{constructor(){this.onDroopedVideoFramesLimit$=new Hy;this.subscription=new j$;this.playing=!1;this.tracks=[];this.forceChecker$=new Hy;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&&!N$(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&&F$(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(O$(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=_$(this.droppedFramesChecker.checkTime).pipe(jy(()=>this.playing),jy(()=>{let r=!!this.isForceCheckCounter;return r&&(this.isForceCheckCounter-=1),!r})),t=this.forceChecker$.pipe(V$(this.droppedFramesChecker.checkTime)),i=q$(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,zy.default)(this.limitCounts).filter(([,a])=>a>=this.droppedFramesChecker.countLimit).sort(([a],[n])=>U$(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}},Zr=ep;import{map as H$,Observable as z$}from"@vkontakte/videoplayer-shared/es2015";import{fromEvent as Q$}from"@vkontakte/videoplayer-shared/es2015";var Ua=()=>{var s;return!!((s=window.documentPictureInPicture)!=null&&s.window)||!!document.pictureInPictureElement};var G$=(s,e)=>new z$(t=>{if(!window.IntersectionObserver)return;let i={root:null},r=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||Ua()))},x(x({},i),e));r.observe(s);let a=Q$(document,"visibilitychange").pipe(H$(n=>!document.hidden||Ua())).subscribe(n=>t.next(n));return()=>{r.unobserve(s),a.unsubscribe()}}),kt=G$;var tD=["paused","playing","ready"],iD=["paused","playing","ready"],qa=class{constructor(e){this.subscription=new Z$;this.videoState=new Y("stopped");this.representations$=new ip([]);this.droppedFramesManager=new Zr;this.maxSeekBackTime$=new ip(1/0);this.zeroTime$=new ip(void 0);this.liveOffset=new hr;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:Wy.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{let n=e.manifest,o=[];for(let u of n){let l=(t=u.name)!=null?t:u.index.toString(10),d=(i=Oi(u.name))!=null?i:eD(u.video),c=u.bitrate/1e3,h=x({},u.video);if(!d)continue;let p={id:l,quality:d,bitrate:c,size:h};o.push({track:p,representation:u})}this.representations$.next(o),this.params.output.availableVideoTracks$.next(o.map(({track:u})=>u)),((r=this.videoState.getTransition())==null?void 0:r.to)==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let n=e.quality,o=(a=this.representations$.getValue().find(({representation:u})=>u===n))==null?void 0:a.track;this.params.output.hostname$.next(new URL(n.headerUrl,this.params.source.url).hostname),tp(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,rp.default)(iD,e)&&(n||o)){this.prepare();return}if((r==null?void 0:r.to)!=="paused"&&a.state==="requested"&&(0,rp.default)(tD,e)){this.seek(a.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(Ie(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(Ie(this.params.source.url,u))}return;default:return Qy(e)}};this.textTracksManager=new Rt(e.source.url),this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=r=>{e.output.error$.next({id:"DashLiveProvider",category:Wy.WTF,message:"DashLiveProvider internal logic error",thrown:r})};this.subscription.add(Ky(this.videoState.stateChangeStarted$.pipe(Du(r=>({transition:r,type:"start"}))),this.videoState.stateChangeEnded$.pipe(Du(r=>({transition:r,type:"end"})))).subscribe(({transition:r,type:a})=>{this.log({message:`[videoState change] ${a}: ${JSON.stringify(r)}`})})),this.video=nt(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(je(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=lt(this.video);this.subscription.add(()=>i.destroy()),this.subscription.add(this.representations$.pipe(Du(r=>r.map(({track:a})=>a)),Yy(r=>!!r.length),J$()).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(K$(),Du(r=>-r/1e3)).subscribe(this.params.output.duration$)).add(W$({zeroTime:this.zeroTime$.pipe(Yy(tp)),position:i.timeUpdate$}).subscribe(({zeroTime:r,position:a})=>this.params.output.liveTime$.next(r+a*1e3),t)).add(Kt(this.video,this.params.desiredState.isLooped,t)).add(ut(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(Pt(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(kt(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:r,min:a}})=>{this.dash.setAutoQualityLimits({max:r&&Xy(r),min:a&&Xy(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 Qy(r.to)}},t)).add(Ky(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,X$(["init"])).pipe(Y$(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),ot(this.video)}createLiveDashPlayer(){let e=new Na({videoElement:this.video,videoState:this.videoState,playbackState:this.params.desiredState.playbackState,liveOffset:this.liveOffset,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode,manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){var l,d,c,h,p,f;let e=this.representations$.getValue(),t=(d=(l=this.params.desiredState.videoTrack.getTransition())==null?void 0:l.to)!=null?d:this.params.desiredState.videoTrack.getState(),i=(h=(c=this.params.desiredState.autoVideoTrackSwitching.getTransition())==null?void 0:c.to)!=null?h:this.params.desiredState.autoVideoTrackSwitching.getState(),r=!i&&tp(t)?t:Zt(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(Ie(this.params.source.url,n)),r&&this.dash.pause(),this.liveOffset.resetTo(n,r)}};var Jy=qa;var dx=H(It(),1);var Oe=(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 _C,assertNonNullable as FC,debounce as NC,ErrorCategory as ux,filter as jp,filterChanged as ol,fromEvent as UC,isNonNullable as lx,map as Hp,merge as ul,observableFrom as zp,once as cx,Subscription as qC}from"@vkontakte/videoplayer-shared/es2015";var Cu=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}},es=class extends Cu{constructor(){super(),this.listeners||Cu.call(this),Object.defineProperty(this,"aborted",{value:!1,writable:!0,configurable:!0}),Object.defineProperty(this,"onabort",{value:null,writable:!0,configurable:!0}),Object.defineProperty(this,"reason",{value:void 0,writable:!0,configurable:!0})}toString(){return"[object AbortSignal]"}dispatchEvent(e){e.type==="abort"&&(this.aborted=!0,typeof this.onabort=="function"&&this.onabort.call(this,e)),super.dispatchEvent(e)}},ja=class{constructor(){Object.defineProperty(this,"signal",{value:new es,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch(r){typeof document!="undefined"?document.createEvent?(t=document.createEvent("Event"),t.initEvent("abort",!1,!1)):(t=document.createEventObject(),t.type="abort"):t={type:"abort",bubbles:!1,cancelable:!1}}let i=e;if(i===void 0)if(typeof document=="undefined")i=new Error("This operation was aborted"),i.name="AbortError";else try{i=new DOMException("signal is aborted without reason")}catch(r){i=new Error("This operation was aborted"),i.name="AbortError"}this.signal.reason=i,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol!="undefined"&&Symbol.toStringTag&&(ja.prototype[Symbol.toStringTag]="AbortController",es.prototype[Symbol.toStringTag]="AbortSignal");function Vu(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 sp(s){typeof s=="function"&&(s={fetch:s});let{fetch:e,Request:t=e.Request,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r=!1}=s;if(!Vu({fetch:e,Request:t,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r}))return{fetch:e,Request:a};let a=t;(a&&!a.prototype.hasOwnProperty("signal")||r)&&(a=function(l,d){let c;d&&d.signal&&(c=d.signal,delete d.signal);let h=new t(l,d);return c&&Object.defineProperty(h,"signal",{writable:!1,enumerable:!1,configurable:!0,value:c}),h},a.prototype=t.prototype);let n=e;return{fetch:(u,l)=>{let d=a&&a.prototype.isPrototypeOf(u)?u.signal:l?l.signal:void 0;if(d){let c;try{c=new DOMException("Aborted","AbortError")}catch(p){c=new Error("Aborted"),c.name="AbortError"}if(d.aborted)return Promise.reject(c);let h=new Promise((p,f)=>{d.addEventListener("abort",()=>f(c),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([h,n(u,l)])}return n(u,l)},Request:a}}var rD=()=>"fetch"in window,Ha=rD()&&Vu({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),Zy=Ha?sp({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,Mt=Ha?Zy.fetch:window.fetch,Zj=Ha?Zy.Request:window.Request,le=Ha?ja:window.AbortController,eH=Ha?es:window.AbortSignal;var Op=H(za(),1);var FT=H(_T(),1);import{ErrorCategory as Ga}from"@vkontakte/videoplayer-shared/es2015";var Ou=s=>{if(!s)return{id:"EmptyResponse",category:Ga.PARSER,message:"Empty response"};if(s.length<=2&&s.match(/^\d+$/))return{id:`UVError#${s}`,category:Ga.NETWORK,message:`UV Error ${s}`};let e=(0,FT.default)(s).substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:Ga.NETWORK,message:"Received unexpected HTML, possibly a ISP block"};if(e.startsWith("<?xml"))return new DOMParser().parseFromString(s,"text/xml").querySelector("parsererror")?{id:"InvalidXML",category:Ga.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:Ga.PARSER,message:"Response is valid XML, but parser failed"}};var He=(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 Dp,assertNonNullable as cs,combine as ds,ErrorCategory as Ht,filter as Zu,filterChanged as Pn,flattenObject as Rn,fromEvent as Ai,getTraceSubscriptionMethod as yC,interval as Cp,isNonNullable as kn,isNullable as ix,map as ps,merge as Sr,now as Vp,Subject as el,Subscription as rx,tap as TC,throttle as IC,ValueSubject as ge}from"@vkontakte/videoplayer-shared/es2015";var Nu=H(It(),1),os=H(qt(),1),Uu=H(za(),1);var qD=(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)},jD=s=>window.clearTimeout(s),NT=s=>typeof s=="function"&&(s==null?void 0:s.toString().endsWith("{ [native code] }")),UT=!NT(window.requestIdleCallback)||!NT(window.cancelIdleCallback),ts=UT?qD:window.requestIdleCallback,ei=UT?jD:window.cancelIdleCallback;var QI=H(ou(),1);import{assertNever as HD,ErrorCategory as qT,Subject as jT}from"@vkontakte/videoplayer-shared/es2015";var zD=18,HT=!1;try{HT=Q.browser.isSafari&&!!Q.browser.safariVersion&&Q.browser.safariVersion<=zD}catch(s){console.error(s)}var cp=class{constructor(e){this.bufferFull$=new jT;this.error$=new jT;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:qT.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}append(e,t){return E(this,null,function*(){return t&&t.aborted?!1:new Promise(i=>{let r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})})}remove(e,t,i){return E(this,null,function*(){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()})})}abort(e){return E(this,null,function*(){return new Promise(t=>{let i,r=a=>{this.abortRequested=!1,t(a)};HT&&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:qT.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:HD(t)}}},zT=cp;var is=s=>{let e=0;for(let t=0;t<s.length;t++)e+=s.end(t)-s.start(t);return e*1e3};import{abortable as Ni,assertNonNullable as dt,ErrorCategory as xi,fromEvent as Rp,getExponentialDelay as kp,isNonNullable as ns,isNullable as ze,now as Fu,once as uC,Subject as lC,Subscription as cC,ValueSubject as gr}from"@vkontakte/videoplayer-shared/es2015";var te=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let i=this.readUint32();this.type=this.readString(4),this.size32=i<=e.buffer.byteLength-e.byteOffset?i:NaN;let r=this.size32?this.size32-8:void 0,a=e.byteOffset+this.cursor;this.size64=0,this.usertype=0,this.content=new DataView(e.buffer,a,r)}get id(){return this.type}get size(){return this.size32}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t="ascii"){let r=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,r}readUint8(){let e=this.source.getUint8(this.cursor);return this.cursor+=1,e}readUint16(){let e=this.source.getUint16(this.cursor);return this.cursor+=2,e}readUint32(){let e=this.source.getUint32(this.cursor);return this.cursor+=4,e}readUint64(){let e=this.source.getBigInt64(this.cursor);return this.cursor+=8,e}};var rs=class extends te{};var Wa=class extends te{constructor(t,i){super(t,i);this.ondemandPrefix="ondemandlivejson";this.ondemandDataReceivedKey="t-in";this.ondemandDataPreparedKey="t-out";let r=this.content.byteOffset,a=r+this.content.byteLength,n=new TextDecoder("ascii").decode(this.content.buffer.slice(r,a)).split(this.ondemandPrefix)[1],o=JSON.parse(n);this.serverDataReceivedTimestamp=o[this.ondemandDataReceivedKey],this.serverDataPreparedTime=o[this.ondemandDataPreparedKey]}};var Ya=class extends te{constructor(e,t){super(e,t),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let i=this.size-this.cursor;for(;i;){let r=this.readString(4);this.compatibleBrands.push(r),i-=4}}};var Ka=class extends te{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var pe=class extends te{constructor(e,t){super(e,t);let i=this.readUint32();this.version=i>>>24,this.flags=i&16777215}};var Xa=class extends pe{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.timescale=this.readUint32(),this.duration=this.readUint32(),this.rate=this.readUint32(),this.volume=this.readUint16()}};var Ja=class extends te{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Za=class extends te{constructor(e,t){super(e,t),this.data=this.content}};var mr=class extends pe{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e,t){super(e,t),this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let i=0;i<this.referenceCount;i++){let r=this.readUint32(),a=r>>>31,n=r<<1>>>1,o=this.readUint32();r=this.readUint32();let u=r>>>28,l=r<<3>>>3;this.segments.push({referenceType:a,referencedSize:n,subsegmentDuration:o,SAPType:u,SAPDeltaTime:l})}}};var en=class extends te{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var tn=class extends te{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var rn=class extends pe{constructor(e,t){switch(super(e,t),this.readUint8()){case 0:this.stereoMode=0;break;case 1:this.stereoMode=1;break;case 2:this.stereoMode=2;break;case 3:this.stereoMode=3;break;case 4:this.stereoMode=4;break}this.cursor+=1}};var sn=class extends pe{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var an=class extends pe{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var nn=class extends te{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var on=class extends pe{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.trackId=this.readUint32(),this.cursor+=4,this.duration=this.readUint32(),this.cursor+=8,this.layer=this.readUint16(),this.alternateGroup=this.readUint16(),this.cursor+=2,this.cursor+=2,this.matrix=[[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()]],this.width=this.readUint32(),this.height=this.readUint32()}};var un=class extends te{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ln=class extends te{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var cn=class extends pe{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var dn=class extends te{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var pn=class extends pe{constructor(e,t){super(e,t),this.trackId=this.readUint32(),this.flags&1&&(this.baseDataOffset=this.readUint64()),this.flags&2&&(this.sampleDescriptionIndex=this.readUint32()),this.flags&8&&(this.defaultSampleDuration=this.readUint32()),this.flags&16&&(this.defaultSampleSize=this.readUint32()),this.flags&32&&(this.defaultSampleFlags=this.readUint32())}};var hn=class extends pe{constructor(t,i){super(t,i);this.baseMediaDecodeTime32=0;this.baseMediaDecodeTime64=BigInt(0);this.version===1?this.baseMediaDecodeTime64=this.readUint64():this.baseMediaDecodeTime32=this.readUint32()}get baseMediaDecodeTime(){return this.version===1?this.baseMediaDecodeTime64:this.baseMediaDecodeTime32}};var fn=class extends pe{constructor(t,i){super(t,i);this.sampleDuration=[];this.sampleSize=[];this.sampleFlags=[];this.sampleCompositionTimeOffset=[];this.optionalFields=0;this.sampleCount=this.readUint32(),this.flags&1&&(this.dataOffset=this.readUint32()),this.flags&4&&(this.firstSampleFlags=this.readUint32());for(let r=0;r<this.sampleCount;r++)this.flags&256&&this.sampleDuration.push(this.readUint32()),this.flags&512&&this.sampleSize.push(this.readUint32()),this.flags&1024&&this.sampleFlags.push(this.readUint32()),this.flags&2048&&this.sampleCompositionTimeOffset.push(this.readUint32())}};var mn=class extends te{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var bn=class extends pe{constructor(e,t){super(e,t),this.entryCount=this.readUint32(),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+8,this.content.byteLength-8))}};var gn=class extends te{constructor(e,t){super(e,t),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+78,this.content.byteLength-78))}};var GD={ftyp:Ya,moov:Ka,mvhd:Xa,moof:Ja,mdat:Za,sidx:mr,trak:en,mdia:nn,mfhd:cn,tkhd:on,traf:dn,tfhd:pn,tfdt:hn,trun:fn,minf:un,sv3d:tn,st3d:rn,prhd:sn,proj:ln,equi:an,uuid:Wa,stbl:mn,stsd:bn,avc1:gn,unknown:rs},Ti=class s{constructor(e={}){this.options=x({offset:0},e)}parse(e){let t=[],i=this.options.offset;for(;i<e.byteLength;)try{let a=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+i+4,4)),n=this.createBox(a,new DataView(e.buffer,e.byteOffset+i));if(!n.size)break;t.push(n),i+=n.size}catch(r){break}return t}createBox(e,t){let i=GD[e];return i?new i(t,new s):new rs(t,new s)}};var Fi=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{var i,r,a;(a=(i=this.index)[r=t.type])!=null||(i[r]=[]),this.index[t.type].push(t),t.children.length>0&&this.indexBoxLevel(t.children)})}find(e){return this.index[e]&&this.index[e][0]?this.index[e][0]:null}findAll(e){return this.index[e]||[]}};var YD=new TextDecoder("ascii"),KD=s=>YD.decode(new DataView(s.buffer,s.byteOffset+4,4))==="ftyp",XD=s=>{let e=new mr(s,new Ti),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})},JD=(s,e)=>{let i=new Ti().parse(s),r=new Fi(i),a=r.findAll("moof"),n=e?r.findAll("uuid"):r.findAll("mdat");if(!(n.length&&a.length))return null;let o=a[0],u=n[n.length-1],l=o.source.byteOffset,c=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(s.buffer,l,c)},ZD=s=>{let t=new Ti().parse(s),i=new Fi(t),r={},a=i.findAll("uuid");return a.length?a[a.length-1]:r},e0=s=>{var r;let t=new Ti().parse(s);return(r=new Fi(t).find("sidx"))==null?void 0:r.timescale},t0=(s,e)=>{let i=new Ti().parse(s),a=new Fi(i).findAll("traf"),n=a[a.length-1].children.find(c=>c.type==="tfhd"),o=a[a.length-1].children.find(c=>c.type==="tfdt"),u=a[a.length-1].children.find(c=>c.type==="trun"),l=0;return u.sampleDuration.length?l=u.sampleDuration.reduce((c,h)=>c+h,0):l=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+l)/e*1e3},i0=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 Ti().parse(s),r=new Fi(i);if(r.find("sv3d")){e.is3dVideo=!0;let n=r.find("st3d");n&&(e.stereoMode=n.stereoMode);let o=r.find("prhd");o&&(e.projectionData.pose.yaw=o.poseYawDegrees,e.projectionData.pose.pitch=o.posePitchDegrees,e.projectionData.pose.roll=o.poseRollDegrees);let u=r.find("equi");u&&(e.projectionData.bounds.top=u.projectionBoundsTop,e.projectionData.bounds.right=u.projectionBoundsRight,e.projectionData.bounds.bottom=u.projectionBoundsBottom,e.projectionData.bounds.left=u.projectionBoundsLeft)}return e},QT={validateData:KD,parseInit:i0,getIndexRange:()=>{},parseSegments:XD,parseFeedableSegmentChunk:JD,getChunkEndTime:t0,getServerLatencyTimestamps:ZD,getTimescaleFromIndex:e0};var vn=H(It(),1);import{assertNonNullable as pp,isNonNullable as KT,isNullable as s0}from"@vkontakte/videoplayer-shared/es2015";import{assertNever as r0}from"@vkontakte/videoplayer-shared/es2015";var GT={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"}},WT=s=>{let e=s.getUint8(0),t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);let i=Sn(s,t),r=i in GT,a=r?GT[i].type:"binary",n=s.getUint8(t),o=0;n&128?o=1:n&64?o=2:n&32?o=3:n&16?o=4:n&8?o=5:n&4?o=6:n&2?o=7:n&1&&(o=8);let u=new DataView(s.buffer,s.byteOffset+t+1,o-1),l=n&255>>o,d=Sn(u),c=l*Ze(2,(o-1)*8)+d,h=t+o,p;return h+c>s.byteLength?p=new DataView(s.buffer,s.byteOffset+h):p=new DataView(s.buffer,s.byteOffset+h,c),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:a,tagHeaderSize:h,tagSize:h+c,value:p,valueSize:c}},Sn=(s,e=s.byteLength)=>{switch(e){case 1:return s.getUint8(0);case 2:return s.getUint16(0);case 3:return s.getUint8(0)*Ze(2,16)+s.getUint16(1);case 4:return s.getUint32(0);case 5:return s.getUint8(0)*Ze(2,32)+s.getUint32(1);case 6:return s.getUint16(0)*Ze(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},jt=(s,e)=>{switch(e){case"int":return s.getInt8(0);case"uint":return Sn(s);case"float":return s.byteLength===4?s.getFloat32(0):s.getFloat64(0);case"string":return new TextDecoder("ascii").decode(s);case"utf8":return new TextDecoder("utf-8").decode(s);case"date":return new Date(Date.UTC(2001,0)+s.getInt8(0)).getTime();case"master":return s;case"binary":return s;default:r0(e)}},br=(s,e)=>{let t=0;for(;t<s.byteLength;){let i=new DataView(s.buffer,s.byteOffset+t),r=WT(i);if(!e(r))return;r.type==="master"&&br(r.value,e),t=r.value.byteOffset-s.byteOffset+r.valueSize}},YT=s=>{if(s.getUint32(0)!==440786851)return!1;let e,t,i,r=WT(s);return br(r.value,({tag:a,type:n,value:o})=>(a===17143?e=jt(o,n):a===17026?t=jt(o,n):a===17029&&(i=jt(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],a0=[231,22612,22743,167,171,163,160,175],n0=s=>{let e,t,i,r,a=!1,n=!1,o=!1,u,l,d=!1,c=0;return br(s,({tag:h,type:p,value:f,valueSize:m})=>{if(h===21419){let g=jt(f,p);l=Sn(g)}else h!==21420&&(l=void 0);return h===408125543?(e=f.byteOffset,t=f.byteOffset+m):h===357149030?a=!0:h===290298740?n=!0:h===2807729?i=jt(f,p):h===17545?r=jt(f,p):h===21420&&l===475249515?u=jt(f,p):h===374648427?br(f,({tag:g,type:S,value:v})=>g===30321?(d=jt(v,S)===1,!1):!0):a&&n&&(0,vn.default)(XT,h)&&(o=!0),!o}),pp(e,"Failed to parse webm Segment start"),pp(t,"Failed to parse webm Segment end"),pp(r,"Failed to parse webm Segment duration"),i=i!=null?i:1e6,{segmentStart:Math.round(e/1e9*i*1e3),segmentEnd:Math.round(t/1e9*i*1e3),timeScale:i,segmentDuration:Math.round(r/1e9*i*1e3),cuesSeekPosition:u,is3dVideo:d,stereoMode:c,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},o0=s=>{if(s0(s.cuesSeekPosition))return;let e=s.segmentStart+s.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},u0=(s,e)=>{let t=!1,i=!1,r=o=>KT(o.time)&&KT(o.position),a=[],n;return br(s,({tag:o,type:u,value:l})=>{switch(o){case 475249515:t=!0;break;case 187:n&&r(n)&&a.push(n),n={};break;case 179:n&&(n.time=jt(l,u));break;case 183:break;case 241:n&&(n.position=jt(l,u));break;default:t&&(0,vn.default)(XT,o)&&(i=!0)}return!(t&&i)}),n&&r(n)&&a.push(n),a.map((o,u)=>{let{time:l,position:d}=o,c=a[u+1];return{status:"none",time:{from:l,to:c?c.time:e.segmentDuration},byte:{from:e.segmentStart+d,to:c?e.segmentStart+c.position-1:e.segmentEnd-1}}})},l0=s=>{let e=0,t=!1;try{br(s,i=>i.tag===524531317?i.tagSize<=s.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):(0,vn.default)(a0,i.tag)?(e+i.tagSize<=s.byteLength&&(e+=i.tagSize,t||(t=(0,vn.default)([163,160,175],i.tag))),!0):!1)}catch(i){}return e>0&&e<=s.byteLength&&t?new DataView(s.buffer,s.byteOffset,e):null},JT={validateData:YT,parseInit:n0,getIndexRange:o0,parseSegments:u0,parseFeedableSegmentChunk:l0};var yn=s=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(s);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return JT;case"mp4":return QT}}throw new ReferenceError(`Unsupported mime type ${s}`)};var wp=H(Sp(),1),UI=H(sr(),1),qI=H(vp(),1),jI=H(qt(),1),Ap=H(pr(),1);var $I=H(It(),1),as=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,$I.default)(["6E","7A","F4"],o)}}return!1};import{isNonNullable as nC,isNullable as FI}from"@vkontakte/videoplayer-shared/es2015";var _u=s=>{if(s.includes("/")){let e=s.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(s)};var DI=s=>{var e;try{let t=sC(),i=s.match(t),{groups:r}=i!=null?i:{};if(r){let a={};if(r.extensions){let u=r.extensions.toLowerCase().match(/(?:[0-9a-wy-z](?:-[a-z0-9]{2,8})+)/g);Array.from(u||[]).forEach(l=>{a[l[0]]=l.slice(2)})}let n=(e=r.variants)==null?void 0:e.split(/-/).filter(u=>u!==""),o={extlang:r.extlang,langtag:r.langtag,language:r.language,privateuse:r.privateuse||r.privateuse2,region:r.region,script:r.script,extensions:a,variants:n};return Object.keys(o).forEach(u=>{let l=o[u];(typeof l=="undefined"||l==="")&&delete o[u]}),o}return null}catch(t){return null}};function sC(){let s="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",d=`^(?:(?<langtag>${`
|
|
117
|
+
`}),v};var je=s=>new URL(s).hostname;import{assertNever as Qy,assertNonNullable as Gy,combine as W$,debounce as Y$,ErrorCategory as Wy,filter as Yy,filterChanged as K$,isNonNullable as tp,map as Du,merge as Ky,observableFrom as X$,once as J$,Subscription as Z$,ValueSubject as ip,videoQualityToHeight as Xy,videoSizeToQuality as eD}from"@vkontakte/videoplayer-shared/es2015";var qy=H(qt(),1);var Oy=H(It(),1);var Vy=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"))},ct=(s,e)=>E(void 0,null,function*(){let t=s.muted;try{yield s.play()}catch(i){if(!Vy(i))return!1;if(e&&e(),t)return console.warn(i),!1;s.muted=!0;try{yield s.play()}catch(r){return Vy(r)&&(s.muted=!1,console.warn(r)),!1}}return!0});import{isNonNullable as Bu,isNullable as M$,assertNonNullable as Fa}from"@vkontakte/videoplayer-shared/es2015";var Fy=H(pr(),1);import{isNonNullable as _y,assertNonNullable as Lu,now as k$}from"@vkontakte/videoplayer-shared/es2015";function Ve(){return k$()}function Xd(s){return Ve()-s}function Jd(s){let e=s.split("/"),t=e.slice(0,e.length-1).join("/"),i=/^([a-z]+:)?\/\//i,r=n=>i.test(n);return{resolve:(n,o,u=!1)=>{r(n)||(n.startsWith("/")||(n="/"+n),n=t+n);let l=n.indexOf("?")>-1?"&":"?";return u&&(n+=l+"lowLat=1",l="&"),o&&(n+=l+"_rnd="+Math.floor(999999999*Math.random())),n}}}function Ny(s,e,t){let i=(...r)=>{t.apply(null,r),s.removeEventListener(e,i)};s.addEventListener(e,i)}function Jr(s,e,t,i){let r=window.XMLHttpRequest,a,n,o,u=!1,l=0,d,c,f=!1,p="arraybuffer",h=7e3,m=2e3,g=()=>{if(u)return;Lu(d);let M=Xd(d),j;if(M<m){j=m-M,setTimeout(g,j);return}m*=2,m>h&&(m=h),n&&n.abort(),n=new r,k()},S=M=>(a=M,F),v=M=>(c=M,F),y=()=>(p="json",F),T=()=>{if(!u){if(--l>=0){g(),i&&i();return}u=!0,c&&c(),t&&t()}},I=M=>(f=M,F),k=()=>{d=Ve(),n=new r,n.open("get",s);let M=0,j,N=0,K=()=>(Lu(d),Math.max(d,Math.max(j||0,N||0)));if(a&&n.addEventListener("progress",P=>{let L=Ve();a.updateChunk&&P.loaded>M&&(a.updateChunk(K(),P.loaded-M),M=P.loaded,j=L)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>T())),n.addEventListener("load",()=>{if(u)return;Lu(n);let P=n.status;if(P>=200&&P<300){let{response:L,responseType:R}=n,A=L==null?void 0:L.byteLength;if(typeof A=="number"&&a){let O=A-M;O&&a.updateChunk&&a.updateChunk(K(),O)}R==="json"&&(!L||!(0,Fy.default)(L).length)?T():(c&&c(),e(L))}else T()}),n.addEventListener("error",()=>{T()}),f){let P=()=>{Lu(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(N=Ve(),n.removeEventListener("readystatechange",P))};n.addEventListener("readystatechange",P)}return n.responseType=p,n.send(),F},F={withBitrateReporting:S,withParallel:I,withJSONResponse:y,withRetryCount:M=>(l=M,F),withRetryInterval:(M,j)=>(_y(M)&&(m=M),_y(j)&&(h=j),F),withTimeout:M=>(o=M,F),withFinally:v,send:k,abort:()=>{n&&(n.abort(),n=void 0),u=!0,c&&c()}};return F}var Oa=class{constructor(e){this.intervals=[];this.currentRate=0;this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,i){return{start:e,end:t,bytes:i}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;let e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-500;if(t-e>2e3){let i=0,r=0;for(;this.intervals.length>0;){let a=this.intervals[0];if(a.end<=t)i+=a.end-a.start,r+=a.bytes,this.intervals.splice(0,1);else{if(a.start>=t)break;{let n=t-a.start,o=a.end-a.start;i+=n;let u=a.bytes*n/o;r+=u,a.start=t,a.bytes-=u}}}if(r>0&&i>0){let a=r*8/(i/1e3);return this._updateRate(a),this.logger(`rate updated, new=${Math.round(a/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(r)}/${Math.round(i)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,i){return this.intervals.push(this._createInterval(e,t,i)),this._joinIntervals(),this.intervals.length>100&&(this.logger(`too many intervals (${this.intervals.length}); will merge`,{type:"warn"}),this._doMergeIntervals(this.intervals[1],this.intervals[0]),this.intervals.splice(0,1)),this._flushIntervals()}getBitRate(){return this.currentRate}};var Uy=H(pr(),1);var _a=class{constructor(e,t,i,r,a){this.pendingQueue=[];this.activeRequests={};this.completeRequests={};this.averageSegmentDuration=2e3;this.lastPrefetchStart=0;this.throttleTimeout=null;this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=i,this.MAX_PARALLEL_REQUESTS=r,this.logger=a}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){let t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){let i=Ve(),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=Ve()-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=Jr(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=Ve()}_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=Ve();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,Uy.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 L$}from"@vkontakte/videoplayer-shared/es2015";var $u=1e4,Zd=3;var B$=6e4,$$=10,D$=1,C$=500,Na=class{constructor(e){this.paused=!1;this.autoQuality=!0;this.autoQualityLimits=void 0;this.buffering=!0;this.destroyed=!1;this.videoPlayStarted=!1;this.lowLatency=!1;this.bitrate=0;this.manifest=[];this.sourceBuffer=0;this.bufferStates=[];this.sourceJitter=-1;this.waitingForFirstBufferAfterSrcChange=!1;this.params=e,this.soundProhibitedEvent$=new L$,this.chunkRateEstimator=new Oa(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=Jd(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setAutoQualityLimits(e){this.autoQualityLimits=e}switchByName(e){let t;for(let i=0;i<this.manifest.length;++i)if(t=this.manifest[i],t.name===e){this._switchToQuality(t);return}}catchUp(){if(this.rep&&this.rep.stop(),this.currentManifestEntry){let e=this.params.playbackState.getState();this.paused=e==="paused",this._initPlayerWith(this.currentManifestEntry),this._notifyBuffering(!0)}}stop(){this.params.videoElement.pause(),this.rep&&(this.rep.stop(),this.rep=null)}pause(){this.paused=!0,this.params.videoElement.pause(),this.videoPlayStarted=!1,this._notifyBuffering(!1)}play(){this.paused=!1;let e=this.lowLatency&&this._getBufferSizeSec()>this.sourceJitter+5;this.rep&&!e?(this.bufferStates=[],this.videoPlayStarted=!1,this.shouldPlay()?this._playVideoElement():this._notifyBuffering(!0)):this.catchUp()}startPlay(e,t){this.autoQuality=t,this._initPlayerWith(e)}destroy(){this.destroyed=!0,this.rep&&(this.rep.stop(),this.rep=null),this.manifestRequest&&this.manifestRequest.abort(),this.manifestRefetchTimer&&(clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=void 0)}reinit(e){this.manifestUrl=e,this.urlResolver=Jd(e),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){let e=this.params.videoElement,t=0,i=e.buffered.length;return i!==0&&(t=e.buffered.end(i-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){let{videoElement:e,logger:t}=this.params;e.addEventListener("error",()=>{var r,a;!!e.error&&!this.destroyed&&(t(`Video element error: ${(r=e.error)==null?void 0:r.code}, details: ${(a=e.error)==null?void 0:a.message}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{let i=this._getBufferSizeSec();!this.paused&&i<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(i+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){let{logger:e,videoElement:t}=this.params,i=t.buffered.length,r;i!==0&&!this.waitingForFirstBufferAfterSrcChange&&(r=t.buffered.start(i-1),t.currentTime<r&&(e("Fixup stall"),t.currentTime=r))}_selectQuality(e){let{videoElement:t}=this.params,i,r,a,n=t&&1.62*(Q.display.pixelRatio||1)*t.offsetHeight||520;for(let o=0;o<this.manifest.length;++o){a=this.manifest[o];let{max:u,min:l}=this.autoQualityLimits||{};!Ay({limits:this.autoQualityLimits,highestAvailableHeight:this.manifest[0].video.height,lowestAvailableHeight:(0,qy.default)(this.manifest,-1).video.height})&&(u&&a.video.height>u||l&&a.video.height<l)||(a.bitrate<e&&n>Math.min(a.video.height,a.video.width)?(!r||a.bitrate>r.bitrate)&&(r=a):(!i||i.bitrate>a.bitrate)&&(i=a))}return r||i}shouldPlay(){if(this.paused)return!1;let t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||Bu(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=()=>{Ny(r,"progress",()=>{r.buffered.length?(r.currentTime=r.buffered.start(0),this.waitingForFirstBufferAfterSrcChange=!1,a({name:"playing"})):n()})};this.waitingForFirstBufferAfterSrcChange=!0,n()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new _a(Zd,$u,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:i,playerCallback:r}=this.params,a=!1,n=null,o=null,u=null,l=null,d=!1,c=()=>{let T=a&&(!d||d===this.rep);return T||t("Not running!"),T},f=(T,I,k)=>{u&&u.abort(),u=Jr(this.urlResolver.resolve(T,!1),I,k,()=>this._retryCallback()).withTimeout($u).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Zd).withFinally(()=>{u=null}).send()},p=(T,I,k)=>{Fa(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(T,!1),I,k,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},h=T=>{let I=i.playbackRate;i.playbackRate!==T&&(t(`Playback rate switch: ${I}=>${T}`),i.playbackRate=T)},m=T=>{this.lowLatency=T,t(`lowLatency changed to ${T}`),g()},g=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)h(1);else{let T=this._getBufferSizeSec();if(this.bufferStates.length<5){h(1);return}let k=Ve()-1e4,C=0;for(let $=0;$<this.bufferStates.length;$++){let w=this.bufferStates[$];T=Math.min(T,w.buf),w.ts<k&&C++}this.bufferStates.splice(0,C),t(`update playback rate; minBuffer=${T} drop=${C} jitter=${this.sourceJitter}`);let V=T-D$;this.sourceJitter>=0?V-=this.sourceJitter/2:this.sourceJitter-=1,V>3?h(1.15):V>1?h(1.1):V>.3?h(1.05):h(1)}},S=T=>{let I,k=()=>I&&I.start?I.start.length:0,C=P=>I.start[P]/1e3,V=P=>I.dur[P]/1e3,$=P=>I.fragIndex+P,w=(P,L)=>({chunkIdx:$(P),startTS:C(P),dur:V(P),discontinuity:L}),F=()=>{let P=0;if(I&&I.dur){let L=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,R=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,A=L;this.sourceJitter>1&&(A+=this.sourceJitter-1);let O=I.dur.length-1;for(;O>=0&&(A-=I.dur[O],!(A<=0));--O);P=Math.min(O,I.dur.length-1-R),P=Math.max(P,0)}return w(P,!0)},M=P=>{let L=k();if(!(L<=0)){if(Bu(P)){for(let R=0;R<L;R++)if(C(R)>P)return w(R)}return F()}},j=P=>{let L=k(),R=P?P.chunkIdx+1:0,A=R-I.fragIndex;if(!(L<=0)){if(!P||A<0||A-L>$$)return t(`Resync: offset=${A} bChunks=${L} chunk=`+JSON.stringify(P)),F();if(!(A>=L))return w(R-I.fragIndex,!1)}},N=(P,L,R)=>{l&&l.abort(),l=Jr(this.urlResolver.resolve(P,!0,this.lowLatency),L,R,()=>this._retryCallback()).withTimeout($u).withRetryCount(Zd).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(P,L)=>{N(T,R=>{if(!c())return;I=R;let A=!!I.lowLatency;A!==this.lowLatency&&m(A);let O=0;for(let de=0;de<I.dur.length;++de)O+=I.dur[de];O>0&&(Fa(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(O/I.dur.length)),r({name:"index",zeroTime:I.zeroTime,shiftDuration:I.shiftDuration}),this.sourceJitter=I.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,I.jitter/1e3)):1,P(M(L))},()=>this._handleNetworkError())},nextChunk:j}},v=()=>{a=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),Fa(this.filesFetcher),this.filesFetcher.abortAll()};return d={start:T=>{let{videoElement:I,logger:k}=this.params,C=S(e.jidxUrl),V,$,w,F,M=0,j,N,K,P=()=>{j&&(clearTimeout(j),j=void 0);let ee=Math.max(C$,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),Ee=M+ee,we=Ve(),Ae=Math.min(1e4,Ee-we);M=we;let Ne=()=>{l||c()&&C.seek(()=>{c()&&(M=Ve(),L(),P())})};Ae>0?j=window.setTimeout(()=>{this.paused?P():Ne()},Ae):Ne()},L=()=>{let ee;for(;ee=C.nextChunk(F);)F=ee,Fe(ee);let Ee=C.nextChunk(w);if(Ee){if(w&&Ee.discontinuity){k("Detected discontinuity; restarting playback"),this.paused?P():(v(),this._initPlayerWith(e));return}de(Ee)}else P()},R=(ee,Ee)=>{if(!c()||!this.sourceBuffer)return;let we,Ae,Ne,At=Lt=>{window.setTimeout(()=>{c()&&R(ee,Ee)},Lt)};if(this.sourceBuffer.updating)k("Source buffer is updating; delaying appendBuffer"),At(100);else{let Lt=Ve(),Gt=I.currentTime;!this.paused&&I.buffered.length>1&&N===Gt&&Lt-K>500&&(k("Stall suspected; trying to fix"),this._fixupStall()),N!==Gt&&(N=Gt,K=Lt);let ii=this._getBufferSizeSec();if(ii>30)k(`Buffered ${ii} seconds; delaying appendBuffer`),At(2e3);else try{this.sourceBuffer.appendBuffer(ee),this.videoPlayStarted?(this.bufferStates.push({ts:Lt,buf:ii}),g(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),Ee&&Ee()}catch(Li){if(Li.name==="QuotaExceededError")k("QuotaExceededError; delaying appendBuffer"),Ne=this.sourceBuffer.buffered.length,Ne!==0&&(we=this.sourceBuffer.buffered.start(0),Ae=Gt,Ae-we>4&&this.sourceBuffer.remove(we,Ae-3)),At(1e3);else throw Li}}},A=()=>{$&&V&&(k([`Appending chunk, sz=${$.byteLength}:`,JSON.stringify(w)]),R($,function(){$=null,L()}))},O=ee=>e.fragUrlTemplate.replace("%%id%%",ee.chunkIdx),de=ee=>{c()&&p(O(ee),(Ee,we)=>{if(c()){if(we/=1e3,$=Ee,w=ee,n=ee.startTS,we){let Ae=Math.min(10,ee.dur/we);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*Ae:Ae}A()}},()=>this._handleNetworkError())},Fe=ee=>{c()&&(Fa(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(O(ee),!1)))},ue=ee=>{c()&&(e.cachedHeader=ee,R(ee,()=>{V=!0,A()}))};a=!0,C.seek(ee=>{if(c()){if(M=Ve(),!ee){P();return}F=ee,!M$(T)||ee.startTS>T?de(ee):(w=ee,L())}},T),e.cachedHeader?ue(e.cachedHeader):f(e.headerUrl,ue,()=>this._handleNetworkError())},stop:v,getTimestampSec:()=>n},d}_switchToQuality(e){let{logger:t,playerCallback:i}=this.params,r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),Bu(r)&&(r+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,Fa(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return Bu(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,i=c=>{if(!this.autoQuality)return;let f,p,h;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&c<this.bitrate&&(p=this._getBufferSizeSec(),h=c/this.bitrate,p>10&&h>.8||p>15&&h>.5||p>20&&h>.3)){e(`Not switching: buffer=${Math.floor(p)}; bitrate=${this.bitrate}; newRate=${Math.floor(c)}`);return}f=this._selectQuality(c),f?this._switchToQuality(f):e(`Could not find quality by bitrate ${c}`)},a={updateChunk:(f,p)=>{let h=Ve();if(this.chunkRateEstimator.addInterval(f,h,p)){let g=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:p,duration:h-f,speed:g}),!0}},get:()=>{let f=this.chunkRateEstimator.getBitRate();return f?f*.85:0}},n=-1/0,o,u=!0,l=()=>{let c=a.get();if(c&&o&&this.autoQuality){if(u&&c>o&&Xd(n)<3e4)return;i(c)}u=this.autoQuality};return{updateChunk:(c,f)=>{let p=a.updateChunk(c,f);return p&&l(),p},notifySwitch:c=>{let f=Ve();c<o&&(n=f),o=c}}}_fetchManifest(e,t,i){this.manifestRequest=Jr(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout($u).withRetryCount(this.params.config.manifestRetryMaxCount).withRetryInterval(this.params.config.manifestRetryInterval,this.params.config.manifestRetryMaxInterval).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(){let{videoElement:e}=this.params;ct(e,()=>{this.soundProhibitedEvent$.next()}).then(t=>{t||(this.params.liveOffset.pause(),this.params.videoState.setState("paused"))})}_handleManifestUpdate(e){let{logger:t,playerCallback:i,videoElement:r}=this.params,a=n=>{let o=[];return n!=null&&n.length?(n.forEach((u,l)=>{var d,c;u.video&&r.canPlayType(u.codecs).replace(/no/,"")&&((c=(d=window.MediaSource)==null?void 0:d.isTypeSupported)!=null&&c.call(d,u.codecs))&&(u.index=l,o.push(u))}),o.sort(function(u,l){return u.video&&l.video?l.video.height-u.video.height:l.bitrate-u.bitrate}),o):(i({name:"error",type:"empty_manifest"}),[])};this.manifest=a(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),i({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},B$))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var zy=H(sr(),1);import{debounce as V$,filter as jy,fromEvent as O$,interval as _$,isHigher as F$,isInvariantQuality as N$,isLower as U$,merge as q$,Subject as Hy,Subscription as j$}from"@vkontakte/videoplayer-shared/es2015";var ep=class{constructor(){this.onDroopedVideoFramesLimit$=new Hy;this.subscription=new j$;this.playing=!1;this.tracks=[];this.forceChecker$=new Hy;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&&!N$(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&&F$(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(O$(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=_$(this.droppedFramesChecker.checkTime).pipe(jy(()=>this.playing),jy(()=>{let r=!!this.isForceCheckCounter;return r&&(this.isForceCheckCounter-=1),!r})),t=this.forceChecker$.pipe(V$(this.droppedFramesChecker.checkTime)),i=q$(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,zy.default)(this.limitCounts).filter(([,a])=>a>=this.droppedFramesChecker.countLimit).sort(([a],[n])=>U$(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}},Zr=ep;import{map as H$,Observable as z$}from"@vkontakte/videoplayer-shared/es2015";import{fromEvent as Q$}from"@vkontakte/videoplayer-shared/es2015";var Ua=()=>{var s;return!!((s=window.documentPictureInPicture)!=null&&s.window)||!!document.pictureInPictureElement};var G$=(s,e)=>new z$(t=>{if(!window.IntersectionObserver)return;let i={root:null},r=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||Ua()))},x(x({},i),e));r.observe(s);let a=Q$(document,"visibilitychange").pipe(H$(n=>!document.hidden||Ua())).subscribe(n=>t.next(n));return()=>{r.unobserve(s),a.unsubscribe()}}),Rt=G$;var tD=["paused","playing","ready"],iD=["paused","playing","ready"],qa=class{constructor(e){this.subscription=new Z$;this.videoState=new Y("stopped");this.representations$=new ip([]);this.droppedFramesManager=new Zr;this.maxSeekBackTime$=new ip(1/0);this.zeroTime$=new ip(void 0);this.liveOffset=new hr;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:Wy.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{let n=e.manifest,o=[];for(let u of n){let l=(t=u.name)!=null?t:u.index.toString(10),d=(i=Oi(u.name))!=null?i:eD(u.video),c=u.bitrate/1e3,f=x({},u.video);if(!d)continue;let p={id:l,quality:d,bitrate:c,size:f};o.push({track:p,representation:u})}this.representations$.next(o),this.params.output.availableVideoTracks$.next(o.map(({track:u})=>u)),((r=this.videoState.getTransition())==null?void 0:r.to)==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let n=e.quality,o=(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),tp(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,rp.default)(iD,e)&&(n||o)){this.prepare();return}if((r==null?void 0:r.to)!=="paused"&&a.state==="requested"&&(0,rp.default)(tD,e)){this.seek(a.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(Ie(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(Ie(this.params.source.url,u))}return;default:return Qy(e)}};this.textTracksManager=new kt(e.source.url),this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=r=>{e.output.error$.next({id:"DashLiveProvider",category:Wy.WTF,message:"DashLiveProvider internal logic error",thrown:r})};this.subscription.add(Ky(this.videoState.stateChangeStarted$.pipe(Du(r=>({transition:r,type:"start"}))),this.videoState.stateChangeEnded$.pipe(Du(r=>({transition:r,type:"end"})))).subscribe(({transition:r,type:a})=>{this.log({message:`[videoState change] ${a}: ${JSON.stringify(r)}`})})),this.video=nt(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(je(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=lt(this.video);this.subscription.add(()=>i.destroy()),this.subscription.add(this.representations$.pipe(Du(r=>r.map(({track:a})=>a)),Yy(r=>!!r.length),J$()).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(K$(),Du(r=>-r/1e3)).subscribe(this.params.output.duration$)).add(W$({zeroTime:this.zeroTime$.pipe(Yy(tp)),position:i.timeUpdate$}).subscribe(({zeroTime:r,position:a})=>this.params.output.liveTime$.next(r+a*1e3),t)).add(Kt(this.video,this.params.desiredState.isLooped,t)).add(ut(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(Pt(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(Rt(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:r,min:a}})=>{this.dash.setAutoQualityLimits({max:r&&Xy(r),min:a&&Xy(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 Qy(r.to)}},t)).add(Ky(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,X$(["init"])).pipe(Y$(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),ot(this.video)}createLiveDashPlayer(){let e=new Na({videoElement:this.video,videoState:this.videoState,playbackState:this.params.desiredState.playbackState,liveOffset:this.liveOffset,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode,manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){var l,d,c,f,p,h;let e=this.representations$.getValue(),t=(d=(l=this.params.desiredState.videoTrack.getTransition())==null?void 0:l.to)!=null?d:this.params.desiredState.videoTrack.getState(),i=(f=(c=this.params.desiredState.autoVideoTrackSwitching.getTransition())==null?void 0:c.to)!=null?f:this.params.desiredState.autoVideoTrackSwitching.getState(),r=!i&&tp(t)?t:Zt(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=(h=e.find(({track:g})=>g.id===a))==null?void 0:h.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(Ie(this.params.source.url,n)),r&&this.dash.pause(),this.liveOffset.resetTo(n,r)}};var Jy=qa;var dx=H(It(),1);var Oe=(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 _C,assertNonNullable as FC,debounce as NC,ErrorCategory as ux,filter as jp,filterChanged as ol,fromEvent as UC,isNonNullable as lx,isNullable as qC,map as Hp,merge as ul,observableFrom as zp,once as cx,Subscription as jC}from"@vkontakte/videoplayer-shared/es2015";var Cu=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}},es=class extends Cu{constructor(){super(),this.listeners||Cu.call(this),Object.defineProperty(this,"aborted",{value:!1,writable:!0,configurable:!0}),Object.defineProperty(this,"onabort",{value:null,writable:!0,configurable:!0}),Object.defineProperty(this,"reason",{value:void 0,writable:!0,configurable:!0})}toString(){return"[object AbortSignal]"}dispatchEvent(e){e.type==="abort"&&(this.aborted=!0,typeof this.onabort=="function"&&this.onabort.call(this,e)),super.dispatchEvent(e)}},ja=class{constructor(){Object.defineProperty(this,"signal",{value:new es,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch(r){typeof document!="undefined"?document.createEvent?(t=document.createEvent("Event"),t.initEvent("abort",!1,!1)):(t=document.createEventObject(),t.type="abort"):t={type:"abort",bubbles:!1,cancelable:!1}}let i=e;if(i===void 0)if(typeof document=="undefined")i=new Error("This operation was aborted"),i.name="AbortError";else try{i=new DOMException("signal is aborted without reason")}catch(r){i=new Error("This operation was aborted"),i.name="AbortError"}this.signal.reason=i,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol!="undefined"&&Symbol.toStringTag&&(ja.prototype[Symbol.toStringTag]="AbortController",es.prototype[Symbol.toStringTag]="AbortSignal");function Vu(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 sp(s){typeof s=="function"&&(s={fetch:s});let{fetch:e,Request:t=e.Request,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r=!1}=s;if(!Vu({fetch:e,Request:t,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r}))return{fetch:e,Request:a};let a=t;(a&&!a.prototype.hasOwnProperty("signal")||r)&&(a=function(l,d){let c;d&&d.signal&&(c=d.signal,delete d.signal);let f=new t(l,d);return c&&Object.defineProperty(f,"signal",{writable:!1,enumerable:!1,configurable:!0,value:c}),f},a.prototype=t.prototype);let n=e;return{fetch:(u,l)=>{let d=a&&a.prototype.isPrototypeOf(u)?u.signal:l?l.signal:void 0;if(d){let c;try{c=new DOMException("Aborted","AbortError")}catch(p){c=new Error("Aborted"),c.name="AbortError"}if(d.aborted)return Promise.reject(c);let f=new Promise((p,h)=>{d.addEventListener("abort",()=>h(c),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([f,n(u,l)])}return n(u,l)},Request:a}}var rD=()=>"fetch"in window,Ha=rD()&&Vu({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),Zy=Ha?sp({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,Mt=Ha?Zy.fetch:window.fetch,tH=Ha?Zy.Request:window.Request,le=Ha?ja:window.AbortController,iH=Ha?es:window.AbortSignal;var Op=H(za(),1);var FT=H(_T(),1);import{ErrorCategory as Ga}from"@vkontakte/videoplayer-shared/es2015";var Ou=s=>{if(!s)return{id:"EmptyResponse",category:Ga.PARSER,message:"Empty response"};if(s.length<=2&&s.match(/^\d+$/))return{id:`UVError#${s}`,category:Ga.NETWORK,message:`UV Error ${s}`};let e=(0,FT.default)(s).substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:Ga.NETWORK,message:"Received unexpected HTML, possibly a ISP block"};if(e.startsWith("<?xml"))return new DOMParser().parseFromString(s,"text/xml").querySelector("parsererror")?{id:"InvalidXML",category:Ga.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:Ga.PARSER,message:"Response is valid XML, but parser failed"}};var He=(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 Dp,assertNonNullable as cs,combine as ds,ErrorCategory as Ht,filter as Zu,filterChanged as Pn,flattenObject as kn,fromEvent as Ai,getTraceSubscriptionMethod as yC,interval as Cp,isNonNullable as Rn,isNullable as ix,map as ps,merge as Sr,now as Vp,Subject as el,Subscription as rx,tap as TC,throttle as IC,ValueSubject as ge}from"@vkontakte/videoplayer-shared/es2015";var Nu=H(It(),1),os=H(qt(),1),Uu=H(za(),1);var qD=(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)},jD=s=>window.clearTimeout(s),NT=s=>typeof s=="function"&&(s==null?void 0:s.toString().endsWith("{ [native code] }")),UT=!NT(window.requestIdleCallback)||!NT(window.cancelIdleCallback),ts=UT?qD:window.requestIdleCallback,ei=UT?jD:window.cancelIdleCallback;var QI=H(ou(),1);import{assertNever as HD,ErrorCategory as qT,Subject as jT}from"@vkontakte/videoplayer-shared/es2015";var zD=18,HT=!1;try{HT=Q.browser.isSafari&&!!Q.browser.safariVersion&&Q.browser.safariVersion<=zD}catch(s){console.error(s)}var cp=class{constructor(e){this.bufferFull$=new jT;this.error$=new jT;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:qT.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}append(e,t){return E(this,null,function*(){return t&&t.aborted?!1:new Promise(i=>{let r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})})}remove(e,t,i){return E(this,null,function*(){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()})})}abort(e){return E(this,null,function*(){return new Promise(t=>{let i,r=a=>{this.abortRequested=!1,t(a)};HT&&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:qT.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:HD(t)}}},zT=cp;var is=s=>{let e=0;for(let t=0;t<s.length;t++)e+=s.end(t)-s.start(t);return e*1e3};import{abortable as Ni,assertNonNullable as dt,ErrorCategory as xi,fromEvent as kp,getExponentialDelay as Rp,isNonNullable as ns,isNullable as ze,now as Fu,once as uC,Subject as lC,Subscription as cC,ValueSubject as gr}from"@vkontakte/videoplayer-shared/es2015";var te=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let i=this.readUint32();this.type=this.readString(4),this.size32=i<=e.buffer.byteLength-e.byteOffset?i:NaN;let r=this.size32?this.size32-8:void 0,a=e.byteOffset+this.cursor;this.size64=0,this.usertype=0,this.content=new DataView(e.buffer,a,r)}get id(){return this.type}get size(){return this.size32}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t="ascii"){let r=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,r}readUint8(){let e=this.source.getUint8(this.cursor);return this.cursor+=1,e}readUint16(){let e=this.source.getUint16(this.cursor);return this.cursor+=2,e}readUint32(){let e=this.source.getUint32(this.cursor);return this.cursor+=4,e}readUint64(){let e=this.source.getBigInt64(this.cursor);return this.cursor+=8,e}};var rs=class extends te{};var Wa=class extends te{constructor(t,i){super(t,i);this.ondemandPrefix="ondemandlivejson";this.ondemandDataReceivedKey="t-in";this.ondemandDataPreparedKey="t-out";let r=this.content.byteOffset,a=r+this.content.byteLength,n=new TextDecoder("ascii").decode(this.content.buffer.slice(r,a)).split(this.ondemandPrefix)[1],o=JSON.parse(n);this.serverDataReceivedTimestamp=o[this.ondemandDataReceivedKey],this.serverDataPreparedTime=o[this.ondemandDataPreparedKey]}};var Ya=class extends te{constructor(e,t){super(e,t),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let i=this.size-this.cursor;for(;i;){let r=this.readString(4);this.compatibleBrands.push(r),i-=4}}};var Ka=class extends te{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var pe=class extends te{constructor(e,t){super(e,t);let i=this.readUint32();this.version=i>>>24,this.flags=i&16777215}};var Xa=class extends pe{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.timescale=this.readUint32(),this.duration=this.readUint32(),this.rate=this.readUint32(),this.volume=this.readUint16()}};var Ja=class extends te{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Za=class extends te{constructor(e,t){super(e,t),this.data=this.content}};var mr=class extends pe{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e,t){super(e,t),this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let i=0;i<this.referenceCount;i++){let r=this.readUint32(),a=r>>>31,n=r<<1>>>1,o=this.readUint32();r=this.readUint32();let u=r>>>28,l=r<<3>>>3;this.segments.push({referenceType:a,referencedSize:n,subsegmentDuration:o,SAPType:u,SAPDeltaTime:l})}}};var en=class extends te{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var tn=class extends te{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var rn=class extends pe{constructor(e,t){switch(super(e,t),this.readUint8()){case 0:this.stereoMode=0;break;case 1:this.stereoMode=1;break;case 2:this.stereoMode=2;break;case 3:this.stereoMode=3;break;case 4:this.stereoMode=4;break}this.cursor+=1}};var sn=class extends pe{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var an=class extends pe{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var nn=class extends te{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var on=class extends pe{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.trackId=this.readUint32(),this.cursor+=4,this.duration=this.readUint32(),this.cursor+=8,this.layer=this.readUint16(),this.alternateGroup=this.readUint16(),this.cursor+=2,this.cursor+=2,this.matrix=[[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()]],this.width=this.readUint32(),this.height=this.readUint32()}};var un=class extends te{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ln=class extends te{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var cn=class extends pe{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var dn=class extends te{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var pn=class extends pe{constructor(e,t){super(e,t),this.trackId=this.readUint32(),this.flags&1&&(this.baseDataOffset=this.readUint64()),this.flags&2&&(this.sampleDescriptionIndex=this.readUint32()),this.flags&8&&(this.defaultSampleDuration=this.readUint32()),this.flags&16&&(this.defaultSampleSize=this.readUint32()),this.flags&32&&(this.defaultSampleFlags=this.readUint32())}};var hn=class extends pe{constructor(t,i){super(t,i);this.baseMediaDecodeTime32=0;this.baseMediaDecodeTime64=BigInt(0);this.version===1?this.baseMediaDecodeTime64=this.readUint64():this.baseMediaDecodeTime32=this.readUint32()}get baseMediaDecodeTime(){return this.version===1?this.baseMediaDecodeTime64:this.baseMediaDecodeTime32}};var fn=class extends pe{constructor(t,i){super(t,i);this.sampleDuration=[];this.sampleSize=[];this.sampleFlags=[];this.sampleCompositionTimeOffset=[];this.optionalFields=0;this.sampleCount=this.readUint32(),this.flags&1&&(this.dataOffset=this.readUint32()),this.flags&4&&(this.firstSampleFlags=this.readUint32());for(let r=0;r<this.sampleCount;r++)this.flags&256&&this.sampleDuration.push(this.readUint32()),this.flags&512&&this.sampleSize.push(this.readUint32()),this.flags&1024&&this.sampleFlags.push(this.readUint32()),this.flags&2048&&this.sampleCompositionTimeOffset.push(this.readUint32())}};var mn=class extends te{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var bn=class extends pe{constructor(e,t){super(e,t),this.entryCount=this.readUint32(),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+8,this.content.byteLength-8))}};var gn=class extends te{constructor(e,t){super(e,t),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+78,this.content.byteLength-78))}};var GD={ftyp:Ya,moov:Ka,mvhd:Xa,moof:Ja,mdat:Za,sidx:mr,trak:en,mdia:nn,mfhd:cn,tkhd:on,traf:dn,tfhd:pn,tfdt:hn,trun:fn,minf:un,sv3d:tn,st3d:rn,prhd:sn,proj:ln,equi:an,uuid:Wa,stbl:mn,stsd:bn,avc1:gn,unknown:rs},Ti=class s{constructor(e={}){this.options=x({offset:0},e)}parse(e){let t=[],i=this.options.offset;for(;i<e.byteLength;)try{let a=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+i+4,4)),n=this.createBox(a,new DataView(e.buffer,e.byteOffset+i));if(!n.size)break;t.push(n),i+=n.size}catch(r){break}return t}createBox(e,t){let i=GD[e];return i?new i(t,new s):new rs(t,new s)}};var Fi=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{var i,r,a;(a=(i=this.index)[r=t.type])!=null||(i[r]=[]),this.index[t.type].push(t),t.children.length>0&&this.indexBoxLevel(t.children)})}find(e){return this.index[e]&&this.index[e][0]?this.index[e][0]:null}findAll(e){return this.index[e]||[]}};var YD=new TextDecoder("ascii"),KD=s=>YD.decode(new DataView(s.buffer,s.byteOffset+4,4))==="ftyp",XD=s=>{let e=new mr(s,new Ti),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})},JD=(s,e)=>{let i=new Ti().parse(s),r=new Fi(i),a=r.findAll("moof"),n=e?r.findAll("uuid"):r.findAll("mdat");if(!(n.length&&a.length))return null;let o=a[0],u=n[n.length-1],l=o.source.byteOffset,c=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(s.buffer,l,c)},ZD=s=>{let t=new Ti().parse(s),i=new Fi(t),r={},a=i.findAll("uuid");return a.length?a[a.length-1]:r},e0=s=>{var r;let t=new Ti().parse(s);return(r=new Fi(t).find("sidx"))==null?void 0:r.timescale},t0=(s,e)=>{let i=new Ti().parse(s),a=new Fi(i).findAll("traf"),n=a[a.length-1].children.find(c=>c.type==="tfhd"),o=a[a.length-1].children.find(c=>c.type==="tfdt"),u=a[a.length-1].children.find(c=>c.type==="trun"),l=0;return u.sampleDuration.length?l=u.sampleDuration.reduce((c,f)=>c+f,0):l=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+l)/e*1e3},i0=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 Ti().parse(s),r=new Fi(i);if(r.find("sv3d")){e.is3dVideo=!0;let n=r.find("st3d");n&&(e.stereoMode=n.stereoMode);let o=r.find("prhd");o&&(e.projectionData.pose.yaw=o.poseYawDegrees,e.projectionData.pose.pitch=o.posePitchDegrees,e.projectionData.pose.roll=o.poseRollDegrees);let u=r.find("equi");u&&(e.projectionData.bounds.top=u.projectionBoundsTop,e.projectionData.bounds.right=u.projectionBoundsRight,e.projectionData.bounds.bottom=u.projectionBoundsBottom,e.projectionData.bounds.left=u.projectionBoundsLeft)}return e},QT={validateData:KD,parseInit:i0,getIndexRange:()=>{},parseSegments:XD,parseFeedableSegmentChunk:JD,getChunkEndTime:t0,getServerLatencyTimestamps:ZD,getTimescaleFromIndex:e0};var vn=H(It(),1);import{assertNonNullable as pp,isNonNullable as KT,isNullable as s0}from"@vkontakte/videoplayer-shared/es2015";import{assertNever as r0}from"@vkontakte/videoplayer-shared/es2015";var GT={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"}},WT=s=>{let e=s.getUint8(0),t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);let i=Sn(s,t),r=i in GT,a=r?GT[i].type:"binary",n=s.getUint8(t),o=0;n&128?o=1:n&64?o=2:n&32?o=3:n&16?o=4:n&8?o=5:n&4?o=6:n&2?o=7:n&1&&(o=8);let u=new DataView(s.buffer,s.byteOffset+t+1,o-1),l=n&255>>o,d=Sn(u),c=l*Ze(2,(o-1)*8)+d,f=t+o,p;return f+c>s.byteLength?p=new DataView(s.buffer,s.byteOffset+f):p=new DataView(s.buffer,s.byteOffset+f,c),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:a,tagHeaderSize:f,tagSize:f+c,value:p,valueSize:c}},Sn=(s,e=s.byteLength)=>{switch(e){case 1:return s.getUint8(0);case 2:return s.getUint16(0);case 3:return s.getUint8(0)*Ze(2,16)+s.getUint16(1);case 4:return s.getUint32(0);case 5:return s.getUint8(0)*Ze(2,32)+s.getUint32(1);case 6:return s.getUint16(0)*Ze(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},jt=(s,e)=>{switch(e){case"int":return s.getInt8(0);case"uint":return Sn(s);case"float":return s.byteLength===4?s.getFloat32(0):s.getFloat64(0);case"string":return new TextDecoder("ascii").decode(s);case"utf8":return new TextDecoder("utf-8").decode(s);case"date":return new Date(Date.UTC(2001,0)+s.getInt8(0)).getTime();case"master":return s;case"binary":return s;default:r0(e)}},br=(s,e)=>{let t=0;for(;t<s.byteLength;){let i=new DataView(s.buffer,s.byteOffset+t),r=WT(i);if(!e(r))return;r.type==="master"&&br(r.value,e),t=r.value.byteOffset-s.byteOffset+r.valueSize}},YT=s=>{if(s.getUint32(0)!==440786851)return!1;let e,t,i,r=WT(s);return br(r.value,({tag:a,type:n,value:o})=>(a===17143?e=jt(o,n):a===17026?t=jt(o,n):a===17029&&(i=jt(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],a0=[231,22612,22743,167,171,163,160,175],n0=s=>{let e,t,i,r,a=!1,n=!1,o=!1,u,l,d=!1,c=0;return br(s,({tag:f,type:p,value:h,valueSize:m})=>{if(f===21419){let g=jt(h,p);l=Sn(g)}else f!==21420&&(l=void 0);return f===408125543?(e=h.byteOffset,t=h.byteOffset+m):f===357149030?a=!0:f===290298740?n=!0:f===2807729?i=jt(h,p):f===17545?r=jt(h,p):f===21420&&l===475249515?u=jt(h,p):f===374648427?br(h,({tag:g,type:S,value:v})=>g===30321?(d=jt(v,S)===1,!1):!0):a&&n&&(0,vn.default)(XT,f)&&(o=!0),!o}),pp(e,"Failed to parse webm Segment start"),pp(t,"Failed to parse webm Segment end"),pp(r,"Failed to parse webm Segment duration"),i=i!=null?i:1e6,{segmentStart:Math.round(e/1e9*i*1e3),segmentEnd:Math.round(t/1e9*i*1e3),timeScale:i,segmentDuration:Math.round(r/1e9*i*1e3),cuesSeekPosition:u,is3dVideo:d,stereoMode:c,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},o0=s=>{if(s0(s.cuesSeekPosition))return;let e=s.segmentStart+s.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},u0=(s,e)=>{let t=!1,i=!1,r=o=>KT(o.time)&&KT(o.position),a=[],n;return br(s,({tag:o,type:u,value:l})=>{switch(o){case 475249515:t=!0;break;case 187:n&&r(n)&&a.push(n),n={};break;case 179:n&&(n.time=jt(l,u));break;case 183:break;case 241:n&&(n.position=jt(l,u));break;default:t&&(0,vn.default)(XT,o)&&(i=!0)}return!(t&&i)}),n&&r(n)&&a.push(n),a.map((o,u)=>{let{time:l,position:d}=o,c=a[u+1];return{status:"none",time:{from:l,to:c?c.time:e.segmentDuration},byte:{from:e.segmentStart+d,to:c?e.segmentStart+c.position-1:e.segmentEnd-1}}})},l0=s=>{let e=0,t=!1;try{br(s,i=>i.tag===524531317?i.tagSize<=s.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):(0,vn.default)(a0,i.tag)?(e+i.tagSize<=s.byteLength&&(e+=i.tagSize,t||(t=(0,vn.default)([163,160,175],i.tag))),!0):!1)}catch(i){}return e>0&&e<=s.byteLength&&t?new DataView(s.buffer,s.byteOffset,e):null},JT={validateData:YT,parseInit:n0,getIndexRange:o0,parseSegments:u0,parseFeedableSegmentChunk:l0};var yn=s=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(s);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return JT;case"mp4":return QT}}throw new ReferenceError(`Unsupported mime type ${s}`)};var wp=H(Sp(),1),UI=H(sr(),1),qI=H(vp(),1),jI=H(qt(),1),Ap=H(pr(),1);var $I=H(It(),1),as=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,$I.default)(["6E","7A","F4"],o)}}return!1};import{isNonNullable as nC,isNullable as FI}from"@vkontakte/videoplayer-shared/es2015";var _u=s=>{if(s.includes("/")){let e=s.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(s)};var DI=s=>{var e;try{let t=sC(),i=s.match(t),{groups:r}=i!=null?i:{};if(r){let a={};if(r.extensions){let u=r.extensions.toLowerCase().match(/(?:[0-9a-wy-z](?:-[a-z0-9]{2,8})+)/g);Array.from(u||[]).forEach(l=>{a[l[0]]=l.slice(2)})}let n=(e=r.variants)==null?void 0:e.split(/-/).filter(u=>u!==""),o={extlang:r.extlang,langtag:r.langtag,language:r.language,privateuse:r.privateuse||r.privateuse2,region:r.region,script:r.script,extensions:a,variants:n};return Object.keys(o).forEach(u=>{let l=o[u];(typeof l=="undefined"||l==="")&&delete o[u]}),o}return null}catch(t){return null}};function sC(){let s="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",d=`^(?:(?<langtag>${`
|
|
118
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(d,"i")}var Tp=H(qt(),1);import{videoSizeToQuality as aC}from"@vkontakte/videoplayer-shared/es2015";var CI=({id:s,width:e,height:t,bitrate:i,fps:r,quality:a,streamId:n})=>{var u;let o=(u=a?Oi(a):void 0)!=null?u:aC({width:e,height:t});return o&&{id:s,quality:o,bitrate:i,size:{width:e,height:t},fps:r,streamId:n}},VI=({id:s,bitrate:e})=>({id:s,bitrate:e}),OI=({language:s,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:s,label:e}),_I=({language:s,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:s,label:e}),Ip=({id:s,language:e,label:t,codecs:i,isDefault:r})=>({id:s,language:e,label:t,codec:(0,Tp.default)(i.split("."),0),isDefault:r}),xp=({id:s,language:e,label:t,hdr:i,codecs:r})=>({id:s,language:e,hdr:i,label:t,codec:(0,Tp.default)(r.split("."),0)}),Ep=s=>"url"in s,rt=s=>s.type==="template",Tn=s=>s instanceof DOMException&&(s.name==="AbortError"||s.code===20);var NI=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},Ii=(s,e)=>{let t=s;t=(0,wp.default)(t,"$$","$");let i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[r,a]of(0,UI.default)(i)){let n=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=(0,wp.default)(t,n,(o,u)=>FI(a)?o:FI(u)?a:(0,qI.default)(a,parseInt(u,10),"0"))}return t},HI=(s,e)=>{var $,w,F,M,j,N,K,P,L,k,A,O,de,Fe,ue,ee,Ee,we,Ae,Ne,At,Lt,Gt,ii,Li,Is,xs,Es,ws,As,Ps,Rs,ks,Ms,Ls,Bs,$s,Ds,Cs,Vs,Os,_s,Fs,Ns,Us,qs,js,Hs,zs,Qs,Gs,Ws,Ys,Ks,Xs,Js,Zs,ea,ta,ia,ra;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(fe=>{var q,Ge;return(Ge=(q=fe.textContent)==null?void 0:q.trim())!=null?Ge:""}),o=($=(0,jI.default)(n,0))!=null?$:"",u=a.getAttribute("type")==="dynamic",l=a.getAttribute("availabilityStartTime"),d=a.getAttribute("publishTime"),c=a.getElementsByTagName("vk:Attrs")[0],h=c==null?void 0:c.getElementsByTagName("vk:XLatestSegmentPublishTime")[0].textContent,p=c==null?void 0:c.getElementsByTagName("vk:XStreamIsLive")[0].textContent,f=c==null?void 0:c.getElementsByTagName("vk:XStreamIsUnpublished")[0].textContent,m=c==null?void 0:c.getElementsByTagName("vk:XPlaybackDuration")[0].textContent,g;u&&(g={availabilityStartTime:l?new Date(l).getTime():0,publishTime:d?new Date(d).getTime():0,latestSegmentPublishTime:h?new Date(h).getTime():0,streamIsAlive:p==="yes",streamIsUnpublished:f==="yes"});let S,v=a.getAttribute("mediaPresentationDuration"),y=[...a.getElementsByTagName("Period")],T=y.reduce((fe,q)=>B(x({},fe),{[q.id]:q.children}),{}),I=y.reduce((fe,q)=>B(x({},fe),{[q.id]:q.getAttribute("duration")}),{});v?S=NI(v):(0,Ap.default)(I).filter(fe=>fe).length&&!u?S=(0,Ap.default)(I).reduce((fe,q)=>{var Ge;return fe+((Ge=NI(q))!=null?Ge:0)},0):m&&(S=parseInt(m,10));let R=0,C=(F=(w=a.getAttribute("profiles"))==null?void 0:w.split(","))!=null?F:[];for(let fe of y.map(q=>q.id))for(let q of T[fe]){let Ge=(M=q.getAttribute("id"))!=null?M:"id"+(R++).toString(10),Bt=(j=q.getAttribute("mimeType"))!=null?j:"",Wi=(N=q.getAttribute("codecs"))!=null?N:"",Yi=(K=q.getAttribute("contentType"))!=null?K:Bt==null?void 0:Bt.split("/")[0],Cl=(L=(P=q.getAttribute("profiles"))==null?void 0:P.split(","))!=null?L:[],sa=(A=DI((k=q.getAttribute("lang"))!=null?k:""))!=null?A:{},ri=(Fe=(de=(O=q.querySelector("Label"))==null?void 0:O.textContent)==null?void 0:de.trim())!=null?Fe:void 0,Vl=q.querySelectorAll("Representation"),Ol=q.querySelector("SegmentTemplate"),_l=(ee=(ue=q.querySelector("Role"))==null?void 0:ue.getAttribute("value"))!=null?ee:void 0,ht=Yi,G={id:Ge,language:sa.language,isDefault:_l==="main",label:ri,codecs:Wi,hdr:ht==="video"&&as(Wi),mime:Bt,representations:[]};for(let U of Vl){let ke=(Ee=U.getAttribute("lang"))!=null?Ee:void 0,$t=(Ae=(we=ri!=null?ri:q.getAttribute("label"))!=null?we:U.getAttribute("label"))!=null?Ae:void 0,si=(Lt=(At=(Ne=U.querySelector("BaseURL"))==null?void 0:Ne.textContent)==null?void 0:At.trim())!=null?Lt:"",We=new URL(si||o,e).toString(),Me=(Gt=U.getAttribute("mimeType"))!=null?Gt:Bt,ai=(Li=(ii=U.getAttribute("codecs"))!=null?ii:Wi)!=null?Li:"",ni;if(Yi==="text"){let Le=U.getAttribute("id")||"",oi=((Is=sa.privateuse)==null?void 0:Is.includes("x-auto"))||Le.includes("_auto"),Ye=U.querySelector("SegmentTemplate");if(Ye){let Dt={representationId:(xs=U.getAttribute("id"))!=null?xs:void 0,bandwidth:(Es=U.getAttribute("bandwidth"))!=null?Es:void 0},ui=parseInt((ws=U.getAttribute("bandwidth"))!=null?ws:"",10)/1e3,li=(Ps=parseInt((As=Ye.getAttribute("startNumber"))!=null?As:"",10))!=null?Ps:1,ft=parseInt((Rs=Ye.getAttribute("timescale"))!=null?Rs:"",10),Ki=(ks=Ye.querySelectorAll("SegmentTimeline S"))!=null?ks:[],mt=Ye.getAttribute("media");if(!mt)continue;let ci=[],di=0,pi="",bt=0,Ct=li,se=0;for(let me of Ki){let Ke=parseInt((Ms=me.getAttribute("d"))!=null?Ms:"",10),ce=parseInt((Ls=me.getAttribute("r"))!=null?Ls:"",10)||0,Be=parseInt((Bs=me.getAttribute("t"))!=null?Bs:"",10);se=Number.isFinite(Be)?Be:se;let Xe=Ke/ft*1e3,$e=se/ft*1e3;for(let ve=0;ve<ce+1;ve++){let De=Ii(mt,B(x({},Dt),{segmentNumber:Ct.toString(10),segmentTime:(se+ve*Ke).toString(10)})),gt=($e!=null?$e:0)+ve*Xe,Ot=gt+Xe;Ct++,ci.push({time:{from:gt,to:Ot},url:De})}se+=(ce+1)*Ke,di+=(ce+1)*Xe}bt=se/ft*1e3,pi=Ii(mt,B(x({},Dt),{segmentNumber:Ct.toString(10),segmentTime:se.toString(10)}));let Vt={time:{from:bt,to:1/0},url:pi},Pe={type:"template",baseUrl:We,segmentTemplateUrl:mt,initUrl:"",totalSegmentsDurationMs:di,segments:ci,nextSegmentBeyondManifest:Vt,timescale:ft};ni={id:Le,kind:"text",segmentReference:Pe,profiles:[],duration:S,bitrate:ui,mime:"",codecs:"",width:0,height:0,isAuto:oi}}else ni={id:Le,isAuto:oi,kind:"text",url:We}}else{let Le=(Ds=($s=U.getAttribute("contentType"))!=null?$s:Me==null?void 0:Me.split("/")[0])!=null?Ds:Yi,oi=(Vs=(Cs=q.getAttribute("profiles"))==null?void 0:Cs.split(","))!=null?Vs:[],Ye=parseInt((Os=U.getAttribute("width"))!=null?Os:"",10),Dt=parseInt((_s=U.getAttribute("height"))!=null?_s:"",10),ui=parseInt((Fs=U.getAttribute("bandwidth"))!=null?Fs:"",10)/1e3,li=(Ns=U.getAttribute("frameRate"))!=null?Ns:"",ft=(Us=U.getAttribute("quality"))!=null?Us:void 0,Ki=li?_u(li):void 0,mt=(qs=U.getAttribute("id"))!=null?qs:"id"+(R++).toString(10),ci=Le==="video"?`${Dt}p`:Le==="audio"?`${ui}Kbps`:ai,di=`${mt}@${ci}`,pi=[...C,...Cl,...oi],bt,Ct=U.querySelector("SegmentBase"),se=(js=U.querySelector("SegmentTemplate"))!=null?js:Ol;if(Ct){let Pe=(zs=(Hs=U.querySelector("SegmentBase Initialization"))==null?void 0:Hs.getAttribute("range"))!=null?zs:"",[me,Ke]=Pe.split("-").map(De=>parseInt(De,10)),ce={from:me,to:Ke},Be=(Qs=U.querySelector("SegmentBase"))==null?void 0:Qs.getAttribute("indexRange"),[Xe,$e]=Be?Be.split("-").map(De=>parseInt(De,10)):[],ve=Be?{from:Xe,to:$e}:void 0;bt={type:"byteRange",url:We,initRange:ce,indexRange:ve}}else if(se){let Pe={representationId:(Gs=U.getAttribute("id"))!=null?Gs:void 0,bandwidth:(Ws=U.getAttribute("bandwidth"))!=null?Ws:void 0},me=parseInt((Ys=se.getAttribute("timescale"))!=null?Ys:"",10),Ke=(Ks=se.getAttribute("initialization"))!=null?Ks:"",ce=se.getAttribute("media"),Be=(Js=parseInt((Xs=se.getAttribute("startNumber"))!=null?Xs:"",10))!=null?Js:1,Xe=Ii(Ke,Pe);if(!ce)throw new ReferenceError("No media attribute in SegmentTemplate");let $e=(Zs=se.querySelectorAll("SegmentTimeline S"))!=null?Zs:[],ve=[],De=0,gt="",Ot=0;if($e.length){let hi=Be,be=0;for(let St of $e){let ye=parseInt((ea=St.getAttribute("d"))!=null?ea:"",10),Je=parseInt((ta=St.getAttribute("r"))!=null?ta:"",10)||0,fi=parseInt((ia=St.getAttribute("t"))!=null?ia:"",10);be=Number.isFinite(fi)?fi:be;let Xi=ye/me*1e3,Ji=be/me*1e3;for(let mi=0;mi<Je+1;mi++){let Nl=Ii(ce,B(x({},Pe),{segmentNumber:hi.toString(10),segmentTime:(be+mi*ye).toString(10)})),aa=(Ji!=null?Ji:0)+mi*Xi,Ul=aa+Xi;hi++,ve.push({time:{from:aa,to:Ul},url:Nl})}be+=(Je+1)*ye,De+=(Je+1)*Xi}Ot=be/me*1e3,gt=Ii(ce,B(x({},Pe),{segmentNumber:hi.toString(10),segmentTime:be.toString(10)}))}else if(nC(S)){let be=parseInt((ra=se.getAttribute("duration"))!=null?ra:"",10)/me*1e3,St=Math.ceil(S/be),ye=0;for(let Je=1;Je<St;Je++){let fi=Ii(ce,B(x({},Pe),{segmentNumber:Je.toString(10),segmentTime:ye.toString(10)}));ve.push({time:{from:ye,to:ye+be},url:fi}),ye+=be}Ot=ye,gt=Ii(ce,B(x({},Pe),{segmentNumber:St.toString(10),segmentTime:ye.toString(10)}))}let Fl={time:{from:Ot,to:1/0},url:gt};bt={type:"template",baseUrl:We,segmentTemplateUrl:ce,initUrl:Xe,totalSegmentsDurationMs:De,segments:ve,nextSegmentBeyondManifest:Fl,timescale:me}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Le||!Me)continue;let Vt={video:"video",audio:"audio",text:"text"}[Le];if(!Vt)continue;ht||(ht=Vt),ni={id:di,kind:Vt,segmentReference:bt,profiles:pi,duration:S,bitrate:ui,mime:Me,codecs:ai,width:Ye,height:Dt,fps:Ki,quality:ft}}G.language||(G.language=ke),G.label||(G.label=$t),G.mime||(G.mime=Me),G.codecs||(G.codecs=ai),G.hdr||(G.hdr=ht==="video"&&as(ai)),G.representations.push(ni)}if(ht){let U=r[ht].find(ke=>ke.id===G.id);if(U&&G.representations.every(ke=>rt(ke.segmentReference)))for(let ke of U.representations){let $t=G.representations.find(Me=>Me.id===ke.id),si=$t==null?void 0:$t.segmentReference,We=ke.segmentReference;We.segments.push(...si.segments),We.nextSegmentBeyondManifest=si.nextSegmentBeyondManifest}else r[ht].push(G)}}return{duration:S,streams:r,baseUrls:n,live:g}};import{isNonNullable as zI}from"@vkontakte/videoplayer-shared/es2015";var z=(s,e)=>zI(s)&&zI(e)&&s.readyState==="open"&&oC(s,e);function oC(s,e){for(let t=0;t<s.activeSourceBuffers.length;++t)if(s.activeSourceBuffers[t]===e)return!0;return!1}var In=class{constructor(e,t,i,{fetcher:r,tuning:a,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new gr(0);this.currentLowLatencySegmentLength$=new gr(0);this.currentSegmentLength$=new gr(0);this.onLastSegment$=new gr(!1);this.fullyBuffered$=new gr(!1);this.playingRepresentation$=new gr(void 0);this.playingRepresentationInit$=new gr(void 0);this.error$=new lC;this.gaps=[];this.subscription=new cC;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new le;this.switchAbortController=new le;this.destroyAbortController=new le;this.bufferLimit=1/0;this.failedDownloads=0;this.baseUrls=[];this.baseUrlsIndex=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.lastDataObtainedTimestampMs=0;this.loadByteRangeSegmentsTimeoutId=0;this.startWith=Ni(this.destroyAbortController.signal,function(e){return X(this,null,function*(){let t=this.representations.get(e);dt(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new zT(this.sourceBuffer),this.subscription.add(Rp(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:xi.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o!=null||(o={id:"SegmentEjection",category:xi.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),this.error$.next(o)})),this.subscription.add(Rp(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:xi.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o||!z(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,is(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=this.getForwardBufferDuration(o),d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,n*2,l<d).catch(c=>{this.handleAsyncError(c,"pruneBuffer")})})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);let i=this.initData.get(t.id),r=this.segments.get(t.id),a=this.parsedInitData.get(t.id);dt(i,"No init buffer for starting representation"),dt(r,"No segments for starting representation"),i instanceof ArrayBuffer&&(this.searchGaps(r,t),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(a))})}.bind(this));this.switchTo=Ni(this.destroyAbortController.signal,function(e,t=!1){return X(this,null,function*(){if(!z(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);dt(i,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if(ze(a)||ze(r)?yield this.loadInit(i,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),dt(r,"No segments for starting representation"),a=this.initData.get(e),!(!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer||!z(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(a,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer();else{let n=this.getCurrentPosition();ns(n)&&!this.isLive&&(this.bufferLimit=1/0,yield new Zi(this.pruneBuffer(n,1/0,!0))),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}this.maintain()}})}.bind(this));this.switchToOld=Ni(this.destroyAbortController.signal,function(e,t=!1){return X(this,null,function*(){if(!z(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);dt(i,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if(ze(a)||ze(r)?yield this.loadInit(i,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),dt(r,"No segments for starting representation"),a=this.initData.get(e),!(!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer||!z(this.mediaSource,this.sourceBuffer)))if(yield this.abort(),yield this.sourceBufferTaskQueue.append(a,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let n=this.getCurrentPosition();ns(n)&&(this.isLive||(this.bufferLimit=1/0,yield new Zi(this.pruneBuffer(n,1/0,!0))),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}})}.bind(this));this.seekLive=Ni(this.destroyAbortController.signal,function(e){return X(this,null,function*(){var u,l;let t=(u=(0,Uu.default)(e,d=>d.representations))!=null?u:[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let d of this.representations.keys()){let c=t.find(f=>f.id===d);c&&this.representations.set(d,c);let h=this.representations.get(d);if(!h||!rt(h.segmentReference))return;let p=this.getActualLiveStartingSegments(h.segmentReference);this.segments.set(h.id,p)}let i=(l=this.switchingToRepresentationId)!=null?l:this.downloadingRepresentationId,r=this.representations.get(i);dt(r);let a=this.segments.get(i);dt(a,"No segments for starting representation");let n=this.initData.get(i);if(dt(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer))return;let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(a,r),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1})}.bind(this));var d;this.fetcher=r,this.tuning=a,this.compatibilityMode=u,this.forwardBufferTarget=a.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!(l!=null&&l.live),this.baseUrls=(d=l==null?void 0:l.baseUrls)!=null?d:[],this.initData=new Map(i.map(c=>[c.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(c=>[c.id,c])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchToWithPreviousAbort(e,t=!1){!z(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new le,Ni(this.switchAbortController.signal,function(i,r=!1){return X(this,null,function*(){this.switchingToRepresentationId=i;let a=this.representations.get(i);dt(a,`No such representation ${i}`);let n=this.segments.get(i),o=this.initData.get(i);if(ze(o)||ze(n)?yield this.loadInit(a,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(i),dt(n,"No segments for starting representation"),o=this.initData.get(i),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer||!z(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(o,this.downloadAbortController.signal),r)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=i,yield this.dropBuffer();else{let u=this.getCurrentPosition();ns(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(){!ze(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}abort(){return E(this,null,function*(){for(let e of this.activeSegments)this.abortSegment(e.segment);return this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new le,this.abortBuffer()})}maintain(e=this.getCurrentPosition()){if(ze(e)||ze(this.downloadingRepresentationId)||ze(this.playingRepresentationId)||ze(this.sourceBuffer)||!z(this.mediaSource,this.sourceBuffer)||ns(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(dt(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;let r=i.find(d=>e>=d.time.from&&e<d.time.to);ns(r)&&isFinite(r.time.from)&&isFinite(r.time.to)&&this.currentSegmentLength$.next((r==null?void 0:r.time.to)-r.time.from);let a=e,n=100;if(this.playingRepresentationId!==this.downloadingRepresentationId){let d=this.getForwardBufferDuration(e),c=r?r.time.to+n:-1/0;r&&r.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&d>=r.time.to-e+n&&(a=c)}if(isFinite(this.bufferLimit)&&is(this.sourceBuffer.buffered)>=this.bufferLimit){let d=this.getForwardBufferDuration(e),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,d<c).catch(h=>{this.handleAsyncError(h,"pruneBuffer")});return}let u=[];if(!this.activeSegments.size&&(u=this.selectForwardBufferSegments(i,t.segmentReference.type,a),u.length)){let d="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if((0,Nu.default)(u,r))d="high";else{let c=(0,os.default)(u,0);c&&c.time.from-r.time.to>=this.forwardBufferTarget/2&&(d="low")}this.loadSegments(u,t,d).catch(c=>{this.handleAsyncError(c,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&r&&r.status==="fed"&&!u.length&&this.getForwardBufferDuration(e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let l=(0,os.default)(i,-1);!this.isLive&&l&&(this.fullyBuffered$.next(l.time.to-e-this.getForwardBufferDuration(e)<n),this.onLastSegment$.next(e-l.time.from>0))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let i=0,r=this.isLive?this.liveInitialAdditionalOffset:0;for(let a of e)Math.trunc(a.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:a.time.from+r}),i=a.time.to;ns(t.duration)&&t.duration-i>0&&!this.isLive&&this.gaps.push({representation:t.id,from:i,to:t.duration})}getActualLiveStartingSegments(e){let t=e.segments,i=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,r=[],a=0,n=t.length-1;do r.unshift(t[n]),a+=t[n].time.to-t[n].time.from,n--;while(a<i&&n>=0);return this.liveInitialAdditionalOffset=a-i,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){let t=(0,Uu.default)(e==null?void 0:e.streams[this.kind],r=>r.representations).find(r=>r.id===this.downloadingRepresentationId);if(!t)return;let i=this.segments.get(t.id);if(i!=null&&i.length)return{from:i[0].time.from,to:i[i.length-1].time.to}}updateLive(e){var i,r,a,n;let t=(i=(0,Uu.default)(e==null?void 0:e.streams[this.kind],o=>o.representations))!=null?i:[];if(![...this.segments.values()].every(o=>!o.length))for(let o of t){if(!o||!rt(o.segmentReference))return;let u=o.segmentReference.segments.map(p=>B(x({},p),{status:"none",size:void 0})),l=100,d=(r=this.segments.get(o.id))!=null?r:[],c=(n=(a=(0,os.default)(d,-1))==null?void 0:a.time.to)!=null?n:0,h=u==null?void 0:u.findIndex(p=>c>=p.time.from+l&&c<=p.time.to+l);if(h===-1){this.liveUpdateSegmentIndex=0;let p=this.getActualLiveStartingSegments(o.segmentReference);this.segments.set(o.id,p)}else{let p=u.slice(h+1);this.segments.set(o.id,[...d,...p])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;dt(e);let t=this.segments.get(e);if(t!=null&&t.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}updateLowLatencyLiveIfNeeded(e){var i;let t=0;for(let r of this.representations.values()){let a=r.segmentReference;if(!rt(a))return;let n=(i=this.segments.get(r.id))!=null?i:[],o=n.find(l=>Math.floor(l.time.from)===Math.floor(e.time.from));if(o&&!isFinite(o.time.to)&&(o.time.to=e.time.to,t=o.time.to-o.time.from),!!!n.find(l=>Math.floor(l.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let l=Math.round(e.time.to*a.timescale/1e3).toString(10),d=Ii(a.segmentTemplateUrl,{segmentTime:l});n.push({status:"none",time:{from:e.time.to,to:1/0},url:d})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){var a,n,o;let t=(n=(a=this.switchingToRepresentationId)!=null?a:this.downloadingRepresentationId)!=null?n:this.playingRepresentationId;if(!t)return;let i=this.segments.get(t);if(!i)return;let r=i.find(u=>u.time.from<=e&&u.time.to>=e);return(o=r==null?void 0:r.time.from)!=null?o:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)==null||e.destroy(),this.gapDetectionIdleCallback&&ei&&ei(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&ei&&ei(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}this.sourceBuffer=null,this.downloadAbortController.abort(),this.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,i){return this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){let i=e.findIndex(r=>t>=r.time.from&&t<r.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=i),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,i){let r=e.findIndex(({status:c,time:{from:h,to:p}},f)=>{let m=h<=i&&p>=i,g=h>i||m||f===0&&i===0,S=Math.min(this.forwardBufferTarget,this.bufferLimit),v=this.preloadOnly&&h<=i+S||p<=i+S;return(c==="none"||c==="partially_ejected"&&g&&v&&this.sourceBuffer&&z(this.mediaSource,this.sourceBuffer)&&!(He(this.sourceBuffer.buffered,h)&&He(this.sourceBuffer.buffered,p)))&&g&&v});if(r===-1)return[];if(t!=="byteRange")return e.slice(r,r+1);let a=e,n=0,o=0,u=[],l=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,d=this.preloadOnly?this.forwardBufferTarget:0;for(let c=r;c<a.length&&(n<=l||o<=d);c++){let h=a[c];if(n+=h.byte.to+1-h.byte.from,o+=h.time.to+1-h.time.from,h.status==="none"||h.status==="partially_ejected")u.push(h);else break}return u}loadSegments(e,t,i="auto"){return E(this,null,function*(){rt(t.segmentReference)?yield this.loadTemplateSegment(e[0],t,i):yield this.loadByteRangeSegments(e,t,i)})}loadTemplateSegment(e,t,i="auto"){return E(this,null,function*(){e.status="downloading";let r={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(r);let{range:a,url:n,signal:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(yield Ni(o,function(){return X(this,null,function*(){let d=kp(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,d))})}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let d=yield this.fetcher.fetch(n,{range:a,signal:o,onProgress:u,priority:i,isLowLatency:this.isActiveLowLatency()});if(this.lastDataObtainedTimestampMs=Fu(),!d)return;let c=new DataView(d),h=yn(t.mime);if(!isFinite(r.segment.time.to)){let m=t.segmentReference.timescale;r.segment.time.to=h.getChunkEndTime(c,m)}u&&r.feedingBytes&&l?yield Promise.all(l):yield this.sourceBufferTaskQueue.append(c,o);let{serverDataReceivedTimestamp:p,serverDataPreparedTime:f}=h.getServerLatencyTimestamps(c);p&&f&&this.currentLiveSegmentServerLatency$.next(f-p),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(d){this.abortActiveSegments([e]),Tn(d)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}})}updateRepresentationsBaseUrlIfNeeded(){if(!this.tuning.dash.enableBaseUrlSupport||!this.baseUrls.length||this.failedDownloads<=this.tuning.dash.maxSegmentRetryCount)return;this.baseUrlsIndex=(this.baseUrlsIndex+1)%this.baseUrls.length;let e=this.baseUrls[this.baseUrlsIndex];for(let t of this.representations.values())rt(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}loadByteRangeSegments(e,t,i="auto"){return E(this,null,function*(){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&&(yield Ni(n,function(){return X(this,null,function*(){let u=kp(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),Rp(window,"online").pipe(uC()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{yield this.fetcher.fetch(a,{range:r,onProgress:o,signal:n,priority:i}),this.lastDataObtainedTimestampMs=Fu(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),Tn(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}})}prepareByteRangeFetchSegmentParams(e,t){if(rt(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:(0,os.default)(e,0).byte.from,to:(0,os.default)(e,-1).byte.to},{signal:a}=this.downloadAbortController;return{url:i,range:r,signal:a,onProgress:(o,u)=>E(this,null,function*(){if(!a.aborted)try{this.lastDataObtainedTimestampMs=Fu(),yield this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:a,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:xi.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}})}}prepareTemplateFetchSegmentParams(e,t){if(!rt(t.segmentReference))throw new Error("Representation is not template type");let i=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&i.searchParams.set("low-latency","yes");let r=i.toString(),{signal:a}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,d)=>{if(!a.aborted)try{this.lastDataObtainedTimestampMs=Fu();let c=this.onSomeTemplateDataLoaded({dataView:l,loaded:d,signal:a,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(c)}catch(c){this.error$.next({id:"SegmentFeeding",category:xi.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}}:void 0;return{url:r,signal:a,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,Nu.default)(e,t.segment)&&this.abortSegment(t.segment)}onSomeTemplateDataLoaded(n){return E(this,arguments,function*({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:a}){if(!this.activeSegments.size||!z(this.mediaSource,this.sourceBuffer))return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){let{segment:l}=u;if(u.representationId===t){if(a.aborted){r();continue}if(u.loadedBytes=i,u.loadedBytes>u.feedingBytes){let d=new DataView(e.buffer,e.byteOffset+u.feedingBytes,u.loadedBytes-u.feedingBytes),c=yn(o.mime).parseFeedableSegmentChunk(d,this.isLive);c!=null&&c.byteLength&&(l.status="partially_fed",u.feedingBytes+=c.byteLength,yield this.sourceBufferTaskQueue.append(c),u.fedBytes+=c.byteLength)}}}})}onSomeByteRangesDataLoaded(o){return E(this,arguments,function*({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:a,onSegmentAppendFailed:n}){if(!this.activeSegments.size||!z(this.mediaSource,this.sourceBuffer))return;let u=this.representations.get(t);if(u)for(let l of this.activeSegments){let{segment:d}=l;if(l.representationId!==t)continue;if(a.aborted){yield n();continue}let c=d.byte.from-i,h=d.byte.to-i,p=h-c+1,f=c<r,m=h<=r;if(!f)continue;let g=yn(u.mime);if(d.status==="downloading"&&m){d.status="downloaded";let S=new DataView(e.buffer,e.byteOffset+c,p);(yield this.sourceBufferTaskQueue.append(S,a))&&!a.aborted?this.onSegmentFullyAppended(l,t):yield n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(d.status==="downloading"||d.status==="partially_fed")&&(l.loadedBytes=Math.min(p,r-c),l.loadedBytes>l.feedingBytes)){let S=new DataView(e.buffer,e.byteOffset+c+l.feedingBytes,l.loadedBytes-l.feedingBytes),v=l.loadedBytes===p?S:g.parseFeedableSegmentChunk(S);v!=null&&v.byteLength&&(d.status="partially_fed",l.feedingBytes+=v.byteLength,(yield this.sourceBufferTaskQueue.append(v,a))&&!a.aborted?(l.fedBytes+=v.byteLength,l.fedBytes===p&&this.onSegmentFullyAppended(l,t)):yield n())}}})}onSegmentFullyAppended(e,t){var i;if(!(ze(this.sourceBuffer)||!z(this.mediaSource,this.sourceBuffer))){!this.isLive&&Q.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(He(this.sourceBuffer.buffered,e.segment.time.from,100)&&He(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:xi.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",Ep(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=ts(()=>(0,QI.default)(this.loadInit(i,"low",!1),()=>this.initLoadIdleCallback=null)))}loadInit(e,t="auto",i=!1){return E(this,null,function*(){let r=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!i&&this.failedDownloads>0?Ni(this.destroyAbortController.signal,function(){return X(this,null,function*(){let o=kp(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))})}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,yn(e.mime),r)).then(o=>E(this,null,function*(){if(!o)return;let{init:u,dataView:l,segments:d}=o,c=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,c);let h=d;this.isLive&&rt(e.segmentReference)&&(h=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,h),u&&this.parsedInitData.set(e.id,u)})).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:xi.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n})}dropBuffer(){return E(this,null,function*(){for(let e of this.segments.values())for(let t of e)t.status="none";yield this.pruneBuffer(0,1/0,!0)})}pruneBuffer(e,t,i=!1){return E(this,null,function*(){if(!this.sourceBuffer||!z(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||ze(e))return!1;let r=[],a=0,n=u=>{u.sort((d,c)=>d.from-c.from);let l=[u[0]];for(let d=1;d<u.length;d++){let{from:c,to:h}=u[d],p=l[l.length-1];p.to>=c?p.to=Math.max(p.to,h):l.push(u[d])}return l},o=u=>{var d;if(a>=t)return r;r.push(x({},u.time)),r=n(r);let l=Ep(u)?(d=u.size)!=null?d:0:u.byte.to-u.byte.from;a+=l};for(let u of this.segments.values())for(let l of u){let d=l.time.to<=e-this.tuning.dash.bufferPruningSafeZone,c=l.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(d||c)&&l.status==="fed"&&o(l)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let l=this.sourceBuffer.buffered.start(u)*1e3,d=this.sourceBuffer.buffered.end(u)*1e3,c=0;for(let h of this.segments.values())for(let p of h)(0,Nu.default)(["none","partially_ejected"],p.status)&&Math.round(p.time.from)<=Math.round(l)&&Math.round(p.time.to)>=Math.round(d)&&c++;if(c===this.segments.size){let h={time:{from:l,to:d},url:"",status:"none"};o(h)}}if(r.length&&i){let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let l of this.segments.values())for(let d of l)d.time.from>=e+u&&d.status==="fed"&&o(d)}return r.length?(yield Promise.all(r.map(l=>this.sourceBufferTaskQueue.remove(l.from,l.to)))).reduce((l,d)=>l||d,!1):!1})}abortBuffer(){return E(this,null,function*(){if(!this.sourceBuffer||!z(this.mediaSource,this.sourceBuffer))return!1;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;return this.sourceBufferTaskQueue.abort(t)})}getDebugBufferState(){if(!(!this.sourceBuffer||!z(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}getForwardBufferDuration(e=this.getCurrentPosition()){return!this.sourceBuffer||!z(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||ze(e)?0:Oe(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!(!this.sourceBuffer||!z(this.mediaSource,this.sourceBuffer))){if(this.tuning.useRefactoredSearchGap)for(let i=0;i<this.sourceBuffer.buffered.length;i++)this.gaps=this.gaps.filter(r=>this.sourceBuffer&&(Math.round(r.from)<Math.round(this.sourceBuffer.buffered.start(i)*1e3)||Math.round(r.to)>Math.round(this.sourceBuffer.buffered.end(i)*1e3)));for(let i of t){let r={representation:e,from:i.time.from,to:i.time.to};for(let a=0;a<this.sourceBuffer.buffered.length;a++){let n=this.sourceBuffer.buffered.start(a)*1e3,o=this.sourceBuffer.buffered.end(a)*1e3;if(!(o<=i.time.from||n>=i.time.to)){if(n<=i.time.from&&o>=i.time.to){r=void 0;break}o>i.time.from&&o<i.time.to&&(r.from=o),n<i.time.to&&n>i.time.from&&(r.to=n)}}r&&r.to-r.from>1&&!this.gaps.some(a=>r&&a.from===r.from&&a.to===r.to)&&this.gaps.push(r)}}}detectGapsWhenIdle(e,t){if(!(this.gapDetectionIdleCallback||!this.sourceBuffer||!z(this.mediaSource,this.sourceBuffer))){if(!this.tuning.useRefactoredSearchGap)for(let i=0;i<this.sourceBuffer.buffered.length;i++)this.gaps=this.gaps.filter(r=>this.sourceBuffer&&(Math.round(r.from)<Math.round(this.sourceBuffer.buffered.start(i)*1e3)||Math.round(r.to)>Math.round(this.sourceBuffer.buffered.end(i)*1e3)));this.gapDetectionIdleCallback=ts(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:xi.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if(ze(this.sourceBuffer)||!z(this.mediaSource,this.sourceBuffer)||ze(this.playingRepresentationId))return;let e=[];for(let i=0;i<this.sourceBuffer.buffered.length;i++){let r=Math.floor(this.sourceBuffer.buffered.start(i)*1e3),a=Math.ceil(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:r,to:a})}let t=100;for(let i of this.segments.values())for(let r of i){let{status:a}=r;if(a!=="fed"&&a!=="partially_ejected")continue;let n=Math.floor(r.time.from),o=Math.ceil(r.time.to),u=e.some(d=>d.from-t<=n&&d.to+t>=o),l=e.filter(d=>n>=d.from&&n<d.to-t||o>d.from+t&&o<=d.to);u||(l.length===1?r.status="partially_ejected":this.gaps.some(d=>d.from===r.time.from||d.to===r.time.to)?r.status="partially_ejected":r.status="none")}}handleAsyncError(e,t){this.error$.next({id:t,category:xi.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}};var Ui=s=>{let e=new URL(s);return e.searchParams.set("quic","1"),e.toString()};var qu=s=>{var a;let e=s.get("X-Delivery-Type"),t=s.get("X-Reused"),i=e===null?"http1":e!=null?e:void 0,r=t===null?void 0:(a={1:!0,0:!1}[t])!=null?a:void 0;return{type:i,reused:r}};import{abortable as xn,assertNever as GI,fromEvent as WI,merge as dC,now as En,Subscription as pC,Subject as YI,ValueSubject as Mp,flattenObject as us,ErrorCategory as wn}from"@vkontakte/videoplayer-shared/es2015";var ju=s=>{let e=new URL(s);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var zu=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:a=!1}){this.lastConnectionType$=new Mp(void 0);this.lastConnectionReused$=new Mp(void 0);this.lastRequestFirstBytes$=new Mp(void 0);this.recoverableError$=new YI;this.error$=new YI;this.abortAllController=new le;this.subscription=new pC;this.fetchManifest=xn(this.abortAllController.signal,function(e){return X(this,null,function*(){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=Ui(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=ju(i));let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(Hu);return r?(t.log("success",us({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(r.headers),r.text()):(t.error("error",us({url:i,message:"No data in request manifest"})),t.end(),null)})}.bind(this));this.fetch=xn(this.abortAllController.signal,function(l){return X(this,arguments,function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:a="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1}={}){var M,j;let d=e,c=new Headers,h=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{c.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let N=new URL(d,location.href);N.searchParams.append("bytes",`${i.from}-${i.to}`),d=N.toString();break}default:GI(t)}this.requestQuic&&(d=Ui(d));let p=this.abortAllController.signal,f;if(n){let N=new le;if(f=dC(WI(this.abortAllController.signal,"abort"),WI(n,"abort")).subscribe(()=>{try{N.abort()}catch(K){Hu(K)}}),this.subscription.add(f),this.abortAllController.signal.aborted||n.aborted)try{N.abort()}catch(K){Hu(K)}p=N.signal}let m=En();h.log("startRequest",us({url:d,priority:a,rangeMethod:t,range:i,isLowLatency:u,requestStartedAt:m}));let g=yield this.doFetch(d,{priority:a,headers:c,signal:p}),S=En();if(!g)return h.error("error",{message:"No response in request"}),h.end(),f==null||f.unsubscribe(),null;if((M=this.throughputEstimator)==null||M.addRawRtt(S-m),!g.ok||!g.body){f==null||f.unsubscribe();let N=`Fetch error ${g.status}: ${g.statusText}`;return h.error("error",{message:N}),h.end(),Promise.reject(new Error(`Fetch error ${g.status}: ${g.statusText}`))}if(this.onHeadersReceived(g.headers),!r&&!o){f==null||f.unsubscribe();let N=En(),K={requestStartedAt:m,requestEndedAt:N,duration:N-m};return h.log("endRequest",us(K)),h.end(),g.arrayBuffer()}let[v,y]=g.body.tee(),T=v.getReader();o&&((j=this.throughputEstimator)==null||j.trackStream(y,u));let I=0,R=new Uint8Array(0),C=!1,V=N=>{f==null||f.unsubscribe(),C=!0,Hu(N)},$=xn(p,function(P){return X(this,arguments,function*({done:N,value:K}){if(I===0&&this.lastRequestFirstBytes$.next(En()-m),p.aborted){f==null||f.unsubscribe();return}if(!N&&K){let L=new Uint8Array(R.length+K.length);L.set(R),L.set(K,R.length),R=L,I+=K.byteLength,r==null||r(new DataView(R.buffer),I),yield T==null?void 0:T.read().then($,V)}})}.bind(this));yield T==null?void 0:T.read().then($,V),f==null||f.unsubscribe();let w=En(),F={failed:C,requestStartedAt:m,requestEndedAt:w,duration:w-m};return C?(h.error("endRequest",us(F)),h.end(),null):(h.log("endRequest",us(F)),h.end(),R.buffer)})}.bind(this));this.fetchByteRangeRepresentation=xn(this.abortAllController.signal,function(e,t,i){return X(this,null,function*(){var S;if(e.type!=="byteRange")return null;let{from:r,to:a}=e.initRange,n=r,o=a,u=!1,l,d;e.indexRange&&(l=e.indexRange.from,d=e.indexRange.to,u=a+1===l,u&&(n=Math.min(l,r),o=Math.max(d,a))),n=Math.min(n,0);let c=yield this.fetch(e.url,{range:{from:n,to:o},priority:i,measureThroughput:!1});if(!c)return null;let h=new DataView(c,r-n,a-n+1);if(!t.validateData(h))throw new Error("Invalid media file");let p=t.parseInit(h),f=(S=e.indexRange)!=null?S:t.getIndexRange(p);if(!f)throw new ReferenceError("No way to load representation index");let m;if(u)m=new DataView(c,f.from-n,f.to-f.from+1);else{let v=yield this.fetch(e.url,{range:f,priority:i,measureThroughput:!1});if(!v)return null;m=new DataView(v)}let g=t.parseSegments(m,p,f);return{init:p,dataView:new DataView(c),segments:g}})}.bind(this));this.fetchTemplateRepresentation=xn(this.abortAllController.signal,function(e,t){return X(this,null,function*(){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=>B(x({},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}=qu(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}fetchRepresentation(e,t,i="auto"){return E(this,null,function*(){var a,n;let{type:r}=e;switch(r){case"byteRange":return(a=yield this.fetchByteRangeRepresentation(e,t,i))!=null?a:null;case"template":return(n=yield this.fetchTemplateRepresentation(e,i))!=null?n:null;default:GI(r)}})}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}doFetch(e,t){return E(this,null,function*(){let i=yield Mt(e,t);if(i.ok)return i;let r=yield i.text(),a=parseInt(r);if(!isNaN(a))switch(a){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:wn.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:wn.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:wn.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:wn.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${a})`,category:wn.FATAL})}})}},Hu=s=>{if(!Tn(s))throw s};var Ei=(s,e,t)=>t*e+(1-t)*s,Lp=(s,e)=>s.reduce((t,i)=>t+i,0)/e,KI=(s,e,t,i)=>{let r=0,a=t,n=Lp(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 hC,ValueSubject as XI}from"@vkontakte/videoplayer-shared/es2015";var qi=class{constructor(e){this.prevReported=void 0;this.pastMeasures=[];this.takenMeasures=0;this.measuresCursor=0;var i;this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new XI(e.initial),this.debounced$=new XI(e.initial);let t=(i=e.label)!=null?i:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new tt(`raw_${t}`),this.smoothedSeries$=new tt(`smoothed_${t}`),this.reportedSeries$=new tt(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,i=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=Ze(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)&&(hC(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 Qu=class extends qi{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=Ei(this.slow,e,this.params.emaAlphaSlow),this.fast=Ei(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var Gu=class extends qi{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=Lp(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Ei(this.emaSmoothed,e,this.params.emaAlpha);let i=KI(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}};var Wu=class extends qi{constructor(t){super(t);this.furtherValues=[];this.currentTopExtremumValue=0;this.extremumInterval=t.extremumInterval}next(t){this.currentTopExtremumValue<=t?(this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.length===this.extremumInterval?(super.next(this.currentTopExtremumValue),this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.push(t)}updateSmoothedValue(t){this.smoothed=this.smoothed?Ei(this.smoothed,t,this.params.emaAlpha):t}};var wi=class{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new Qu({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new Gu({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 Wu(x({initial:e,label:"liveEdgeDelay"},t))}};var ls=(s,e)=>{s&&s.playbackRate!==e&&(s.playbackRate=e)};import{isNullable as fC,ValueSubject as mC}from"@vkontakte/videoplayer-shared/es2015";var An=class s{constructor(e,t){this.currentRepresentation$=new mC(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(!fC(e))for(let i of this.representations)for(let r of i){let a=r.segmentReference,n=a.segments.length,o=a.segments[0].time.from,u=a.segments[n-1].time.to;if(e<o||e>u)continue;let l=a.segments.find(d=>d.time.from<=e&&d.time.to>=e);!l||((t=this.currentSegment)==null?void 0:t.time.from)===l.time.from&&this.currentSegment.time.to===l.time.to||(this.currentSegment=l,this.currentRepresentation$.next(B(x({},r),{label:"Live Text",language:"ru",isAuto:!0,url:new URL(l.url,a.baseUrl).toString()})))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e!=null?e:[]){let i=s.filterRepresentations(t.representations);if(i){this.representations[this.representationsCursor]=i,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!(e!=null&&e.some(t=>s.filterRepresentations(t.representations)))}static filterRepresentations(e){return e==null?void 0:e.filter(t=>t.kind==="text"&&"segmentReference"in t&&rt(t.segmentReference))}};var Ku=H(qt(),1);import{assertNever as Xu}from"@vkontakte/videoplayer-shared/es2015";var JI=(s,{useManagedMediaSource:e,useOldMSEDetection:t})=>{let{containers:i,protocols:r,codecs:a,nativeHlsSupported:n}=Q.video,o=(a.h264||a.h265)&&a.aac,u=r.mse&&(!t||!!window.MediaStreamTrack)||r.mms&&e;return s.filter(l=>{switch(l){case"DASH_SEP":return u&&i.mp4&&o;case"DASH_WEBM":return u&&i.webm&&a.vp9&&a.opus;case"DASH_WEBM_AV1":return u&&i.webm&&a.av1&&a.opus;case"DASH_STREAMS":return u&&(i.mp4&&o||i.webm&&(a.vp9||a.av1)&&(a.opus||a.aac));case"DASH_LIVE":return u&&i.mp4&&o;case"DASH_LIVE_CMAF":return u&&i.mp4&&o&&i.cmaf;case"DASH_ONDEMAND":return u&&i.mp4&&o;case"HLS":case"HLS_ONDEMAND":case"HLS_LIVE":case"HLS_LIVE_CMAF":return n;case"MPEG":return i.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return r.webrtc&&r.ws&&a.h264&&(i.mp4||i.webm);default:return Xu(l)}})},Yu=s=>{let{webmDecodingInfo:e}=Q.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:Xu(s)}return[t,i]},ZI=({webmCodec:s,androidPreferredFormat:e,preferMultiStream:t})=>{let i=[...t?["DASH_STREAMS"]:[],...Yu(s),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],r=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(Q.device.isAndroid)switch(e){case"mpeg":return["MPEG",...i,"HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...i,"MPEG"];case"dash":return[...i,"HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return[...r,"MPEG",...Yu(s),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...Yu(s),"MPEG",...r,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...Yu(s),...r,"HLS","HLS_ONDEMAND"];default:Xu(e)}return Q.video.nativeHlsSupported?[...i,"HLS","HLS_ONDEMAND","MPEG"]:[...i,"HLS","HLS_ONDEMAND","MPEG"]},ex=({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=Q.device.isMac&&Q.browser.isSafari;if(Q.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:Xu(s)}else Q.video.nativeHlsSupported&&!u?o=n:u?o=e?["DASH_LIVE_CMAF","HLS_LIVE_CMAF","HLS_LIVE","DASH_LIVE"]:["HLS_LIVE","DASH_LIVE","DASH_LIVE_CMAF","HLS_LIVE_CMAF"]:o=a;return t?["WEB_RTC_LIVE",...o]:[...o,"WEB_RTC_LIVE"]},Bp=s=>s?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],Ju=s=>{if(s.size===0)return;if(s.size===1){let t=s.values().next();return(0,Ku.default)(t.value.split("."),0)}for(let t of s){let i=(0,Ku.default)(t.split("."),0);if(i==="opus"||i==="vp09"||i==="av01")return i}let e=s.values().next();return(0,Ku.default)(e.value.split("."),0)};var xC=["timeupdate","progress","play","seeked","stalled","waiting"],EC=["timeupdate","progress","loadeddata","playing","seeked"];var tl=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new rx;this.representationSubscription=new rx;this.state$=new Y("none");this.currentVideoRepresentation$=new ge(void 0);this.currentVideoRepresentationInit$=new ge(void 0);this.currentAudioRepresentation$=new ge(void 0);this.currentVideoSegmentLength$=new ge(0);this.currentAudioSegmentLength$=new ge(0);this.error$=new el;this.lastConnectionType$=new ge(void 0);this.lastConnectionReused$=new ge(void 0);this.lastRequestFirstBytes$=new ge(void 0);this.currentLiveTextRepresentation$=new ge(null);this.isLive$=new ge(!1);this.isActiveLive$=new ge(!1);this.isLowLatency$=new ge(!1);this.liveDuration$=new ge(0);this.liveSeekableDuration$=new ge(0);this.liveAvailabilityStartTime$=new ge(0);this.liveStreamStatus$=new ge(void 0);this.bufferLength$=new ge(0);this.liveLatency$=new ge(void 0);this.liveLoadBufferLength$=new ge(0);this.livePositionFromPlayer$=new ge(0);this.currentStallDuration$=new ge(0);this.videoLastDataObtainedTimestamp$=new ge(0);this.fetcherRecoverableError$=new el;this.fetcherError$=new el;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new el;this.gapWatchdogActive=!1;this.destroyController=new le;this.initManifest=Dp(this.destroyController.signal,function(e,t,i){return X(this,null,function*(){var r;this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=Ie(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:Ht.PARSER,message:"No playable video representations"})})}.bind(this));this.updateManifest=Dp(this.destroyController.signal,function(){return X(this,null,function*(){var n,o;this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(u=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:Ht.NETWORK,message:"Failed to load manifest",thrown:u})});if(!e)return null;let t=null;try{t=HI(e!=null?e:"",this.manifestUrlString)}catch(u){let l=(n=Ou(e))!=null?n:{id:"ManifestParsing",category:Ht.PARSER,message:"Failed to parse MPD manifest",thrown:u};this.error$.next(l)}if(!t)return null;let i=(u,l,d)=>{var c,h,p,f;return!!((h=(c=this.element)==null?void 0:c.canPlayType)!=null&&h.call(c,l)&&((f=(p=Et())==null?void 0:p.isTypeSupported)!=null&&f.call(p,`${l}; codecs="${d}"`))||u==="text")};if(t.live){this.isLive$.next(!!t.live);let{availabilityStartTime:u,latestSegmentPublishTime:l,streamIsUnpublished:d,streamIsAlive:c}=t.live,h=((o=t.duration)!=null?o:0)/1e3;this.liveSeekableDuration$.next(-1*h),this.liveDuration$.next((l-u)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let p="active";c||(p=d?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(p)}let r={text:t.streams.text,video:[],audio:[]};for(let u of["video","audio"]){let d=t.streams[u].filter(({mime:p,codecs:f})=>i(u,p,f)),c=new Set(d.map(({codecs:p})=>p)),h=Ju(c);if(h&&(r[u]=d.filter(({codecs:p})=>p.startsWith(h))),u==="video"){let p=this.tuning.preferHDR,f=r.video.some(g=>g.hdr),m=r.video.some(g=>!g.hdr);Q.display.isHDR&&p&&f?r.video=r.video.filter(g=>g.hdr):m&&(r.video=r.video.filter(g=>!g.hdr))}}let a=B(x({},t),{streams:r});return this.tracer.log("updateManifestEnd",Rn(a)),a})}.bind(this));this.initRepresentations=Dp(this.destroyController.signal,function(e,t,i){return X(this,null,function*(){var h;this.tracer.log("initRepresentationsStart",Rn({initialVideo:e,initialAudio:t,sourceHls:i})),cs(this.manifest),cs(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let r=p=>{this.representationSubscription.add(Ai(p,"error").pipe(Zu(f=>{var m;return!!((m=this.element)!=null&&m.played.length)})).subscribe(f=>{this.error$.next({id:"VideoSource",category:Ht.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:f})}))};this.source=this.tuning.useManagedMediaSource?hu():new MediaSource;let a=document.createElement("source");if(r(a),a.src=URL.createObjectURL(this.source),this.element.appendChild(a),this.tuning.useManagedMediaSource&&Gr())if(i){let p=document.createElement("source");r(p),p.type="application/x-mpegurl",p.src=i.url,this.element.appendChild(p)}else this.element.disableRemotePlayback=!0;this.isActiveLive$.next(this.isLive$.getValue());let n={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),manifest:this.manifest},o=this.manifest.streams.video.reduce((p,f)=>[...p,...f.representations],[]);if(this.videoBufferManager=new In("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],kn(t)){let p=this.manifest.streams.audio.reduce((f,m)=>[...f,...m.representations],[]);this.audioBufferManager=new In("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}An.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new An(this.manifest.streams.text,n)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$));let u=()=>{var p;(p=this.stallWatchdogSubscription)==null||p.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add(Sr(...EC.map(p=>Ai(this.element,p))).pipe(ps(p=>this.element?Oe(this.element.buffered,this.element.currentTime*1e3):0),Pn(),TC(p=>{p>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add(Sr(Ai(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe(Pn()).subscribe(f=>this.liveStreamEndTimestamp=Vp())),this.subscription.add(Ai(this.element,"pause").subscribe(()=>{this.livePauseWatchdogSubscription=Cp(1e3).subscribe(f=>{let m=Ci(this.manifestUrlString,2);this.manifestUrlString=Ie(this.manifestUrlString,m+1e3,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add(Ai(this.element,"play").subscribe(f=>{var m;return(m=this.livePauseWatchdogSubscription)==null?void 0:m.unsubscribe()})),this.representationSubscription.add(ds({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(ps(({isActiveLive:f,isLowLatency:m})=>f&&m),Pn()).subscribe(f=>{this.isManualDecreasePlaybackInLive()||ls(this.element,1)})),this.representationSubscription.add(ds({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(Zu(({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(ds({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(Zu(({isLive:f})=>f),Pn((f,m)=>m.bufferLength<f.bufferLength),ps(({rtt:f,bufferLength:m,segmentServerLatency:g})=>{let S=Ci(this.manifestUrlString,2);return(f/2+m+g+S)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(ds({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:f,isActiveLive:m,isLowLatency:g})=>{if(!g||!m)return;let S=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,v=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,y=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,T=f-S;if(this.isManualDecreasePlaybackInLive())return;let I=1;Math.abs(T)>v&&(I=1+Math.sign(T)*y),ls(this.element,I)})),this.representationSubscription.add(this.bufferLength$.subscribe(f=>{var g,S;let m=0;if(f){let v=((S=(g=this.element)==null?void 0:g.currentTime)!=null?S:0)*1e3;m=Math.min(...this.bufferManagers.map(T=>{var I,R;return(R=(I=T.getLiveSegmentsToLoadState(this.manifest))==null?void 0:I.to)!=null?R:v}))-v}this.liveLoadBufferLength$.getValue()!==m&&this.liveLoadBufferLength$.next(m)}));let p=0;this.representationSubscription.add(ds({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(IC(1e3)).subscribe(g=>E(this,[g],function*({liveLoadBufferLength:f,bufferLength:m}){if(!this.element||this.isUpdatingLive)return;let S=this.element.playbackRate,v=Ci(this.manifestUrlString,2),y=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,T=Math.min(y,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*S),I=this.tuning.dashCmafLive.normalizedActualBufferOffset*S,R=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*S,C=isFinite(f)?f:m,V=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),$=y<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next($);let w="none";if(V?w="active_low_latency":this.isLowLatency$.getValue()&&$?(this.bufferManagers.forEach(F=>F.proceedLowLatencyLive()),w="active_low_latency"):v!==0&&C<T?w="live_forward_buffering":C<T+R&&(w="live_with_target_offset"),isFinite(f)&&(p=f>p?f:p),w==="live_forward_buffering"||w==="live_with_target_offset"){let F=p-(T+I),M=this.normolizeLiveOffset(Math.trunc(v+F/S)),j=Math.abs(M-v),N=0;!f||j<=this.tuning.dashCmafLive.offsetCalculationError?N=v:M>0&&j>this.tuning.dashCmafLive.offsetCalculationError&&(N=M),this.manifestUrlString=Ie(this.manifestUrlString,N,2)}(w==="live_with_target_offset"||w==="live_forward_buffering")&&(p=0,yield this.updateLive())}),f=>{this.error$.next({id:"updateLive",category:Ht.VIDEO_PIPELINE,thrown:f,message:"Failed to update live with subscription"})}))}let l=Sr(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe(ps(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),d=Sr(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe(ps(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue()))),c=ds({allBuffersFull:l,someBufferEnded:d}).pipe(Pn(),ps(({allBuffersFull:p,someBufferEnded:f})=>p&&f),Zu(p=>p));if(this.representationSubscription.add(Sr(this.forceEnded$,c).subscribe(()=>{var p;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(f=>!f.updating))try{(p=this.source)==null||p.endOfStream()}catch(f){this.error$.next({id:"EndOfStream",category:Ht.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:f})}})),this.representationSubscription.add(Sr(...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:Ht.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,Op.default)((0,Op.default)([...this.manifest.streams.audio,...this.manifest.streams.video],f=>f.representations),f=>{let m=[];return f.duration&&m.push(f.duration),rt(f.segmentReference)&&f.segmentReference.totalSegmentsDurationMs&&m.push(f.segmentReference.totalSegmentsDurationMs),m})];this.source.duration=Math.max(...p)/1e3}this.audioBufferManager&&kn(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=Cp(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),n=>{this.error$.next({id:"GapWatchdog",category:Ht.WTF,message:"Error handling gaps",thrown:n})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.fetcher=new zu({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=wi.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,x({},e.tuning.dashCmafLive.lowLatency.bufferEstimator)),this.initTracerSubscription()}seekLive(e){return E(this,null,function*(){var r,a,n;cs(this.element);let t=this.liveStreamStatus$.getValue()!=="active"?Vp()-this.liveStreamEndTimestamp:0,i=this.normolizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=Ie(this.manifestUrlString,i,2),this.manifest=yield this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,yield(r=this.videoBufferManager)==null?void 0:r.seekLive(this.manifest.streams.video),yield(a=this.audioBufferManager)==null?void 0:a.seekLive(this.manifest.streams.audio),(n=this.liveTextManager)==null||n.seekLive(this.manifest.streams.text))})}initBuffer(){cs(this.element),this.state$.setState("running"),this.subscription.add(Sr(...xC.map(e=>Ai(this.element,e)),Ai(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:Ht.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(Ai(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(Ai(this.element,"waiting").subscribe(()=>{var t;this.element&&this.element.readyState===2&&!this.element.seeking&&He(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{var p,f,m,g,S,v,y,T,I,R,C;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=Vp(),n=100,o=(m=(f=this.videoBufferManager)==null?void 0:f.lastDataObtainedTimestamp)!=null?m:0;this.videoLastDataObtainedTimestamp$.next(o);let u=(S=(g=this.audioBufferManager)==null?void 0:g.lastDataObtainedTimestamp)!=null?S:0,l=(y=(v=this.videoBufferManager)==null?void 0:v.getForwardBufferDuration())!=null?y:0,d=(I=(T=this.audioBufferManager)==null?void 0:T.getForwardBufferDuration())!=null?I:0,c=l<n&&a-o>this.tuning.dash.crashOnStallTWithoutDataTimeout,h=this.audioBufferManager&&d<n&&a-u>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((c||h)&&i>this.tuning.dash.crashOnStallTWithoutDataTimeout||i>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${i} ms`);if(this.isLive$.getValue()&&i%2e3===0){let V=this.normolizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(V).catch($=>{this.error$.next({id:"stallIntervalCallback",category:Ht.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:$})}),r.liveLastOffset=V}else{let V=this.element.currentTime*1e3;(R=this.videoBufferManager)==null||R.maintain(V),(C=this.audioBufferManager)==null||C.maintain(V),r.position=V}this.tracer.log("stallIntervalCallback",Rn(r))};(t=this.stallWatchdogSubscription)==null||t.unsubscribe(),this.stallWatchdogSubscription=Cp(50).subscribe(e,i=>{this.error$.next({id:"StallWatchdogCallback",category:Ht.NETWORK,message:"Can't restore DASH after stall.",thrown:i})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}switchRepresentation(e,t,i=!1){return E(this,null,function*(){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)})}seek(e,t){return E(this,null,function*(){var r,a,n,o,u;cs(this.element),cs(this.videoBufferManager);let i;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?i=e:i=Math.max((r=this.videoBufferManager.findSegmentStartTime(e))!=null?r:e,(n=(a=this.audioBufferManager)==null?void 0:a.findSegmentStartTime(e))!=null?n:e),this.warmUpMediaSourceIfNeeded(i),He(this.element.buffered,i)||(yield Promise.all([this.videoBufferManager.abort(),(o=this.audioBufferManager)==null?void 0:o.abort()])),!(ix(this.element)||ix(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),(u=this.audioBufferManager)==null||u.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",Rn({requestedPosition:e,forcePrecise:t,position:i})))})}warmUpMediaSourceIfNeeded(e=(t=>(t=this.element)==null?void 0:t.currentTime)()){var i;kn(this.element)&&kn(this.source)&&kn(e)&&((i=this.source)==null?void 0:i.readyState)==="ended"&&this.element.duration*1e3-e>this.tuning.dash.seekBiasInTheEnd&&this.bufferManagers.forEach(r=>r.warmUpMediaSource())}get isStreamEnded(){var e;return((e=this.source)==null?void 0:e.readyState)==="ended"}stop(){var e,t,i;this.tracer.log("stop"),(e=this.element)==null||e.querySelectorAll("source").forEach(r=>{URL.revokeObjectURL(r.src),r.remove()}),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(t=this.videoBufferManager)==null||t.destroy(),this.videoBufferManager=null,(i=this.audioBufferManager)==null||i.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){var e;return(e=this.manifest)==null?void 0:e.streams}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){var e;this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),((e=this.source)==null?void 0:e.readyState)==="open"&&Array.from(this.source.sourceBuffers).every(t=>!t.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=yC(this.tracer.error.bind(this.tracer));this.subscription.add(this.error$.subscribe(e("error")))}isManualDecreasePlaybackInLive(){if(!this.element||!this.isLive$.getValue())return!1;let e=1-this.element.playbackRate;return Number(e.toFixed(2))>Number(this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup.toFixed(2))}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}updateLive(){return E(this,null,function*(){var e,t;this.isUpdatingLive=!0,this.manifest=yield this.updateManifest(),this.manifest&&((e=this.bufferManagers)==null||e.forEach(i=>i.updateLive(this.manifest)),(t=this.liveTextManager)==null||t.updateLive(this.manifest)),this.isUpdatingLive=!1})}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getDebugBufferState();if(!e)return;let t=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),i={isJumpGapAfterSeekLive:this.isJumpGapAfterSeekLive,isActiveLowLatency:t,initialCurrentTime:this.element.currentTime};this.isJumpGapAfterSeekLive&&!t&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let r=this.element.currentTime*1e3,a=[],n=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let o of this.bufferManagers)for(let u of o.gaps)o.playingRepresentation$.getValue()===u.representation&&u.from-n<=r&&u.to+n>r&&(this.element.duration*1e3-u.to<this.tuning.endGapTolerance?a.push(1/0):a.push(u.to));if(a.length){let o=Math.max(...a)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,o===1/0?this.forceEnded$.next():(this.element.currentTime=o/1e3,i=B(x({},i),{gapEnds:a,jumpTo:o,resultCurrentTime:this.element.currentTime}),this.tracer.log("jumpGap",Rn(i)))}}};var il=class{constructor(e,t){this.fov=e,this.orientation=t}};var rl=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/Ze(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=x({},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*Ze(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 ax=`attribute vec2 a_vertex;
|
|
124
|
+
`})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(d,"i")}var Tp=H(qt(),1);import{videoSizeToQuality as aC}from"@vkontakte/videoplayer-shared/es2015";var CI=({id:s,width:e,height:t,bitrate:i,fps:r,quality:a,streamId:n})=>{var u;let o=(u=a?Oi(a):void 0)!=null?u:aC({width:e,height:t});return o&&{id:s,quality:o,bitrate:i,size:{width:e,height:t},fps:r,streamId:n}},VI=({id:s,bitrate:e})=>({id:s,bitrate:e}),OI=({language:s,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:s,label:e}),_I=({language:s,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:s,label:e}),Ip=({id:s,language:e,label:t,codecs:i,isDefault:r})=>({id:s,language:e,label:t,codec:(0,Tp.default)(i.split("."),0),isDefault:r}),xp=({id:s,language:e,label:t,hdr:i,codecs:r})=>({id:s,language:e,hdr:i,label:t,codec:(0,Tp.default)(r.split("."),0)}),Ep=s=>"url"in s,rt=s=>s.type==="template",Tn=s=>s instanceof DOMException&&(s.name==="AbortError"||s.code===20);var NI=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},Ii=(s,e)=>{let t=s;t=(0,wp.default)(t,"$$","$");let i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[r,a]of(0,UI.default)(i)){let n=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=(0,wp.default)(t,n,(o,u)=>FI(a)?o:FI(u)?a:(0,qI.default)(a,parseInt(u,10),"0"))}return t},HI=(s,e)=>{var $,w,F,M,j,N,K,P,L,R,A,O,de,Fe,ue,ee,Ee,we,Ae,Ne,At,Lt,Gt,ii,Li,Is,xs,Es,ws,As,Ps,ks,Rs,Ms,Ls,Bs,$s,Ds,Cs,Vs,Os,_s,Fs,Ns,Us,qs,js,Hs,zs,Qs,Gs,Ws,Ys,Ks,Xs,Js,Zs,ea,ta,ia,ra;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(fe=>{var q,Ge;return(Ge=(q=fe.textContent)==null?void 0:q.trim())!=null?Ge:""}),o=($=(0,jI.default)(n,0))!=null?$:"",u=a.getAttribute("type")==="dynamic",l=a.getAttribute("availabilityStartTime"),d=a.getAttribute("publishTime"),c=a.getElementsByTagName("vk:Attrs")[0],f=c==null?void 0:c.getElementsByTagName("vk:XLatestSegmentPublishTime")[0].textContent,p=c==null?void 0:c.getElementsByTagName("vk:XStreamIsLive")[0].textContent,h=c==null?void 0:c.getElementsByTagName("vk:XStreamIsUnpublished")[0].textContent,m=c==null?void 0:c.getElementsByTagName("vk:XPlaybackDuration")[0].textContent,g;u&&(g={availabilityStartTime:l?new Date(l).getTime():0,publishTime:d?new Date(d).getTime():0,latestSegmentPublishTime:f?new Date(f).getTime():0,streamIsAlive:p==="yes",streamIsUnpublished:h==="yes"});let S,v=a.getAttribute("mediaPresentationDuration"),y=[...a.getElementsByTagName("Period")],T=y.reduce((fe,q)=>B(x({},fe),{[q.id]:q.children}),{}),I=y.reduce((fe,q)=>B(x({},fe),{[q.id]:q.getAttribute("duration")}),{});v?S=NI(v):(0,Ap.default)(I).filter(fe=>fe).length&&!u?S=(0,Ap.default)(I).reduce((fe,q)=>{var Ge;return fe+((Ge=NI(q))!=null?Ge:0)},0):m&&(S=parseInt(m,10));let k=0,C=(F=(w=a.getAttribute("profiles"))==null?void 0:w.split(","))!=null?F:[];for(let fe of y.map(q=>q.id))for(let q of T[fe]){let Ge=(M=q.getAttribute("id"))!=null?M:"id"+(k++).toString(10),Bt=(j=q.getAttribute("mimeType"))!=null?j:"",Wi=(N=q.getAttribute("codecs"))!=null?N:"",Yi=(K=q.getAttribute("contentType"))!=null?K:Bt==null?void 0:Bt.split("/")[0],Cl=(L=(P=q.getAttribute("profiles"))==null?void 0:P.split(","))!=null?L:[],sa=(A=DI((R=q.getAttribute("lang"))!=null?R:""))!=null?A:{},ri=(Fe=(de=(O=q.querySelector("Label"))==null?void 0:O.textContent)==null?void 0:de.trim())!=null?Fe:void 0,Vl=q.querySelectorAll("Representation"),Ol=q.querySelector("SegmentTemplate"),_l=(ee=(ue=q.querySelector("Role"))==null?void 0:ue.getAttribute("value"))!=null?ee:void 0,ht=Yi,G={id:Ge,language:sa.language,isDefault:_l==="main",label:ri,codecs:Wi,hdr:ht==="video"&&as(Wi),mime:Bt,representations:[]};for(let U of Vl){let Re=(Ee=U.getAttribute("lang"))!=null?Ee:void 0,$t=(Ae=(we=ri!=null?ri:q.getAttribute("label"))!=null?we:U.getAttribute("label"))!=null?Ae:void 0,si=(Lt=(At=(Ne=U.querySelector("BaseURL"))==null?void 0:Ne.textContent)==null?void 0:At.trim())!=null?Lt:"",We=new URL(si||o,e).toString(),Me=(Gt=U.getAttribute("mimeType"))!=null?Gt:Bt,ai=(Li=(ii=U.getAttribute("codecs"))!=null?ii:Wi)!=null?Li:"",ni;if(Yi==="text"){let Le=U.getAttribute("id")||"",oi=((Is=sa.privateuse)==null?void 0:Is.includes("x-auto"))||Le.includes("_auto"),Ye=U.querySelector("SegmentTemplate");if(Ye){let Dt={representationId:(xs=U.getAttribute("id"))!=null?xs:void 0,bandwidth:(Es=U.getAttribute("bandwidth"))!=null?Es:void 0},ui=parseInt((ws=U.getAttribute("bandwidth"))!=null?ws:"",10)/1e3,li=(Ps=parseInt((As=Ye.getAttribute("startNumber"))!=null?As:"",10))!=null?Ps:1,ft=parseInt((ks=Ye.getAttribute("timescale"))!=null?ks:"",10),Ki=(Rs=Ye.querySelectorAll("SegmentTimeline S"))!=null?Rs:[],mt=Ye.getAttribute("media");if(!mt)continue;let ci=[],di=0,pi="",bt=0,Ct=li,se=0;for(let me of Ki){let Ke=parseInt((Ms=me.getAttribute("d"))!=null?Ms:"",10),ce=parseInt((Ls=me.getAttribute("r"))!=null?Ls:"",10)||0,Be=parseInt((Bs=me.getAttribute("t"))!=null?Bs:"",10);se=Number.isFinite(Be)?Be:se;let Xe=Ke/ft*1e3,$e=se/ft*1e3;for(let ve=0;ve<ce+1;ve++){let De=Ii(mt,B(x({},Dt),{segmentNumber:Ct.toString(10),segmentTime:(se+ve*Ke).toString(10)})),gt=($e!=null?$e:0)+ve*Xe,Ot=gt+Xe;Ct++,ci.push({time:{from:gt,to:Ot},url:De})}se+=(ce+1)*Ke,di+=(ce+1)*Xe}bt=se/ft*1e3,pi=Ii(mt,B(x({},Dt),{segmentNumber:Ct.toString(10),segmentTime:se.toString(10)}));let Vt={time:{from:bt,to:1/0},url:pi},Pe={type:"template",baseUrl:We,segmentTemplateUrl:mt,initUrl:"",totalSegmentsDurationMs:di,segments:ci,nextSegmentBeyondManifest:Vt,timescale:ft};ni={id:Le,kind:"text",segmentReference:Pe,profiles:[],duration:S,bitrate:ui,mime:"",codecs:"",width:0,height:0,isAuto:oi}}else ni={id:Le,isAuto:oi,kind:"text",url:We}}else{let Le=(Ds=($s=U.getAttribute("contentType"))!=null?$s:Me==null?void 0:Me.split("/")[0])!=null?Ds:Yi,oi=(Vs=(Cs=q.getAttribute("profiles"))==null?void 0:Cs.split(","))!=null?Vs:[],Ye=parseInt((Os=U.getAttribute("width"))!=null?Os:"",10),Dt=parseInt((_s=U.getAttribute("height"))!=null?_s:"",10),ui=parseInt((Fs=U.getAttribute("bandwidth"))!=null?Fs:"",10)/1e3,li=(Ns=U.getAttribute("frameRate"))!=null?Ns:"",ft=(Us=U.getAttribute("quality"))!=null?Us:void 0,Ki=li?_u(li):void 0,mt=(qs=U.getAttribute("id"))!=null?qs:"id"+(k++).toString(10),ci=Le==="video"?`${Dt}p`:Le==="audio"?`${ui}Kbps`:ai,di=`${mt}@${ci}`,pi=[...C,...Cl,...oi],bt,Ct=U.querySelector("SegmentBase"),se=(js=U.querySelector("SegmentTemplate"))!=null?js:Ol;if(Ct){let Pe=(zs=(Hs=U.querySelector("SegmentBase Initialization"))==null?void 0:Hs.getAttribute("range"))!=null?zs:"",[me,Ke]=Pe.split("-").map(De=>parseInt(De,10)),ce={from:me,to:Ke},Be=(Qs=U.querySelector("SegmentBase"))==null?void 0:Qs.getAttribute("indexRange"),[Xe,$e]=Be?Be.split("-").map(De=>parseInt(De,10)):[],ve=Be?{from:Xe,to:$e}:void 0;bt={type:"byteRange",url:We,initRange:ce,indexRange:ve}}else if(se){let Pe={representationId:(Gs=U.getAttribute("id"))!=null?Gs:void 0,bandwidth:(Ws=U.getAttribute("bandwidth"))!=null?Ws:void 0},me=parseInt((Ys=se.getAttribute("timescale"))!=null?Ys:"",10),Ke=(Ks=se.getAttribute("initialization"))!=null?Ks:"",ce=se.getAttribute("media"),Be=(Js=parseInt((Xs=se.getAttribute("startNumber"))!=null?Xs:"",10))!=null?Js:1,Xe=Ii(Ke,Pe);if(!ce)throw new ReferenceError("No media attribute in SegmentTemplate");let $e=(Zs=se.querySelectorAll("SegmentTimeline S"))!=null?Zs:[],ve=[],De=0,gt="",Ot=0;if($e.length){let hi=Be,be=0;for(let St of $e){let ye=parseInt((ea=St.getAttribute("d"))!=null?ea:"",10),Je=parseInt((ta=St.getAttribute("r"))!=null?ta:"",10)||0,fi=parseInt((ia=St.getAttribute("t"))!=null?ia:"",10);be=Number.isFinite(fi)?fi:be;let Xi=ye/me*1e3,Ji=be/me*1e3;for(let mi=0;mi<Je+1;mi++){let Nl=Ii(ce,B(x({},Pe),{segmentNumber:hi.toString(10),segmentTime:(be+mi*ye).toString(10)})),aa=(Ji!=null?Ji:0)+mi*Xi,Ul=aa+Xi;hi++,ve.push({time:{from:aa,to:Ul},url:Nl})}be+=(Je+1)*ye,De+=(Je+1)*Xi}Ot=be/me*1e3,gt=Ii(ce,B(x({},Pe),{segmentNumber:hi.toString(10),segmentTime:be.toString(10)}))}else if(nC(S)){let be=parseInt((ra=se.getAttribute("duration"))!=null?ra:"",10)/me*1e3,St=Math.ceil(S/be),ye=0;for(let Je=1;Je<St;Je++){let fi=Ii(ce,B(x({},Pe),{segmentNumber:Je.toString(10),segmentTime:ye.toString(10)}));ve.push({time:{from:ye,to:ye+be},url:fi}),ye+=be}Ot=ye,gt=Ii(ce,B(x({},Pe),{segmentNumber:St.toString(10),segmentTime:ye.toString(10)}))}let Fl={time:{from:Ot,to:1/0},url:gt};bt={type:"template",baseUrl:We,segmentTemplateUrl:ce,initUrl:Xe,totalSegmentsDurationMs:De,segments:ve,nextSegmentBeyondManifest:Fl,timescale:me}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Le||!Me)continue;let Vt={video:"video",audio:"audio",text:"text"}[Le];if(!Vt)continue;ht||(ht=Vt),ni={id:di,kind:Vt,segmentReference:bt,profiles:pi,duration:S,bitrate:ui,mime:Me,codecs:ai,width:Ye,height:Dt,fps:Ki,quality:ft}}G.language||(G.language=Re),G.label||(G.label=$t),G.mime||(G.mime=Me),G.codecs||(G.codecs=ai),G.hdr||(G.hdr=ht==="video"&&as(ai)),G.representations.push(ni)}if(ht){let U=r[ht].find(Re=>Re.id===G.id);if(U&&G.representations.every(Re=>rt(Re.segmentReference)))for(let Re of U.representations){let $t=G.representations.find(Me=>Me.id===Re.id),si=$t==null?void 0:$t.segmentReference,We=Re.segmentReference;We.segments.push(...si.segments),We.nextSegmentBeyondManifest=si.nextSegmentBeyondManifest}else r[ht].push(G)}}return{duration:S,streams:r,baseUrls:n,live:g}};import{isNonNullable as zI}from"@vkontakte/videoplayer-shared/es2015";var z=(s,e)=>zI(s)&&zI(e)&&s.readyState==="open"&&oC(s,e);function oC(s,e){for(let t=0;t<s.activeSourceBuffers.length;++t)if(s.activeSourceBuffers[t]===e)return!0;return!1}var In=class{constructor(e,t,i,{fetcher:r,tuning:a,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new gr(0);this.currentLowLatencySegmentLength$=new gr(0);this.currentSegmentLength$=new gr(0);this.onLastSegment$=new gr(!1);this.fullyBuffered$=new gr(!1);this.playingRepresentation$=new gr(void 0);this.playingRepresentationInit$=new gr(void 0);this.error$=new lC;this.gaps=[];this.subscription=new cC;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new le;this.switchAbortController=new le;this.destroyAbortController=new le;this.bufferLimit=1/0;this.failedDownloads=0;this.baseUrls=[];this.baseUrlsIndex=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.lastDataObtainedTimestampMs=0;this.loadByteRangeSegmentsTimeoutId=0;this.startWith=Ni(this.destroyAbortController.signal,function(e){return X(this,null,function*(){let t=this.representations.get(e);dt(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new zT(this.sourceBuffer),this.subscription.add(kp(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:xi.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o!=null||(o={id:"SegmentEjection",category:xi.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),this.error$.next(o)})),this.subscription.add(kp(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:xi.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o||!z(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,is(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=this.getForwardBufferDuration(o),d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,n*2,l<d).catch(c=>{this.handleAsyncError(c,"pruneBuffer")})})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);let i=this.initData.get(t.id),r=this.segments.get(t.id),a=this.parsedInitData.get(t.id);dt(i,"No init buffer for starting representation"),dt(r,"No segments for starting representation"),i instanceof ArrayBuffer&&(this.searchGaps(r,t),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(a))})}.bind(this));this.switchTo=Ni(this.destroyAbortController.signal,function(e,t=!1){return X(this,null,function*(){if(!z(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);dt(i,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if(ze(a)||ze(r)?yield this.loadInit(i,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),dt(r,"No segments for starting representation"),a=this.initData.get(e),!(!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer||!z(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(a,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer();else{let n=this.getCurrentPosition();ns(n)&&!this.isLive&&(this.bufferLimit=1/0,yield new Zi(this.pruneBuffer(n,1/0,!0))),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}this.maintain()}})}.bind(this));this.switchToOld=Ni(this.destroyAbortController.signal,function(e,t=!1){return X(this,null,function*(){if(!z(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);dt(i,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if(ze(a)||ze(r)?yield this.loadInit(i,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),dt(r,"No segments for starting representation"),a=this.initData.get(e),!(!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer||!z(this.mediaSource,this.sourceBuffer)))if(yield this.abort(),yield this.sourceBufferTaskQueue.append(a,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let n=this.getCurrentPosition();ns(n)&&(this.isLive||(this.bufferLimit=1/0,yield new Zi(this.pruneBuffer(n,1/0,!0))),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}})}.bind(this));this.seekLive=Ni(this.destroyAbortController.signal,function(e){return X(this,null,function*(){var u,l;let t=(u=(0,Uu.default)(e,d=>d.representations))!=null?u:[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let d of this.representations.keys()){let c=t.find(h=>h.id===d);c&&this.representations.set(d,c);let f=this.representations.get(d);if(!f||!rt(f.segmentReference))return;let p=this.getActualLiveStartingSegments(f.segmentReference);this.segments.set(f.id,p)}let i=(l=this.switchingToRepresentationId)!=null?l:this.downloadingRepresentationId,r=this.representations.get(i);dt(r);let a=this.segments.get(i);dt(a,"No segments for starting representation");let n=this.initData.get(i);if(dt(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer))return;let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(a,r),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1})}.bind(this));var d;this.fetcher=r,this.tuning=a,this.compatibilityMode=u,this.forwardBufferTarget=a.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!(l!=null&&l.live),this.baseUrls=(d=l==null?void 0:l.baseUrls)!=null?d:[],this.initData=new Map(i.map(c=>[c.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(c=>[c.id,c])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchToWithPreviousAbort(e,t=!1){!z(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new le,Ni(this.switchAbortController.signal,function(i,r=!1){return X(this,null,function*(){this.switchingToRepresentationId=i;let a=this.representations.get(i);dt(a,`No such representation ${i}`);let n=this.segments.get(i),o=this.initData.get(i);if(ze(o)||ze(n)?yield this.loadInit(a,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(i),dt(n,"No segments for starting representation"),o=this.initData.get(i),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer||!z(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(o,this.downloadAbortController.signal),r)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=i,yield this.dropBuffer();else{let u=this.getCurrentPosition();ns(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(){!ze(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}abort(){return E(this,null,function*(){for(let e of this.activeSegments)this.abortSegment(e.segment);return this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new le,this.abortBuffer()})}maintain(e=this.getCurrentPosition()){if(ze(e)||ze(this.downloadingRepresentationId)||ze(this.playingRepresentationId)||ze(this.sourceBuffer)||!z(this.mediaSource,this.sourceBuffer)||ns(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(dt(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;let r=i.find(d=>e>=d.time.from&&e<d.time.to);ns(r)&&isFinite(r.time.from)&&isFinite(r.time.to)&&this.currentSegmentLength$.next((r==null?void 0:r.time.to)-r.time.from);let a=e,n=100;if(this.playingRepresentationId!==this.downloadingRepresentationId){let d=this.getForwardBufferDuration(e),c=r?r.time.to+n:-1/0;r&&r.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&d>=r.time.to-e+n&&(a=c)}if(isFinite(this.bufferLimit)&&is(this.sourceBuffer.buffered)>=this.bufferLimit){let d=this.getForwardBufferDuration(e),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,d<c).catch(f=>{this.handleAsyncError(f,"pruneBuffer")});return}let u=[];if(!this.activeSegments.size&&(u=this.selectForwardBufferSegments(i,t.segmentReference.type,a),u.length)){let d="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if((0,Nu.default)(u,r))d="high";else{let c=(0,os.default)(u,0);c&&c.time.from-r.time.to>=this.forwardBufferTarget/2&&(d="low")}this.loadSegments(u,t,d).catch(c=>{this.handleAsyncError(c,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&r&&r.status==="fed"&&!u.length&&this.getForwardBufferDuration(e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let l=(0,os.default)(i,-1);!this.isLive&&l&&(this.fullyBuffered$.next(l.time.to-e-this.getForwardBufferDuration(e)<n),this.onLastSegment$.next(e-l.time.from>0))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let i=0,r=this.isLive?this.liveInitialAdditionalOffset:0;for(let a of e)Math.trunc(a.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:a.time.from+r}),i=a.time.to;ns(t.duration)&&t.duration-i>0&&!this.isLive&&this.gaps.push({representation:t.id,from:i,to:t.duration})}getActualLiveStartingSegments(e){let t=e.segments,i=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,r=[],a=0,n=t.length-1;do r.unshift(t[n]),a+=t[n].time.to-t[n].time.from,n--;while(a<i&&n>=0);return this.liveInitialAdditionalOffset=a-i,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){let t=(0,Uu.default)(e==null?void 0:e.streams[this.kind],r=>r.representations).find(r=>r.id===this.downloadingRepresentationId);if(!t)return;let i=this.segments.get(t.id);if(i!=null&&i.length)return{from:i[0].time.from,to:i[i.length-1].time.to}}updateLive(e){var i,r,a,n;let t=(i=(0,Uu.default)(e==null?void 0:e.streams[this.kind],o=>o.representations))!=null?i:[];if(![...this.segments.values()].every(o=>!o.length))for(let o of t){if(!o||!rt(o.segmentReference))return;let u=o.segmentReference.segments.map(p=>B(x({},p),{status:"none",size:void 0})),l=100,d=(r=this.segments.get(o.id))!=null?r:[],c=(n=(a=(0,os.default)(d,-1))==null?void 0:a.time.to)!=null?n:0,f=u==null?void 0:u.findIndex(p=>c>=p.time.from+l&&c<=p.time.to+l);if(f===-1){this.liveUpdateSegmentIndex=0;let p=this.getActualLiveStartingSegments(o.segmentReference);this.segments.set(o.id,p)}else{let p=u.slice(f+1);this.segments.set(o.id,[...d,...p])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;dt(e);let t=this.segments.get(e);if(t!=null&&t.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}updateLowLatencyLiveIfNeeded(e){var i;let t=0;for(let r of this.representations.values()){let a=r.segmentReference;if(!rt(a))return;let n=(i=this.segments.get(r.id))!=null?i:[],o=n.find(l=>Math.floor(l.time.from)===Math.floor(e.time.from));if(o&&!isFinite(o.time.to)&&(o.time.to=e.time.to,t=o.time.to-o.time.from),!!!n.find(l=>Math.floor(l.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let l=Math.round(e.time.to*a.timescale/1e3).toString(10),d=Ii(a.segmentTemplateUrl,{segmentTime:l});n.push({status:"none",time:{from:e.time.to,to:1/0},url:d})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){var a,n,o;let t=(n=(a=this.switchingToRepresentationId)!=null?a:this.downloadingRepresentationId)!=null?n:this.playingRepresentationId;if(!t)return;let i=this.segments.get(t);if(!i)return;let r=i.find(u=>u.time.from<=e&&u.time.to>=e);return(o=r==null?void 0:r.time.from)!=null?o:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)==null||e.destroy(),this.gapDetectionIdleCallback&&ei&&ei(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&ei&&ei(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:f,time:{from:p,to:h}},m)=>{let g=p<=i&&h>=i,S=p>i||g||m===0&&i===0,v=Math.min(this.forwardBufferTarget,this.bufferLimit),y=this.preloadOnly&&p<=i+v||r<v&&h-p>=v||h<=i+v;return(f==="none"||f==="partially_ejected"&&S&&y&&this.sourceBuffer&&z(this.mediaSource,this.sourceBuffer)&&!(He(this.sourceBuffer.buffered,p)&&He(this.sourceBuffer.buffered,h)))&&S&&y});if(a===-1)return[];if(t!=="byteRange")return e.slice(a,a+1);let n=e,o=0,u=0,l=[],d=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,c=this.preloadOnly?this.forwardBufferTarget:0;for(let f=a;f<n.length&&(o<=d||u<=c);f++){let p=n[f];if(o+=p.byte.to+1-p.byte.from,u+=p.time.to+1-p.time.from,p.status==="none"||p.status==="partially_ejected")l.push(p);else break}return l}loadSegments(e,t,i="auto"){return E(this,null,function*(){rt(t.segmentReference)?yield this.loadTemplateSegment(e[0],t,i):yield this.loadByteRangeSegments(e,t,i)})}loadTemplateSegment(e,t,i="auto"){return E(this,null,function*(){e.status="downloading";let r={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(r);let{range:a,url:n,signal:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(yield Ni(o,function(){return X(this,null,function*(){let d=Rp(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,d))})}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let d=yield this.fetcher.fetch(n,{range:a,signal:o,onProgress:u,priority:i,isLowLatency:this.isActiveLowLatency()});if(this.lastDataObtainedTimestampMs=Fu(),!d)return;let c=new DataView(d),f=yn(t.mime);if(!isFinite(r.segment.time.to)){let m=t.segmentReference.timescale;r.segment.time.to=f.getChunkEndTime(c,m)}u&&r.feedingBytes&&l?yield Promise.all(l):yield this.sourceBufferTaskQueue.append(c,o);let{serverDataReceivedTimestamp:p,serverDataPreparedTime:h}=f.getServerLatencyTimestamps(c);p&&h&&this.currentLiveSegmentServerLatency$.next(h-p),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(d){this.abortActiveSegments([e]),Tn(d)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}})}updateRepresentationsBaseUrlIfNeeded(){if(!this.tuning.dash.enableBaseUrlSupport||!this.baseUrls.length||this.failedDownloads<=this.tuning.dash.maxSegmentRetryCount)return;this.baseUrlsIndex=(this.baseUrlsIndex+1)%this.baseUrls.length;let e=this.baseUrls[this.baseUrlsIndex];for(let t of this.representations.values())rt(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}loadByteRangeSegments(e,t,i="auto"){return E(this,null,function*(){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&&(yield Ni(n,function(){return X(this,null,function*(){let u=Rp(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),kp(window,"online").pipe(uC()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{yield this.fetcher.fetch(a,{range:r,onProgress:o,signal:n,priority:i}),this.lastDataObtainedTimestampMs=Fu(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),Tn(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}})}prepareByteRangeFetchSegmentParams(e,t){if(rt(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:(0,os.default)(e,0).byte.from,to:(0,os.default)(e,-1).byte.to},{signal:a}=this.downloadAbortController;return{url:i,range:r,signal:a,onProgress:(o,u)=>E(this,null,function*(){if(!a.aborted)try{this.lastDataObtainedTimestampMs=Fu(),yield this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:a,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:xi.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}})}}prepareTemplateFetchSegmentParams(e,t){if(!rt(t.segmentReference))throw new Error("Representation is not template type");let i=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&i.searchParams.set("low-latency","yes");let r=i.toString(),{signal:a}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,d)=>{if(!a.aborted)try{this.lastDataObtainedTimestampMs=Fu();let c=this.onSomeTemplateDataLoaded({dataView:l,loaded:d,signal:a,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(c)}catch(c){this.error$.next({id:"SegmentFeeding",category:xi.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}}:void 0;return{url:r,signal:a,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,Nu.default)(e,t.segment)&&this.abortSegment(t.segment)}onSomeTemplateDataLoaded(n){return E(this,arguments,function*({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:a}){if(!this.activeSegments.size||!z(this.mediaSource,this.sourceBuffer))return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){let{segment:l}=u;if(u.representationId===t){if(a.aborted){r();continue}if(u.loadedBytes=i,u.loadedBytes>u.feedingBytes){let d=new DataView(e.buffer,e.byteOffset+u.feedingBytes,u.loadedBytes-u.feedingBytes),c=yn(o.mime).parseFeedableSegmentChunk(d,this.isLive);c!=null&&c.byteLength&&(l.status="partially_fed",u.feedingBytes+=c.byteLength,yield this.sourceBufferTaskQueue.append(c),u.fedBytes+=c.byteLength)}}}})}onSomeByteRangesDataLoaded(o){return E(this,arguments,function*({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:a,onSegmentAppendFailed:n}){if(!this.activeSegments.size||!z(this.mediaSource,this.sourceBuffer))return;let u=this.representations.get(t);if(u)for(let l of this.activeSegments){let{segment:d}=l;if(l.representationId!==t)continue;if(a.aborted){yield n();continue}let c=d.byte.from-i,f=d.byte.to-i,p=f-c+1,h=c<r,m=f<=r;if(!h)continue;let g=yn(u.mime);if(d.status==="downloading"&&m){d.status="downloaded";let S=new DataView(e.buffer,e.byteOffset+c,p);(yield this.sourceBufferTaskQueue.append(S,a))&&!a.aborted?this.onSegmentFullyAppended(l,t):yield n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(d.status==="downloading"||d.status==="partially_fed")&&(l.loadedBytes=Math.min(p,r-c),l.loadedBytes>l.feedingBytes)){let S=new DataView(e.buffer,e.byteOffset+c+l.feedingBytes,l.loadedBytes-l.feedingBytes),v=l.loadedBytes===p?S:g.parseFeedableSegmentChunk(S);v!=null&&v.byteLength&&(d.status="partially_fed",l.feedingBytes+=v.byteLength,(yield this.sourceBufferTaskQueue.append(v,a))&&!a.aborted?(l.fedBytes+=v.byteLength,l.fedBytes===p&&this.onSegmentFullyAppended(l,t)):yield n())}}})}onSegmentFullyAppended(e,t){var i;if(!(ze(this.sourceBuffer)||!z(this.mediaSource,this.sourceBuffer))){!this.isLive&&Q.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(He(this.sourceBuffer.buffered,e.segment.time.from,100)&&He(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:xi.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",Ep(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=ts(()=>(0,QI.default)(this.loadInit(i,"low",!1),()=>this.initLoadIdleCallback=null)))}loadInit(e,t="auto",i=!1){return E(this,null,function*(){let r=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!i&&this.failedDownloads>0?Ni(this.destroyAbortController.signal,function(){return X(this,null,function*(){let o=Rp(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))})}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,yn(e.mime),r)).then(o=>E(this,null,function*(){if(!o)return;let{init:u,dataView:l,segments:d}=o,c=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,c);let f=d;this.isLive&&rt(e.segmentReference)&&(f=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,f),u&&this.parsedInitData.set(e.id,u)})).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:xi.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n})}dropBuffer(){return E(this,null,function*(){for(let e of this.segments.values())for(let t of e)t.status="none";yield this.pruneBuffer(0,1/0,!0)})}pruneBuffer(e,t,i=!1){return E(this,null,function*(){if(!this.sourceBuffer||!z(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||ze(e))return!1;let r=[],a=0,n=u=>{u.sort((d,c)=>d.from-c.from);let l=[u[0]];for(let d=1;d<u.length;d++){let{from:c,to:f}=u[d],p=l[l.length-1];p.to>=c?p.to=Math.max(p.to,f):l.push(u[d])}return l},o=u=>{var d;if(a>=t)return r;r.push(x({},u.time)),r=n(r);let l=Ep(u)?(d=u.size)!=null?d:0:u.byte.to-u.byte.from;a+=l};for(let u of this.segments.values())for(let l of u){let d=l.time.to<=e-this.tuning.dash.bufferPruningSafeZone,c=l.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(d||c)&&l.status==="fed"&&o(l)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let l=this.sourceBuffer.buffered.start(u)*1e3,d=this.sourceBuffer.buffered.end(u)*1e3,c=0;for(let f of this.segments.values())for(let p of f)(0,Nu.default)(["none","partially_ejected"],p.status)&&Math.round(p.time.from)<=Math.round(l)&&Math.round(p.time.to)>=Math.round(d)&&c++;if(c===this.segments.size){let f={time:{from:l,to:d},url:"",status:"none"};o(f)}}if(r.length&&i){let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let l of this.segments.values())for(let d of l)d.time.from>=e+u&&d.status==="fed"&&o(d)}return r.length?(yield Promise.all(r.map(l=>this.sourceBufferTaskQueue.remove(l.from,l.to)))).reduce((l,d)=>l||d,!1):!1})}abortBuffer(){return E(this,null,function*(){if(!this.sourceBuffer||!z(this.mediaSource,this.sourceBuffer))return!1;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;return this.sourceBufferTaskQueue.abort(t)})}getDebugBufferState(){if(!(!this.sourceBuffer||!z(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}getForwardBufferDuration(e=this.getCurrentPosition()){return!this.sourceBuffer||!z(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||ze(e)?0:Oe(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!(!this.sourceBuffer||!z(this.mediaSource,this.sourceBuffer))){if(this.tuning.useRefactoredSearchGap)for(let i=0;i<this.sourceBuffer.buffered.length;i++)this.gaps=this.gaps.filter(r=>this.sourceBuffer&&(Math.round(r.from)<Math.round(this.sourceBuffer.buffered.start(i)*1e3)||Math.round(r.to)>Math.round(this.sourceBuffer.buffered.end(i)*1e3)));for(let i of t){let r={representation:e,from:i.time.from,to:i.time.to};for(let a=0;a<this.sourceBuffer.buffered.length;a++){let n=this.sourceBuffer.buffered.start(a)*1e3,o=this.sourceBuffer.buffered.end(a)*1e3;if(!(o<=i.time.from||n>=i.time.to)){if(n<=i.time.from&&o>=i.time.to){r=void 0;break}o>i.time.from&&o<i.time.to&&(r.from=o),n<i.time.to&&n>i.time.from&&(r.to=n)}}r&&r.to-r.from>1&&!this.gaps.some(a=>r&&a.from===r.from&&a.to===r.to)&&this.gaps.push(r)}}}detectGapsWhenIdle(e,t){if(!(this.gapDetectionIdleCallback||!this.sourceBuffer||!z(this.mediaSource,this.sourceBuffer))){if(!this.tuning.useRefactoredSearchGap)for(let i=0;i<this.sourceBuffer.buffered.length;i++)this.gaps=this.gaps.filter(r=>this.sourceBuffer&&(Math.round(r.from)<Math.round(this.sourceBuffer.buffered.start(i)*1e3)||Math.round(r.to)>Math.round(this.sourceBuffer.buffered.end(i)*1e3)));this.gapDetectionIdleCallback=ts(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:xi.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if(ze(this.sourceBuffer)||!z(this.mediaSource,this.sourceBuffer)||ze(this.playingRepresentationId))return;let e=[];for(let i=0;i<this.sourceBuffer.buffered.length;i++){let r=Math.floor(this.sourceBuffer.buffered.start(i)*1e3),a=Math.ceil(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:r,to:a})}let t=100;for(let i of this.segments.values())for(let r of i){let{status:a}=r;if(a!=="fed"&&a!=="partially_ejected")continue;let n=Math.floor(r.time.from),o=Math.ceil(r.time.to),u=e.some(d=>d.from-t<=n&&d.to+t>=o),l=e.filter(d=>n>=d.from&&n<d.to-t||o>d.from+t&&o<=d.to);u||(l.length===1?r.status="partially_ejected":this.gaps.some(d=>d.from===r.time.from||d.to===r.time.to)?r.status="partially_ejected":r.status="none")}}handleAsyncError(e,t){this.error$.next({id:t,category:xi.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}};var Ui=s=>{let e=new URL(s);return e.searchParams.set("quic","1"),e.toString()};var qu=s=>{var a;let e=s.get("X-Delivery-Type"),t=s.get("X-Reused"),i=e===null?"http1":e!=null?e:void 0,r=t===null?void 0:(a={1:!0,0:!1}[t])!=null?a:void 0;return{type:i,reused:r}};import{abortable as xn,assertNever as GI,fromEvent as WI,merge as dC,now as En,Subscription as pC,Subject as YI,ValueSubject as Mp,flattenObject as us,ErrorCategory as wn}from"@vkontakte/videoplayer-shared/es2015";var ju=s=>{let e=new URL(s);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var zu=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:a=!1}){this.lastConnectionType$=new Mp(void 0);this.lastConnectionReused$=new Mp(void 0);this.lastRequestFirstBytes$=new Mp(void 0);this.recoverableError$=new YI;this.error$=new YI;this.abortAllController=new le;this.subscription=new pC;this.fetchManifest=xn(this.abortAllController.signal,function(e){return X(this,null,function*(){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=Ui(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=ju(i));let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(Hu);return r?(t.log("success",us({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(r.headers),r.text()):(t.error("error",us({url:i,message:"No data in request manifest"})),t.end(),null)})}.bind(this));this.fetch=xn(this.abortAllController.signal,function(l){return X(this,arguments,function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:a="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1}={}){var M,j;let d=e,c=new Headers,f=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{c.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let N=new URL(d,location.href);N.searchParams.append("bytes",`${i.from}-${i.to}`),d=N.toString();break}default:GI(t)}this.requestQuic&&(d=Ui(d));let p=this.abortAllController.signal,h;if(n){let N=new le;if(h=dC(WI(this.abortAllController.signal,"abort"),WI(n,"abort")).subscribe(()=>{try{N.abort()}catch(K){Hu(K)}}),this.subscription.add(h),this.abortAllController.signal.aborted||n.aborted)try{N.abort()}catch(K){Hu(K)}p=N.signal}let m=En();f.log("startRequest",us({url:d,priority:a,rangeMethod:t,range:i,isLowLatency:u,requestStartedAt:m}));let g=yield this.doFetch(d,{priority:a,headers:c,signal:p}),S=En();if(!g)return f.error("error",{message:"No response in request"}),f.end(),h==null||h.unsubscribe(),null;if((M=this.throughputEstimator)==null||M.addRawRtt(S-m),!g.ok||!g.body){h==null||h.unsubscribe();let N=`Fetch error ${g.status}: ${g.statusText}`;return f.error("error",{message:N}),f.end(),Promise.reject(new Error(`Fetch error ${g.status}: ${g.statusText}`))}if(this.onHeadersReceived(g.headers),!r&&!o){h==null||h.unsubscribe();let N=En(),K={requestStartedAt:m,requestEndedAt:N,duration:N-m};return f.log("endRequest",us(K)),f.end(),g.arrayBuffer()}let[v,y]=g.body.tee(),T=v.getReader();o&&((j=this.throughputEstimator)==null||j.trackStream(y,u));let I=0,k=new Uint8Array(0),C=!1,V=N=>{h==null||h.unsubscribe(),C=!0,Hu(N)},$=xn(p,function(P){return X(this,arguments,function*({done:N,value:K}){if(I===0&&this.lastRequestFirstBytes$.next(En()-m),p.aborted){h==null||h.unsubscribe();return}if(!N&&K){let L=new Uint8Array(k.length+K.length);L.set(k),L.set(K,k.length),k=L,I+=K.byteLength,r==null||r(new DataView(k.buffer),I),yield T==null?void 0:T.read().then($,V)}})}.bind(this));yield T==null?void 0:T.read().then($,V),h==null||h.unsubscribe();let w=En(),F={failed:C,requestStartedAt:m,requestEndedAt:w,duration:w-m};return C?(f.error("endRequest",us(F)),f.end(),null):(f.log("endRequest",us(F)),f.end(),k.buffer)})}.bind(this));this.fetchByteRangeRepresentation=xn(this.abortAllController.signal,function(e,t,i){return X(this,null,function*(){var S;if(e.type!=="byteRange")return null;let{from:r,to:a}=e.initRange,n=r,o=a,u=!1,l,d;e.indexRange&&(l=e.indexRange.from,d=e.indexRange.to,u=a+1===l,u&&(n=Math.min(l,r),o=Math.max(d,a))),n=Math.min(n,0);let c=yield this.fetch(e.url,{range:{from:n,to:o},priority:i,measureThroughput:!1});if(!c)return null;let f=new DataView(c,r-n,a-n+1);if(!t.validateData(f))throw new Error("Invalid media file");let p=t.parseInit(f),h=(S=e.indexRange)!=null?S:t.getIndexRange(p);if(!h)throw new ReferenceError("No way to load representation index");let m;if(u)m=new DataView(c,h.from-n,h.to-h.from+1);else{let v=yield this.fetch(e.url,{range:h,priority:i,measureThroughput:!1});if(!v)return null;m=new DataView(v)}let g=t.parseSegments(m,p,h);return{init:p,dataView:new DataView(c),segments:g}})}.bind(this));this.fetchTemplateRepresentation=xn(this.abortAllController.signal,function(e,t){return X(this,null,function*(){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=>B(x({},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}=qu(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}fetchRepresentation(e,t,i="auto"){return E(this,null,function*(){var a,n;let{type:r}=e;switch(r){case"byteRange":return(a=yield this.fetchByteRangeRepresentation(e,t,i))!=null?a:null;case"template":return(n=yield this.fetchTemplateRepresentation(e,i))!=null?n:null;default:GI(r)}})}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}doFetch(e,t){return E(this,null,function*(){let i=yield Mt(e,t);if(i.ok)return i;let r=yield i.text(),a=parseInt(r);if(!isNaN(a))switch(a){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:wn.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:wn.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:wn.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:wn.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${a})`,category:wn.FATAL})}})}},Hu=s=>{if(!Tn(s))throw s};var Ei=(s,e,t)=>t*e+(1-t)*s,Lp=(s,e)=>s.reduce((t,i)=>t+i,0)/e,KI=(s,e,t,i)=>{let r=0,a=t,n=Lp(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 hC,ValueSubject as XI}from"@vkontakte/videoplayer-shared/es2015";var qi=class{constructor(e){this.prevReported=void 0;this.pastMeasures=[];this.takenMeasures=0;this.measuresCursor=0;var i;this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new XI(e.initial),this.debounced$=new XI(e.initial);let t=(i=e.label)!=null?i:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new tt(`raw_${t}`),this.smoothedSeries$=new tt(`smoothed_${t}`),this.reportedSeries$=new tt(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,i=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=Ze(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)&&(hC(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 Qu=class extends qi{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=Ei(this.slow,e,this.params.emaAlphaSlow),this.fast=Ei(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var Gu=class extends qi{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=Lp(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Ei(this.emaSmoothed,e,this.params.emaAlpha);let i=KI(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}};var Wu=class extends qi{constructor(t){super(t);this.furtherValues=[];this.currentTopExtremumValue=0;this.extremumInterval=t.extremumInterval}next(t){this.currentTopExtremumValue<=t?(this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.length===this.extremumInterval?(super.next(this.currentTopExtremumValue),this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.push(t)}updateSmoothedValue(t){this.smoothed=this.smoothed?Ei(this.smoothed,t,this.params.emaAlpha):t}};var wi=class{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new Qu({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new Gu({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 Wu(x({initial:e,label:"liveEdgeDelay"},t))}};var ls=(s,e)=>{s&&s.playbackRate!==e&&(s.playbackRate=e)};import{isNullable as fC,ValueSubject as mC}from"@vkontakte/videoplayer-shared/es2015";var An=class s{constructor(e,t){this.currentRepresentation$=new mC(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(!fC(e))for(let i of this.representations)for(let r of i){let a=r.segmentReference,n=a.segments.length,o=a.segments[0].time.from,u=a.segments[n-1].time.to;if(e<o||e>u)continue;let l=a.segments.find(d=>d.time.from<=e&&d.time.to>=e);!l||((t=this.currentSegment)==null?void 0:t.time.from)===l.time.from&&this.currentSegment.time.to===l.time.to||(this.currentSegment=l,this.currentRepresentation$.next(B(x({},r),{label:"Live Text",language:"ru",isAuto:!0,url:new URL(l.url,a.baseUrl).toString()})))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e!=null?e:[]){let i=s.filterRepresentations(t.representations);if(i){this.representations[this.representationsCursor]=i,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!(e!=null&&e.some(t=>s.filterRepresentations(t.representations)))}static filterRepresentations(e){return e==null?void 0:e.filter(t=>t.kind==="text"&&"segmentReference"in t&&rt(t.segmentReference))}};var Ku=H(qt(),1);import{assertNever as Xu}from"@vkontakte/videoplayer-shared/es2015";var JI=(s,{useManagedMediaSource:e,useOldMSEDetection:t})=>{let{containers:i,protocols:r,codecs:a,nativeHlsSupported:n}=Q.video,o=(a.h264||a.h265)&&a.aac,u=r.mse&&(!t||!!window.MediaStreamTrack)||r.mms&&e;return s.filter(l=>{switch(l){case"DASH_SEP":return u&&i.mp4&&o;case"DASH_WEBM":return u&&i.webm&&a.vp9&&a.opus;case"DASH_WEBM_AV1":return u&&i.webm&&a.av1&&a.opus;case"DASH_STREAMS":return u&&(i.mp4&&o||i.webm&&(a.vp9||a.av1)&&(a.opus||a.aac));case"DASH_LIVE":return u&&i.mp4&&o;case"DASH_LIVE_CMAF":return u&&i.mp4&&o&&i.cmaf;case"DASH_ONDEMAND":return u&&i.mp4&&o;case"HLS":case"HLS_ONDEMAND":case"HLS_LIVE":case"HLS_LIVE_CMAF":return n;case"MPEG":return i.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return r.webrtc&&r.ws&&a.h264&&(i.mp4||i.webm);default:return Xu(l)}})},Yu=s=>{let{webmDecodingInfo:e}=Q.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:Xu(s)}return[t,i]},ZI=({webmCodec:s,androidPreferredFormat:e,preferMultiStream:t})=>{let i=[...t?["DASH_STREAMS"]:[],...Yu(s),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],r=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(Q.device.isAndroid)switch(e){case"mpeg":return["MPEG",...i,"HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...i,"MPEG"];case"dash":return[...i,"HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return[...r,"MPEG",...Yu(s),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...Yu(s),"MPEG",...r,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...Yu(s),...r,"HLS","HLS_ONDEMAND"];default:Xu(e)}return Q.video.nativeHlsSupported?[...i,"HLS","HLS_ONDEMAND","MPEG"]:[...i,"HLS","HLS_ONDEMAND","MPEG"]},ex=({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=Q.device.isMac&&Q.browser.isSafari;if(Q.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:Xu(s)}else Q.video.nativeHlsSupported&&!u?o=n:u?o=e?["DASH_LIVE_CMAF","HLS_LIVE_CMAF","HLS_LIVE","DASH_LIVE"]:["HLS_LIVE","DASH_LIVE","DASH_LIVE_CMAF","HLS_LIVE_CMAF"]:o=a;return t?["WEB_RTC_LIVE",...o]:[...o,"WEB_RTC_LIVE"]},Bp=s=>s?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],Ju=s=>{if(s.size===0)return;if(s.size===1){let t=s.values().next();return(0,Ku.default)(t.value.split("."),0)}for(let t of s){let i=(0,Ku.default)(t.split("."),0);if(i==="opus"||i==="vp09"||i==="av01")return i}let e=s.values().next();return(0,Ku.default)(e.value.split("."),0)};var xC=["timeupdate","progress","play","seeked","stalled","waiting"],EC=["timeupdate","progress","loadeddata","playing","seeked"];var tl=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new rx;this.representationSubscription=new rx;this.state$=new Y("none");this.currentVideoRepresentation$=new ge(void 0);this.currentVideoRepresentationInit$=new ge(void 0);this.currentAudioRepresentation$=new ge(void 0);this.currentVideoSegmentLength$=new ge(0);this.currentAudioSegmentLength$=new ge(0);this.error$=new el;this.lastConnectionType$=new ge(void 0);this.lastConnectionReused$=new ge(void 0);this.lastRequestFirstBytes$=new ge(void 0);this.currentLiveTextRepresentation$=new ge(null);this.isLive$=new ge(!1);this.isActiveLive$=new ge(!1);this.isLowLatency$=new ge(!1);this.liveDuration$=new ge(0);this.liveSeekableDuration$=new ge(0);this.liveAvailabilityStartTime$=new ge(0);this.liveStreamStatus$=new ge(void 0);this.bufferLength$=new ge(0);this.liveLatency$=new ge(void 0);this.liveLoadBufferLength$=new ge(0);this.livePositionFromPlayer$=new ge(0);this.currentStallDuration$=new ge(0);this.videoLastDataObtainedTimestamp$=new ge(0);this.fetcherRecoverableError$=new el;this.fetcherError$=new el;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new el;this.gapWatchdogActive=!1;this.destroyController=new le;this.initManifest=Dp(this.destroyController.signal,function(e,t,i){return X(this,null,function*(){var r;this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=Ie(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:Ht.PARSER,message:"No playable video representations"})})}.bind(this));this.updateManifest=Dp(this.destroyController.signal,function(){return X(this,null,function*(){var n,o;this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(u=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:Ht.NETWORK,message:"Failed to load manifest",thrown:u})});if(!e)return null;let t=null;try{t=HI(e!=null?e:"",this.manifestUrlString)}catch(u){let l=(n=Ou(e))!=null?n:{id:"ManifestParsing",category:Ht.PARSER,message:"Failed to parse MPD manifest",thrown:u};this.error$.next(l)}if(!t)return null;let i=(u,l,d)=>{var c,f,p,h;return!!((f=(c=this.element)==null?void 0:c.canPlayType)!=null&&f.call(c,l)&&((h=(p=Et())==null?void 0:p.isTypeSupported)!=null&&h.call(p,`${l}; codecs="${d}"`))||u==="text")};if(t.live){this.isLive$.next(!!t.live);let{availabilityStartTime:u,latestSegmentPublishTime:l,streamIsUnpublished:d,streamIsAlive:c}=t.live,f=((o=t.duration)!=null?o:0)/1e3;this.liveSeekableDuration$.next(-1*f),this.liveDuration$.next((l-u)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let p="active";c||(p=d?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(p)}let r={text:t.streams.text,video:[],audio:[]};for(let u of["video","audio"]){let d=t.streams[u].filter(({mime:p,codecs:h})=>i(u,p,h)),c=new Set(d.map(({codecs:p})=>p)),f=Ju(c);if(f&&(r[u]=d.filter(({codecs:p})=>p.startsWith(f))),u==="video"){let p=this.tuning.preferHDR,h=r.video.some(g=>g.hdr),m=r.video.some(g=>!g.hdr);Q.display.isHDR&&p&&h?r.video=r.video.filter(g=>g.hdr):m&&(r.video=r.video.filter(g=>!g.hdr))}}let a=B(x({},t),{streams:r});return this.tracer.log("updateManifestEnd",kn(a)),a})}.bind(this));this.initRepresentations=Dp(this.destroyController.signal,function(e,t,i){return X(this,null,function*(){var f;this.tracer.log("initRepresentationsStart",kn({initialVideo:e,initialAudio:t,sourceHls:i})),cs(this.manifest),cs(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let r=p=>{this.representationSubscription.add(Ai(p,"error").pipe(Zu(h=>{var m;return!!((m=this.element)!=null&&m.played.length)})).subscribe(h=>{this.error$.next({id:"VideoSource",category:Ht.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=this.tuning.useManagedMediaSource?hu():new MediaSource;let a=document.createElement("source");if(r(a),a.src=URL.createObjectURL(this.source),this.element.appendChild(a),this.tuning.useManagedMediaSource&&Gr())if(i){let p=document.createElement("source");r(p),p.type="application/x-mpegurl",p.src=i.url,this.element.appendChild(p)}else this.element.disableRemotePlayback=!0;this.isActiveLive$.next(this.isLive$.getValue());let n={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),manifest:this.manifest},o=this.manifest.streams.video.reduce((p,h)=>[...p,...h.representations],[]);if(this.videoBufferManager=new In("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],Rn(t)){let p=this.manifest.streams.audio.reduce((h,m)=>[...h,...m.representations],[]);this.audioBufferManager=new In("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}An.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new An(this.manifest.streams.text,n)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$));let u=()=>{var p;(p=this.stallWatchdogSubscription)==null||p.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add(Sr(...EC.map(p=>Ai(this.element,p))).pipe(ps(p=>this.element?Oe(this.element.buffered,this.element.currentTime*1e3):0),Pn(),TC(p=>{p>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add(Sr(Ai(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe(Pn()).subscribe(h=>this.liveStreamEndTimestamp=Vp())),this.subscription.add(Ai(this.element,"pause").subscribe(()=>{this.livePauseWatchdogSubscription=Cp(1e3).subscribe(h=>{let m=Ci(this.manifestUrlString,2);this.manifestUrlString=Ie(this.manifestUrlString,m+1e3,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add(Ai(this.element,"play").subscribe(h=>{var m;return(m=this.livePauseWatchdogSubscription)==null?void 0:m.unsubscribe()})),this.representationSubscription.add(ds({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(ps(({isActiveLive:h,isLowLatency:m})=>h&&m),Pn()).subscribe(h=>{this.isManualDecreasePlaybackInLive()||ls(this.element,1)})),this.representationSubscription.add(ds({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(Zu(({bufferLength:h,isActiveLive:m,isLowLatency:g})=>m&&g&&!!h)).subscribe(({bufferLength:h})=>this.liveBuffer.next(h))),this.representationSubscription.add(this.videoBufferManager.currentLowLatencySegmentLength$.subscribe(h=>{if(!this.isActiveLive$.getValue()&&!this.isLowLatency$.getValue()&&!h)return;let m=this.liveSeekableDuration$.getValue()-h/1e3;this.liveSeekableDuration$.next(Math.max(m,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+h/1e3)})),this.representationSubscription.add(ds({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(Zu(({isLive:h})=>h),Pn((h,m)=>m.bufferLength<h.bufferLength),ps(({rtt:h,bufferLength:m,segmentServerLatency:g})=>{let S=Ci(this.manifestUrlString,2);return(h/2+m+g+S)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(ds({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:h,isActiveLive:m,isLowLatency:g})=>{if(!g||!m)return;let S=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,v=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,y=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,T=h-S;if(this.isManualDecreasePlaybackInLive())return;let I=1;Math.abs(T)>v&&(I=1+Math.sign(T)*y),ls(this.element,I)})),this.representationSubscription.add(this.bufferLength$.subscribe(h=>{var g,S;let m=0;if(h){let v=((S=(g=this.element)==null?void 0:g.currentTime)!=null?S:0)*1e3;m=Math.min(...this.bufferManagers.map(T=>{var I,k;return(k=(I=T.getLiveSegmentsToLoadState(this.manifest))==null?void 0:I.to)!=null?k:v}))-v}this.liveLoadBufferLength$.getValue()!==m&&this.liveLoadBufferLength$.next(m)}));let p=0;this.representationSubscription.add(ds({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(IC(1e3)).subscribe(g=>E(this,[g],function*({liveLoadBufferLength:h,bufferLength:m}){if(!this.element||this.isUpdatingLive)return;let S=this.element.playbackRate,v=Ci(this.manifestUrlString,2),y=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,T=Math.min(y,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*S),I=this.tuning.dashCmafLive.normalizedActualBufferOffset*S,k=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*S,C=isFinite(h)?h:m,V=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),$=y<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next($);let w="none";if(V?w="active_low_latency":this.isLowLatency$.getValue()&&$?(this.bufferManagers.forEach(F=>F.proceedLowLatencyLive()),w="active_low_latency"):v!==0&&C<T?w="live_forward_buffering":C<T+k&&(w="live_with_target_offset"),isFinite(h)&&(p=h>p?h:p),w==="live_forward_buffering"||w==="live_with_target_offset"){let F=p-(T+I),M=this.normolizeLiveOffset(Math.trunc(v+F/S)),j=Math.abs(M-v),N=0;!h||j<=this.tuning.dashCmafLive.offsetCalculationError?N=v:M>0&&j>this.tuning.dashCmafLive.offsetCalculationError&&(N=M),this.manifestUrlString=Ie(this.manifestUrlString,N,2)}(w==="live_with_target_offset"||w==="live_forward_buffering")&&(p=0,yield this.updateLive())}),h=>{this.error$.next({id:"updateLive",category:Ht.VIDEO_PIPELINE,thrown:h,message:"Failed to update live with subscription"})}))}let l=Sr(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe(ps(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),d=Sr(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe(ps(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue()))),c=ds({allBuffersFull:l,someBufferEnded:d}).pipe(Pn(),ps(({allBuffersFull:p,someBufferEnded:h})=>p&&h),Zu(p=>p));if(this.representationSubscription.add(Sr(this.forceEnded$,c).subscribe(()=>{var p;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(h=>!h.updating))try{(p=this.source)==null||p.endOfStream()}catch(h){this.error$.next({id:"EndOfStream",category:Ht.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:h})}})),this.representationSubscription.add(Sr(...this.bufferManagers.map(p=>p.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.representationSubscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.representationSubscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.liveTextManager&&this.representationSubscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$)),this.source.readyState!=="open"){let p=this.tuning.dash.sourceOpenTimeout>=0;yield new Promise(h=>{var m;p&&(this.timeoutSourceOpenId=setTimeout(()=>{var g;if(((g=this.source)==null?void 0:g.readyState)==="open"){h();return}this.error$.next({id:"OpenOfStream",category:Ht.VIDEO_PIPELINE,message:"Failed to open MediaSource",thrown:new Error("Timeout reject when wait sourceopen event"),traceAsLog:!0})},this.tuning.dash.sourceOpenTimeout)),(m=this.source)==null||m.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),h()},{once:!0})})}if(!this.isLive$.getValue()){let p=[(f=this.manifest.duration)!=null?f:0,...(0,Op.default)((0,Op.default)([...this.manifest.streams.audio,...this.manifest.streams.video],h=>h.representations),h=>{let m=[];return h.duration&&m.push(h.duration),rt(h.segmentReference)&&h.segmentReference.totalSegmentsDurationMs&&m.push(h.segmentReference.totalSegmentsDurationMs),m})];this.source.duration=Math.max(...p)/1e3}this.audioBufferManager&&Rn(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")})}.bind(this));this.tick=()=>{var t,i,r,a;if(!this.element||!this.videoBufferManager||((t=this.source)==null?void 0:t.readyState)!=="open")return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),(i=this.audioBufferManager)==null||i.maintain(e),(r=this.liveTextManager)==null||r.maintain(e),(this.videoBufferManager.gaps.length||(a=this.audioBufferManager)!=null&&a.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=Cp(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),n=>{this.error$.next({id:"GapWatchdog",category:Ht.WTF,message:"Error handling gaps",thrown:n})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.fetcher=new zu({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=wi.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,x({},e.tuning.dashCmafLive.lowLatency.bufferEstimator)),this.initTracerSubscription()}seekLive(e){return E(this,null,function*(){var r,a,n;cs(this.element);let t=this.liveStreamStatus$.getValue()!=="active"?Vp()-this.liveStreamEndTimestamp:0,i=this.normolizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=Ie(this.manifestUrlString,i,2),this.manifest=yield this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,yield(r=this.videoBufferManager)==null?void 0:r.seekLive(this.manifest.streams.video),yield(a=this.audioBufferManager)==null?void 0:a.seekLive(this.manifest.streams.audio),(n=this.liveTextManager)==null||n.seekLive(this.manifest.streams.text))})}initBuffer(){cs(this.element),this.state$.setState("running"),this.subscription.add(Sr(...xC.map(e=>Ai(this.element,e)),Ai(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:Ht.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(Ai(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(Ai(this.element,"waiting").subscribe(()=>{var t;this.element&&this.element.readyState===2&&!this.element.seeking&&He(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{var p,h,m,g,S,v,y,T,I,k,C;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=Vp(),n=100,o=(m=(h=this.videoBufferManager)==null?void 0:h.lastDataObtainedTimestamp)!=null?m:0;this.videoLastDataObtainedTimestamp$.next(o);let u=(S=(g=this.audioBufferManager)==null?void 0:g.lastDataObtainedTimestamp)!=null?S:0,l=(y=(v=this.videoBufferManager)==null?void 0:v.getForwardBufferDuration())!=null?y:0,d=(I=(T=this.audioBufferManager)==null?void 0:T.getForwardBufferDuration())!=null?I:0,c=l<n&&a-o>this.tuning.dash.crashOnStallTWithoutDataTimeout,f=this.audioBufferManager&&d<n&&a-u>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((c||f)&&i>this.tuning.dash.crashOnStallTWithoutDataTimeout||i>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${i} ms`);if(this.isLive$.getValue()&&i%2e3===0){let V=this.normolizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(V).catch($=>{this.error$.next({id:"stallIntervalCallback",category:Ht.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:$})}),r.liveLastOffset=V}else{let V=this.element.currentTime*1e3;(k=this.videoBufferManager)==null||k.maintain(V),(C=this.audioBufferManager)==null||C.maintain(V),r.position=V}this.tracer.log("stallIntervalCallback",kn(r))};(t=this.stallWatchdogSubscription)==null||t.unsubscribe(),this.stallWatchdogSubscription=Cp(50).subscribe(e,i=>{this.error$.next({id:"StallWatchdogCallback",category:Ht.NETWORK,message:"Can't restore DASH after stall.",thrown:i})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}switchRepresentation(e,t,i=!1){return E(this,null,function*(){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)})}seek(e,t){return E(this,null,function*(){var r,a,n,o,u;cs(this.element),cs(this.videoBufferManager);let i;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?i=e:i=Math.max((r=this.videoBufferManager.findSegmentStartTime(e))!=null?r:e,(n=(a=this.audioBufferManager)==null?void 0:a.findSegmentStartTime(e))!=null?n:e),this.warmUpMediaSourceIfNeeded(i),He(this.element.buffered,i)||(yield Promise.all([this.videoBufferManager.abort(),(o=this.audioBufferManager)==null?void 0:o.abort()])),!(ix(this.element)||ix(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),(u=this.audioBufferManager)==null||u.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",kn({requestedPosition:e,forcePrecise:t,position:i})))})}warmUpMediaSourceIfNeeded(e=(t=>(t=this.element)==null?void 0:t.currentTime)()){var i;Rn(this.element)&&Rn(this.source)&&Rn(e)&&((i=this.source)==null?void 0:i.readyState)==="ended"&&this.element.duration*1e3-e>this.tuning.dash.seekBiasInTheEnd&&this.bufferManagers.forEach(r=>r.warmUpMediaSource())}get isStreamEnded(){var e;return((e=this.source)==null?void 0:e.readyState)==="ended"}stop(){var e,t,i;this.tracer.log("stop"),(e=this.element)==null||e.querySelectorAll("source").forEach(r=>{URL.revokeObjectURL(r.src),r.remove()}),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(t=this.videoBufferManager)==null||t.destroy(),this.videoBufferManager=null,(i=this.audioBufferManager)==null||i.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){var e;return(e=this.manifest)==null?void 0:e.streams}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){var e;this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),((e=this.source)==null?void 0:e.readyState)==="open"&&Array.from(this.source.sourceBuffers).every(t=>!t.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=yC(this.tracer.error.bind(this.tracer));this.subscription.add(this.error$.subscribe(e("error")))}isManualDecreasePlaybackInLive(){if(!this.element||!this.isLive$.getValue())return!1;let e=1-this.element.playbackRate;return Number(e.toFixed(2))>Number(this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup.toFixed(2))}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}updateLive(){return E(this,null,function*(){var e,t;this.isUpdatingLive=!0,this.manifest=yield this.updateManifest(),this.manifest&&((e=this.bufferManagers)==null||e.forEach(i=>i.updateLive(this.manifest)),(t=this.liveTextManager)==null||t.updateLive(this.manifest)),this.isUpdatingLive=!1})}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getDebugBufferState();if(!e)return;let t=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),i={isJumpGapAfterSeekLive:this.isJumpGapAfterSeekLive,isActiveLowLatency:t,initialCurrentTime:this.element.currentTime};this.isJumpGapAfterSeekLive&&!t&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let r=this.element.currentTime*1e3,a=[],n=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let o of this.bufferManagers)for(let u of o.gaps)o.playingRepresentation$.getValue()===u.representation&&u.from-n<=r&&u.to+n>r&&(this.element.duration*1e3-u.to<this.tuning.endGapTolerance?a.push(1/0):a.push(u.to));if(a.length){let o=Math.max(...a)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,o===1/0?this.forceEnded$.next():(this.element.currentTime=o/1e3,i=B(x({},i),{gapEnds:a,jumpTo:o,resultCurrentTime:this.element.currentTime}),this.tracer.log("jumpGap",kn(i)))}}};var il=class{constructor(e,t){this.fov=e,this.orientation=t}};var rl=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/Ze(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=x({},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*Ze(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 ax=`attribute vec2 a_vertex;
|
|
125
125
|
attribute vec2 a_texel;
|
|
126
126
|
|
|
127
127
|
varying vec2 v_texel;
|
|
@@ -175,13 +175,13 @@ void main(void) {
|
|
|
175
175
|
// sample using new coordinates
|
|
176
176
|
gl_FragColor = texture2D(u_texture, tc);
|
|
177
177
|
}
|
|
178
|
-
`;var hs=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 il(this.params.fov,this.params.orientation),this.cameraRotationManager=new rl(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(ax,this.gl.VERTEX_SHADER),i=this.createShader(nx,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,i),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){let e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,i=1,r=this.frameHeight/(this.frameWidth/this.viewportWidth);return r>this.viewportHeight?t=this.viewportHeight/r:i=r/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-i,t,-i,t,i,-t,i]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){let e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,i=this.camera.fov.x/360/2,r=this.camera.fov.y/180/2,a=e-i,n=t-r,o=e+i,u=t-r,l=e+i,d=t+r,c=e-i,h=t+r;return[a,n,o,u,l,d,c,h]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){let e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}};import{isNullable as PC,now as Mn,once as RC,Subscription as kC,ValueSubject as _p,isNonNullable as MC,safeStorage as Fp,filterChanged as LC}from"@vkontakte/videoplayer-shared/es2015";var sl="stalls_manager_metrics",Np="stalls_manager_abr_params",ox="stalls_manager_default_tuning_abr_params",Up=class{constructor(){this.isSeeked$=new _p(!1);this.isBuffering$=new _p(!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 kC;this.severeStallOccurred$=new _p(!1)}init(e){this.currentStallDuration$=e.currentStallDuration$,this.videoLastDataObtainedTimestamp$=e.videoLastDataObtainedTimestamp$,this.throughput$=e.throughput$,this.rtt$=e.rtt$,this.tuning=e.tuning,this.abrParams=e.abrParams,this.resetStoredAbrParamsIfNeeded(),this.subscribe(e)}get videoMaxQualityLimit(){return this.maxQualityLimit}get predictedThroughput(){return this.predictedThroughputWithoutData}get abrTuningParams(){let e=this.tuning.enabled?this.getStoredData(Np):{};return x(x({},this.abrParams),e)}set lastVideoTrackSelected(e){var t;((t=this.lastUniqueVideoTrackSelected)==null?void 0:t.id)!==e.id&&(this.lastUniqueVideoTrackSelected=e,this.lastUniqueVideoTrackSelectedTimestamp=Mn(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe(),this.currentStallDuration$.getValue()!==0&&this.updateStallData();let e=(Mn()-this.providerStartWatchingTimestamp-this.sumStallsDuration)/1e3,t=this.sumStallsDuration;this.addStallInfoToHistory(e,t),this.updateStoredAbrParams()}resetStoredAbrParamsIfNeeded(){let{bitrateFactorAtEmptyBuffer:e,bitrateFactorAtFullBuffer:t,containerSizeFactor:i}=x({},this.getStoredData(ox)),{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:a,containerSizeFactor:n}=x({},this.abrParams);this.tuning.enabled&&e===r&&t===a&&i===n||(this.removeStoredData(Np),this.setStoredData(ox,{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:a,containerSizeFactor:n}))}updateStoredAbrParams(){let e=[],t=this.getStoredData(sl,"[]");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(sl,[]),this.setStoredData(Np,r)}calculateOptimalAbrParams(e,t){let{targetStallsDurationPerTvt:i,deviationStallsDurationPerTvt:r,criticalStallsDurationPerTvt:a,abrAdjustingSpeed:n,significantTvt:o,stallsMetricsHistoryLength:u}=this.tuning,l=n*Math.min(t/(o*u),1),d=this.abrTuningParams;return e<i-r?d={bitrateFactorAtEmptyBuffer:Math.max(d.bitrateFactorAtEmptyBuffer-l,this.abrParams.minBitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.max(d.bitrateFactorAtFullBuffer-l,this.abrParams.minBitrateFactorAtFullBuffer),containerSizeFactor:Math.min(d.containerSizeFactor+l,this.abrParams.maxContainerSizeFactor)}:e>i+r&&(d={bitrateFactorAtEmptyBuffer:Math.min(d.bitrateFactorAtEmptyBuffer+l,this.abrParams.maxBitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.min(d.bitrateFactorAtFullBuffer+l,this.abrParams.maxBitrateFactorAtFullBuffer),containerSizeFactor:Math.max(d.containerSizeFactor-l,this.abrParams.minContainerSizeFactor)}),e>a&&(d={bitrateFactorAtEmptyBuffer:Math.max(d.bitrateFactorAtEmptyBuffer,this.abrParams.bitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.max(d.bitrateFactorAtFullBuffer,this.abrParams.bitrateFactorAtFullBuffer),containerSizeFactor:Math.min(d.containerSizeFactor,this.abrParams.containerSizeFactor)}),d}getStoredData(e,t="{}"){var i;return JSON.parse((i=Fp.get(e))!=null?i:t)}setStoredData(e,t){Fp.set(e,JSON.stringify(t))}removeStoredData(e){Fp.remove(e)}addStallInfoToHistory(e,t){if(e<this.tuning.minTvtToBeCounted||e>this.tuning.maxTvtToBeCounted||e*1e3<t)return;let i=this.getStoredData(sl,"[]"),r=t/e,a=i.length?Ei(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(sl,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(RC()).subscribe(t=>this.providerStartWatchingTimestamp=Mn())),this.subscription.add(this.currentStallDuration$.pipe(LC()).subscribe(t=>{let{stallDurationNoDataBeforeQualityDecrease:i,stallCountBeforeQualityDecrease:r,resetQualityRestrictionTimeout:a,ignoreStallsOnSeek:n}=this.tuning;if(PC(this.lastUniqueVideoTrackSelected)||n&&this.isSeeked$.getValue())return;let o=this.rtt$.getValue(),u=this.throughput$.getValue(),l=this.videoLastDataObtainedTimestamp$.getValue(),d=Mn(),c=r&&this.currentStallsCount>=r,h=i&&d-this.lastUniqueVideoTrackSelectedTimestamp>=i+o&&d-l>=i+o&&t>=i;(c||h)&&(this.severeStallOccurred$.next(!0),window.clearTimeout(this.qualityRestrictionTimer),this.maxQualityLimit=this.lastUniqueVideoTrackSelected.quality,MC(this.lastUniqueVideoTrackSelected.bitrate)&&u>this.lastUniqueVideoTrackSelected.bitrate&&(this.predictedThroughputWithoutData=this.lastUniqueVideoTrackSelected.bitrate)),!t&&Mn()-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}))}},al=Up;import{combine as BC,map as $C,observeElementSize as DC,Subscription as CC,ValueSubject as qp,noop as VC}from"@vkontakte/videoplayer-shared/es2015";var nl=class{constructor(){this.subscription=new CC;this.pipSize$=new qp(void 0);this.videoSize$=new qp(void 0);this.elementSize$=new qp(void 0);this.pictureInPictureWindowRemoveEventListener=VC}connect({observableVideo:e,video:t}){let i=r=>{let a=r.target;this.pipSize$.next({width:a.width,height:a.height})};this.subscription.add(DC(t).subscribe(this.videoSize$)).add(e.enterPip$.subscribe(({pictureInPictureWindow:r})=>{this.pipSize$.next({width:r.width,height:r.height}),r.addEventListener("resize",i),this.pictureInPictureWindowRemoveEventListener=()=>{r.removeEventListener("resize",i)}})).add(e.leavePip$.subscribe(()=>{this.pictureInPictureWindowRemoveEventListener()})).add(BC({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe($C(({videoSize:r,inPip: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 vr=class{constructor(e){this.subscription=new qC;this.videoState=new Y("stopped");this.droppedFramesManager=new Zr;this.stallsManager=new al;this.elementSizeManager=new nl;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new _i;this.audioTrackSwitchHistory=new _i;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(r.state==="requested"&&(i==null?void 0:i.to)!=="paused"&&e!=="stopped"&&t!=="stopped"&&this.seek(r.position,r.forcePrecise),t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),D(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"),D(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="ready"&&D(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"&&D(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&D(this.params.desiredState.playbackState,"paused");return;default:return _C(e)}}};this.init3DScene=e=>{var i,r,a;if(this.scene3D)return;this.scene3D=new hs(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 Rt(e.source.url),this.params=e,this.video=nt(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(je(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 tl({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params,i=lt(this.video);this.subscription.add(()=>i.destroy());let r=this.constructor.name,a=o=>{e.error$.next({id:r,category:ux.WTF,message:`${r} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:i,genericErrorListener:a,connect:(o,u)=>this.subscription.add(o.subscribe(u,a))}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:a}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(jp(l=>!!l.length),cx()).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(Hp(l=>l.to.state!=="none"),ol());this.stallsManager.init({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$,videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,tuning:this.params.tuning.stallsManager,abrParams:this.params.tuning.autoTrackSelection,isBuffering$:i.isBuffering$,looped$:i.looped$,playing$:i.playing$}),a(i.ended$,e.endedEvent$),a(i.looped$,e.loopedEvent$),a(i.error$,e.error$),a(i.isBuffering$,e.isBuffering$),a(i.currentBuffer$,e.currentBuffer$),a(i.playing$,e.firstFrameEvent$),a(i.canplay$,e.canplay$),a(i.inPiP$,e.inPiP$),a(i.inFullscreen$,e.inFullscreen$),a(i.loadedMetadata$,e.loadedMetadataEvent$),a(this.player.error$,e.error$),a(this.player.fetcherRecoverableError$,e.fetcherRecoverableError$),a(this.player.fetcherError$,e.fetcherError$),a(this.player.lastConnectionType$,e.httpConnectionType$),a(this.player.lastConnectionReused$,e.httpConnectionReused$),a(this.player.isLive$,e.isLive$),a(this.player.lastRequestFirstBytes$.pipe(jp(lx),cx()),e.firstBytesEvent$),a(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),a(this.videoState.stateChangeEnded$.pipe(Hp(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(Kt(this.video,t.isLooped,r)),this.subscription.add(ut(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Pt(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),a(kt(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),D(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),D(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:l})=>{if(l==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let d=this.player.getStreams();if(FC(d,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let h=[];for(let p of d.audio){h.push(Ip(p));let f=[];for(let m of p.representations){let g=VI(m);f.push(g),this.audioTracksMap.set(g,{stream:p,representation:m})}this.audioStreamsMap.set(p,f)}this.params.output.availableAudioStreams$.next(h)}let c=[];for(let h of d.video){c.push(xp(h));let p=[];for(let f of h.representations){let m=CI(B(x({},f),{streamId:h.id}));m&&(p.push(m),this.videoTracksMap.set(m,{stream:h,representation:f}))}this.videoStreamsMap.set(h,p)}this.params.output.availableVideoStreams$.next(c);for(let h of d.text)for(let p of h.representations){let f=OI(h,p);this.textTracksMap.set(f,{stream:h,representation:p})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else l==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r)),this.subscription.add(ul(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$,UC(this.video,"progress")).pipe(jp(()=>this.videoTracksMap.size>0)).subscribe(()=>E(this,null,function*(){let l=this.player.state$.getState(),d=this.player.state$.getTransition();if(!(0,dx.default)(["manifest_ready","running"],l)||d)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let c=this.selectVideoAudioRepresentations();if(!c)return;let[h,p]=c,f=[...this.videoTracksMap.keys()].find(g=>{var S;return((S=this.videoTracksMap.get(g))==null?void 0:S.representation.id)===h.id});lx(f)&&(this.stallsManager.lastVideoTrackSelected=f);let m=this.params.desiredState.autoVideoTrackLimits.getTransition();if(m&&this.params.output.autoVideoTrackLimits$.next(m.to),l==="manifest_ready")yield this.player.initRepresentations(h.id,p==null?void 0:p.id,this.params.sourceHls);else if(yield this.player.switchRepresentation("video",h.id),p){let g=!!t.audioStream.getTransition();yield this.player.switchRepresentation("audio",p.id,g)}}),r)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:l})=>{this.scene3D&&l&&this.scene3D.pointCameraTo(l.x,l.y)})),this.subscription.add(this.elementSizeManager.subscribe(l=>{this.scene3D&&l&&this.scene3D.setViewportSize(l.width,l.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(ol()).subscribe(l=>{let d=[...this.videoTracksMap.entries()].find(([,{representation:f}])=>f.id===l);if(!d){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[c,{stream:h}]=d,p=this.params.desiredState.videoStream.getTransition();p&&p.to&&p.to.id===h.id&&this.params.desiredState.videoStream.setState(p.to),e.currentVideoTrack$.next(c),e.currentVideoStream$.next(xp(h))},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(ol()).subscribe(l=>{let d=[...this.audioTracksMap.entries()].find(([,{representation:f}])=>f.id===l);if(!d){e.currentAudioStream$.next(void 0);return}let[c,{stream:h}]=d,p=this.params.desiredState.audioStream.getTransition();p&&p.to&&p.to.id===h.id&&this.params.desiredState.audioStream.setState(p.to),e.currentAudioStream$.next(Ip(h))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(l=>{var d,c;if(l!=null&&l.is3dVideo&&((d=this.params.tuning.spherical)!=null&&d.enabled))try{this.init3DScene(l),e.is3DVideo$.next(!0)}catch(h){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${h}`})}else this.destroy3DScene(),(c=this.params.tuning.spherical)!=null&&c.enabled&&e.is3DVideo$.next(!1)},r)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,r)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,r)),this.textTracksManager.connect(this.video,t,e);let o=t.playbackState.stateChangeStarted$.pipe(Hp(({to:l})=>l==="ready"),ol());this.subscription.add(ul(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,zp(["init"])).subscribe(()=>{let l=t.autoVideoTrackSwitching.getState(),c=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:l?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(c)})),this.subscription.add(ul(o,this.player.state$.stateChangeEnded$,zp(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let u=ul(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,zp(["init"])).pipe(NC(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){var w,F,M,j,N,K,P,L,k,A,O,de,Fe;if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?Va:Ca,t=this.params.tuning.useNewAutoSelectVideoTrack?Mu:ku,i=this.params.tuning.useNewAutoSelectVideoTrack?Zt:Ru,{desiredState:r,output:a}=this.params,n=r.autoVideoTrackSwitching.getState(),o=(w=r.videoTrack.getState())==null?void 0:w.id,l=[...this.videoTracksMap.keys()].find(({id:ue})=>ue===o),d=a.currentVideoTrack$.getValue(),c=((j=(M=r.videoStream.getState())!=null?M:l&&((F=this.videoTracksMap.get(l))==null?void 0:F.stream))!=null?j:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!c)return;let h=[...this.videoStreamsMap.keys()].find(({id:ue})=>ue===c.id),p=h&&this.videoStreamsMap.get(h);if(!p)return;let f=Oe(this.video.buffered,this.video.currentTime*1e3),m;this.player.isActiveLive$.getValue()?m=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?m=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:m=n?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let g=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,S=Math.min(f/Math.min(m,g||1/0),1),v=(N=r.audioStream.getState())!=null?N:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,y=(K=[...this.audioStreamsMap.keys()].find(({id:ue})=>ue===(v==null?void 0:v.id)))!=null?K:this.audioStreamsMap.keys().next().value,T=0;if(y){if(l&&!n){let ue=e(l,p,(P=this.audioStreamsMap.get(y))!=null?P:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);T=Math.max(T,(L=ue==null?void 0:ue.bitrate)!=null?L:-1/0)}if(d){let ue=e(d,p,(k=this.audioStreamsMap.get(y))!=null?k:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);T=Math.max(T,(A=ue==null?void 0:ue.bitrate)!=null?A:-1/0)}}let I=i(p,{container:this.elementSizeManager.getValue(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.stallsManager.abrTuningParams,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:T,forwardBufferHealth:S,current:d,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,stallsVideoMaxQualityLimit:this.stallsManager.videoMaxQualityLimit,stallsPredictedThroughput:this.stallsManager.predictedThroughput,abrLogger:this.params.dependencies.abrLogger}),R=n?I!=null?I:l:l!=null?l:I,C=y&&t(R,p,(O=this.audioStreamsMap.get(y))!=null?O:[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.stallsManager.abrTuningParams,forwardBufferHealth:S,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),V=(de=this.videoTracksMap.get(R))==null?void 0:de.representation,$=C&&((Fe=this.audioTracksMap.get(C))==null?void 0:Fe.representation);if(V&&$)return[V,$];if(V&&!$&&this.audioTracksMap.size===0)return[V,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){ct(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),D(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:ux.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),ot(this.video),this.tracer.end()}};var Ln=class extends vr{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};import{combine as Qp,merge as px,filter as hx,filterChanged as jC,isNullable as Gp,map as fx,ValueSubject as Wp,isNonNullable as HC}from"@vkontakte/videoplayer-shared/es2015";var Bn=class extends vr{constructor(e){super(e),this.textTracksManager.destroy()}subscribe(){super.subscribe();let e=-1,{output:t,observableVideo:i,desiredState:r,connect:a}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),a(i.timeUpdate$,t.liveBufferTime$),a(this.player.liveSeekableDuration$,t.duration$),a(this.player.liveLatency$,t.liveLatency$);let n=new Wp(1);a(i.playbackRateState$,n),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(r.isLowLatency.stateChangeEnded$.pipe(fx(o=>o.to)).subscribe(this.player.isLowLatency$)).add(Qp({liveBufferTime:t.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(fx(({liveBufferTime:o,liveAvailabilityStartTime:u})=>o&&u?o+u:void 0)).subscribe(t.liveTime$)).add(this.player.liveStreamStatus$.pipe(hx(o=>HC(o))).subscribe(o=>t.isLiveEnded$.next(o!=="active"&&t.position$.getValue()===0))).add(Qp({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:px(i.playbackRateState$,new Wp(1))}).pipe(hx(({liveStreamStatus:o,liveDuration:u})=>o==="active"&&!!u)).subscribe(({liveDuration:o,playbackRate:u})=>{let l=t.liveBufferTime$.getValue(),d=t.position$.getValue(),{playbackCatchupSpeedup:c}=this.params.tuning.dashCmafLive.lowLatency;d||u<1-c||this.video.paused||Gp(l)||(e=o-l)})).add(Qp({time:t.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:px(i.playbackRateState$,new Wp(1))}).pipe(jC((o,u)=>this.player.liveStreamStatus$.getValue()==="active"?o.liveDuration===u.liveDuration:o.time===u.time)).subscribe(({time:o,liveDuration:u,playbackRate:l})=>{let d=t.position$.getValue(),{playbackCatchupSpeedup:c}=this.params.tuning.dashCmafLive.lowLatency;if(!d&&!this.video.paused&&l>=1-c||Gp(o)||Gp(u))return;let h=-1*(u-o-e);t.position$.next(Math.min(h,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(o=>{if(o){let u=_I(o);this.params.output.availableTextTracks$.next([u])}}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=Math.trunc(t/1e3<=Math.abs(this.params.output.duration$.getValue())?t:0);this.player.seekLive(i).then(()=>{this.params.output.position$.next(e/1e3)})}};import{assertNever as VV,assertNonNullable as OV,debounce as _V,ErrorCategory as Qx,filter as bh,filterChanged as yl,fromEvent as FV,isNonNullable as Gx,map as gh,merge as Tl,observableFrom as Sh,once as Wx,Subscription as NV}from"@vkontakte/videoplayer-shared/es2015";var fh=H(za(),1);import{abortable as ch,assertNonNullable as Ss,combine as vs,ErrorCategory as Qt,filter as bl,filterChanged as po,flattenObject as ho,fromEvent as ti,getTraceSubscriptionMethod as AV,interval as dh,isNonNullable as fo,isNullable as Hx,map as ys,merge as wr,now as ph,Subject as gl,Subscription as hh,tap as PV,throttle as zx,ValueSubject as Se}from"@vkontakte/videoplayer-shared/es2015";var pl=H(It(),1),bs=H(qt(),1),hl=H(za(),1);var Fx=H(ou(),1);import{assertNever as zC,ErrorCategory as mx,Subject as bx}from"@vkontakte/videoplayer-shared/es2015";var QC=18,gx=!1;try{gx=Q.browser.isSafari&&!!Q.browser.safariVersion&&Q.browser.safariVersion<=QC}catch(s){console.error(s)}var Yp=class{constructor(e){this.bufferFull$=new bx;this.error$=new bx;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:mx.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}append(e,t){return E(this,null,function*(){return t&&t.aborted?!1:new Promise(i=>{let r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})})}remove(e,t,i){return E(this,null,function*(){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()})})}abort(e){return E(this,null,function*(){return new Promise(t=>{let i,r=a=>{this.abortRequested=!1,t(a)};gx&&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:mx.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:zC(t)}}},Sx=Yp;import{abortable as Hi,assertNonNullable as pt,ErrorCategory as xr,fromEvent as nh,getExponentialDelay as oh,isNonNullable as ms,isNullable as Qe,now as dl,once as gV,Subject as SV,Subscription as vV,ValueSubject as Er}from"@vkontakte/videoplayer-shared/es2015";var ie=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let i=this.readUint32();this.type=this.readString(4),i>e.byteLength-e.byteOffset&&(this.size32=NaN);let r=this.size32?this.size32-8:void 0,a=e.byteOffset+this.cursor;this.size64=0,this.usertype=0,this.content=new DataView(e.buffer,a,r)}get id(){return this.type}get size(){return this.size32}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t="ascii"){let r=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,r}readUint8(){let e=this.source.getUint8(this.cursor);return this.cursor+=1,e}readUint16(){let e=this.source.getUint16(this.cursor);return this.cursor+=2,e}readUint32(){let e=this.source.getUint32(this.cursor);return this.cursor+=4,e}readUint64(){let e=this.source.getBigInt64(this.cursor);return this.cursor+=8,e}};var fs=class extends ie{};var $n=class extends ie{constructor(t,i){super(t,i);this.ondemandPrefix="ondemandlivejson";this.ondemandDataReceivedKey="t-in";this.ondemandDataPreparedKey="t-out";let r=this.content.byteOffset,a=r+this.content.byteLength,n=new TextDecoder("ascii").decode(this.content.buffer.slice(r,a)).split(this.ondemandPrefix)[1],o=JSON.parse(n);this.serverDataReceivedTimestamp=o[this.ondemandDataReceivedKey],this.serverDataPreparedTime=o[this.ondemandDataPreparedKey]}};var Dn=class extends ie{constructor(e,t){super(e,t),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let i=this.size-this.cursor;for(;i;){let r=this.readString(4);this.compatibleBrands.push(r),i-=4}}};var Cn=class extends ie{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var he=class extends ie{constructor(e,t){super(e,t);let i=this.readUint32();this.version=i>>>24,this.flags=i&16777215}};var Vn=class extends he{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.timescale=this.readUint32(),this.duration=this.readUint32(),this.rate=this.readUint32(),this.volume=this.readUint16()}};var On=class extends ie{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var _n=class extends ie{constructor(e,t){super(e,t),this.data=this.content}};var yr=class extends he{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e,t){super(e,t),this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let i=0;i<this.referenceCount;i++){let r=this.readUint32(),a=r>>>31,n=r<<1>>>1,o=this.readUint32();r=this.readUint32();let u=r>>>28,l=r<<3>>>3;this.segments.push({referenceType:a,referencedSize:n,subsegmentDuration:o,SAPType:u,SAPDeltaTime:l})}}};var Fn=class extends ie{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Nn=class extends ie{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Un=class extends he{constructor(e,t){switch(super(e,t),this.readUint8()){case 0:this.stereoMode=0;break;case 1:this.stereoMode=1;break;case 2:this.stereoMode=2;break;case 3:this.stereoMode=3;break;case 4:this.stereoMode=4;break}this.cursor+=1}};var qn=class extends he{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var jn=class extends he{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var Hn=class extends ie{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var zn=class extends he{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 Qn=class extends ie{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Gn=class extends ie{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Wn=class extends he{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var Yn=class extends ie{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Kn=class extends he{constructor(e,t){super(e,t),this.trackId=this.readUint32(),this.flags&1&&(this.baseDataOffset=this.readUint64()),this.flags&2&&(this.sampleDescriptionIndex=this.readUint32()),this.flags&8&&(this.defaultSampleDuration=this.readUint32()),this.flags&16&&(this.defaultSampleSize=this.readUint32()),this.flags&32&&(this.defaultSampleFlags=this.readUint32())}};var Xn=class extends he{constructor(t,i){super(t,i);this.baseMediaDecodeTime32=0;this.baseMediaDecodeTime64=BigInt(0);this.version===1?this.baseMediaDecodeTime64=this.readUint64():this.baseMediaDecodeTime32=this.readUint32()}get baseMediaDecodeTime(){return this.version===1?this.baseMediaDecodeTime64:this.baseMediaDecodeTime32}};var Jn=class extends he{constructor(t,i){super(t,i);this.sampleDuration=[];this.sampleSize=[];this.sampleFlags=[];this.sampleCompositionTimeOffset=[];this.optionalFields=0;this.sampleCount=this.readUint32(),this.flags&1&&(this.dataOffset=this.readUint32()),this.flags&4&&(this.firstSampleFlags=this.readUint32());for(let r=0;r<this.sampleCount;r++)this.flags&256&&this.sampleDuration.push(this.readUint32()),this.flags&512&&this.sampleSize.push(this.readUint32()),this.flags&1024&&this.sampleFlags.push(this.readUint32()),this.flags&2048&&this.sampleCompositionTimeOffset.push(this.readUint32())}};var Zn=class extends ie{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var eo=class extends he{constructor(e,t){super(e,t),this.entryCount=this.readUint32(),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+8,this.content.byteLength-8))}};var to=class extends ie{constructor(e,t){super(e,t),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+78,this.content.byteLength-78))}};var WC={ftyp:Dn,moov:Cn,mvhd:Vn,moof:On,mdat:_n,sidx:yr,trak:Fn,mdia:Hn,mfhd:Wn,tkhd:zn,traf:Yn,tfhd:Kn,tfdt:Xn,trun:Jn,minf:Qn,sv3d:Nn,st3d:Un,prhd:qn,proj:Gn,equi:jn,uuid:$n,stbl:Zn,stsd:eo,avc1:to,unknown:fs},Pi=class s{constructor(e={}){this.options=x({offset:0},e)}parse(e){let t=[],i=this.options.offset;for(;i<e.byteLength;)try{let a=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+i+4,4)),n=this.createBox(a,new DataView(e.buffer,e.byteOffset+i,e.byteLength-i));if(!n.size)break;t.push(n),i+=n.size}catch(r){break}return t}createBox(e,t){let i=WC[e];return i?new i(t,new s):new fs(t,new s)}};var ji=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{var i,r,a;(a=(i=this.index)[r=t.type])!=null||(i[r]=[]),this.index[t.type].push(t),t.children.length>0&&this.indexBoxLevel(t.children)})}find(e){return this.index[e]&&this.index[e][0]?this.index[e][0]:null}findAll(e){return this.index[e]||[]}};var KC=new TextDecoder("ascii"),XC=s=>KC.decode(new DataView(s.buffer,s.byteOffset+4,4))==="ftyp",JC=s=>{let e=new yr(s,new Pi),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})},ZC=(s,e)=>{let i=new Pi().parse(s),r=new ji(i),a=r.findAll("moof"),n=e?r.findAll("uuid"):r.findAll("mdat");if(!(n.length&&a.length))return null;let o=a[0],u=n[n.length-1],l=o.source.byteOffset,c=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(s.buffer,l,c)},eV=s=>{let t=new Pi().parse(s),i=new ji(t),r={},a=i.findAll("uuid");return a.length?a[a.length-1]:r},tV=s=>{var r;let t=new Pi().parse(s);return(r=new ji(t).find("sidx"))==null?void 0:r.timescale},iV=(s,e)=>{let i=new Pi().parse(s),a=new ji(i).findAll("traf"),n=a[a.length-1].children.find(c=>c.type==="tfhd"),o=a[a.length-1].children.find(c=>c.type==="tfdt"),u=a[a.length-1].children.find(c=>c.type==="trun"),l=0;return u.sampleDuration.length?l=u.sampleDuration.reduce((c,h)=>c+h,0):l=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+l)/e*1e3},rV=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 Pi().parse(s),r=new ji(i);if(r.find("sv3d")){e.is3dVideo=!0;let n=r.find("st3d");n&&(e.stereoMode=n.stereoMode);let o=r.find("prhd");o&&(e.projectionData.pose.yaw=o.poseYawDegrees,e.projectionData.pose.pitch=o.posePitchDegrees,e.projectionData.pose.roll=o.poseRollDegrees);let u=r.find("equi");u&&(e.projectionData.bounds.top=u.projectionBoundsTop,e.projectionData.bounds.right=u.projectionBoundsRight,e.projectionData.bounds.bottom=u.projectionBoundsBottom,e.projectionData.bounds.left=u.projectionBoundsLeft)}return e},vx={validateData:XC,parseInit:rV,getIndexRange:()=>{},parseSegments:JC,parseFeedableSegmentChunk:ZC,getChunkEndTime:iV,getServerLatencyTimestamps:eV,getTimescaleFromIndex:tV};var ro=H(It(),1);import{assertNonNullable as Xp,isNonNullable as xx,isNullable as aV}from"@vkontakte/videoplayer-shared/es2015";import{assertNever as sV}from"@vkontakte/videoplayer-shared/es2015";var yx={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"}},Tx=s=>{let e=s.getUint8(0),t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);let i=io(s,t),r=i in yx,a=r?yx[i].type:"binary",n=s.getUint8(t),o=0;n&128?o=1:n&64?o=2:n&32?o=3:n&16?o=4:n&8?o=5:n&4?o=6:n&2?o=7:n&1&&(o=8);let u=new DataView(s.buffer,s.byteOffset+t+1,o-1),l=n&255>>o,d=io(u),c=l*Ze(2,(o-1)*8)+d,h=t+o,p;return h+c>s.byteLength?p=new DataView(s.buffer,s.byteOffset+h):p=new DataView(s.buffer,s.byteOffset+h,c),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:a,tagHeaderSize:h,tagSize:h+c,value:p,valueSize:c}},io=(s,e=s.byteLength)=>{switch(e){case 1:return s.getUint8(0);case 2:return s.getUint16(0);case 3:return s.getUint8(0)*Ze(2,16)+s.getUint16(1);case 4:return s.getUint32(0);case 5:return s.getUint8(0)*Ze(2,32)+s.getUint32(1);case 6:return s.getUint16(0)*Ze(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},zt=(s,e)=>{switch(e){case"int":return s.getInt8(0);case"uint":return io(s);case"float":return s.byteLength===4?s.getFloat32(0):s.getFloat64(0);case"string":return new TextDecoder("ascii").decode(s);case"utf8":return new TextDecoder("utf-8").decode(s);case"date":return new Date(Date.UTC(2001,0)+s.getInt8(0)).getTime();case"master":return s;case"binary":return s;default:sV(e)}},Tr=(s,e)=>{let t=0;for(;t<s.byteLength;){let i=new DataView(s.buffer,s.byteOffset+t),r=Tx(i);if(!e(r))return;r.type==="master"&&Tr(r.value,e),t=r.value.byteOffset-s.byteOffset+r.valueSize}},Ix=s=>{if(s.getUint32(0)!==440786851)return!1;let e,t,i,r=Tx(s);return Tr(r.value,({tag:a,type:n,value:o})=>(a===17143?e=zt(o,n):a===17026?t=zt(o,n):a===17029&&(i=zt(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)};var Ex=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],nV=[231,22612,22743,167,171,163,160,175],oV=s=>{let e,t,i,r,a=!1,n=!1,o=!1,u,l,d=!1,c=0;return Tr(s,({tag:h,type:p,value:f,valueSize:m})=>{if(h===21419){let g=zt(f,p);l=io(g)}else h!==21420&&(l=void 0);return h===408125543?(e=f.byteOffset,t=f.byteOffset+m):h===357149030?a=!0:h===290298740?n=!0:h===2807729?i=zt(f,p):h===17545?r=zt(f,p):h===21420&&l===475249515?u=zt(f,p):h===374648427?Tr(f,({tag:g,type:S,value:v})=>g===30321?(d=zt(v,S)===1,!1):!0):a&&n&&(0,ro.default)(Ex,h)&&(o=!0),!o}),Xp(e,"Failed to parse webm Segment start"),Xp(t,"Failed to parse webm Segment end"),Xp(r,"Failed to parse webm Segment duration"),i=i!=null?i:1e6,{segmentStart:Math.round(e/1e9*i*1e3),segmentEnd:Math.round(t/1e9*i*1e3),timeScale:i,segmentDuration:Math.round(r/1e9*i*1e3),cuesSeekPosition:u,is3dVideo:d,stereoMode:c,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},uV=s=>{if(aV(s.cuesSeekPosition))return;let e=s.segmentStart+s.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},lV=(s,e)=>{let t=!1,i=!1,r=o=>xx(o.time)&&xx(o.position),a=[],n;return Tr(s,({tag:o,type:u,value:l})=>{switch(o){case 475249515:t=!0;break;case 187:n&&r(n)&&a.push(n),n={};break;case 179:n&&(n.time=zt(l,u));break;case 183:break;case 241:n&&(n.position=zt(l,u));break;default:t&&(0,ro.default)(Ex,o)&&(i=!0)}return!(t&&i)}),n&&r(n)&&a.push(n),a.map((o,u)=>{let{time:l,position:d}=o,c=a[u+1];return{status:"none",time:{from:l,to:c?c.time:e.segmentDuration},byte:{from:e.segmentStart+d,to:c?e.segmentStart+c.position-1:e.segmentEnd-1}}})},cV=s=>{let e=0,t=!1;try{Tr(s,i=>i.tag===524531317?i.tagSize<=s.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):(0,ro.default)(nV,i.tag)?(e+i.tagSize<=s.byteLength&&(e+=i.tagSize,t||(t=(0,ro.default)([163,160,175],i.tag))),!0):!1)}catch(i){}return e>0&&e<=s.byteLength&&t?new DataView(s.buffer,s.byteOffset,e):null},wx={validateData:Ix,parseInit:oV,getIndexRange:uV,parseSegments:lV,parseFeedableSegmentChunk:cV};var so=s=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(s);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return wx;case"mp4":return vx}}throw new ReferenceError(`Unsupported mime type ${s}`)};var rh=H(Sp(),1),Cx=H(sr(),1),Vx=H(vp(),1),Ox=H(qt(),1),sh=H(pr(),1);import{isNonNullable as fV,isNullable as $x}from"@vkontakte/videoplayer-shared/es2015";var Ax=s=>{var e;try{let t=dV(),i=s.match(t),{groups:r}=i!=null?i:{};if(r){let a={};if(r.extensions){let u=r.extensions.toLowerCase().match(/(?:[0-9a-wy-z](?:-[a-z0-9]{2,8})+)/g);Array.from(u||[]).forEach(l=>{a[l[0]]=l.slice(2)})}let n=(e=r.variants)==null?void 0:e.split(/-/).filter(u=>u!==""),o={extlang:r.extlang,langtag:r.langtag,language:r.language,privateuse:r.privateuse||r.privateuse2,region:r.region,script:r.script,extensions:a,variants:n};return Object.keys(o).forEach(u=>{let l=o[u];(typeof l=="undefined"||l==="")&&delete o[u]}),o}return null}catch(t){return null}};function dV(){let s="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",d=`^(?:(?<langtag>${`
|
|
178
|
+
`;var hs=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 il(this.params.fov,this.params.orientation),this.cameraRotationManager=new rl(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(ax,this.gl.VERTEX_SHADER),i=this.createShader(nx,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,i),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){let e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,i=1,r=this.frameHeight/(this.frameWidth/this.viewportWidth);return r>this.viewportHeight?t=this.viewportHeight/r:i=r/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-i,t,-i,t,i,-t,i]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){let e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,i=this.camera.fov.x/360/2,r=this.camera.fov.y/180/2,a=e-i,n=t-r,o=e+i,u=t-r,l=e+i,d=t+r,c=e-i,f=t+r;return[a,n,o,u,l,d,c,f]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){let e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}};import{isNullable as PC,now as Mn,once as kC,Subscription as RC,ValueSubject as _p,isNonNullable as MC,safeStorage as Fp,filterChanged as LC}from"@vkontakte/videoplayer-shared/es2015";var sl="stalls_manager_metrics",Np="stalls_manager_abr_params",ox="stalls_manager_default_tuning_abr_params",Up=class{constructor(){this.isSeeked$=new _p(!1);this.isBuffering$=new _p(!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 RC;this.severeStallOccurred$=new _p(!1)}init(e){this.currentStallDuration$=e.currentStallDuration$,this.videoLastDataObtainedTimestamp$=e.videoLastDataObtainedTimestamp$,this.throughput$=e.throughput$,this.rtt$=e.rtt$,this.tuning=e.tuning,this.abrParams=e.abrParams,this.resetStoredAbrParamsIfNeeded(),this.subscribe(e)}get videoMaxQualityLimit(){return this.maxQualityLimit}get predictedThroughput(){return this.predictedThroughputWithoutData}get abrTuningParams(){let e=this.tuning.enabled?this.getStoredData(Np):{};return x(x({},this.abrParams),e)}set lastVideoTrackSelected(e){var t;((t=this.lastUniqueVideoTrackSelected)==null?void 0:t.id)!==e.id&&(this.lastUniqueVideoTrackSelected=e,this.lastUniqueVideoTrackSelectedTimestamp=Mn(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe(),this.currentStallDuration$.getValue()!==0&&this.updateStallData();let e=(Mn()-this.providerStartWatchingTimestamp-this.sumStallsDuration)/1e3,t=this.sumStallsDuration;this.addStallInfoToHistory(e,t),this.updateStoredAbrParams()}resetStoredAbrParamsIfNeeded(){let{bitrateFactorAtEmptyBuffer:e,bitrateFactorAtFullBuffer:t,containerSizeFactor:i}=x({},this.getStoredData(ox)),{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:a,containerSizeFactor:n}=x({},this.abrParams);this.tuning.enabled&&e===r&&t===a&&i===n||(this.removeStoredData(Np),this.setStoredData(ox,{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:a,containerSizeFactor:n}))}updateStoredAbrParams(){let e=[],t=this.getStoredData(sl,"[]");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(sl,[]),this.setStoredData(Np,r)}calculateOptimalAbrParams(e,t){let{targetStallsDurationPerTvt:i,deviationStallsDurationPerTvt:r,criticalStallsDurationPerTvt:a,abrAdjustingSpeed:n,significantTvt:o,stallsMetricsHistoryLength:u}=this.tuning,l=n*Math.min(t/(o*u),1),d=this.abrTuningParams;return e<i-r?d={bitrateFactorAtEmptyBuffer:Math.max(d.bitrateFactorAtEmptyBuffer-l,this.abrParams.minBitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.max(d.bitrateFactorAtFullBuffer-l,this.abrParams.minBitrateFactorAtFullBuffer),containerSizeFactor:Math.min(d.containerSizeFactor+l,this.abrParams.maxContainerSizeFactor)}:e>i+r&&(d={bitrateFactorAtEmptyBuffer:Math.min(d.bitrateFactorAtEmptyBuffer+l,this.abrParams.maxBitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.min(d.bitrateFactorAtFullBuffer+l,this.abrParams.maxBitrateFactorAtFullBuffer),containerSizeFactor:Math.max(d.containerSizeFactor-l,this.abrParams.minContainerSizeFactor)}),e>a&&(d={bitrateFactorAtEmptyBuffer:Math.max(d.bitrateFactorAtEmptyBuffer,this.abrParams.bitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.max(d.bitrateFactorAtFullBuffer,this.abrParams.bitrateFactorAtFullBuffer),containerSizeFactor:Math.min(d.containerSizeFactor,this.abrParams.containerSizeFactor)}),d}getStoredData(e,t="{}"){var i;return JSON.parse((i=Fp.get(e))!=null?i:t)}setStoredData(e,t){Fp.set(e,JSON.stringify(t))}removeStoredData(e){Fp.remove(e)}addStallInfoToHistory(e,t){if(e<this.tuning.minTvtToBeCounted||e>this.tuning.maxTvtToBeCounted||e*1e3<t)return;let i=this.getStoredData(sl,"[]"),r=t/e,a=i.length?Ei(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(sl,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(kC()).subscribe(t=>this.providerStartWatchingTimestamp=Mn())),this.subscription.add(this.currentStallDuration$.pipe(LC()).subscribe(t=>{let{stallDurationNoDataBeforeQualityDecrease:i,stallCountBeforeQualityDecrease:r,resetQualityRestrictionTimeout:a,ignoreStallsOnSeek:n}=this.tuning;if(PC(this.lastUniqueVideoTrackSelected)||n&&this.isSeeked$.getValue())return;let o=this.rtt$.getValue(),u=this.throughput$.getValue(),l=this.videoLastDataObtainedTimestamp$.getValue(),d=Mn(),c=r&&this.currentStallsCount>=r,f=i&&d-this.lastUniqueVideoTrackSelectedTimestamp>=i+o&&d-l>=i+o&&t>=i;(c||f)&&(this.severeStallOccurred$.next(!0),window.clearTimeout(this.qualityRestrictionTimer),this.maxQualityLimit=this.lastUniqueVideoTrackSelected.quality,MC(this.lastUniqueVideoTrackSelected.bitrate)&&u>this.lastUniqueVideoTrackSelected.bitrate&&(this.predictedThroughputWithoutData=this.lastUniqueVideoTrackSelected.bitrate)),!t&&Mn()-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}))}},al=Up;import{combine as BC,map as $C,observeElementSize as DC,Subscription as CC,ValueSubject as qp,noop as VC}from"@vkontakte/videoplayer-shared/es2015";var nl=class{constructor(){this.subscription=new CC;this.pipSize$=new qp(void 0);this.videoSize$=new qp(void 0);this.elementSize$=new qp(void 0);this.pictureInPictureWindowRemoveEventListener=VC}connect({observableVideo:e,video:t}){let i=r=>{let a=r.target;this.pipSize$.next({width:a.width,height:a.height})};this.subscription.add(DC(t).subscribe(this.videoSize$)).add(e.enterPip$.subscribe(({pictureInPictureWindow:r})=>{this.pipSize$.next({width:r.width,height:r.height}),r.addEventListener("resize",i),this.pictureInPictureWindowRemoveEventListener=()=>{r.removeEventListener("resize",i)}})).add(e.leavePip$.subscribe(()=>{this.pictureInPictureWindowRemoveEventListener()})).add(BC({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe($C(({videoSize:r,inPip: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 vr=class{constructor(e){this.subscription=new jC;this.videoState=new Y("stopped");this.observableVideo=null;this.droppedFramesManager=new Zr;this.stallsManager=new al;this.elementSizeManager=new nl;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new _i;this.audioTrackSwitchHistory=new _i;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(r.state==="requested"&&(i==null?void 0:i.to)!=="paused"&&e!=="stopped"&&t!=="stopped"&&this.seek(r.position,r.forcePrecise),t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),D(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"),D(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="ready"&&D(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"&&D(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&D(this.params.desiredState.playbackState,"paused");return;default:return _C(e)}}};this.init3DScene=e=>{var i,r,a;if(this.scene3D)return;this.scene3D=new hs(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 kt(e.source.url),this.params=e,this.video=nt(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(je(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 tl({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params;qC(this.observableVideo)&&(this.observableVideo=lt(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:ux.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(jp(l=>!!l.length),cx()).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(Hp(l=>l.to.state!=="none"),ol());this.stallsManager.init({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$,videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,tuning:this.params.tuning.stallsManager,abrParams:this.params.tuning.autoTrackSelection,isBuffering$:i.isBuffering$,looped$:i.looped$,playing$:i.playing$}),a(i.ended$,e.endedEvent$),a(i.looped$,e.loopedEvent$),a(i.error$,e.error$),a(i.isBuffering$,e.isBuffering$),a(i.currentBuffer$,e.currentBuffer$),a(i.playing$,e.firstFrameEvent$),a(i.canplay$,e.canplay$),a(i.inPiP$,e.inPiP$),a(i.inFullscreen$,e.inFullscreen$),a(i.loadedMetadata$,e.loadedMetadataEvent$),a(this.player.error$,e.error$),a(this.player.fetcherRecoverableError$,e.fetcherRecoverableError$),a(this.player.fetcherError$,e.fetcherError$),a(this.player.lastConnectionType$,e.httpConnectionType$),a(this.player.lastConnectionReused$,e.httpConnectionReused$),a(this.player.isLive$,e.isLive$),a(this.player.lastRequestFirstBytes$.pipe(jp(lx),cx()),e.firstBytesEvent$),a(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),a(this.videoState.stateChangeEnded$.pipe(Hp(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(Kt(this.video,t.isLooped,r)),this.subscription.add(ut(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Pt(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),a(Rt(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),D(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),D(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:l})=>{if(l==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let d=this.player.getStreams();if(FC(d,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let f=[];for(let p of d.audio){f.push(Ip(p));let h=[];for(let m of p.representations){let g=VI(m);h.push(g),this.audioTracksMap.set(g,{stream:p,representation:m})}this.audioStreamsMap.set(p,h)}this.params.output.availableAudioStreams$.next(f)}let c=[];for(let f of d.video){c.push(xp(f));let p=[];for(let h of f.representations){let m=CI(B(x({},h),{streamId:f.id}));m&&(p.push(m),this.videoTracksMap.set(m,{stream:f,representation:h}))}this.videoStreamsMap.set(f,p)}this.params.output.availableVideoStreams$.next(c);for(let f of d.text)for(let p of f.representations){let h=OI(f,p);this.textTracksMap.set(h,{stream:f,representation:p})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else l==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r)),this.subscription.add(ul(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$,UC(this.video,"progress")).pipe(jp(()=>this.videoTracksMap.size>0)).subscribe(()=>E(this,null,function*(){let l=this.player.state$.getState(),d=this.player.state$.getTransition();if(!(0,dx.default)(["manifest_ready","running"],l)||d)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let c=this.selectVideoAudioRepresentations();if(!c)return;let[f,p]=c,h=[...this.videoTracksMap.keys()].find(g=>{var S;return((S=this.videoTracksMap.get(g))==null?void 0:S.representation.id)===f.id});lx(h)&&(this.stallsManager.lastVideoTrackSelected=h);let m=this.params.desiredState.autoVideoTrackLimits.getTransition();if(m&&this.params.output.autoVideoTrackLimits$.next(m.to),l==="manifest_ready")yield this.player.initRepresentations(f.id,p==null?void 0:p.id,this.params.sourceHls);else if(yield this.player.switchRepresentation("video",f.id),p){let g=!!t.audioStream.getTransition();yield this.player.switchRepresentation("audio",p.id,g)}}),r)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:l})=>{this.scene3D&&l&&this.scene3D.pointCameraTo(l.x,l.y)})),this.subscription.add(this.elementSizeManager.subscribe(l=>{this.scene3D&&l&&this.scene3D.setViewportSize(l.width,l.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(ol()).subscribe(l=>{let d=[...this.videoTracksMap.entries()].find(([,{representation:h}])=>h.id===l);if(!d){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[c,{stream:f}]=d,p=this.params.desiredState.videoStream.getTransition();p&&p.to&&p.to.id===f.id&&this.params.desiredState.videoStream.setState(p.to),e.currentVideoTrack$.next(c),e.currentVideoStream$.next(xp(f))},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(ol()).subscribe(l=>{let d=[...this.audioTracksMap.entries()].find(([,{representation:h}])=>h.id===l);if(!d){e.currentAudioStream$.next(void 0);return}let[c,{stream:f}]=d,p=this.params.desiredState.audioStream.getTransition();p&&p.to&&p.to.id===f.id&&this.params.desiredState.audioStream.setState(p.to),e.currentAudioStream$.next(Ip(f))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(l=>{var d,c;if(l!=null&&l.is3dVideo&&((d=this.params.tuning.spherical)!=null&&d.enabled))try{this.init3DScene(l),e.is3DVideo$.next(!0)}catch(f){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${f}`})}else this.destroy3DScene(),(c=this.params.tuning.spherical)!=null&&c.enabled&&e.is3DVideo$.next(!1)},r)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,r)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,r)),this.textTracksManager.connect(this.video,t,e);let o=t.playbackState.stateChangeStarted$.pipe(Hp(({to:l})=>l==="ready"),ol());this.subscription.add(ul(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,zp(["init"])).subscribe(()=>{let l=t.autoVideoTrackSwitching.getState(),c=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:l?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(c)})),this.subscription.add(ul(o,this.player.state$.stateChangeEnded$,zp(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let u=ul(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,zp(["init"])).pipe(NC(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){var w,F,M,j,N,K,P,L,R,A,O,de,Fe;if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?Va:Ca,t=this.params.tuning.useNewAutoSelectVideoTrack?Mu:Ru,i=this.params.tuning.useNewAutoSelectVideoTrack?Zt:ku,{desiredState:r,output:a}=this.params,n=r.autoVideoTrackSwitching.getState(),o=(w=r.videoTrack.getState())==null?void 0:w.id,l=[...this.videoTracksMap.keys()].find(({id:ue})=>ue===o),d=a.currentVideoTrack$.getValue(),c=((j=(M=r.videoStream.getState())!=null?M:l&&((F=this.videoTracksMap.get(l))==null?void 0:F.stream))!=null?j:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!c)return;let f=[...this.videoStreamsMap.keys()].find(({id:ue})=>ue===c.id),p=f&&this.videoStreamsMap.get(f);if(!p)return;let h=Oe(this.video.buffered,this.video.currentTime*1e3),m;this.player.isActiveLive$.getValue()?m=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?m=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:m=n?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let g=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,S=Math.min(h/Math.min(m,g||1/0),1),v=(N=r.audioStream.getState())!=null?N:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,y=(K=[...this.audioStreamsMap.keys()].find(({id:ue})=>ue===(v==null?void 0:v.id)))!=null?K:this.audioStreamsMap.keys().next().value,T=0;if(y){if(l&&!n){let ue=e(l,p,(P=this.audioStreamsMap.get(y))!=null?P:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);T=Math.max(T,(L=ue==null?void 0:ue.bitrate)!=null?L:-1/0)}if(d){let ue=e(d,p,(R=this.audioStreamsMap.get(y))!=null?R:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);T=Math.max(T,(A=ue==null?void 0:ue.bitrate)!=null?A:-1/0)}}let I=i(p,{container:this.elementSizeManager.getValue(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.stallsManager.abrTuningParams,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:T,forwardBufferHealth:S,current:d,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,stallsVideoMaxQualityLimit:this.stallsManager.videoMaxQualityLimit,stallsPredictedThroughput:this.stallsManager.predictedThroughput,abrLogger:this.params.dependencies.abrLogger}),k=n?I!=null?I:l:l!=null?l:I,C=y&&t(k,p,(O=this.audioStreamsMap.get(y))!=null?O:[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.stallsManager.abrTuningParams,forwardBufferHealth:S,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),V=(de=this.videoTracksMap.get(k))==null?void 0:de.representation,$=C&&((Fe=this.audioTracksMap.get(C))==null?void 0:Fe.representation);if(V&&$)return[V,$];if(V&&!$&&this.audioTracksMap.size===0)return[V,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){ct(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),D(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:ux.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),ot(this.video),this.tracer.end()}};var Ln=class extends vr{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};import{combine as Qp,merge as px,filter as hx,filterChanged as HC,isNullable as Gp,map as fx,ValueSubject as Wp,isNonNullable as zC}from"@vkontakte/videoplayer-shared/es2015";var Bn=class extends vr{constructor(e){super(e),this.textTracksManager.destroy()}subscribe(){super.subscribe();let e=-1,{output:t,observableVideo:i,desiredState:r,connect:a}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),a(i.timeUpdate$,t.liveBufferTime$),a(this.player.liveSeekableDuration$,t.duration$),a(this.player.liveLatency$,t.liveLatency$);let n=new Wp(1);a(i.playbackRateState$,n),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(r.isLowLatency.stateChangeEnded$.pipe(fx(o=>o.to)).subscribe(this.player.isLowLatency$)).add(Qp({liveBufferTime:t.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(fx(({liveBufferTime:o,liveAvailabilityStartTime:u})=>o&&u?o+u:void 0)).subscribe(t.liveTime$)).add(this.player.liveStreamStatus$.pipe(hx(o=>zC(o))).subscribe(o=>t.isLiveEnded$.next(o!=="active"&&t.position$.getValue()===0))).add(Qp({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:px(i.playbackRateState$,new Wp(1))}).pipe(hx(({liveStreamStatus:o,liveDuration:u})=>o==="active"&&!!u)).subscribe(({liveDuration:o,playbackRate:u})=>{let l=t.liveBufferTime$.getValue(),d=t.position$.getValue(),{playbackCatchupSpeedup:c}=this.params.tuning.dashCmafLive.lowLatency;d||u<1-c||this.video.paused||Gp(l)||(e=o-l)})).add(Qp({time:t.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:px(i.playbackRateState$,new Wp(1))}).pipe(HC((o,u)=>this.player.liveStreamStatus$.getValue()==="active"?o.liveDuration===u.liveDuration:o.time===u.time)).subscribe(({time:o,liveDuration:u,playbackRate:l})=>{let d=t.position$.getValue(),{playbackCatchupSpeedup:c}=this.params.tuning.dashCmafLive.lowLatency;if(!d&&!this.video.paused&&l>=1-c||Gp(o)||Gp(u))return;let f=-1*(u-o-e);t.position$.next(Math.min(f,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(o=>{if(o){let u=_I(o);this.params.output.availableTextTracks$.next([u])}}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=Math.trunc(t/1e3<=Math.abs(this.params.output.duration$.getValue())?t:0);this.player.seekLive(i).then(()=>{this.params.output.position$.next(e/1e3)})}};import{assertNever as OV,assertNonNullable as _V,debounce as FV,ErrorCategory as Qx,filter as bh,filterChanged as yl,fromEvent as NV,isNonNullable as Gx,isNullable as UV,map as gh,merge as Tl,observableFrom as Sh,once as Wx,Subscription as qV}from"@vkontakte/videoplayer-shared/es2015";var fh=H(za(),1);import{abortable as ch,assertNonNullable as Ss,combine as vs,ErrorCategory as Qt,filter as bl,filterChanged as po,flattenObject as ho,fromEvent as ti,getTraceSubscriptionMethod as PV,interval as dh,isNonNullable as fo,isNullable as Hx,map as ys,merge as wr,now as ph,Subject as gl,Subscription as hh,tap as kV,throttle as zx,ValueSubject as Se}from"@vkontakte/videoplayer-shared/es2015";var pl=H(It(),1),bs=H(qt(),1),hl=H(za(),1);var Fx=H(ou(),1);import{assertNever as QC,ErrorCategory as mx,Subject as bx}from"@vkontakte/videoplayer-shared/es2015";var GC=18,gx=!1;try{gx=Q.browser.isSafari&&!!Q.browser.safariVersion&&Q.browser.safariVersion<=GC}catch(s){console.error(s)}var Yp=class{constructor(e){this.bufferFull$=new bx;this.error$=new bx;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:mx.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}append(e,t){return E(this,null,function*(){return t&&t.aborted?!1:new Promise(i=>{let r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})})}remove(e,t,i){return E(this,null,function*(){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()})})}abort(e){return E(this,null,function*(){return new Promise(t=>{let i,r=a=>{this.abortRequested=!1,t(a)};gx&&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:mx.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:QC(t)}}},Sx=Yp;import{abortable as Hi,assertNonNullable as pt,ErrorCategory as xr,fromEvent as nh,getExponentialDelay as oh,isNonNullable as ms,isNullable as Qe,now as dl,once as SV,Subject as vV,Subscription as yV,ValueSubject as Er}from"@vkontakte/videoplayer-shared/es2015";var ie=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let i=this.readUint32();this.type=this.readString(4),i>e.byteLength-e.byteOffset&&(this.size32=NaN);let r=this.size32?this.size32-8:void 0,a=e.byteOffset+this.cursor;this.size64=0,this.usertype=0,this.content=new DataView(e.buffer,a,r)}get id(){return this.type}get size(){return this.size32}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t="ascii"){let r=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,r}readUint8(){let e=this.source.getUint8(this.cursor);return this.cursor+=1,e}readUint16(){let e=this.source.getUint16(this.cursor);return this.cursor+=2,e}readUint32(){let e=this.source.getUint32(this.cursor);return this.cursor+=4,e}readUint64(){let e=this.source.getBigInt64(this.cursor);return this.cursor+=8,e}};var fs=class extends ie{};var $n=class extends ie{constructor(t,i){super(t,i);this.ondemandPrefix="ondemandlivejson";this.ondemandDataReceivedKey="t-in";this.ondemandDataPreparedKey="t-out";let r=this.content.byteOffset,a=r+this.content.byteLength,n=new TextDecoder("ascii").decode(this.content.buffer.slice(r,a)).split(this.ondemandPrefix)[1],o=JSON.parse(n);this.serverDataReceivedTimestamp=o[this.ondemandDataReceivedKey],this.serverDataPreparedTime=o[this.ondemandDataPreparedKey]}};var Dn=class extends ie{constructor(e,t){super(e,t),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let i=this.size-this.cursor;for(;i;){let r=this.readString(4);this.compatibleBrands.push(r),i-=4}}};var Cn=class extends ie{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var he=class extends ie{constructor(e,t){super(e,t);let i=this.readUint32();this.version=i>>>24,this.flags=i&16777215}};var Vn=class extends he{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.timescale=this.readUint32(),this.duration=this.readUint32(),this.rate=this.readUint32(),this.volume=this.readUint16()}};var On=class extends ie{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var _n=class extends ie{constructor(e,t){super(e,t),this.data=this.content}};var yr=class extends he{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e,t){super(e,t),this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let i=0;i<this.referenceCount;i++){let r=this.readUint32(),a=r>>>31,n=r<<1>>>1,o=this.readUint32();r=this.readUint32();let u=r>>>28,l=r<<3>>>3;this.segments.push({referenceType:a,referencedSize:n,subsegmentDuration:o,SAPType:u,SAPDeltaTime:l})}}};var Fn=class extends ie{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Nn=class extends ie{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Un=class extends he{constructor(e,t){switch(super(e,t),this.readUint8()){case 0:this.stereoMode=0;break;case 1:this.stereoMode=1;break;case 2:this.stereoMode=2;break;case 3:this.stereoMode=3;break;case 4:this.stereoMode=4;break}this.cursor+=1}};var qn=class extends he{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var jn=class extends he{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var Hn=class extends ie{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var zn=class extends he{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 Qn=class extends ie{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Gn=class extends ie{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Wn=class extends he{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var Yn=class extends ie{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Kn=class extends he{constructor(e,t){super(e,t),this.trackId=this.readUint32(),this.flags&1&&(this.baseDataOffset=this.readUint64()),this.flags&2&&(this.sampleDescriptionIndex=this.readUint32()),this.flags&8&&(this.defaultSampleDuration=this.readUint32()),this.flags&16&&(this.defaultSampleSize=this.readUint32()),this.flags&32&&(this.defaultSampleFlags=this.readUint32())}};var Xn=class extends he{constructor(t,i){super(t,i);this.baseMediaDecodeTime32=0;this.baseMediaDecodeTime64=BigInt(0);this.version===1?this.baseMediaDecodeTime64=this.readUint64():this.baseMediaDecodeTime32=this.readUint32()}get baseMediaDecodeTime(){return this.version===1?this.baseMediaDecodeTime64:this.baseMediaDecodeTime32}};var Jn=class extends he{constructor(t,i){super(t,i);this.sampleDuration=[];this.sampleSize=[];this.sampleFlags=[];this.sampleCompositionTimeOffset=[];this.optionalFields=0;this.sampleCount=this.readUint32(),this.flags&1&&(this.dataOffset=this.readUint32()),this.flags&4&&(this.firstSampleFlags=this.readUint32());for(let r=0;r<this.sampleCount;r++)this.flags&256&&this.sampleDuration.push(this.readUint32()),this.flags&512&&this.sampleSize.push(this.readUint32()),this.flags&1024&&this.sampleFlags.push(this.readUint32()),this.flags&2048&&this.sampleCompositionTimeOffset.push(this.readUint32())}};var Zn=class extends ie{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var eo=class extends he{constructor(e,t){super(e,t),this.entryCount=this.readUint32(),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+8,this.content.byteLength-8))}};var to=class extends ie{constructor(e,t){super(e,t),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+78,this.content.byteLength-78))}};var YC={ftyp:Dn,moov:Cn,mvhd:Vn,moof:On,mdat:_n,sidx:yr,trak:Fn,mdia:Hn,mfhd:Wn,tkhd:zn,traf:Yn,tfhd:Kn,tfdt:Xn,trun:Jn,minf:Qn,sv3d:Nn,st3d:Un,prhd:qn,proj:Gn,equi:jn,uuid:$n,stbl:Zn,stsd:eo,avc1:to,unknown:fs},Pi=class s{constructor(e={}){this.options=x({offset:0},e)}parse(e){let t=[],i=this.options.offset;for(;i<e.byteLength;)try{let a=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+i+4,4)),n=this.createBox(a,new DataView(e.buffer,e.byteOffset+i,e.byteLength-i));if(!n.size)break;t.push(n),i+=n.size}catch(r){break}return t}createBox(e,t){let i=YC[e];return i?new i(t,new s):new fs(t,new s)}};var ji=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{var i,r,a;(a=(i=this.index)[r=t.type])!=null||(i[r]=[]),this.index[t.type].push(t),t.children.length>0&&this.indexBoxLevel(t.children)})}find(e){return this.index[e]&&this.index[e][0]?this.index[e][0]:null}findAll(e){return this.index[e]||[]}};var XC=new TextDecoder("ascii"),JC=s=>XC.decode(new DataView(s.buffer,s.byteOffset+4,4))==="ftyp",ZC=s=>{let e=new yr(s,new Pi),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})},eV=(s,e)=>{let i=new Pi().parse(s),r=new ji(i),a=r.findAll("moof"),n=e?r.findAll("uuid"):r.findAll("mdat");if(!(n.length&&a.length))return null;let o=a[0],u=n[n.length-1],l=o.source.byteOffset,c=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(s.buffer,l,c)},tV=s=>{let t=new Pi().parse(s),i=new ji(t),r={},a=i.findAll("uuid");return a.length?a[a.length-1]:r},iV=s=>{var r;let t=new Pi().parse(s);return(r=new ji(t).find("sidx"))==null?void 0:r.timescale},rV=(s,e)=>{let i=new Pi().parse(s),a=new ji(i).findAll("traf"),n=a[a.length-1].children.find(c=>c.type==="tfhd"),o=a[a.length-1].children.find(c=>c.type==="tfdt"),u=a[a.length-1].children.find(c=>c.type==="trun"),l=0;return u.sampleDuration.length?l=u.sampleDuration.reduce((c,f)=>c+f,0):l=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+l)/e*1e3},sV=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 Pi().parse(s),r=new ji(i);if(r.find("sv3d")){e.is3dVideo=!0;let n=r.find("st3d");n&&(e.stereoMode=n.stereoMode);let o=r.find("prhd");o&&(e.projectionData.pose.yaw=o.poseYawDegrees,e.projectionData.pose.pitch=o.posePitchDegrees,e.projectionData.pose.roll=o.poseRollDegrees);let u=r.find("equi");u&&(e.projectionData.bounds.top=u.projectionBoundsTop,e.projectionData.bounds.right=u.projectionBoundsRight,e.projectionData.bounds.bottom=u.projectionBoundsBottom,e.projectionData.bounds.left=u.projectionBoundsLeft)}return e},vx={validateData:JC,parseInit:sV,getIndexRange:()=>{},parseSegments:ZC,parseFeedableSegmentChunk:eV,getChunkEndTime:rV,getServerLatencyTimestamps:tV,getTimescaleFromIndex:iV};var ro=H(It(),1);import{assertNonNullable as Xp,isNonNullable as xx,isNullable as nV}from"@vkontakte/videoplayer-shared/es2015";import{assertNever as aV}from"@vkontakte/videoplayer-shared/es2015";var yx={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"}},Tx=s=>{let e=s.getUint8(0),t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);let i=io(s,t),r=i in yx,a=r?yx[i].type:"binary",n=s.getUint8(t),o=0;n&128?o=1:n&64?o=2:n&32?o=3:n&16?o=4:n&8?o=5:n&4?o=6:n&2?o=7:n&1&&(o=8);let u=new DataView(s.buffer,s.byteOffset+t+1,o-1),l=n&255>>o,d=io(u),c=l*Ze(2,(o-1)*8)+d,f=t+o,p;return f+c>s.byteLength?p=new DataView(s.buffer,s.byteOffset+f):p=new DataView(s.buffer,s.byteOffset+f,c),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:a,tagHeaderSize:f,tagSize:f+c,value:p,valueSize:c}},io=(s,e=s.byteLength)=>{switch(e){case 1:return s.getUint8(0);case 2:return s.getUint16(0);case 3:return s.getUint8(0)*Ze(2,16)+s.getUint16(1);case 4:return s.getUint32(0);case 5:return s.getUint8(0)*Ze(2,32)+s.getUint32(1);case 6:return s.getUint16(0)*Ze(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},zt=(s,e)=>{switch(e){case"int":return s.getInt8(0);case"uint":return io(s);case"float":return s.byteLength===4?s.getFloat32(0):s.getFloat64(0);case"string":return new TextDecoder("ascii").decode(s);case"utf8":return new TextDecoder("utf-8").decode(s);case"date":return new Date(Date.UTC(2001,0)+s.getInt8(0)).getTime();case"master":return s;case"binary":return s;default:aV(e)}},Tr=(s,e)=>{let t=0;for(;t<s.byteLength;){let i=new DataView(s.buffer,s.byteOffset+t),r=Tx(i);if(!e(r))return;r.type==="master"&&Tr(r.value,e),t=r.value.byteOffset-s.byteOffset+r.valueSize}},Ix=s=>{if(s.getUint32(0)!==440786851)return!1;let e,t,i,r=Tx(s);return Tr(r.value,({tag:a,type:n,value:o})=>(a===17143?e=zt(o,n):a===17026?t=zt(o,n):a===17029&&(i=zt(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)};var Ex=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],oV=[231,22612,22743,167,171,163,160,175],uV=s=>{let e,t,i,r,a=!1,n=!1,o=!1,u,l,d=!1,c=0;return Tr(s,({tag:f,type:p,value:h,valueSize:m})=>{if(f===21419){let g=zt(h,p);l=io(g)}else f!==21420&&(l=void 0);return f===408125543?(e=h.byteOffset,t=h.byteOffset+m):f===357149030?a=!0:f===290298740?n=!0:f===2807729?i=zt(h,p):f===17545?r=zt(h,p):f===21420&&l===475249515?u=zt(h,p):f===374648427?Tr(h,({tag:g,type:S,value:v})=>g===30321?(d=zt(v,S)===1,!1):!0):a&&n&&(0,ro.default)(Ex,f)&&(o=!0),!o}),Xp(e,"Failed to parse webm Segment start"),Xp(t,"Failed to parse webm Segment end"),Xp(r,"Failed to parse webm Segment duration"),i=i!=null?i:1e6,{segmentStart:Math.round(e/1e9*i*1e3),segmentEnd:Math.round(t/1e9*i*1e3),timeScale:i,segmentDuration:Math.round(r/1e9*i*1e3),cuesSeekPosition:u,is3dVideo:d,stereoMode:c,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},lV=s=>{if(nV(s.cuesSeekPosition))return;let e=s.segmentStart+s.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},cV=(s,e)=>{let t=!1,i=!1,r=o=>xx(o.time)&&xx(o.position),a=[],n;return Tr(s,({tag:o,type:u,value:l})=>{switch(o){case 475249515:t=!0;break;case 187:n&&r(n)&&a.push(n),n={};break;case 179:n&&(n.time=zt(l,u));break;case 183:break;case 241:n&&(n.position=zt(l,u));break;default:t&&(0,ro.default)(Ex,o)&&(i=!0)}return!(t&&i)}),n&&r(n)&&a.push(n),a.map((o,u)=>{let{time:l,position:d}=o,c=a[u+1];return{status:"none",time:{from:l,to:c?c.time:e.segmentDuration},byte:{from:e.segmentStart+d,to:c?e.segmentStart+c.position-1:e.segmentEnd-1}}})},dV=s=>{let e=0,t=!1;try{Tr(s,i=>i.tag===524531317?i.tagSize<=s.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):(0,ro.default)(oV,i.tag)?(e+i.tagSize<=s.byteLength&&(e+=i.tagSize,t||(t=(0,ro.default)([163,160,175],i.tag))),!0):!1)}catch(i){}return e>0&&e<=s.byteLength&&t?new DataView(s.buffer,s.byteOffset,e):null},wx={validateData:Ix,parseInit:uV,getIndexRange:lV,parseSegments:cV,parseFeedableSegmentChunk:dV};var so=s=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(s);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return wx;case"mp4":return vx}}throw new ReferenceError(`Unsupported mime type ${s}`)};var rh=H(Sp(),1),Cx=H(sr(),1),Vx=H(vp(),1),Ox=H(qt(),1),sh=H(pr(),1);import{isNonNullable as mV,isNullable as $x}from"@vkontakte/videoplayer-shared/es2015";var Ax=s=>{var e;try{let t=pV(),i=s.match(t),{groups:r}=i!=null?i:{};if(r){let a={};if(r.extensions){let u=r.extensions.toLowerCase().match(/(?:[0-9a-wy-z](?:-[a-z0-9]{2,8})+)/g);Array.from(u||[]).forEach(l=>{a[l[0]]=l.slice(2)})}let n=(e=r.variants)==null?void 0:e.split(/-/).filter(u=>u!==""),o={extlang:r.extlang,langtag:r.langtag,language:r.language,privateuse:r.privateuse||r.privateuse2,region:r.region,script:r.script,extensions:a,variants:n};return Object.keys(o).forEach(u=>{let l=o[u];(typeof l=="undefined"||l==="")&&delete o[u]}),o}return null}catch(t){return null}};function pV(){let s="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",d=`^(?:(?<langtag>${`
|
|
179
179
|
(?<language>${`(?:[a-z]{2,3}(?:-${s})?|[a-z]{4}|[a-z]{5,8})`})
|
|
180
180
|
(-(?<script>[a-z]{4}))?
|
|
181
181
|
(-(?<region>(?:[a-z]{2}|[0-9]{3})))?
|
|
182
182
|
(?<variants>(?:-(?:[a-z0-9]{5,8}|[0-9][a-z0-9]{3}))*)
|
|
183
183
|
(?<extensions>(?:-[0-9a-wy-z](?:-[a-z0-9]{2,8})+)*)
|
|
184
184
|
(?:-(?<privateuse>(?:${e})))?
|
|
185
|
-
`})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(d,"i")}var Zp=H(qt(),1);import{videoSizeToQuality as pV,throttleFn as hV}from"@vkontakte/videoplayer-shared/es2015";var Px=({id:s,width:e,height:t,bitrate:i,fps:r,quality:a,streamId:n})=>{var u;let o=(u=a?Oi(a):void 0)!=null?u:pV({width:e,height:t});return o&&{id:s,quality:o,bitrate:i,size:{width:e,height:t},fps:r,streamId:n}},Rx=({id:s,bitrate:e})=>({id:s,bitrate:e}),kx=({language:s,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:s,label:e}),Mx=({language:s,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:s,label:e}),eh=({id:s,language:e,label:t,codecs:i,isDefault:r})=>({id:s,language:e,label:t,codec:(0,Zp.default)(i.split("."),0),isDefault:r}),th=({id:s,language:e,label:t,hdr:i,codecs:r})=>({id:s,language:e,hdr:i,label:t,codec:(0,Zp.default)(r.split("."),0)}),ih=s=>"url"in s,st=s=>s.type==="template",ao=s=>s instanceof DOMException&&(s.name==="AbortError"||s.code===20);var Lx=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},Ir=(s,e)=>{for(let t of s)if(e(t))return t;return null},Bx=s=>{let e=!1,t=hV(()=>{e=!0},s);return()=>{try{return t(),e}finally{e=!1}}};var Dx=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},Ri=(s,e)=>{let t=s;t=(0,rh.default)(t,"$$","$");let i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[r,a]of(0,Cx.default)(i)){let n=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=(0,rh.default)(t,n,(o,u)=>$x(a)?o:$x(u)?a:(0,Vx.default)(a,parseInt(u,10),"0"))}return t},_x=(s,e)=>{var $,w,F,M,j,N,K,P,L,k,A,O,de,Fe,ue,ee,Ee,we,Ae,Ne,At,Lt,Gt,ii,Li,Is,xs,Es,ws,As,Ps,Rs,ks,Ms,Ls,Bs,$s,Ds,Cs,Vs,Os,_s,Fs,Ns,Us,qs,js,Hs,zs,Qs,Gs,Ws,Ys,Ks,Xs,Js,Zs,ea,ta,ia,ra;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(fe=>{var q,Ge;return(Ge=(q=fe.textContent)==null?void 0:q.trim())!=null?Ge:""}),o=($=(0,Ox.default)(n,0))!=null?$:"",u=a.getAttribute("type")==="dynamic",l=a.getAttribute("availabilityStartTime"),d=a.getAttribute("publishTime"),c=a.getElementsByTagName("vk:Attrs")[0],h=c==null?void 0:c.getElementsByTagName("vk:XLatestSegmentPublishTime")[0].textContent,p=c==null?void 0:c.getElementsByTagName("vk:XStreamIsLive")[0].textContent,f=c==null?void 0:c.getElementsByTagName("vk:XStreamIsUnpublished")[0].textContent,m=c==null?void 0:c.getElementsByTagName("vk:XPlaybackDuration")[0].textContent,g;u&&(g={availabilityStartTime:l?new Date(l).getTime():0,publishTime:d?new Date(d).getTime():0,latestSegmentPublishTime:h?new Date(h).getTime():0,streamIsAlive:p==="yes",streamIsUnpublished:f==="yes"});let S,v=a.getAttribute("mediaPresentationDuration"),y=[...a.getElementsByTagName("Period")],T=y.reduce((fe,q)=>B(x({},fe),{[q.id]:q.children}),{}),I=y.reduce((fe,q)=>B(x({},fe),{[q.id]:q.getAttribute("duration")}),{});v?S=Dx(v):(0,sh.default)(I).filter(fe=>fe).length&&!u?S=(0,sh.default)(I).reduce((fe,q)=>{var Ge;return fe+((Ge=Dx(q))!=null?Ge:0)},0):m&&(S=parseInt(m,10));let R=0,C=(F=(w=a.getAttribute("profiles"))==null?void 0:w.split(","))!=null?F:[];for(let fe of y.map(q=>q.id))for(let q of T[fe]){let Ge=(M=q.getAttribute("id"))!=null?M:"id"+(R++).toString(10),Bt=(j=q.getAttribute("mimeType"))!=null?j:"",Wi=(N=q.getAttribute("codecs"))!=null?N:"",Yi=(K=q.getAttribute("contentType"))!=null?K:Bt==null?void 0:Bt.split("/")[0],Cl=(L=(P=q.getAttribute("profiles"))==null?void 0:P.split(","))!=null?L:[],sa=(A=Ax((k=q.getAttribute("lang"))!=null?k:""))!=null?A:{},ri=(Fe=(de=(O=q.querySelector("Label"))==null?void 0:O.textContent)==null?void 0:de.trim())!=null?Fe:void 0,Vl=q.querySelectorAll("Representation"),Ol=q.querySelector("SegmentTemplate"),_l=(ee=(ue=q.querySelector("Role"))==null?void 0:ue.getAttribute("value"))!=null?ee:void 0,ht=Yi,G={id:Ge,language:sa.language,isDefault:_l==="main",label:ri,codecs:Wi,hdr:ht==="video"&&as(Wi),mime:Bt,representations:[]};for(let U of Vl){let ke=(Ee=U.getAttribute("lang"))!=null?Ee:void 0,$t=(Ae=(we=ri!=null?ri:q.getAttribute("label"))!=null?we:U.getAttribute("label"))!=null?Ae:void 0,si=(Lt=(At=(Ne=U.querySelector("BaseURL"))==null?void 0:Ne.textContent)==null?void 0:At.trim())!=null?Lt:"",We=new URL(si||o,e).toString(),Me=(Gt=U.getAttribute("mimeType"))!=null?Gt:Bt,ai=(Li=(ii=U.getAttribute("codecs"))!=null?ii:Wi)!=null?Li:"",ni;if(Yi==="text"){let Le=U.getAttribute("id")||"",oi=((Is=sa.privateuse)==null?void 0:Is.includes("x-auto"))||Le.includes("_auto"),Ye=U.querySelector("SegmentTemplate");if(Ye){let Dt={representationId:(xs=U.getAttribute("id"))!=null?xs:void 0,bandwidth:(Es=U.getAttribute("bandwidth"))!=null?Es:void 0},ui=parseInt((ws=U.getAttribute("bandwidth"))!=null?ws:"",10)/1e3,li=(Ps=parseInt((As=Ye.getAttribute("startNumber"))!=null?As:"",10))!=null?Ps:1,ft=parseInt((Rs=Ye.getAttribute("timescale"))!=null?Rs:"",10),Ki=(ks=Ye.querySelectorAll("SegmentTimeline S"))!=null?ks:[],mt=Ye.getAttribute("media");if(!mt)continue;let ci=[],di=0,pi="",bt=0,Ct=li,se=0;for(let me of Ki){let Ke=parseInt((Ms=me.getAttribute("d"))!=null?Ms:"",10),ce=parseInt((Ls=me.getAttribute("r"))!=null?Ls:"",10)||0,Be=parseInt((Bs=me.getAttribute("t"))!=null?Bs:"",10);se=Number.isFinite(Be)?Be:se;let Xe=Ke/ft*1e3,$e=se/ft*1e3;for(let ve=0;ve<ce+1;ve++){let De=Ri(mt,B(x({},Dt),{segmentNumber:Ct.toString(10),segmentTime:(se+ve*Ke).toString(10)})),gt=($e!=null?$e:0)+ve*Xe,Ot=gt+Xe;Ct++,ci.push({time:{from:gt,to:Ot},url:De})}se+=(ce+1)*Ke,di+=(ce+1)*Xe}bt=se/ft*1e3,pi=Ri(mt,B(x({},Dt),{segmentNumber:Ct.toString(10),segmentTime:se.toString(10)}));let Vt={time:{from:bt,to:1/0},url:pi},Pe={type:"template",baseUrl:We,segmentTemplateUrl:mt,initUrl:"",totalSegmentsDurationMs:di,segments:ci,nextSegmentBeyondManifest:Vt,timescale:ft};ni={id:Le,kind:"text",segmentReference:Pe,profiles:[],duration:S,bitrate:ui,mime:"",codecs:"",width:0,height:0,isAuto:oi}}else ni={id:Le,isAuto:oi,kind:"text",url:We}}else{let Le=(Ds=($s=U.getAttribute("contentType"))!=null?$s:Me==null?void 0:Me.split("/")[0])!=null?Ds:Yi,oi=(Vs=(Cs=q.getAttribute("profiles"))==null?void 0:Cs.split(","))!=null?Vs:[],Ye=parseInt((Os=U.getAttribute("width"))!=null?Os:"",10),Dt=parseInt((_s=U.getAttribute("height"))!=null?_s:"",10),ui=parseInt((Fs=U.getAttribute("bandwidth"))!=null?Fs:"",10)/1e3,li=(Ns=U.getAttribute("frameRate"))!=null?Ns:"",ft=(Us=U.getAttribute("quality"))!=null?Us:void 0,Ki=li?_u(li):void 0,mt=(qs=U.getAttribute("id"))!=null?qs:"id"+(R++).toString(10),ci=Le==="video"?`${Dt}p`:Le==="audio"?`${ui}Kbps`:ai,di=`${mt}@${ci}`,pi=[...C,...Cl,...oi],bt,Ct=U.querySelector("SegmentBase"),se=(js=U.querySelector("SegmentTemplate"))!=null?js:Ol;if(Ct){let Pe=(zs=(Hs=U.querySelector("SegmentBase Initialization"))==null?void 0:Hs.getAttribute("range"))!=null?zs:"",[me,Ke]=Pe.split("-").map(De=>parseInt(De,10)),ce={from:me,to:Ke},Be=(Qs=U.querySelector("SegmentBase"))==null?void 0:Qs.getAttribute("indexRange"),[Xe,$e]=Be?Be.split("-").map(De=>parseInt(De,10)):[],ve=Be?{from:Xe,to:$e}:void 0;bt={type:"byteRange",url:We,initRange:ce,indexRange:ve}}else if(se){let Pe={representationId:(Gs=U.getAttribute("id"))!=null?Gs:void 0,bandwidth:(Ws=U.getAttribute("bandwidth"))!=null?Ws:void 0},me=parseInt((Ys=se.getAttribute("timescale"))!=null?Ys:"",10),Ke=(Ks=se.getAttribute("initialization"))!=null?Ks:"",ce=se.getAttribute("media"),Be=(Js=parseInt((Xs=se.getAttribute("startNumber"))!=null?Xs:"",10))!=null?Js:1,Xe=Ri(Ke,Pe);if(!ce)throw new ReferenceError("No media attribute in SegmentTemplate");let $e=(Zs=se.querySelectorAll("SegmentTimeline S"))!=null?Zs:[],ve=[],De=0,gt="",Ot=0;if($e.length){let hi=Be,be=0;for(let St of $e){let ye=parseInt((ea=St.getAttribute("d"))!=null?ea:"",10),Je=parseInt((ta=St.getAttribute("r"))!=null?ta:"",10)||0,fi=parseInt((ia=St.getAttribute("t"))!=null?ia:"",10);be=Number.isFinite(fi)?fi:be;let Xi=ye/me*1e3,Ji=be/me*1e3;for(let mi=0;mi<Je+1;mi++){let Nl=Ri(ce,B(x({},Pe),{segmentNumber:hi.toString(10),segmentTime:(be+mi*ye).toString(10)})),aa=(Ji!=null?Ji:0)+mi*Xi,Ul=aa+Xi;hi++,ve.push({time:{from:aa,to:Ul},url:Nl})}be+=(Je+1)*ye,De+=(Je+1)*Xi}Ot=be/me*1e3,gt=Ri(ce,B(x({},Pe),{segmentNumber:hi.toString(10),segmentTime:be.toString(10)}))}else if(fV(S)){let be=parseInt((ra=se.getAttribute("duration"))!=null?ra:"",10)/me*1e3,St=Math.ceil(S/be),ye=0;for(let Je=1;Je<St;Je++){let fi=Ri(ce,B(x({},Pe),{segmentNumber:Je.toString(10),segmentTime:ye.toString(10)}));ve.push({time:{from:ye,to:ye+be},url:fi}),ye+=be}Ot=ye,gt=Ri(ce,B(x({},Pe),{segmentNumber:St.toString(10),segmentTime:ye.toString(10)}))}let Fl={time:{from:Ot,to:1/0},url:gt};bt={type:"template",baseUrl:We,segmentTemplateUrl:ce,initUrl:Xe,totalSegmentsDurationMs:De,segments:ve,nextSegmentBeyondManifest:Fl,timescale:me}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Le||!Me)continue;let Vt={video:"video",audio:"audio",text:"text"}[Le];if(!Vt)continue;ht||(ht=Vt),ni={id:di,kind:Vt,segmentReference:bt,profiles:pi,duration:S,bitrate:ui,mime:Me,codecs:ai,width:Ye,height:Dt,fps:Ki,quality:ft}}G.language||(G.language=ke),G.label||(G.label=$t),G.mime||(G.mime=Me),G.codecs||(G.codecs=ai),G.hdr||(G.hdr=ht==="video"&&as(ai)),G.representations.push(ni)}if(ht){let U=r[ht].find(ke=>ke.id===G.id);if(U&&G.representations.every(ke=>st(ke.segmentReference)))for(let ke of U.representations){let $t=G.representations.find(Me=>Me.id===ke.id),si=$t==null?void 0:$t.segmentReference,We=ke.segmentReference;We.segments.push(...si.segments),We.nextSegmentBeyondManifest=si.nextSegmentBeyondManifest}else r[ht].push(G)}}return{duration:S,streams:r,baseUrls:n,live:g}};import{fromEvent as mV,Subscription as bV}from"@vkontakte/videoplayer-shared/es2015";var ll=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 cl=class{constructor(e,t){this.lastUpdateTs=0;this.lastCallTs=0;this.prevRanges=[];this.subscription=new bV;this.mediaSource=e,this.sourceBuffer=t,this.subscription.add(mV(this.sourceBuffer,"updateend").subscribe(()=>this.updateend()))}updateend(){if(!z(this.mediaSource,this.sourceBuffer))return;let{prevRanges:e}=this,t=ll(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 no=class{constructor(e,t,i,{fetcher:r,tuning:a,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new Er(0);this.currentLowLatencySegmentLength$=new Er(0);this.currentSegmentLength$=new Er(0);this.onLastSegment$=new Er(!1);this.fullyBuffered$=new Er(!1);this.playingRepresentation$=new Er(void 0);this.playingRepresentationInit$=new Er(void 0);this.error$=new SV;this.gaps=[];this.subscription=new vV;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new le;this.switchAbortController=new le;this.destroyAbortController=new le;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=Hi(this.destroyAbortController.signal,function(e){return X(this,null,function*(){let t=this.representations.get(e);pt(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new Sx(this.sourceBuffer),this.sourceBufferBufferedDiff=new cl(this.mediaSource,this.sourceBuffer),this.subscription.add(nh(this.sourceBuffer,"updateend").subscribe(()=>{this.maintain()})),this.subscription.add(nh(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:xr.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o||!z(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,is(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=Oe(this.sourceBuffer.buffered,o),d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,n*2,l<d).catch(c=>{this.handleAsyncError(c,"pruneBuffer")})})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);let i=this.initData.get(t.id),r=this.segments.get(t.id),a=this.parsedInitData.get(t.id);pt(i,"No init buffer for starting representation"),pt(r,"No segments for starting representation"),i instanceof ArrayBuffer&&(this.searchGaps(r,t),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(a))})}.bind(this));this.switchTo=Hi(this.destroyAbortController.signal,function(e,t=!1){return X(this,null,function*(){if(!z(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);pt(i,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if(Qe(a)||Qe(r)?yield this.loadInit(i,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),pt(r,"No segments for starting representation"),a=this.initData.get(e),!(!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer||!z(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(a,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer();else{let n=this.getCurrentPosition();ms(n)&&!this.isLive&&(this.bufferLimit=1/0,yield new Zi(this.pruneBuffer(n,1/0,!0))),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}this.maintain()}})}.bind(this));this.switchToOld=Hi(this.destroyAbortController.signal,function(e,t=!1){return X(this,null,function*(){if(!z(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);pt(i,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if(Qe(a)||Qe(r)?yield this.loadInit(i,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),pt(r,"No segments for starting representation"),a=this.initData.get(e),!(!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer||!z(this.mediaSource,this.sourceBuffer)))if(yield this.abort(),yield this.sourceBufferTaskQueue.append(a,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let n=this.getCurrentPosition();ms(n)&&(this.isLive||(this.bufferLimit=1/0,yield new Zi(this.pruneBuffer(n,1/0,!0))),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}})}.bind(this));this.seekLive=Hi(this.destroyAbortController.signal,function(e){return X(this,null,function*(){var u,l;let t=(u=(0,hl.default)(e,d=>d.representations))!=null?u:[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let d of this.representations.keys()){let c=t.find(f=>f.id===d);c&&this.representations.set(d,c);let h=this.representations.get(d);if(!h||!st(h.segmentReference))return;let p=this.getActualLiveStartingSegments(h.segmentReference);this.segments.set(h.id,p)}let i=(l=this.switchingToRepresentationId)!=null?l:this.downloadingRepresentationId,r=this.representations.get(i);pt(r);let a=this.segments.get(i);pt(a,"No segments for starting representation");let n=this.initData.get(i);if(pt(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer))return;let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(a,r),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1})}.bind(this));var d;this.fetcher=r,this.tuning=a,this.compatibilityMode=u,this.forwardBufferTarget=a.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!(l!=null&&l.live),this.baseUrls=(d=l==null?void 0:l.baseUrls)!=null?d:[],this.initData=new Map(i.map(c=>[c.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(c=>[c.id,c])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchToWithPreviousAbort(e,t=!1){!z(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new le,Hi(this.switchAbortController.signal,function(i,r=!1){return X(this,null,function*(){this.switchingToRepresentationId=i;let a=this.representations.get(i);pt(a,`No such representation ${i}`);let n=this.segments.get(i),o=this.initData.get(i);if(Qe(o)||Qe(n)?yield this.loadInit(a,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(i),pt(n,"No segments for starting representation"),o=this.initData.get(i),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer||!z(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(o,this.downloadAbortController.signal),r)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=i,yield this.dropBuffer();else{let u=this.getCurrentPosition();ms(u)&&!this.isLive&&(this.bufferLimit=this.forwardBufferTarget,yield this.pruneBuffer(u,1/0,!0)),this.downloadingRepresentationId=i,this.switchingToRepresentationId=void 0}this.maintain()}})}.bind(this))(e,t))}warmUpMediaSource(){!Qe(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}abort(){return E(this,null,function*(){for(let e of this.activeSegments)this.abortSegment(e.segment);return this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new le,this.abortBuffer()})}maintain(e=this.getCurrentPosition()){if(Qe(e)||Qe(this.downloadingRepresentationId)||Qe(this.playingRepresentationId)||Qe(this.sourceBuffer)||!z(this.mediaSource,this.sourceBuffer)||ms(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(pt(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;let r=i.find(d=>e>=d.time.from&&e<d.time.to);ms(r)&&isFinite(r.time.from)&&isFinite(r.time.to)&&this.currentSegmentLength$.next((r==null?void 0:r.time.to)-r.time.from);let a=e,n=100;if(this.playingRepresentationId!==this.downloadingRepresentationId){let d=Oe(this.sourceBuffer.buffered,e),c=r?r.time.to+n:-1/0;r&&r.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&d>=r.time.to-e+n&&(a=c)}if(isFinite(this.bufferLimit)&&is(this.sourceBuffer.buffered)>=this.bufferLimit){let d=Oe(this.sourceBuffer.buffered,e),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,d<c).catch(h=>{this.handleAsyncError(h,"pruneBuffer")});return}let u=null;if(!this.activeSegments.size&&(u=this.selectForwardBufferSegments(i,t.segmentReference.type,a),u!=null&&u.length)){let d="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if((0,pl.default)(u,r))d="high";else{let c=(0,bs.default)(u,0);c&&c.time.from-r.time.to>=this.forwardBufferTarget/2&&(d="low")}this.loadSegments(u,t,d).catch(c=>{this.handleAsyncError(c,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&r&&r.status==="fed"&&!(u!=null&&u.length)&&Oe(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let l=(0,bs.default)(i,-1);!this.isLive&&l&&(this.fullyBuffered$.next(l.time.to-e-Oe(this.sourceBuffer.buffered,e)<n),this.onLastSegment$.next(e-l.time.from>0))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let i=0,r=this.isLive?this.liveInitialAdditionalOffset:0;for(let a of e)Math.trunc(a.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:a.time.from+r,persistent:!0}),i=a.time.to;ms(t.duration)&&t.duration-i>0&&!this.isLive&&this.gaps.push({representation:t.id,from:i,to:t.duration,persistent:!0})}getActualLiveStartingSegments(e){let t=e.segments,i=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,r=[],a=0,n=t.length-1;do r.unshift(t[n]),a+=t[n].time.to-t[n].time.from,n--;while(a<i&&n>=0);return this.liveInitialAdditionalOffset=a-i,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){let t=(0,hl.default)(e==null?void 0:e.streams[this.kind],r=>r.representations).find(r=>r.id===this.downloadingRepresentationId);if(!t)return;let i=this.segments.get(t.id);if(i!=null&&i.length)return{from:i[0].time.from,to:i[i.length-1].time.to}}updateLive(e){var i,r,a,n;let t=(i=(0,hl.default)(e==null?void 0:e.streams[this.kind],o=>o.representations))!=null?i:[];if(![...this.segments.values()].every(o=>!o.length))for(let o of t){if(!o||!st(o.segmentReference))return;let u=o.segmentReference.segments.map(p=>B(x({},p),{status:"none",size:void 0})),l=100,d=(r=this.segments.get(o.id))!=null?r:[],c=(n=(a=(0,bs.default)(d,-1))==null?void 0:a.time.to)!=null?n:0,h=u==null?void 0:u.findIndex(p=>c>=p.time.from+l&&c<=p.time.to+l);if(h===-1){this.liveUpdateSegmentIndex=0;let p=this.getActualLiveStartingSegments(o.segmentReference);this.segments.set(o.id,p)}else{let p=u.slice(h+1);this.segments.set(o.id,[...d,...p])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;pt(e);let t=this.segments.get(e);if(t!=null&&t.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}updateLowLatencyLiveIfNeeded(e){let t=0;for(let i of this.representations.values()){let r=i.segmentReference;if(!st(r))return;let a=this.segments.get(i.id);if(!a)continue;let n=a.find(u=>Math.floor(u.time.from)===Math.floor(e.time.from));if(n&&!isFinite(n.time.to)&&(n.time.to=e.time.to,t=n.time.to-n.time.from),!!!a.find(u=>Math.floor(u.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let u=Math.round(e.time.to*r.timescale/1e3).toString(10),l=Ri(r.segmentTemplateUrl,{segmentTime:u});a.push({status:"none",time:{from:e.time.to,to:1/0},url:l})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){var a,n,o;let t=(n=(a=this.switchingToRepresentationId)!=null?a:this.downloadingRepresentationId)!=null?n:this.playingRepresentationId;if(!t)return;let i=this.segments.get(t);if(!i)return;let r=i.find(u=>u.time.from<=e&&u.time.to>=e);return(o=r==null?void 0:r.time.from)!=null?o:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e,t;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)==null||e.destroy(),(t=this.sourceBufferBufferedDiff)==null||t.destroy(),this.gapDetectionIdleCallback&&ei&&ei(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&ei&&ei(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=e.findIndex(({status:c,time:{from:h,to:p}},f)=>{let m=h<=i&&p>=i,g=h>i||m||f===0&&i===0,S=Math.min(this.forwardBufferTarget,this.bufferLimit),v=this.preloadOnly&&h<=i+S||p<=i+S;return(c==="none"||c==="partially_ejected"&&g&&v&&this.sourceBuffer&&z(this.mediaSource,this.sourceBuffer)&&!(He(this.sourceBuffer.buffered,h)&&He(this.sourceBuffer.buffered,p)))&&g&&v});if(r===-1)return null;if(t!=="byteRange")return e.slice(r,r+1);let a=e,n=0,o=0,u=[],l=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,d=this.preloadOnly?this.forwardBufferTarget:0;for(let c=r;c<a.length&&(n<=l||o<=d);c++){let h=a[c];if(n+=h.byte.to+1-h.byte.from,o+=h.time.to+1-h.time.from,h.status==="none"||h.status==="partially_ejected")u.push(h);else break}return u}loadSegments(e,t,i="auto"){return E(this,null,function*(){st(t.segmentReference)?yield this.loadTemplateSegment(e[0],t,i):yield this.loadByteRangeSegments(e,t,i)})}loadTemplateSegment(e,t,i="auto"){return E(this,null,function*(){e.status="downloading";let r={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(r);let{range:a,url:n,signal:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(yield Hi(o,function(){return X(this,null,function*(){let d=oh(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,d))})}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let d=yield this.fetcher.fetch(n,{range:a,signal:o,onProgress:u,priority:i,isLowLatency:this.isActiveLowLatency()});if(this.lastDataObtainedTimestampMs=dl(),!d)return;let c=new DataView(d),h=so(t.mime);if(!isFinite(r.segment.time.to)){let m=t.segmentReference.timescale;r.segment.time.to=h.getChunkEndTime(c,m)}u&&r.feedingBytes&&l?yield Promise.all(l):yield this.sourceBufferTaskQueue.append(c,o);let{serverDataReceivedTimestamp:p,serverDataPreparedTime:f}=h.getServerLatencyTimestamps(c);p&&f&&this.currentLiveSegmentServerLatency$.next(f-p),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(d){this.abortActiveSegments([e]),ao(d)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}})}updateRepresentationsBaseUrlIfNeeded(){if(!this.tuning.dash.enableBaseUrlSupport||!this.baseUrls.length||this.failedDownloads<=this.tuning.dash.maxSegmentRetryCount)return;this.baseUrlsIndex=(this.baseUrlsIndex+1)%this.baseUrls.length;let e=this.baseUrls[this.baseUrlsIndex];for(let t of this.representations.values())st(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}loadByteRangeSegments(e,t,i="auto"){return E(this,null,function*(){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&&(yield Hi(n,function(){return X(this,null,function*(){let u=oh(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),nh(window,"online").pipe(gV()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{yield this.fetcher.fetch(a,{range:r,onProgress:o,signal:n,priority:i}),this.lastDataObtainedTimestampMs=dl(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),ao(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}})}prepareByteRangeFetchSegmentParams(e,t){if(st(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:(0,bs.default)(e,0).byte.from,to:(0,bs.default)(e,-1).byte.to},{signal:a}=this.downloadAbortController;return{url:i,range:r,signal:a,onProgress:(o,u)=>E(this,null,function*(){if(!a.aborted)try{this.lastDataObtainedTimestampMs=dl(),yield this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:a,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:xr.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}})}}prepareTemplateFetchSegmentParams(e,t){if(!st(t.segmentReference))throw new Error("Representation is not template type");let i=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&i.searchParams.set("low-latency","yes");let r=i.toString(),{signal:a}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,d)=>{if(!a.aborted)try{this.lastDataObtainedTimestampMs=dl();let c=this.onSomeTemplateDataLoaded({dataView:l,loaded:d,signal:a,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(c)}catch(c){this.error$.next({id:"SegmentFeeding",category:xr.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}}:void 0;return{url:r,signal:a,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,pl.default)(e,t.segment)&&this.abortSegment(t.segment)}onSomeTemplateDataLoaded(n){return E(this,arguments,function*({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:a}){if(!this.activeSegments.size||!z(this.mediaSource,this.sourceBuffer))return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){let{segment:l}=u;if(u.representationId===t){if(a.aborted){r();continue}if(u.loadedBytes=i,u.loadedBytes>u.feedingBytes){let d=new DataView(e.buffer,e.byteOffset+u.feedingBytes,u.loadedBytes-u.feedingBytes),c=so(o.mime).parseFeedableSegmentChunk(d,this.isLive);c!=null&&c.byteLength&&(l.status="partially_fed",u.feedingBytes+=c.byteLength,yield this.sourceBufferTaskQueue.append(c),u.fedBytes+=c.byteLength)}}}})}onSomeByteRangesDataLoaded(o){return E(this,arguments,function*({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:a,onSegmentAppendFailed:n}){if(!this.activeSegments.size||!z(this.mediaSource,this.sourceBuffer))return;let u=this.representations.get(t);if(u)for(let l of this.activeSegments){if(l.representationId!==t)continue;if(a.aborted){yield n();continue}let{segment:d}=l,c=d.byte.from-i,h=d.byte.to-i,p=h-c+1,f=c<r,m=h<=r;if(f){if(d.status==="downloading"&&m){d.status="downloaded";let g=new DataView(e.buffer,e.byteOffset+c,p);(yield this.sourceBufferTaskQueue.append(g,a))&&!a.aborted?this.onSegmentFullyAppended(l,t):yield n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(d.status==="downloading"||d.status==="partially_fed")&&(l.loadedBytes=Math.min(p,r-c),l.loadedBytes>l.feedingBytes)){let g=new DataView(e.buffer,e.byteOffset+c+l.feedingBytes,l.loadedBytes-l.feedingBytes),S=l.loadedBytes===p?g:so(u.mime).parseFeedableSegmentChunk(g);S!=null&&S.byteLength&&(d.status="partially_fed",l.feedingBytes+=S.byteLength,(yield this.sourceBufferTaskQueue.append(S,a))&&!a.aborted?(l.fedBytes+=S.byteLength,l.fedBytes===p&&this.onSegmentFullyAppended(l,t)):yield n())}}}})}onSegmentFullyAppended(e,t){if(!(Qe(this.sourceBuffer)||!z(this.mediaSource,this.sourceBuffer))){!this.isLive&&Q.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(He(this.sourceBuffer.buffered,e.segment.time.from,100)&&He(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:xr.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",ih(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=ts(()=>(0,Fx.default)(this.loadInit(i,"low",!1),()=>this.initLoadIdleCallback=null)))}loadInit(e,t="auto",i=!1){return E(this,null,function*(){let r=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!i&&this.failedDownloads>0?Hi(this.destroyAbortController.signal,function(){return X(this,null,function*(){let o=oh(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))})}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,so(e.mime),r)).then(o=>{if(!o)return;let{init:u,dataView:l,segments:d}=o,c=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,c);let h=d;this.isLive&&st(e.segmentReference)&&(h=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,h),u&&this.parsedInitData.set(e.id,u)}).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:xr.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n})}dropBuffer(){return E(this,null,function*(){for(let e of this.segments.values())for(let t of e)t.status="none";yield this.pruneBuffer(0,1/0,!0)})}pruneBuffer(e,t,i=!1){return E(this,null,function*(){if(!this.sourceBuffer||!z(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||Qe(e))return!1;this.checkEjectedSegments();let r=[],a=0,n=o=>{var l;if(a>=t)return;r.push(x({},o.time));let u=ih(o)?(l=o.size)!=null?l:0:o.byte.to-o.byte.from;a+=u};for(let o of this.segments.values())for(let u of o){let l=u.time.to<=e-this.tuning.dash.bufferPruningSafeZone,d=u.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(l||d)&&u.status==="fed"&&n(u)}for(let o=0;o<this.sourceBuffer.buffered.length;o++){let u=this.sourceBuffer.buffered.start(o)*1e3,l=this.sourceBuffer.buffered.end(o)*1e3,d=0;for(let c of this.segments.values())for(let h of c)(0,pl.default)(["none","partially_ejected"],h.status)&&Math.round(h.time.from)<=Math.round(u)&&Math.round(h.time.to)>=Math.round(l)&&d++;if(d===this.segments.size){let c={time:{from:u,to:l},url:"",status:"none"};n(c)}}if(r.length&&i){let o=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let u of this.segments.values())for(let l of u)l.time.from>=e+o&&l.status==="fed"&&n(l)}return r.length?(r=Lx(r),(yield Promise.all(r.map(u=>this.sourceBufferTaskQueue.remove(u.from,u.to)))).reduce((u,l)=>u||l,!1)):!1})}abortBuffer(){return E(this,null,function*(){if(!this.sourceBuffer||!z(this.mediaSource,this.sourceBuffer))return!1;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;return this.sourceBufferTaskQueue.abort(t)})}getDebugBufferState(){if(!(!this.sourceBuffer||!z(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}getBufferedTo(){return!this.sourceBuffer||!z(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length?null:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}getForwardBufferDuration(e=this.getCurrentPosition()){return!this.sourceBuffer||!z(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||Qe(e)?0:Oe(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!this.sourceBuffer||!z(this.mediaSource,this.sourceBuffer))return;let{buffered:i}=this.sourceBuffer;this.tuning.useRefactoredSearchGap&&(this.gaps=this.gaps.filter(a=>{if(a.persistent)return!0;let n=Math.round(a.from),o=Math.round(a.to);for(let u=0;u<i.length;u++)if(n>=Math.round(i.start(u)*1e3)&&o<=Math.round(i.end(u)*1e3))return!1;return!0}));let r={representation:e,from:t.time.from,to:t.time.to,persistent:!1};for(let a=0;a<i.length;a++){let n=i.start(a)*1e3,o=i.end(a)*1e3;if(!(o<=t.time.from||n>=t.time.to)){if(n<=t.time.from&&o>=t.time.to){r=void 0;break}o>t.time.from&&o<t.time.to&&(r.from=o),n<t.time.to&&n>t.time.from&&(r.to=n)}}r&&r.to-r.from>1&&!this.gaps.some(a=>r&&a.from===r.from&&a.to===r.to)&&this.gaps.push(r)}detectGapsWhenIdle(e,t){if(!(this.gapDetectionIdleCallback||!this.sourceBuffer||!z(this.mediaSource,this.sourceBuffer))){if(!this.tuning.useRefactoredSearchGap)for(let i=0;i<this.sourceBuffer.buffered.length;i++)this.gaps=this.gaps.filter(r=>r.persistent||this.sourceBuffer&&(Math.round(r.from)<Math.round(this.sourceBuffer.buffered.start(i)*1e3)||Math.round(r.to)>Math.round(this.sourceBuffer.buffered.end(i)*1e3)));this.gapDetectionIdleCallback=ts(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:xr.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if(Qe(this.sourceBuffer)||!z(this.mediaSource,this.sourceBuffer)||Qe(this.playingRepresentationId)||this.sourceBufferBufferedDiff&&!this.sourceBufferBufferedDiff.wasUpdated())return;let e=ll(this.sourceBuffer.buffered),t=100;for(let i of this.segments.values())for(let r of i){let{status:a}=r;if(a!=="fed"&&a!=="partially_ejected")continue;let n=Math.floor(r.time.from),o=Math.ceil(r.time.to),u=!1,l=0;for(let d=0;d<e.length;d+=2){let c=e[d],h=e[d+1];u||(u=c-t<=n&&h+t>=o),(n>=c&&n<h-t||o>c+t&&o<=h)&&(l+=1)}u||(l===1?r.status="partially_ejected":this.gaps.some(d=>d.from===r.time.from||d.to===r.time.to)?r.status="partially_ejected":r.status="none")}}handleAsyncError(e,t){this.error$.next({id:t,category:xr.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}};import{abortable as oo,assertNever as Nx,fromEvent as Ux,merge as yV,now as uo,Subject as qx,ValueSubject as uh,flattenObject as gs,ErrorCategory as lo,SubscriptionRemovable as TV}from"@vkontakte/videoplayer-shared/es2015";var ml=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:a=!1}){this.lastConnectionType$=new uh(void 0);this.lastConnectionReused$=new uh(void 0);this.lastRequestFirstBytes$=new uh(void 0);this.recoverableError$=new qx;this.error$=new qx;this.abortAllController=new le;this.subscription=new TV;this.fetchManifest=oo(this.abortAllController.signal,function(e){return X(this,null,function*(){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=Ui(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=ju(i));let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(fl);return r?(t.log("success",gs({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(r.headers),r.text()):(t.error("error",gs({url:i,message:"No data in request manifest"})),t.end(),null)})}.bind(this));this.fetch=oo(this.abortAllController.signal,function(l){return X(this,arguments,function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:a="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1}={}){var j,N,K;let d=e,c=new Headers,h=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{c.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let P=new URL(d,location.href);P.searchParams.append("bytes",`${i.from}-${i.to}`),d=P.toString();break}default:Nx(t)}this.requestQuic&&(d=Ui(d));let p=this.abortAllController.signal,f;if(n){let P=new le;if(f=yV(Ux(this.abortAllController.signal,"abort"),Ux(n,"abort")).subscribe(()=>{try{P.abort()}catch(L){fl(L)}}),this.subscription.add(f),this.abortAllController.signal.aborted||n.aborted)try{P.abort()}catch(L){fl(L)}p=P.signal}let m=uo();h.log("startRequest",gs({url:d,priority:a,rangeMethod:t,range:i,isLowLatency:u,requestStartedAt:m}));let g=yield this.doFetch(d,{priority:a,headers:c,signal:p}),S=uo();if(!g)return h.error("error",{message:"No response in request"}),h.end(),this.unsubscribeAbortSubscription(f),null;if((j=this.throughputEstimator)==null||j.addRawRtt(S-m),!g.ok||!g.body){this.unsubscribeAbortSubscription(f);let P=`Fetch error ${g.status}: ${g.statusText}`;return h.error("error",{message:P}),h.end(),Promise.reject(new Error(`Fetch error ${g.status}: ${g.statusText}`))}if(this.onHeadersReceived(g.headers),!r&&!o){this.unsubscribeAbortSubscription(f);let P=uo(),L={requestStartedAt:m,requestEndedAt:P,duration:P-m};return h.log("endRequest",gs(L)),h.end(),g.arrayBuffer()}let v=g.body;if(o){let P;[v,P]=g.body.tee(),(N=this.throughputEstimator)==null||N.trackStream(P,u)}let y=v.getReader(),T,I=parseInt((K=g.headers.get("content-length"))!=null?K:"",10);Number.isFinite(I)&&(T=I),!T&&i&&(T=i.to-i.from+1);let R=0,C=T?new Uint8Array(T):new Uint8Array(0),V=!1,$=P=>{this.unsubscribeAbortSubscription(f),V=!0,fl(P)},w=oo(p,function(k){return X(this,arguments,function*({done:P,value:L}){if(R===0&&this.lastRequestFirstBytes$.next(uo()-m),p.aborted){this.unsubscribeAbortSubscription(f);return}if(!P&&L){if(T)C.set(L,R),R+=L.byteLength;else{let A=new Uint8Array(C.length+L.length);A.set(C),A.set(L,C.length),C=A,R+=L.byteLength}r==null||r(new DataView(C.buffer),R),yield y==null?void 0:y.read().then(w,$)}})}.bind(this));yield y==null?void 0:y.read().then(w,$),this.unsubscribeAbortSubscription(f);let F=uo(),M={failed:V,requestStartedAt:m,requestEndedAt:F,duration:F-m};return V?(h.error("endRequest",gs(M)),h.end(),null):(h.log("endRequest",gs(M)),h.end(),C.buffer)})}.bind(this));this.fetchByteRangeRepresentation=oo(this.abortAllController.signal,function(e,t,i){return X(this,null,function*(){var S;if(e.type!=="byteRange")return null;let{from:r,to:a}=e.initRange,n=r,o=a,u=!1,l,d;e.indexRange&&(l=e.indexRange.from,d=e.indexRange.to,u=a+1===l,u&&(n=Math.min(l,r),o=Math.max(d,a))),n=Math.min(n,0);let c=yield this.fetch(e.url,{range:{from:n,to:o},priority:i,measureThroughput:!1});if(!c)return null;let h=new DataView(c,r-n,a-n+1);if(!t.validateData(h))throw new Error("Invalid media file");let p=t.parseInit(h),f=(S=e.indexRange)!=null?S:t.getIndexRange(p);if(!f)throw new ReferenceError("No way to load representation index");let m;if(u)m=new DataView(c,f.from-n,f.to-f.from+1);else{let v=yield this.fetch(e.url,{range:f,priority:i,measureThroughput:!1});if(!v)return null;m=new DataView(v)}let g=t.parseSegments(m,p,f);return{init:p,dataView:new DataView(c),segments:g}})}.bind(this));this.fetchTemplateRepresentation=oo(this.abortAllController.signal,function(e,t){return X(this,null,function*(){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=>B(x({},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}=qu(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}fetchRepresentation(e,t,i="auto"){return E(this,null,function*(){var a,n;let{type:r}=e;switch(r){case"byteRange":return(a=yield this.fetchByteRangeRepresentation(e,t,i))!=null?a:null;case"template":return(n=yield this.fetchTemplateRepresentation(e,i))!=null?n:null;default:Nx(r)}})}destroy(){this.abortAllController.abort(),this.tracer.end(),this.subscription.unsubscribe()}doFetch(e,t){return E(this,null,function*(){let i=yield Mt(e,t);if(i.ok)return i;let r=yield i.text(),a=parseInt(r);if(!isNaN(a))switch(a){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:lo.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:lo.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:lo.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:lo.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${a})`,category:lo.FATAL})}})}unsubscribeAbortSubscription(e){e&&(e.unsubscribe(),this.subscription.remove(e))}},fl=s=>{if(!ao(s))throw s};import{isNullable as IV,ValueSubject as xV}from"@vkontakte/videoplayer-shared/es2015";var co=class s{constructor(e,t){this.currentRepresentation$=new xV(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(!IV(e))for(let i of this.representations)for(let r of i){let a=r.segmentReference,n=a.segments.length,o=a.segments[0].time.from,u=a.segments[n-1].time.to;if(e<o||e>u)continue;let l=a.segments.find(d=>d.time.from<=e&&d.time.to>=e);!l||((t=this.currentSegment)==null?void 0:t.time.from)===l.time.from&&this.currentSegment.time.to===l.time.to||(this.currentSegment=l,this.currentRepresentation$.next(B(x({},r),{label:"Live Text",language:"ru",isAuto:!0,url:new URL(l.url,a.baseUrl).toString()})))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e!=null?e:[]){let i=s.filterRepresentations(t.representations);if(i){this.representations[this.representationsCursor]=i,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!(e!=null&&e.some(t=>s.filterRepresentations(t.representations)))}static filterRepresentations(e){return e==null?void 0:e.filter(t=>t.kind==="text"&&"segmentReference"in t&&st(t.segmentReference))}};var RV=["progress","play","seeked","stalled","waiting"],kV=["timeupdate","progress","loadeddata","playing","seeked"];var Sl=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new hh;this.representationSubscription=new hh;this.state$=new Y("none");this.currentVideoRepresentation$=new Se(void 0);this.currentVideoRepresentationInit$=new Se(void 0);this.currentAudioRepresentation$=new Se(void 0);this.currentVideoSegmentLength$=new Se(0);this.currentAudioSegmentLength$=new Se(0);this.error$=new gl;this.lastConnectionType$=new Se(void 0);this.lastConnectionReused$=new Se(void 0);this.lastRequestFirstBytes$=new Se(void 0);this.currentLiveTextRepresentation$=new Se(null);this.isLive$=new Se(!1);this.isActiveLive$=new Se(!1);this.isLowLatency$=new Se(!1);this.liveDuration$=new Se(0);this.liveSeekableDuration$=new Se(0);this.liveAvailabilityStartTime$=new Se(0);this.liveStreamStatus$=new Se(void 0);this.bufferLength$=new Se(0);this.liveLatency$=new Se(void 0);this.liveLoadBufferLength$=new Se(0);this.livePositionFromPlayer$=new Se(0);this.currentStallDuration$=new Se(0);this.videoLastDataObtainedTimestamp$=new Se(0);this.fetcherRecoverableError$=new gl;this.fetcherError$=new gl;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new gl;this.gapWatchdogActive=!1;this.destroyController=new le;this.initManifest=ch(this.destroyController.signal,function(e,t,i){return X(this,null,function*(){var r;this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=Ie(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:Qt.PARSER,message:"No playable video representations"})})}.bind(this));this.updateManifest=ch(this.destroyController.signal,function(){return X(this,null,function*(){var n,o;this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(u=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:Qt.NETWORK,message:"Failed to load manifest",thrown:u})});if(!e)return null;let t=null;try{t=_x(e!=null?e:"",this.manifestUrlString)}catch(u){let l=(n=Ou(e))!=null?n:{id:"ManifestParsing",category:Qt.PARSER,message:"Failed to parse MPD manifest",thrown:u};this.error$.next(l)}if(!t)return null;let i=(u,l,d)=>{var c,h,p,f;return!!((h=(c=this.element)==null?void 0:c.canPlayType)!=null&&h.call(c,l)&&((f=(p=Et())==null?void 0:p.isTypeSupported)!=null&&f.call(p,`${l}; codecs="${d}"`))||u==="text")};if(t.live){this.isLive$.next(!!t.live);let{availabilityStartTime:u,latestSegmentPublishTime:l,streamIsUnpublished:d,streamIsAlive:c}=t.live,h=((o=t.duration)!=null?o:0)/1e3;this.liveSeekableDuration$.next(-1*h),this.liveDuration$.next((l-u)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let p="active";c||(p=d?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(p)}let r={text:t.streams.text,video:[],audio:[]};for(let u of["video","audio"]){let d=t.streams[u].filter(({mime:p,codecs:f})=>i(u,p,f)),c=new Set(d.map(({codecs:p})=>p)),h=Ju(c);if(h&&(r[u]=d.filter(({codecs:p})=>p.startsWith(h))),u==="video"){let p=this.tuning.preferHDR,f=r.video.some(g=>g.hdr),m=r.video.some(g=>!g.hdr);Q.display.isHDR&&p&&f?r.video=r.video.filter(g=>g.hdr):m&&(r.video=r.video.filter(g=>!g.hdr))}}let a=B(x({},t),{streams:r});return this.tracer.log("updateManifestEnd",ho(a)),a})}.bind(this));this.initRepresentations=ch(this.destroyController.signal,function(e,t,i){return X(this,null,function*(){var h;this.tracer.log("initRepresentationsStart",ho({initialVideo:e,initialAudio:t,sourceHls:i})),Ss(this.manifest),Ss(this.element),this.representationSubscription.unsubscribe(),this.representationSubscription=new hh,this.state$.startTransitionTo("representations_ready");let r=p=>{this.representationSubscription.add(ti(p,"error").pipe(bl(f=>{var m;return!!((m=this.element)!=null&&m.played.length)})).subscribe(f=>{this.error$.next({id:"VideoSource",category:Qt.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:f})}))};this.source=this.tuning.useManagedMediaSource?hu():new MediaSource;let a=document.createElement("source");if(r(a),a.src=URL.createObjectURL(this.source),this.element.appendChild(a),this.tuning.useManagedMediaSource&&Gr())if(i){let p=document.createElement("source");r(p),p.type="application/x-mpegurl",p.src=i.url,this.element.appendChild(p)}else this.element.disableRemotePlayback=!0;this.isActiveLive$.next(this.isLive$.getValue());let n={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),manifest:this.manifest},o=this.manifest.streams.video.reduce((p,f)=>[...p,...f.representations],[]);if(this.videoBufferManager=new no("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],fo(t)){let p=this.manifest.streams.audio.reduce((f,m)=>[...f,...m.representations],[]);this.audioBufferManager=new no("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}co.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new co(this.manifest.streams.text,n)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$));let u=()=>{var p;(p=this.stallWatchdogSubscription)==null||p.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add(wr(...kV.map(p=>ti(this.element,p))).pipe(ys(p=>this.element?Oe(this.element.buffered,this.element.currentTime*1e3):0),po(),PV(p=>{p>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add(wr(ti(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe(po()).subscribe(f=>this.liveStreamEndTimestamp=ph())),this.subscription.add(ti(this.element,"pause").subscribe(()=>{this.livePauseWatchdogSubscription=dh(1e3).subscribe(f=>{let m=Ci(this.manifestUrlString,2);this.manifestUrlString=Ie(this.manifestUrlString,m+1e3,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add(ti(this.element,"play").subscribe(f=>{var m;return(m=this.livePauseWatchdogSubscription)==null?void 0:m.unsubscribe()})),this.representationSubscription.add(vs({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(ys(({isActiveLive:f,isLowLatency:m})=>f&&m),po()).subscribe(f=>{this.isManualDecreasePlaybackInLive()||ls(this.element,1)})),this.representationSubscription.add(vs({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(bl(({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(vs({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(bl(({isLive:f})=>f),po((f,m)=>m.bufferLength<f.bufferLength),ys(({rtt:f,bufferLength:m,segmentServerLatency:g})=>{let S=Ci(this.manifestUrlString,2);return(f/2+m+g+S)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(vs({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:f,isActiveLive:m,isLowLatency:g})=>{if(!g||!m)return;let S=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,v=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,y=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,T=f-S;if(this.isManualDecreasePlaybackInLive())return;let I=1;Math.abs(T)>v&&(I=1+Math.sign(T)*y),ls(this.element,I)})),this.representationSubscription.add(this.bufferLength$.subscribe(f=>{var g,S;let m=0;if(f){let v=((S=(g=this.element)==null?void 0:g.currentTime)!=null?S:0)*1e3;m=Math.min(...this.bufferManagers.map(T=>{var I,R;return(R=(I=T.getLiveSegmentsToLoadState(this.manifest))==null?void 0:I.to)!=null?R:v}))-v}this.liveLoadBufferLength$.getValue()!==m&&this.liveLoadBufferLength$.next(m)}));let p=0;this.representationSubscription.add(vs({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(zx(1e3)).subscribe(g=>E(this,[g],function*({liveLoadBufferLength:f,bufferLength:m}){if(!this.element||this.isUpdatingLive)return;let S=this.element.playbackRate,v=Ci(this.manifestUrlString,2),y=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,T=Math.min(y,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*S),I=this.tuning.dashCmafLive.normalizedActualBufferOffset*S,R=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*S,C=isFinite(f)?f:m,V=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),$=y<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next($);let w="none";if(V?w="active_low_latency":this.isLowLatency$.getValue()&&$?(this.bufferManagers.forEach(F=>F.proceedLowLatencyLive()),w="active_low_latency"):v!==0&&C<T?w="live_forward_buffering":C<T+R&&(w="live_with_target_offset"),isFinite(f)&&(p=f>p?f:p),w==="live_forward_buffering"||w==="live_with_target_offset"){let F=p-(T+I),M=this.normolizeLiveOffset(Math.trunc(v+F/S)),j=Math.abs(M-v),N=0;!f||j<=this.tuning.dashCmafLive.offsetCalculationError?N=v:M>0&&j>this.tuning.dashCmafLive.offsetCalculationError&&(N=M),this.manifestUrlString=Ie(this.manifestUrlString,N,2)}(w==="live_with_target_offset"||w==="live_forward_buffering")&&(p=0,yield this.updateLive())}),f=>{this.error$.next({id:"updateLive",category:Qt.VIDEO_PIPELINE,thrown:f,message:"Failed to update live with subscription"})}))}let l=wr(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe(ys(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),d=wr(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe(ys(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue()))),c=vs({allBuffersFull:l,someBufferEnded:d}).pipe(po(),ys(({allBuffersFull:p,someBufferEnded:f})=>p&&f),bl(p=>p));if(this.representationSubscription.add(wr(this.forceEnded$,c).subscribe(()=>{var p;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(f=>!f.updating))try{(p=this.source)==null||p.endOfStream()}catch(f){this.error$.next({id:"EndOfStream",category:Qt.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:f})}})),this.representationSubscription.add(wr(...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:Qt.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,fh.default)((0,fh.default)([...this.manifest.streams.audio,...this.manifest.streams.video],f=>f.representations),f=>{let m=[];return f.duration&&m.push(f.duration),st(f.segmentReference)&&f.segmentReference.totalSegmentsDurationMs&&m.push(f.segmentReference.totalSegmentsDurationMs),m})];this.source.duration=Math.max(...p)/1e3}this.audioBufferManager&&fo(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")})}.bind(this));this.tick=()=>{var t,i,r,a;if(!this.element||!this.videoBufferManager||((t=this.source)==null?void 0:t.readyState)!=="open")return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),(i=this.audioBufferManager)==null||i.maintain(e),(r=this.liveTextManager)==null||r.maintain(e),(this.videoBufferManager.gaps.length||(a=this.audioBufferManager)!=null&&a.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=dh(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),n=>{this.error$.next({id:"GapWatchdog",category:Qt.WTF,message:"Error handling gaps",thrown:n})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.fetcher=new ml({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=wi.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,x({},e.tuning.dashCmafLive.lowLatency.bufferEstimator)),this.initTracerSubscription()}seekLive(e){return E(this,null,function*(){var r,a,n;Ss(this.element);let t=this.liveStreamStatus$.getValue()!=="active"?ph()-this.liveStreamEndTimestamp:0,i=this.normolizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=Ie(this.manifestUrlString,i,2),this.manifest=yield this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,yield(r=this.videoBufferManager)==null?void 0:r.seekLive(this.manifest.streams.video),yield(a=this.audioBufferManager)==null?void 0:a.seekLive(this.manifest.streams.audio),(n=this.liveTextManager)==null||n.seekLive(this.manifest.streams.text))})}initBuffer(){Ss(this.element),this.state$.setState("running");let e=ti(this.element,"timeupdate");this.tuning.dash.timeupdateEventTickThrottle&&(e=e.pipe(zx(this.tuning.dash.timeupdateEventTickThrottle))),this.subscription.add(wr(...RV.map(t=>ti(this.element,t)),ti(window,"online"),e).subscribe(()=>this.tick(),t=>{this.error$.next({id:"DashVKPlayer",category:Qt.WTF,message:"Internal logic error",thrown:t})})),this.subscription.add(ti(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(ti(this.element,"waiting").subscribe(()=>{var i;this.element&&this.element.readyState===HTMLMediaElement.HAVE_CURRENT_DATA&&!this.element.seeking&&He(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let t=()=>{var f,m,g,S,v,y,T,I,R,C,V;if(!this.element||((f=this.source)==null?void 0:f.readyState)!=="open")return;let r=this.currentStallDuration$.getValue();r+=50,this.currentStallDuration$.next(r);let a={timeInWaiting:r},n=ph(),o=100,u=(g=(m=this.videoBufferManager)==null?void 0:m.lastDataObtainedTimestamp)!=null?g:0;this.videoLastDataObtainedTimestamp$.next(u);let l=(v=(S=this.audioBufferManager)==null?void 0:S.lastDataObtainedTimestamp)!=null?v:0,d=(T=(y=this.videoBufferManager)==null?void 0:y.getForwardBufferDuration())!=null?T:0,c=(R=(I=this.audioBufferManager)==null?void 0:I.getForwardBufferDuration())!=null?R:0,h=d<o&&n-u>this.tuning.dash.crashOnStallTWithoutDataTimeout,p=this.audioBufferManager&&c<o&&n-l>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((h||p)&&r>this.tuning.dash.crashOnStallTWithoutDataTimeout||r>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${r} ms`);if(this.isLive$.getValue()&&r%2e3===0){let $=this.normolizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive($).catch(w=>{this.error$.next({id:"stallIntervalCallback",category:Qt.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:w})}),a.liveLastOffset=$}else{let $=this.element.currentTime*1e3;(C=this.videoBufferManager)==null||C.maintain($),(V=this.audioBufferManager)==null||V.maintain($),a.position=$}this.tracer.log("stallIntervalCallback",ho(a))};(i=this.stallWatchdogSubscription)==null||i.unsubscribe(),this.stallWatchdogSubscription=dh(50).subscribe(t,r=>{this.error$.next({id:"StallWatchdogCallback",category:Qt.NETWORK,message:"Can't restore DASH after stall.",thrown:r})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}switchRepresentation(e,t,i=!1){return E(this,null,function*(){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)})}seek(e,t){return E(this,null,function*(){var r,a,n,o,u;Ss(this.element),Ss(this.videoBufferManager);let i;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?i=e:i=Math.max((r=this.videoBufferManager.findSegmentStartTime(e))!=null?r:e,(n=(a=this.audioBufferManager)==null?void 0:a.findSegmentStartTime(e))!=null?n:e),this.warmUpMediaSourceIfNeeded(i),He(this.element.buffered,i)||(yield Promise.all([this.videoBufferManager.abort(),(o=this.audioBufferManager)==null?void 0:o.abort()])),!(Hx(this.element)||Hx(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),(u=this.audioBufferManager)==null||u.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",ho({requestedPosition:e,forcePrecise:t,position:i})))})}warmUpMediaSourceIfNeeded(e=(t=>(t=this.element)==null?void 0:t.currentTime)()){var i;fo(this.element)&&fo(this.source)&&fo(e)&&((i=this.source)==null?void 0:i.readyState)==="ended"&&this.element.duration*1e3-e>this.tuning.dash.seekBiasInTheEnd&&this.bufferManagers.forEach(r=>r.warmUpMediaSource())}get isStreamEnded(){var e;return((e=this.source)==null?void 0:e.readyState)==="ended"}stop(){var e,t,i;this.tracer.log("stop"),(e=this.element)==null||e.querySelectorAll("source").forEach(r=>{URL.revokeObjectURL(r.src),r.remove()}),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(t=this.videoBufferManager)==null||t.destroy(),this.videoBufferManager=null,(i=this.audioBufferManager)==null||i.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){var e;return(e=this.manifest)==null?void 0:e.streams}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){var e;this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),((e=this.source)==null?void 0:e.readyState)==="open"&&Array.from(this.source.sourceBuffers).every(t=>!t.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=AV(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}updateLive(){return E(this,null,function*(){var e,t;this.isUpdatingLive=!0,this.manifest=yield this.updateManifest(),this.manifest&&((e=this.bufferManagers)==null||e.forEach(i=>i.updateLive(this.manifest)),(t=this.liveTextManager)==null||t.updateLive(this.manifest)),this.isUpdatingLive=!1})}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getBufferedTo();if(e===null)return;let t=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),i=this.isJumpGapAfterSeekLive,r=this.element.currentTime;this.isJumpGapAfterSeekLive&&!t&&this.element.currentTime>e&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let a=this.element.currentTime*1e3,n=null,o=this.element.readyState===HTMLMediaElement.HAVE_METADATA?this.tuning.endGapTolerance:0;for(let u of this.bufferManagers)for(let l of u.gaps)(l.persistent||u.playingRepresentation$.getValue()===l.representation)&&l.from-o<=a&&l.to+o>a&&(this.element.duration*1e3-l.to<this.tuning.endGapTolerance?n=1/0:(n===null||l.to>n)&&(n=l.to));if(n!==null){let u=n+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,u===1/0?this.forceEnded$.next():(this.element.currentTime=u/1e3,this.tracer.log("jumpGap",ho({isJumpGapAfterSeekLive:i,isActiveLowLatency:t,initialCurrentTime:r,jumpTo:u,resultCurrentTime:this.element.currentTime})))}}};import{combine as MV,map as LV,observeElementSize as BV,Subscription as $V,ValueSubject as mh,noop as DV}from"@vkontakte/videoplayer-shared/es2015";var vl=class{constructor(){this.subscription=new $V;this.pipSize$=new mh(void 0);this.videoSize$=new mh(void 0);this.elementSize$=new mh(void 0);this.pictureInPictureWindowRemoveEventListener=DV}connect({observableVideo:e,video:t}){let i=r=>{let a=r.target;this.pipSize$.next({width:a.width,height:a.height})};this.subscription.add(BV(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(MV({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(LV(({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 Ar=class{constructor(e){this.subscription=new NV;this.videoState=new Y("stopped");this.droppedFramesManager=new Zr;this.stallsManager=new al;this.elementSizeManager=new vl;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new _i;this.audioTrackSwitchHistory=new _i;this.selectedRepresentations={audio:null,video:null};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(r.state==="requested"&&(i==null?void 0:i.to)!=="paused"&&e!=="stopped"&&t!=="stopped"&&this.seek(r.position,r.forcePrecise),t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),D(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"),D(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="ready"&&D(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"&&D(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&D(this.params.desiredState.playbackState,"paused");return;default:return VV(e)}}};this.init3DScene=e=>{var i,r,a;if(this.scene3D)return;this.scene3D=new hs(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 Rt(e.source.url),this.params=e,this.video=nt(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(je(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 Sl({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params,i=lt(this.video);this.subscription.add(()=>i.destroy());let r=this.constructor.name,a=o=>{e.error$.next({id:r,category:Qx.WTF,message:`${r} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:i,genericErrorListener:a,connect:(o,u)=>this.subscription.add(o.subscribe(u,a))}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:a}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(bh(c=>!!c.length),Wx()).subscribe(c=>{this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:c})}));let n=this.params.desiredState.seekState.stateChangeEnded$.pipe(gh(c=>c.to.state!=="none"),yl());this.stallsManager.init({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$,videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,tuning:this.params.tuning.stallsManager,abrParams:this.params.tuning.autoTrackSelection,isBuffering$:i.isBuffering$,looped$:i.looped$,playing$:i.playing$}),a(i.ended$,e.endedEvent$),a(i.looped$,e.loopedEvent$),a(i.error$,e.error$),a(i.isBuffering$,e.isBuffering$),a(i.currentBuffer$,e.currentBuffer$),a(i.playing$,e.firstFrameEvent$),a(i.canplay$,e.canplay$),a(i.inPiP$,e.inPiP$),a(i.inFullscreen$,e.inFullscreen$),a(i.loadedMetadata$,e.loadedMetadataEvent$),a(this.player.error$,e.error$),a(this.player.fetcherRecoverableError$,e.fetcherRecoverableError$),a(this.player.fetcherError$,e.fetcherError$),a(this.player.lastConnectionType$,e.httpConnectionType$),a(this.player.lastConnectionReused$,e.httpConnectionReused$),a(this.player.isLive$,e.isLive$),a(this.player.lastRequestFirstBytes$.pipe(bh(Gx),Wx()),e.firstBytesEvent$),a(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),a(this.videoState.stateChangeEnded$.pipe(gh(c=>c.to)),this.params.output.playbackState$),this.subscription.add(i.looped$.subscribe(()=>this.player.warmUpMediaSourceIfNeeded(),r)),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(Kt(this.video,t.isLooped,r)),this.subscription.add(ut(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Pt(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),a(kt(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),D(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),D(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:c})=>{if(c==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let h=this.player.getStreams();if(OV(h,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let f=[];for(let m of h.audio){f.push(eh(m));let g=[];for(let S of m.representations){let v=Rx(S);g.push(v),this.audioTracksMap.set(v,{stream:m,representation:S})}this.audioStreamsMap.set(m,g)}this.params.output.availableAudioStreams$.next(f)}let p=[];for(let f of h.video){p.push(th(f));let m=[];for(let g of f.representations){let S=Px(B(x({},g),{streamId:f.id}));S&&(m.push(S),this.videoTracksMap.set(S,{stream:f,representation:g}))}this.videoStreamsMap.set(f,m)}this.params.output.availableVideoStreams$.next(p);for(let f of h.text)for(let m of f.representations){let g=kx(f,m);this.textTracksMap.set(g,{stream:f,representation:m})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else c==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r));let{vktvAbrThrottle:o}=this.params.tuning.dash,u=o&&Bx(o)||null;this.subscription.add(Tl(this.player.currentStallDuration$,this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,this.elementSizeManager.getObservable(),this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,FV(this.video,"progress")).pipe(bh(()=>this.videoTracksMap.size>0)).subscribe(()=>E(this,null,function*(){let c=this.player.state$.getState(),h=this.player.state$.getTransition();if(c!=="manifest_ready"&&c!=="running"||h||c==="running"&&u&&!u())return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState()),this.selectVideoAudioRepresentations();let{video:p,audio:f}=this.selectedRepresentations;if(!p)return;let m=Ir(this.videoTracksMap.keys(),S=>{var v;return((v=this.videoTracksMap.get(S))==null?void 0:v.representation.id)===p.id});Gx(m)&&(this.stallsManager.lastVideoTrackSelected=m);let g=this.params.desiredState.autoVideoTrackLimits.getTransition();if(g&&this.params.output.autoVideoTrackLimits$.next(g.to),c==="manifest_ready")yield this.player.initRepresentations(p.id,f==null?void 0:f.id,this.params.sourceHls);else if(yield this.player.switchRepresentation("video",p.id),f){let S=!!t.audioStream.getTransition();yield this.player.switchRepresentation("audio",f.id,S)}}),r)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:c})=>{this.scene3D&&c&&this.scene3D.pointCameraTo(c.x,c.y)})),this.subscription.add(this.elementSizeManager.subscribe(c=>{this.scene3D&&c&&this.scene3D.setViewportSize(c.width,c.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(yl()).subscribe(c=>{let h=Ir(this.videoTracksMap.entries(),([,{representation:g}])=>g.id===c);if(!h){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[p,{stream:f}]=h,m=this.params.desiredState.videoStream.getTransition();m&&m.to&&m.to.id===f.id&&this.params.desiredState.videoStream.setState(m.to),e.currentVideoTrack$.next(p),e.currentVideoStream$.next(th(f))},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(yl()).subscribe(c=>{let h=Ir(this.audioTracksMap.entries(),([,{representation:g}])=>g.id===c);if(!h){e.currentAudioStream$.next(void 0);return}let[p,{stream:f}]=h,m=this.params.desiredState.audioStream.getTransition();m&&m.to&&m.to.id===f.id&&this.params.desiredState.audioStream.setState(m.to),e.currentAudioStream$.next(eh(f))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(c=>{var h,p;if(c!=null&&c.is3dVideo&&((h=this.params.tuning.spherical)!=null&&h.enabled))try{this.init3DScene(c),e.is3DVideo$.next(!0)}catch(f){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${f}`})}else this.destroy3DScene(),(p=this.params.tuning.spherical)!=null&&p.enabled&&e.is3DVideo$.next(!1)},r)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,r)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,r)),this.textTracksManager.connect(this.video,t,e);let l=t.playbackState.stateChangeStarted$.pipe(gh(({to:c})=>c==="ready"),yl());this.subscription.add(Tl(l,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,Sh(["init"])).subscribe(()=>{let c=t.autoVideoTrackSwitching.getState(),p=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:c?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(p)})),this.subscription.add(Tl(l,this.player.state$.stateChangeEnded$,Sh(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let d=Tl(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Sh(["init"])).pipe(_V(0));this.subscription.add(d.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){var V,$,w,F,M,j,N,K,P,L,k,A;if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?Va:Ca,t=this.params.tuning.useNewAutoSelectVideoTrack?Mu:ku,i=this.params.tuning.useNewAutoSelectVideoTrack?Zt:Ru,{desiredState:r,output:a}=this.params,n=r.autoVideoTrackSwitching.getState(),o=(V=r.videoTrack.getState())==null?void 0:V.id,u=Ir(this.videoTracksMap.keys(),O=>O.id===o),l=a.currentVideoTrack$.getValue(),d=((F=(w=r.videoStream.getState())!=null?w:u&&(($=this.videoTracksMap.get(u))==null?void 0:$.stream))!=null?F:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!d)return;let c=Ir(this.videoStreamsMap.keys(),O=>O.id===d.id),h=c&&this.videoStreamsMap.get(c);if(!h)return;let p=Oe(this.video.buffered,this.video.currentTime*1e3),f;this.player.isActiveLive$.getValue()?f=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?f=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:f=n?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let m=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,g=Math.min(p/Math.min(f,m||1/0),1),S=(M=r.audioStream.getState())!=null?M:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,v=(S==null?void 0:S.id)&&Ir(this.audioStreamsMap.keys(),O=>O.id===S.id)||this.audioStreamsMap.keys().next().value,y=0;if(v){if(u&&!n){let O=e(u,h,(j=this.audioStreamsMap.get(v))!=null?j:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);y=Math.max(y,(N=O==null?void 0:O.bitrate)!=null?N:-1/0)}if(l){let O=e(l,h,(K=this.audioStreamsMap.get(v))!=null?K:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);y=Math.max(y,(P=O==null?void 0:O.bitrate)!=null?P:-1/0)}}let T=u;(n||!T)&&(T=i(h,{container:this.elementSizeManager.getValue(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.stallsManager.abrTuningParams,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:y,forwardBufferHealth:g,current:l,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,stallsVideoMaxQualityLimit:this.stallsManager.videoMaxQualityLimit,stallsPredictedThroughput:this.stallsManager.predictedThroughput,abrLogger:this.params.dependencies.abrLogger}));let I=v&&t(T,h,(L=this.audioStreamsMap.get(v))!=null?L:[],{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}),R=(k=this.videoTracksMap.get(T))==null?void 0:k.representation,C=I&&((A=this.audioTracksMap.get(I))==null?void 0:A.representation);R&&C?(this.selectedRepresentations.video=R,this.selectedRepresentations.audio=C):R&&!C&&this.audioTracksMap.size===0&&(this.selectedRepresentations.video=R,this.selectedRepresentations.audio=null)}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){ct(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),D(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Qx.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),ot(this.video),this.tracer.end()}};var mo=class extends Ar{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 vh,merge as Yx,filter as Kx,filterChanged as UV,isNullable as yh,map as Xx,ValueSubject as Th,isNonNullable as qV}from"@vkontakte/videoplayer-shared/es2015";var bo=class extends Ar{constructor(e){super(e),this.textTracksManager.destroy()}subscribe(){super.subscribe();let e=-1,{output:t,observableVideo:i,desiredState:r,connect:a}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),a(i.timeUpdate$,t.liveBufferTime$),a(this.player.liveSeekableDuration$,t.duration$),a(this.player.liveLatency$,t.liveLatency$);let n=new Th(1);a(i.playbackRateState$,n),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(r.isLowLatency.stateChangeEnded$.pipe(Xx(o=>o.to)).subscribe(this.player.isLowLatency$)).add(vh({liveBufferTime:t.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(Xx(({liveBufferTime:o,liveAvailabilityStartTime:u})=>o&&u?o+u:void 0)).subscribe(t.liveTime$)).add(this.player.liveStreamStatus$.pipe(Kx(o=>qV(o))).subscribe(o=>t.isLiveEnded$.next(o!=="active"&&t.position$.getValue()===0))).add(vh({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:Yx(i.playbackRateState$,new Th(1))}).pipe(Kx(({liveStreamStatus:o,liveDuration:u})=>o==="active"&&!!u)).subscribe(({liveDuration:o,playbackRate:u})=>{let l=t.liveBufferTime$.getValue(),d=t.position$.getValue(),{playbackCatchupSpeedup:c}=this.params.tuning.dashCmafLive.lowLatency;d||u<1-c||this.video.paused||yh(l)||(e=o-l)})).add(vh({time:t.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:Yx(i.playbackRateState$,new Th(1))}).pipe(UV((o,u)=>this.player.liveStreamStatus$.getValue()==="active"?o.liveDuration===u.liveDuration:o.time===u.time)).subscribe(({time:o,liveDuration:u,playbackRate:l})=>{let d=t.position$.getValue(),{playbackCatchupSpeedup:c}=this.params.tuning.dashCmafLive.lowLatency;if(!d&&!this.video.paused&&l>=1-c||yh(o)||yh(u))return;let h=-1*(u-o-e);t.position$.next(Math.min(h,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(o=>{if(o){let u=Mx(o);this.params.output.availableTextTracks$.next([u])}}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=Math.trunc(t/1e3<=Math.abs(this.params.output.duration$.getValue())?t:0);this.player.seekLive(i).then(()=>{this.params.output.position$.next(e/1e3)})}};var Jx="X-Playback-Duration",Ih=s=>E(void 0,null,function*(){var r;let e=yield Mt(s),t=yield 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(Jx)?parseInt(e.headers.get(Jx),10):void 0});import{assertNever as ZV,combine as eO,debounce as tO,ErrorCategory as El,filter as iO,filterChanged as rO,isNonNullable as tE,isNullable as wl,map as iE,merge as sO,observableFrom as aO,Subscription as nO,ValueSubject as wh,VideoQuality as oO}from"@vkontakte/videoplayer-shared/es2015";var Eh=H(Xc(),1);import{videoSizeToQuality as jV,getExponentialDelay as HV}from"@vkontakte/videoplayer-shared/es2015";var zV=s=>{let e=null;if(s.QUALITY&&(e=Oi(s.QUALITY)),!e&&s.RESOLUTION){let[t,i]=s.RESOLUTION.split("x").map(r=>parseInt(r,10));e=jV({width:t,height:i})}return e!=null?e:null},QV=(s,e)=>{var a,n;let t=s.split(`
|
|
186
|
-
`),i=[],r=[];for(let o=0;o<t.length;o++){let u=t[o],l=u.match(/^#EXT-X-STREAM-INF:(.+)/),d=u.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!l&&!d)){if(l){let c=(0,Eh.default)(l[1].split(",").map(v=>v.split("="))),
|
|
187
|
-
`),a=0;for(let n=0;n<r.length;++n){let o=r[n];switch(!0){case o.startsWith("#EXTINF:"):{let u=r[++n],l=new URL(u,t).toString(),d=Number(this.extractPlaylistRowValue("#EXTINF:",o))*1e3;if(i.segments.push({time:{from:a,to:a+d},url:l}),a=a+d,!i.segmentStartTime){let c=new Date(i.vkStartTime).valueOf(),h=new Date(i.programDateTime).valueOf();i.segmentStartTime=h-c}break}case o.startsWith("#EXT-X-TARGETDURATION:"):i.targetDuration=Number(this.extractPlaylistRowValue("#EXT-X-TARGETDURATION:",o));break;case o.startsWith("#EXT-X-MEDIA-SEQUENCE:"):i.mediaSequence=Number(this.extractPlaylistRowValue("#EXT-X-MEDIA-SEQUENCE:",o));break;case o.startsWith("#EXT-X-VK-PLAYBACK-DURATION:"):i.vkPlaybackDuration=Number(this.extractPlaylistRowValue("#EXT-X-VK-PLAYBACK-DURATION:",o));break;case o.startsWith("#EXT-X-PROGRAM-DATE-TIME:"):{let u=this.extractPlaylistRowValue("#EXT-X-PROGRAM-DATE-TIME:",o);i.programDateTime=u;let l=new Date(u);l.setMilliseconds(0),a=l.valueOf();break}case o.startsWith("#EXT-X-VK-START-TIME:"):i.vkStartTime=this.extractPlaylistRowValue("#EXT-X-VK-START-TIME:",o);break}}return i}extractPlaylistRowValue(e,t){switch(e){case"#EXTINF:":return t.substring(e.length,t.length-1);default:return t.substring(e.length)}}processLiveTime(e){if(WV(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([B(x({},this.currentTextTrackData.textTrack),{url:n.url,isAuto:!0})]);break}}}fetchNextManifestData(){return E(this,null,function*(){try{if(this.abortControllers.nextManifest)return;this.abortControllers.nextManifest=new le;let{textTracks:e}=yield this.fetchManifestData(),t=yield 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}})}fetchManifestData(){return E(this,null,function*(){var t;let e=(t=this.prepareUrl)!=null?t:this.params.sourceUrl;return yield this.params.fetchManifestData(e,{signal:this.abortControllers.destroy.signal})})}error(e,t){this.error$.next({id:"[LiveTextManager][HLS_LIVE_CMAF]",category:JV.WTF,thrown:t,message:e})}};var go=class{constructor(e){this.subscription=new nO;this.videoState=new Y("stopped");this.textTracksManager=null;this.liveTextManager=null;this.manifests$=new wh([]);this.liveOffset=new hr;this.manifestStartTime$=new wh(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"),D(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(a||n||o){let d=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(d),this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((r==null?void 0:r.to)!=="paused"&&l.state==="requested"){this.videoState.startTransitionTo("ready"),this.seek(l.position&&l.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":i==="ready"?D(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),D(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"&&D(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"&&(D(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return ZV(t)}};var i;this.params=e,this.video=nt(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:oO.INVARIANT,url:this.params.source.url};let t=(r,a)=>Il(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 xl(this.params.output.liveTime$,this.video,t,this.params.source.url,this.params.tuning.hlsLiveNewTextManagerDownloadThreshold):this.textTracksManager=new Rt(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:El.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:El.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(je(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new wh((i=e.source.maxSeekBackTime)!=null?i:1/0),this.subscribe()}selectManifest(){var u,l,d,c;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),a=(c=(d=(u=r==null?void 0:r.to)==null?void 0:u.id)!=null?d:(l=t.getState())==null?void 0:l.id)!=null?c:"master",n=this.manifests$.getValue();if(!n.length)return;let o=i?"master":a;return i&&!r&&t.startTransitionTo(this.masterManifest),n.find(h=>h.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsLiveProvider",category:El.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},r=lt(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(ut(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Pt(this.video,t.playbackRate,r.playbackRateState$,i)),a(kt(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"),D(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),D(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(rO(),iE(o=>-o/1e3)).subscribe(this.params.output.duration$,i)),this.subscription.add(r.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&tE(l.to)){let c=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let h=this.manifests$.getValue().find(p=>p.id===c);h&&(this.params.output.currentVideoTrack$.next(h),this.params.output.hostname$.next(je(h.url)))}d&&this.params.desiredState.autoVideoTrackSwitching.setState(d.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o&&o.state==="requested"&&this.seek(o.position)},i)),this.subscription.add(r.loadedData$.subscribe(()=>{var u,l,d;let o=(d=(l=(u=this.video)==null?void 0:u.getStartDate)==null?void 0:l.call(u))==null?void 0:d.getTime();this.manifestStartTime$.next(o||void 0)},i)),this.subscription.add(eO({startTime:this.manifestStartTime$.pipe(iO(tE)),currentTime:r.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),i)),this.subscription.add(this.manifests$.pipe(iE(o=>o.map(({id:u,quality:l,size:d,bandwidth:c,fps:h})=>({id:u,quality:l,size:d,fps:h,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,i));let n=sO(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,aO(["init"])).pipe(tO(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),ot(this.video)}prepare(){var o,u,l;let e=this.selectManifest();if(wl(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:d,min:c}=(u=(o=t==null?void 0:t.to)!=null?o:i)!=null?u:{};for(let[h,p]of[[d,"mq"],[c,"lq"]]){let f=String(parseFloat(h||""));p&&h&&r.searchParams.set(p,f)}}let a=this.params.format==="HLS_LIVE_CMAF"?2:0,n=Ie(r.toString(),this.liveOffset.getTotalOffset(),a);(l=this.liveTextManager)==null||l.prepare(n),this.video.setAttribute("src",n),this.video.load(),Ih(n).then(d=>{var c;if(!wl(d))this.maxSeekBackTime$.next(d);else{let h=(c=this.params.source.maxSeekBackTime)!=null?c:this.maxSeekBackTime$.getValue();(wl(h)||!isFinite(h))&&Mt(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();Ih(g).then(S=>{wl(S)||this.maxSeekBackTime$.next(S)})}}).catch(()=>{})}})}playIfAllowed(){ct(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),D(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:El.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=Ie(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 uO,debounce as lO,ErrorCategory as Ah,fromEvent as Ph,isNonNullable as cO,isNullable as dO,map as rE,merge as sE,observableFrom as aE,Subscription as pO,ValueSubject as hO,VideoQuality as fO}from"@vkontakte/videoplayer-shared/es2015";var So=class{constructor(e){this.subscription=new pO;this.videoState=new Y("stopped");this.manifests$=new hO([]);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"),D(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(a||n||o){let d=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(d);let{currentTime:c}=this.video;this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:c*1e3,forcePrecise:!0});return}switch((r==null?void 0:r.to)!=="paused"&&l.state==="requested"&&this.seek(l.position),t){case"ready":i==="ready"?D(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),D(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"&&D(this.params.desiredState.playbackState,"playing");return;case"paused":i==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&D(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return uO(t)}};this.textTracksManager=new Rt(e.source.url),this.params=e,this.video=nt(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:fO.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(je(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),Il(Ie(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:t,textTracks:i})=>{this.manifests$.next([this.masterManifest,...t]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(i)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:Ah.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){var u,l,d,c;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),a=(c=(d=(u=r==null?void 0:r.to)==null?void 0:u.id)!=null?d:(l=t.getState())==null?void 0:l.id)!=null?c:"master",n=this.manifests$.getValue();if(!n.length)return;let o=i?"master":a;return i&&(!r||!r.from)&&t.startTransitionTo(this.masterManifest),n.find(h=>h.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsProvider",category:Ah.WTF,message:"HlsProvider internal logic error",thrown:o})},r=lt(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(rE(o=>o.to)),this.params.output.playbackState$),this.subscription.add(Kt(this.video,t.isLooped,i)),this.subscription.add(ut(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Pt(this.video,t.playbackRate,r.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),D(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),D(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i).add(r.loadedMetadata$.subscribe(()=>{var p;let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&cO(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(je(m.url)))}let c=this.params.desiredState.playbackRate.getState(),h=(p=this.params.output.element$.getValue())==null?void 0:p.playbackRate;if(c!==h){let f=this.params.output.element$.getValue();f&&(this.params.desiredState.playbackRate.setState(c),f.playbackRate=c)}d&&this.params.desiredState.autoVideoTrackSwitching.setState(d.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o.state==="requested"&&this.seek(o.position)},i))),this.subscription.add(this.manifests$.pipe(rE(o=>o.map(({id:u,quality:l,size:d,bandwidth:c,fps:h})=>({id:u,quality:l,size:d,fps:h,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,i)),!Q.device.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(sE(Ph(o,"addtrack"),Ph(o,"removetrack"),Ph(o,"change"),aE(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},i))}let n=sE(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,aE(["init"])).pipe(lO(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),ot(this.video)}prepare(){var a,n;let e=this.selectManifest();if(dO(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:o,min:u}=(n=(a=t==null?void 0:t.to)!=null?a:i)!=null?n:{};for(let[l,d]of[[o,"mq"],[u,"lq"]]){let c=String(parseFloat(l||""));d&&l&&r.searchParams.set(d,c)}}this.video.setAttribute("src",r.toString()),this.video.load()}playIfAllowed(){ct(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),D(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Ah.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var uE=H(sr(),1),Rh=H(pr(),1),lE=H(qt(),1);import{assertNever as mO,assertNonNullable as nE,debounce as bO,ErrorCategory as oE,isHigherOrEqual as gO,isLowerOrEqual as SO,isNonNullable as vO,merge as yO,observableFrom as TO,Subscription as IO,map as xO}from"@vkontakte/videoplayer-shared/es2015";var vo=class{constructor(e){this.subscription=new IO;this.videoState=new Y("stopped");this.trackUrls={};this.textTracksManager=new Rt;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"),D(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"?D(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),D(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"&&D(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&D(this.params.desiredState.playbackState,"paused");return;default:return mO(e)}};this.params=e,this.video=nt(e.container,e.tuning),this.params.output.element$.next(this.video),(0,uE.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,Rh.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:oE.WTF,message:"MpegProvider internal logic error",thrown:o})},r=lt(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(xO(o=>o.to)),this.params.output.playbackState$),this.subscription.add(Kt(this.video,t.isLooped,i)),this.subscription.add(ut(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Pt(this.video,t.playbackRate,r.playbackRateState$,i)),a(kt(this.video),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),D(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),D(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&&vO(o.to)){this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to.id].track);let d=this.params.desiredState.playbackRate.getState(),c=(l=this.params.output.element$.getValue())==null?void 0:l.playbackRate;if(d!==c){let h=this.params.output.element$.getValue();h&&(this.params.desiredState.playbackRate.setState(d),h.playbackRate=d)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.textTracksManager.connect(this.video,t,e);let n=yO(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,TO(["init"])).pipe(bO(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),ot(this.video)}prepare(){var i;let e=(i=this.params.desiredState.videoTrack.getState())==null?void 0:i.id;nE(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];nE(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=Ui(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(je(t))}playIfAllowed(){ct(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),D(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:oE.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){var l,d;this.params.output.autoVideoTrackLimits$.next(e);let t=c=>{this.params.output.currentVideoTrack$.next(c),this.params.desiredState.videoTrack.startTransitionTo(c)},i=c=>{let h=Zt(n,{container:this.video.getBoundingClientRect(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,limits:c,abrLogger:this.params.dependencies.abrLogger});t(h)},r=(l=this.params.output.currentVideoTrack$.getValue())==null?void 0:l.quality,a=!!(e.max||e.min),n=(0,Rh.default)(this.trackUrls).map(c=>c.track);if(!r||!a||Wr(e,n[0].quality,(d=(0,lE.default)(n,-1))==null?void 0:d.quality)){i();return}let o=e.max?SO(r,e.max):!0,u=e.min?gO(r,e.min):!0;o&&u||i(e)}};import{assertNever as dE,debounce as PO,merge as pE,observableFrom as RO,Subscription as kO,map as hE,ValueSubject as MO,ErrorCategory as Mh,VideoQuality as LO}from"@vkontakte/videoplayer-shared/es2015";import{ErrorCategory as EO}from"@vkontakte/videoplayer-shared/es2015";var cE=["stun:videostun.mycdn.me:80"],wO=1e3,AO=3,kh=()=>null,Al=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=kh;this.externalStopCallback=kh;this.externalErrorCallback=kh;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}}handleUpdateMessage(e){return E(this,null,function*(){try{let t=yield this.createOffer();this.peerConnection&&(yield this.peerConnection.setLocalDescription(t)),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}})}handleLogin(){return E(this,null,function*(){try{let e={iceServers:[{urls:cE}]};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=yield this.createOffer();yield this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}})}handleAnswer(e){return E(this,null,function*(){try{this.peerConnection&&(yield this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e})))}catch(t){this.handleRTCError(t)}})}handleCandidate(e){return E(this,null,function*(){if(e)try{this.peerConnection&&(yield 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:EO.WTF,message:e.message})}onPeerConnectionStream(e){return E(this,null,function*(){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()))}}createOffer(){return E(this,null,function*(){let e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");let t=yield 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),wO)}normalizeOptions(e={}){let t={stunServerList:cE,maxRetryNumber:AO,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var yo=class{constructor(e){this.videoState=new Y("stopped");this.maxSeekBackTime$=new MO(0);this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.pause(),this.video.srcObject=null,this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),D(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"),D(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"&&D(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&D(this.params.desiredState.playbackState,"paused");return;default:return dE(e)}};this.subscription=new kO,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=nt(e.container,e.tuning),this.liveStreamClient=new Al(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),ot(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,i=n=>{e.error$.next({id:"WebRTCLiveProvider",category:Mh.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};this.subscription.add(pE(this.videoState.stateChangeStarted$.pipe(hE(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(hE(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})}));let r=lt(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(kt(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(ut(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 dE(n.to)}},i)).add(pE(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,RO(["init"])).pipe(PO(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(je(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.currentVideoTrack$.next({id:"webrtc",quality:LO.INVARIANT}),this.video.srcObject=e,D(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:Mh.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){ct(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),D(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Mh.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var To=class{constructor(e){this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next()}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return!!this.current.done}};import{assertNever as xo,assertNonNullable as zi,ErrorCategory as Pl,filter as vE,isNonNullable as yE,isNullable as _O,map as FO,merge as NO,once as UO,Subject as _e,Subscription as TE,ValueSubject as J,flattenObject as Lh}from"@vkontakte/videoplayer-shared/es2015";import{Observable as BO,map as fE,Subscription as $O,Subject as DO}from"@vkontakte/videoplayer-shared/es2015";var mE=s=>new BO(e=>{let t=new $O,i=s.desiredPlaybackState$.stateChangeStarted$.pipe(fE(({from:l,to:d})=>`${l}-${d}`)),r=s.desiredPlaybackState$.stateChangeEnded$,a=s.providerChanged$.pipe(fE(({type:l})=>l!==void 0)),n=new DO,o=0,u="unknown";return t.add(i.subscribe(l=>{o&&window.clearTimeout(o),u=l,o=window.setTimeout(()=>n.next(l),s.maxTransitionInterval)})),t.add(r.subscribe(()=>{window.clearTimeout(o),u="unknown",o=0})),t.add(a.subscribe(l=>{o&&(window.clearTimeout(o),o=0,l&&(o=window.setTimeout(()=>n.next(u),s.maxTransitionInterval)))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});import{ErrorCategory as CO,Subscription as VO,combine as OO,filter as gE,once as SE}from"@vkontakte/videoplayer-shared/es2015";function bE(){return new(window.AudioContext||window.webkitAudioContext)}var Io=class Io{constructor(e,t,i,r){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=i;this.volumeMultiplier=r;this.destroyController=new le;this.subscriptions=new VO;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe(gE(a=>!!a.type),SE()).subscribe(({type:a})=>this.subscribe(a)))}subscribe(e){Q.browser.isSafari&&e!=="MPEG"||this.subscriptions.add(OO({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(gE(({playbackState:t,video:i,volume:{muted:r,volume:a}})=>t==="playing"&&!!i&&!r&&!!a),SE()).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}initAudioContextOnce(e){return E(this,null,function*(){let{volumeMultiplier:t}=this,i=bE();this.audioContext=i;let r=i.createGain();if(this.gainNode=r,r.gain.value=t,r.connect(i.destination),i.state==="suspended"&&(yield 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:Io.errorId,category:CO.VIDEO_PIPELINE,message:(t=e==null?void 0:e.message)!=null?t:`${Io.errorId} exception`,thrown:e})}};Io.errorId="VolumeMultiplierManager";var Ts=Io;var qO={chunkDuration:5e3,maxParallelRequests:5},Eo=class{constructor(e){this.current$=new J({type:void 0});this.providerError$=new _e;this.noAvailableProvidersError$=new _e;this.volumeMultiplierError$=new _e;this.providerOutput={position$:new J(0),duration$:new J(1/0),volume$:new J({muted:!1,volume:1}),availableVideoStreams$:new J([]),currentVideoStream$:new J(void 0),availableVideoTracks$:new J([]),currentVideoTrack$:new J(void 0),availableAudioStreams$:new J([]),currentAudioStream$:new J(void 0),availableAudioTracks$:new J([]),currentVideoSegmentLength$:new J(0),currentAudioSegmentLength$:new J(0),isAudioAvailable$:new J(!0),autoVideoTrackLimitingAvailable$:new J(!1),autoVideoTrackLimits$:new J(void 0),currentBuffer$:new J(void 0),isBuffering$:new J(!0),error$:new _e,fetcherError$:new _e,fetcherRecoverableError$:new _e,warning$:new _e,willSeekEvent$:new _e,soundProhibitedEvent$:new _e,seekedEvent$:new _e,loopedEvent$:new _e,endedEvent$:new _e,firstBytesEvent$:new _e,loadedMetadataEvent$:new _e,firstFrameEvent$:new _e,canplay$:new _e,isLive$:new J(void 0),isLiveEnded$:new J(null),isLowLatency$:new J(!1),canChangePlaybackSpeed$:new J(!0),liveTime$:new J(void 0),liveBufferTime$:new J(void 0),liveLatency$:new J(void 0),severeStallOccurred$:new _e,availableTextTracks$:new J([]),currentTextTrack$:new J(void 0),hostname$:new J(void 0),httpConnectionType$:new J(void 0),httpConnectionReused$:new J(void 0),inPiP$:new J(!1),inFullscreen$:new J(!1),element$:new J(void 0),elementVisible$:new J(!0),availableSources$:new J(void 0),is3DVideo$:new J(!1),playbackState$:new J(""),getCurrentTime$:new J(null)};this.subscription=new TE;this.volumeMultiplierManager=null;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer"),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name);let t=JI([...ex(this.params.tuning),...ZI(this.params.tuning)],this.params.tuning).filter(l=>yE(e.sources[l])),{forceFormat:i,formatsToAvoid:r}=this.params.tuning,a=[];i?a=[i]:r.length?a=[...t.filter(l=>!(0,Bh.default)(r,l)),...t.filter(l=>(0,Bh.default)(r,l))]:a=t,this.log({message:`Selected formats: ${a.join(" > ")}`}),this.tracer.log("Selected formats",Lh(a)),this.screenFormatsIterator=new To(a);let n=[...Bp(!0),...Bp(!1)];this.chromecastFormatsIterator=new To(n.filter(l=>yE(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:o=1,tuning:{useVolumeMultiplier:u}}=this.params;u&&o!==1&&Ts.isSupported()&&(this.volumeMultiplierManager=new Ts(this.providerOutput,this.current$,this.volumeMultiplierError$,o))}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()}))}destroy(){var e;this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe(),(e=this.volumeMultiplierManager)==null||e.destroy(),this.volumeMultiplierManager=null,this.tracer.end()}initProvider(){let e=this.chooseDestination(),t=this.chooseFormat(e);if(_O(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:Pl.WTF,message:"Failed to create provider",thrown:r})}i?this.current$.next({type:t,provider:i,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.tracer.log("reinitProvider"),this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.tracer.log("switchToNextProvider",{destination:e}),this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}destroyProvider(){let e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"}),this.tracer.log("destroyProvider"),e.destroy();let t=this.providerOutput.position$.getValue()*1e3,i=this.params.desiredState.seekState.getState(),r=i.state!=="none";if(this.params.desiredState.seekState.setState({state:"requested",position:r?i.position:t,forcePrecise:r?i.forcePrecise:!1}),e.scene3D){let n=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:n.x,y:n.y})}let a=this.providerOutput.isBuffering$;a.getValue()||a.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),this.tracer.log("createProvider",{destination:e,format:t}),e){case"SCREEN":return this.createScreenProvider(t);case"CHROMECAST":return this.createChromecastProvider(t);default:return xo(e)}}createScreenProvider(e){let{sources:t,container:i,desiredState:r,panelSize:a}=this.params,n=this.providerOutput,o={container:i,source:null,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning,panelSize:a};switch(e){case"DASH_SEP":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_ONDEMAND":case"DASH_STREAMS":{let u=this.applyFailoverHost(t[e]),l=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return zi(u),this.params.tuning.useNewDashProvider?new mo(B(x({},o),{source:u,sourceHls:l})):new Ln(B(x({},o),{source:u,sourceHls:l}))}case"DASH_LIVE_CMAF":{let u=this.applyFailoverHost(t[e]);return zi(u),this.params.tuning.useNewDashProvider?new bo(B(x({},o),{source:u})):new Bn(B(x({},o),{source:u}))}case"HLS":case"HLS_ONDEMAND":{let u=this.applyFailoverHost(t[e]);return zi(u),new So(B(x({},o),{source:u}))}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let u=this.applyFailoverHost(t[e]);return zi(u),new go(B(x({},o),{source:u,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e}))}case"MPEG":{let u=this.applyFailoverHost(t[e]);return zi(u),new vo(B(x({},o),{source:u}))}case"DASH_LIVE":{let u=this.applyFailoverHost(t[e]);return zi(u),new Jy(B(x({},o),{source:u,config:B(x({},qO),{maxPausedTime:this.params.tuning.live.maxPausedTime})}))}case"WEB_RTC_LIVE":{let u=this.applyFailoverHost(t[e]);return zi(u),new yo({container:i,source:u,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return xo(e)}}createChromecastProvider(e){let{sources:t,container:i,desiredState:r,meta:a}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return zi(o),new ka({connection:o,meta:a,container:i,source:t,format:e,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?"CHROMECAST":"SCREEN"}chooseFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case"CHROMECAST":return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return xo(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return xo(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 xo(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 B(x({},e),{url:i(e.url)})}return(0,xE.default)((0,IE.default)(e).map(([r,a])=>[r,i(a)]))}initProviderErrorHandling(){let e=new TE,t=!1,i=0;return e.add(NO(this.providerOutput.error$.pipe(vE(r=>!this.params.tuning.ignoreAudioRendererError||!r.message||!/AUDIO_RENDERER_ERROR/ig.test(r.message))),mE({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(FO(r=>({id:`ProviderHangup:${r}`,category:Pl.WTF,message:`A ${r} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.providerOutput.fetcherError$.subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;let r=this.params.desiredState.playbackState.transitionEnded$.pipe(vE(({to:a})=>a==="playing"),UO()).subscribe(()=>t=!0);e.add(r)})),e.add(this.providerError$.subscribe(r=>{let a=this.current$.getValue().destination,n={error:r,currentDestination:a};if(a==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("SCREEN"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let o=r.category===Pl.NETWORK,u=r.category===Pl.FATAL,l=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),d=i<this.params.tuning.providerErrorLimit&&!u,c=l&&!u&&(o&&t||!d);n=B(x({},n),{isNetworkError:o,isFatalError:u,haveFailoverHost:l,tryFailover:c,canReinitProvider:d}),d?(i++,this.reinitProvider()):c?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):(i=0,this.switchToNextProvider(a!=null?a:"SCREEN"))}r.traceAsLog?this.tracer.log("providerInfo",Lh(n)):this.tracer.error("providerError",Lh(n))})),e}};import{fromEvent as Rl,once as jO,combine as HO,Subscription as EE,ValueSubject as $h,map as zO,filter as QO,isNonNullable as kl,now as wt,safeStorage as Dh}from"@vkontakte/videoplayer-shared/es2015";var GO=5e3,wE="one_video_throughput",AE="one_video_rtt",ki=window.navigator.connection,PE=()=>{let s=ki==null?void 0:ki.downlink;if(kl(s)&&s!==10)return s*1e3},RE=()=>{let s=ki==null?void 0:ki.rtt;if(kl(s)&&s!==3e3)return s},kE=(s,e,t)=>{let i=t*8,r=i/s;return i/(r+e)},Ch=class s{constructor(e){this.subscription=new EE;this.concurrentDownloads=new Set;var r,a;this.tuningConfig=e;let t=s.load(wE)||(e.useBrowserEstimation?PE():void 0)||GO,i=(a=(r=s.load(AE))!=null?r:e.useBrowserEstimation?RE():void 0)!=null?a:0;if(this.throughput$=new $h(t),this.rtt$=new $h(i),this.rttAdjustedThroughput$=new $h(kE(t,i,e.rttPenaltyRequestSize)),this.throughput=wi.getSmoothedValue(t,-1,e),this.rtt=wi.getSmoothedValue(i,1,e),e.useBrowserEstimation){let n=()=>{let u=PE();u&&this.throughput.next(u);let l=RE();kl(l)&&this.rtt.next(l)};ki&&"onchange"in ki&&this.subscription.add(Rl(ki,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{Dh.set(wE,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{Dh.set(AE,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(HO({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(zO(({throughput:n,rtt:o})=>kE(n,o,e.rttPenaltyRequestSize)),QO(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=wt(),r=new EE;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add(Rl(e,"progress").pipe(jO()).subscribe(a=>{t=a.loaded,i=wt()}));break;case 1:case 0:r.add(Rl(e,"loadstart").subscribe(()=>{t=0,i=wt()}));break}r.add(Rl(e,"loadend").subscribe(a=>{if(e.status===200){let n=a.loaded,o=wt(),u=n-t,l=o-i;this.addRawSpeed(u,l,1)}this.concurrentDownloads.delete(e),r.unsubscribe()}))}trackStream(e,t=!1){let i=e.getReader();if(!i){e.cancel("Could not get reader");return}let r=0,a=wt(),n=0,o=wt(),u=d=>{this.concurrentDownloads.delete(e),i.releaseLock(),e.cancel(`Throughput Estimator error: ${d}`).catch(()=>{})},l=h=>E(this,[h],function*({done:d,value:c}){if(d)!t&&this.addRawSpeed(r,wt()-a,1),this.concurrentDownloads.delete(e);else if(c){if(t){let p=wt();if(p-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||p-a>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let m=o-a;m&&this.addRawSpeed(n,m,1,t),n=c.byteLength,a=wt()}else n+=c.byteLength;o=wt()}else r+=c.byteLength,n+=c.byteLength,n>=this.tuningConfig.streamMinSampleSize&&wt()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,wt()-o,this.concurrentDownloads.size),n=0,o=wt());yield i==null?void 0:i.read().then(l,u)}});this.concurrentDownloads.add(e),i==null||i.read().then(l,u)}addRawSpeed(e,t,i=1,r=!1){if(s.sanityCheck(e,t,r)){let a=e*8/t;this.throughput.next(a*i)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,i=!1){let r=e*8/t;return!(!r||!isFinite(r)||r>1e6||r<30||i&&e<1e4||!i&&e<10*1024||!i&&t<=20)}static load(e){var i;let t=Dh.get(e);if(kl(t))return(i=parseInt(t,10))!=null?i:void 0}},ME=Ch;import{fillWithDefault as WO,VideoQuality as Ml}from"@vkontakte/videoplayer-shared/es2015";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:Ml.Q_4320P,activeVideoAreaThreshold:.1,highQualityLimit:Ml.Q_720P,trafficSavingLimit:Ml.Q_480P},stallsManager:{enabled:!1,stallDurationNoDataBeforeQualityDecrease:500,stallDurationToBeCount:100,stallCountBeforeQualityDecrease:3,resetQualityRestrictionTimeout:1e4,ignoreStallsOnSeek:!0,stallsMetricsHistoryLength:5,maxPossibleStallDuration:3e4,minTvtToBeCounted:5,maxTvtToBeCounted:10800,significantTvt:600,targetStallsDurationPerTvt:1,deviationStallsDurationPerTvt:.5,criticalStallsDurationPerTvt:6,abrAdjustingSpeed:.1,emaAlpha:.6,useTotalStallsDurationPerTvt:!0,useAverageStallsDurationPerTvt:!0,useEmaStallsDurationPerTvt:!0},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:Ml.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,seekBiasInTheEnd:2e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,crashOnStallTimeout:25e3,crashOnStallTWithoutDataTimeout:5e3,enableSubSegmentBufferFeeding:!0,bufferEmptinessTolerance:100,useFetchPriorityHints:!0,enableBaseUrlSupport:!0,maxSegmentRetryCount:5,sourceOpenTimeout:1e3,vktvAbrThrottle:0,timeupdateEventTickThrottle:300},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,maxLiveDuration:7200,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:250,playbackCatchupSpeedup:.05,isActiveOnDefault:!1,bufferEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:"07A4434E",useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"dash",preferCMAF:!1,preferWebRTC:!1,preferMultiStream:!1,preferHDR:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,seekNearDurationBias:1,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useHlsJs:!1,useNativeHLSTextTracks:!1,useManagedMediaSource:!0,useNewSwitchTo:!1,useNewDashProvider:!1,useNewAutoSelectVideoTrack:!1,useSafariEndlessRequestBugfix:!0,useRefactoredSearchGap:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,audioVideoSyncRate:20,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50},useVolumeMultiplier:!1,ignoreAudioRendererError:!1,useEnableSubtitlesParam:!1,useOldMSEDetection:!1,useHlsLiveNewTextManager:!1,exposeInternalsToGlobal:!1,hlsLiveNewTextManagerDownloadThreshold:4e3,disableYandexPiP:!1,asyncResolveClientChecker:!1,autostartOnlyIfVisible:!1},BE=s=>{var e;return B(x({},WO(s,LE)),{configName:[...(e=s.configName)!=null?e:[],...LE.configName]})};import{assertNonNullable as Ll,combine as Mi,ErrorCategory as Bl,filter as W,filterChanged as ae,fromEvent as Oh,isNonNullable as VE,isNullable as t_,Logger as i_,map as re,mapTo as OE,merge as Qi,now as $l,once as Z,Subject as ne,Subscription as _E,tap as _h,ValueSubject as _,isHigher as r_,isInvariantQuality as FE,flattenObject as Gi,throttle as Fh,getTraceSubscriptionMethod as NE,TracerFactory as s_,InternalsExposure as a_}from"@vkontakte/videoplayer-shared/es2015";import{merge as YO,map as KO,filter as $E,isNonNullable as XO}from"@vkontakte/videoplayer-shared/es2015";var Vh=({seekState:s,position$:e})=>YO(s.stateChangeEnded$.pipe(KO(({to:t})=>{var i;return t.state==="none"?void 0:((i=t.position)!=null?i:NaN)/1e3}),$E(XO)),e.pipe($E(()=>s.getState().state==="none")));import{assertNonNullable as JO}from"@vkontakte/videoplayer-shared/es2015";var DE=s=>{let e=typeof s.container=="string"?document.getElementById(s.container):s.container;return JO(e,`Wrong container or containerId {${s.container}}`),e};import{filter as ZO,once as e_}from"@vkontakte/videoplayer-shared/es2015";var CE=(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(ZO(r=>r.length>0),e_()).subscribe(r=>{r.find(i)&&e.startTransitionTo(s)}):(s===void 0||t!=null&&t.getValue().find(i))&&e.startTransitionTo(s)};var Dl=class{constructor(e={configName:[]},t=s_.createRootTracer(!1)){this.subscription=new _E;this.logger=new i_;this.abrLogger=this.logger.createComponentLog("ABR");this.internalsExposure=null;this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new _(!1);this.hasLiveOffsetByPausedTimer=0;this.playerInitRequest=0;this.playerInited=new _(!1);this.wasSetStartedQuality=!1;this.desiredState={playbackState:new Y("stopped"),seekState:new Y({state:"none"}),volume:new Y({volume:1,muted:!1}),videoTrack:new Y(void 0),videoStream:new Y(void 0),audioStream:new Y(void 0),autoVideoTrackSwitching:new Y(!0),autoVideoTrackLimits:new Y({}),isLooped:new Y(!1),isLowLatency:new Y(!1),playbackRate:new Y(1),externalTextTracks:new Y([]),internalTextTracks:new Y([]),currentTextTrack:new Y(void 0),textTrackCuesSettings:new Y({}),cameraOrientation:new Y({x:0,y:0})};this.info={playbackState$:new _(void 0),position$:new _(0),duration$:new _(1/0),muted$:new _(!1),volume$:new _(1),availableVideoStreams$:new _([]),currentVideoStream$:new _(void 0),availableQualities$:new _([]),availableQualitiesFps$:new _({}),currentQuality$:new _(void 0),isAutoQualityEnabled$:new _(!0),autoQualityLimitingAvailable$:new _(!1),autoQualityLimits$:new _({}),predefinedQualityLimitType$:new _("unknown"),availableAudioStreams$:new _([]),currentAudioStream$:new _(void 0),availableAudioTracks$:new _([]),isAudioAvailable$:new _(!0),currentPlaybackRate$:new _(1),currentBuffer$:new _({start:0,end:0}),isBuffering$:new _(!0),isStalled$:new _(!1),isEnded$:new _(!1),isLooped$:new _(!1),isLive$:new _(void 0),isLiveEnded$:new _(null),canChangePlaybackSpeed$:new _(void 0),atLiveEdge$:new _(void 0),atLiveDurationEdge$:new _(void 0),liveTime$:new _(void 0),liveBufferTime$:new _(void 0),liveLatency$:new _(void 0),currentFormat$:new _(void 0),availableTextTracks$:new _([]),currentTextTrack$:new _(void 0),throughputEstimation$:new _(void 0),rttEstimation$:new _(void 0),videoBitrate$:new _(void 0),hostname$:new _(void 0),httpConnectionType$:new _(void 0),httpConnectionReused$:new _(void 0),surface$:new _("none"),chromecastState$:new _("NOT_AVAILABLE"),chromecastDeviceName$:new _(void 0),intrinsicVideoSize$:new _(void 0),availableSources$:new _(void 0),is3DVideo$:new _(!1),currentVideoSegmentLength$:new _(0),currentAudioSegmentLength$:new _(0)};this.events={inited$:new ne,ready$:new ne,started$:new ne,playing$:new ne,paused$:new ne,stopped$:new ne,willReady$:new ne,willStart$:new ne,willResume$:new ne,willPause$:new ne,willStop$:new ne,willDestruct$:new ne,watchCoverageRecord$:new ne,watchCoverageLive$:new ne,managedError$:new ne,fatalError$:new ne,fetcherRecoverableError$:new ne,ended$:new ne,looped$:new ne,seeked$:new ne,willSeek$:new ne,autoplaySoundProhibited$:new ne,firstBytes$:new ne,loadedMetadata$:new ne,firstFrame$:new ne,canplay$:new ne,log$:new ne,fetcherError$:new ne,severeStallOccured$:new ne};this.experimental={element$:new _(void 0),tuningConfigName$:new _([]),enableDebugTelemetry$:new _(!1),dumpTelemetry:Ey,getCurrentTime$:new _(null)};if(this.initLogs(),this.tuning=BE(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new $o({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new ME(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new a_("CORE"),this.internalsExposure.expose({player:this})),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(i,r,a)=>{let n=Reflect.get(i,r,a);return typeof n!="function"?n:(...o)=>{try{return n.apply(i,o)}catch(u){let l=o.map(h=>JSON.stringify(h,(p,f)=>{let m=typeof f;return(0,UE.default)(["number","string","boolean"],m)?f:f===null?null:`<${m}>`})),d=`Player.${String(r)}`,c=`Exception calling ${d} (${l.join(", ")})`;throw this.events.fatalError$.next({id:d,category:Bl.WTF,message:c,thrown:u}),u}}}})}initVideo(e){var a;this.config=e,(a=this.internalsExposure)==null||a.expose({config:e,logger:this.logger,tuning:this.tuning}),this.setMuted(this.tuning.isAudioDisabled);let t=()=>{var l,d,c;let u=e,{container:n}=u,o=qh(u,["container"]);this.tracer.log("initVideo",Gi(o)),this.domContainer=DE(e),this.chromecastInitializer.contentId=(l=e.meta)==null?void 0:l.videoId,this.providerContainer=new Eo({sources:e.sources,meta:(d=e.meta)!=null?d:{},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?Q.isInited$.pipe(W(n=>!!n),Z()).subscribe(()=>{console.log("Core SDK async start"),i()}):i()};return this.isNotActiveTabCase()?(this.tracer.log("request play from hidden tab"),Oh(document,"visibilitychange").pipe(Z()).subscribe(r)):r(),this}destroy(){var e,t;this.tracer.log("destroy"),window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.playerInitRequest&&window.cancelAnimationFrame(this.playerInitRequest),this.events.willDestruct$.next(),this.stop(),(e=this.providerContainer)==null||e.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe(),this.tracer.end(),(t=this.internalsExposure)==null||t.destroy()}prepare(){return this.subscription.add(this.playerInited.pipe(W(e=>!!e),Z()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("prepare",{currentPlayBackState:e.getState()}),e.getState()==="stopped"&&e.startTransitionTo("ready")})),this}play(){return this.subscription.add(this.playerInited.pipe(W(e=>!!e),Z()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("play",{currentPlayBackState:e.getState()}),e.getState()!=="playing"&&e.startTransitionTo("playing")})),this}pause(){return this.subscription.add(this.playerInited.pipe(W(e=>!!e),Z()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("pause",{currentPlayBackState:e.getState()}),e.getState()!=="paused"&&e.startTransitionTo("paused")})),this}stop(){return this.subscription.add(this.playerInited.pipe(W(e=>!!e),Z()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("stop",{currentPlayBackState:e.getState()}),e.getState()!=="stopped"&&e.startTransitionTo("stopped")})),this}seekTime(e,t=!0){return this.subscription.add(this.playerInited.pipe(W(i=>!!i),Z()).subscribe(()=>{let i=this.info.duration$.getValue(),r=this.info.isLive$.getValue(),a=e;e>=i&&!r&&(a=i-this.tuning.seekNearDurationBias),this.tracer.log("seekTime",{duration:i,isLive:r,time:e,calculatedTime:a,forcePrecise:t}),Number.isFinite(a)&&(this.events.willSeek$.next({from:this.getExactTime(),to:a}),this.desiredState.seekState.setState({state:"requested",position:a*1e3,forcePrecise:t}))})),this}seekPercent(e){return this.subscription.add(this.playerInited.pipe(W(t=>!!t),Z()).subscribe(()=>{let t=this.info.duration$.getValue();this.tracer.log("seekPercent",{percent:e,duration:t}),isFinite(t)&&this.seekTime(Math.abs(t)*e,!1)})),this}setVolume(e,t){return this.subscription.add(this.playerInited.pipe(W(i=>!!i),Z()).subscribe(()=>{var o;let i=this.desiredState.volume,r=i.getTransition(),a=(o=r==null?void 0:r.to.muted)!=null?o:this.info.muted$.getValue(),n=t!=null?t:this.tuning.isAudioDisabled||a;this.tracer.log("setVolume",{volume:e,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:n}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setVolume(e):i.startTransitionTo({volume:e,muted:n})})),this}setMuted(e,t=!1){return this.subscription.add(this.playerInited.pipe(W(i=>!!i),Z()).subscribe(()=>{var o;let i=this.desiredState.volume,r=this.tuning.isAudioDisabled&&!t||e,a=i.getTransition(),n=(o=a==null?void 0:a.to.volume)!=null?o:this.info.volume$.getValue();this.tracer.log("setMuted",{isMuted:e,nextMuted:r,volume:n,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue()}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setMuted(r):i.startTransitionTo({volume:n,muted:r})})),this}setVideoStream(e){return this.subscription.add(this.playerInited.pipe(W(t=>!!t),Z()).subscribe(()=>{this.desiredState.videoStream.startTransitionTo(e)})),this}setAudioStream(e){return this.subscription.add(this.playerInited.pipe(W(t=>!!t),Z()).subscribe(()=>{this.desiredState.audioStream.startTransitionTo(e)})),this}setQuality(e){return this.subscription.add(this.playerInited.pipe(W(t=>!!t),Z()).subscribe(()=>{Ll(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(W(i=>i.length>0),Z()).subscribe(i=>{this.setVideoTrackIdByQuality(i,e)}):this.explicitInitialQuality=e:t.length>0&&this.setVideoTrackIdByQuality(t,e)})),this}setAutoQuality(e){return this.subscription.add(this.playerInited.pipe(W(t=>!!t),Z()).subscribe(()=>{this.tracer.log("setAutoQuality",{enable:e}),this.desiredState.autoVideoTrackSwitching.startTransitionTo(e)})),this}setAutoQualityLimits(e){return this.subscription.add(this.playerInited.pipe(W(t=>!!t),Z()).subscribe(()=>{this.tracer.log("setAutoQualityLimits",Gi(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e)})),this}setPredefinedQualityLimits(e){return this.subscription.add(this.playerInited.pipe(W(t=>!!t),Z()).subscribe(()=>{if(this.info.predefinedQualityLimitType$.getValue()===e)return this;let{highQualityLimit:t,trafficSavingLimit:i}=this.tuning.autoTrackSelection,r;switch(e){case"high_quality":r={min:t,max:void 0};break;case"traffic_saving":r={max:i,min:void 0};break;default:r={max:void 0,min:void 0}}this.setAutoQualityLimits(r)})),this}setPlaybackRate(e){return this.subscription.add(this.playerInited.pipe(W(t=>!!t),Z()).subscribe(()=>{var i;Ll(this.providerContainer);let t=(i=this.providerContainer)==null?void 0:i.providerOutput.element$.getValue();this.tracer.log("setPlaybackRate",{playbackRate:e,isVideoElementAvailable:!!t}),t&&(this.desiredState.playbackRate.setState(e),t.playbackRate=e)})),this}setExternalTextTracks(e){return this.subscription.add(this.playerInited.pipe(W(t=>!!t),Z()).subscribe(()=>{e.length&&this.tracer.log("setExternalTextTracks",Gi(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>x({type:"external"},t)))})),this}selectTextTrack(e){return this.subscription.add(this.playerInited.pipe(W(t=>!!t),Z()).subscribe(()=>{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.subscription.add(this.playerInited.pipe(W(t=>!!t),Z()).subscribe(()=>{this.tracer.log("setTextTrackCueSettings",x({},e)),this.desiredState.textTrackCuesSettings.startTransitionTo(e)})),this}setLiveLowLatency(e){let t=this.info.isLive$.getValue(),i=this.desiredState.isLowLatency.getState();return!t||i===e?this:(this.tracer.log("live switch to low latency "+e),this.desiredState.isLowLatency.setState(e),this.seekTime(0))}setLooped(e){return this.subscription.add(this.playerInited.pipe(W(t=>!!t),Z()).subscribe(()=>{this.tracer.log("setLooped",{isLooped:e}),this.desiredState.isLooped.startTransitionTo(e)})),this}toggleChromecast(){this.tracer.log("toggleChromecast"),this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){return this.subscription.add(this.playerInited.pipe(W(i=>!!i),Z()).subscribe(()=>{let i=this.getScene3D();this.tracer.log("startCameraManualRotation",{isScene3DAvailable:!!i,mx:e,my:t}),i&&i.startCameraManualRotation(e,t)})),this}stopCameraManualRotation(e=!1){return this.subscription.add(this.playerInited.pipe(W(t=>!!t),Z()).subscribe(()=>{let t=this.getScene3D();this.tracer.log("stopCameraManualRotation",{isScene3DAvailable:!!t,immediate:e}),t&&t.stopCameraManualRotation(e)})),this}moveCameraFocusPX(e,t){return this.subscription.add(this.playerInited.pipe(W(i=>!!i),Z()).subscribe(()=>{let i=this.getScene3D();if(this.tracer.log("moveCameraFocusPX",{isScene3DAvailable:!!i,dxpx:e,dypx:t}),i){let r=i.getCameraRotation(),a=i.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:r.x+a.x,y:r.y+a.y})}})),this}holdCamera(){return this.subscription.add(this.playerInited.pipe(W(e=>e),Z()).subscribe(()=>{let e=this.getScene3D();e&&e.holdCamera()})),this}releaseCamera(){return this.subscription.add(this.playerInited.pipe(W(e=>!!e),Z()).subscribe(()=>{let e=this.getScene3D();e&&e.releaseCamera()})),this}getExactTime(){if(!this.providerContainer)return 0;let e=this.providerContainer.providerOutput.element$.getValue();if(t_(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),i=t.state==="none"?void 0:t.position;return VE(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(Qi(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(re(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(re(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(re(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(re(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(re(e=>e.to)).subscribe(e=>{this.info.autoQualityLimits$.next(e);let{highQualityLimit:t,trafficSavingLimit:i}=this.tuning.autoTrackSelection;this.info.predefinedQualityLimitType$.next(Yd(e,t,i))})),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(W(({from:e})=>e==="stopped"),Z()).subscribe(()=>{this.initedAt=$l(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case"ready":this.events.ready$.next();break;case"playing":this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case"paused":this.events.paused$.next();break;case"stopped":this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case"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",Gi(n)),n.state==="requested"?this.desiredState.seekState.setState(B(x({},n),{state:"applying"})):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:Bl.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe(Z()).subscribe(this.events.autoplaySoundProhibited$)).add(e.providerOutput.severeStallOccurred$.subscribe(this.events.severeStallOccured$)).add(e.providerOutput.seekedEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("seekedEvent",Gi(n)),n.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe(re(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(re(n=>n.destination),ae()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(Mi({availableVideoTracks:e.providerOutput.availableVideoTracks$,currentVideoStream:e.providerOutput.currentVideoStream$}).pipe(re(({availableVideoTracks:n,currentVideoStream:o})=>n.filter(u=>o?o.id===u.streamId:!0).map(({quality:u})=>u).sort((u,l)=>FE(u)?1:FE(l)?-1:r_(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(ae()).subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.pipe(W(n=>VE(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(ae((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe(ae((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(ae()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(ae()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(ae()).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(re(n=>n?{start:n.from,end:n.to}:{start:0,end:0})).subscribe(this.info.currentBuffer$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.isLiveEnded$.pipe(_h(n=>n&&this.stop())).subscribe(this.info.isLiveEnded$)).add(e.providerOutput.canChangePlaybackSpeed$.subscribe(this.info.canChangePlaybackSpeed$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.liveBufferTime$.subscribe(this.info.liveBufferTime$)).add(e.providerOutput.liveLatency$.subscribe(this.info.liveLatency$)).add(Mi({hasLiveOffsetByPaused:Qi(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(re(n=>n.to),ae(),re(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(Mi({atLiveEdge:Mi({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Vh({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(re(({isLive:n,position:o,isLowLatency:u})=>{let l=this.getActiveLiveDelay(u);return n&&Math.abs(o)<l/1e3}),ae(),_h(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(re(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add(Mi({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(re(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),ae(),_h(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(re(n=>n.muted),ae()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(re(n=>n.volume),ae()).subscribe(this.info.volume$)).add(Vh({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(Qi(e.providerOutput.endedEvent$.pipe(OE(!0)),e.providerOutput.seekedEvent$.pipe(OE(!1))).pipe(ae()).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(re(n=>({id:n?`No${n}`:"NoProviders",category:Bl.VIDEO_PIPELINE,message:n?`${n} was forced but failed or not available`:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.getCurrentTime$.subscribe(this.experimental.getCurrentTime$)).add(e.providerOutput.firstBytesEvent$.pipe(Z(),re(n=>n!=null?n:$l()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(Z(),re(()=>$l()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(Z(),re(()=>$l()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$)).add(e.providerOutput.availableSources$.subscribe(this.info.availableSources$));let t=new _(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let i=new _(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(W(({to:n})=>n==="playing"),Z()).subscribe(()=>i.next(!1)));let r=0,a=Qi(e.providerOutput.isBuffering$,t,i).pipe(re(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||i.getValue();return n&&!o}),ae());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(Qi(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(Qi(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,e.providerOutput.elementVisible$,this.chromecastInitializer.castState$).subscribe(()=>{let n=e.providerOutput.inPiP$.getValue(),o=e.providerOutput.inFullscreen$.getValue(),u=e.providerOutput.element$.getValue(),l=e.providerOutput.elementVisible$.getValue(),d=this.chromecastInitializer.castState$.getValue(),c;d==="CONNECTED"?c="second_screen":u?l?n?c="pip":o?c="fullscreen":c="inline":c="invisible":c="none",this.info.surface$.getValue()!==c&&this.info.surface$.next(c)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(re(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(ae((i,r)=>i.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(W(i=>i.length>0),Z()).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=Zt(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(Qi(this.desiredState.videoTrack.stateChangeStarted$.pipe(re(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(re(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(re(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(re(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(re(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(re(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(re(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(re(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(re(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;Ll(this.providerContainer),Ll(e),xy(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(i=>Iy(i)),this.providerContainer.current$.subscribe(({type:i})=>Da("provider",i)),e.duration$.subscribe(i=>Da("duration",i)),e.availableVideoTracks$.pipe(W(i=>!!i.length),Z()).subscribe(i=>Da("tracks",i)),this.events.fatalError$.subscribe(new tt("fatalError")),this.events.managedError$.subscribe(new tt("managedError")),e.position$.subscribe(new tt("position")),e.currentVideoTrack$.pipe(re(i=>i==null?void 0:i.quality)).subscribe(new tt("quality")),this.info.currentBuffer$.subscribe(new tt("buffer")),e.isBuffering$.subscribe(new tt("isBuffering"))].forEach(i=>this.subscription.add(i)),Da("codecs",Q.video.supportedCodecs)}initTracerSubscription(){let e=NE(this.tracer.log.bind(this.tracer)),t=NE(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(ae()).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(Mi({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe(W(({currentQuality:i,videoBitrate:r})=>!!i&&!!r),ae((i,r)=>i.currentQuality===r.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe(W(i=>i>0),ae()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe(W(i=>i>0),ae()).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(Mi({currentBuffer:this.info.currentBuffer$.pipe(W(i=>i.end>0),ae((i,r)=>i.end===r.end&&i.start===r.start)),position:this.info.position$.pipe(ae())}).pipe(Fh(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe(ae()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe(ae()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe(ae()).subscribe(e("canChangePlaybackSpeed"))).add(Mi({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(W(({liveTime:i,liveBufferTime:r})=>!!i&&!!r),Fh(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(ae(),W(i=>i===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(ae(),W(i=>i===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe(ae()).subscribe(e("muted"))).add(this.info.volume$.pipe(ae()).subscribe(e("volume"))).add(this.info.isEnded$.pipe(ae(),W(i=>i===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add(Mi({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(W(({throughputEstimation:i,rtt:r})=>!!i&&!!r),Fh(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(ae(),W(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=()=>E(this,null,function*(){t(),e=yield window.navigator.wakeLock.request("screen").catch(r=>{r instanceof DOMException&&r.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:Bl.DOM,message:String(r)})})});this.subscription.add(Qi(Oh(document,"visibilitychange"),Oh(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let r=document.visibilityState==="visible",a=this.desiredState.playbackState.getState()==="playing",n=!!e&&!(e!=null&&e.released);r&&a?n||i():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let i=e.find(r=>r.quality===t);this.tracer.log("setVideoTrackIdByQuality",Gi({quality:t,availableTracks:Gi(e),track:Gi(i),isAutoQuality:!i})),i?this.desiredState.videoTrack.startTransitionTo(i):this.setAutoQuality(!0)}getActiveLiveDelay(e=!1){return e?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay}isNotActiveTabCase(){return document.hidden&&this.tuning.autoplayOnlyInActiveTab&&!Ua()}};import{Subscription as pte,Observable as hte,Subject as fte,ValueSubject as mte,VideoQuality as bte}from"@vkontakte/videoplayer-shared/es2015";var gte=`@vkontakte/videoplayer-core@${jh}`;export{Ao as ChromecastState,Hl as HttpConnectionType,hte as Observable,at as PlaybackState,Dl as Player,Po as PredefinedQualityLimits,gte as SDK_VERSION,fte as Subject,pte as Subscription,zl as Surface,jh as VERSION,mte as ValueSubject,bi as VideoFormat,bte as VideoQuality,Q as clientChecker,$a as isMobile};
|
|
185
|
+
`})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(d,"i")}var Zp=H(qt(),1);import{videoSizeToQuality as hV,throttleFn as fV}from"@vkontakte/videoplayer-shared/es2015";var Px=({id:s,width:e,height:t,bitrate:i,fps:r,quality:a,streamId:n})=>{var u;let o=(u=a?Oi(a):void 0)!=null?u:hV({width:e,height:t});return o&&{id:s,quality:o,bitrate:i,size:{width:e,height:t},fps:r,streamId:n}},kx=({id:s,bitrate:e})=>({id:s,bitrate:e}),Rx=({language:s,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:s,label:e}),Mx=({language:s,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:s,label:e}),eh=({id:s,language:e,label:t,codecs:i,isDefault:r})=>({id:s,language:e,label:t,codec:(0,Zp.default)(i.split("."),0),isDefault:r}),th=({id:s,language:e,label:t,hdr:i,codecs:r})=>({id:s,language:e,hdr:i,label:t,codec:(0,Zp.default)(r.split("."),0)}),ih=s=>"url"in s,st=s=>s.type==="template",ao=s=>s instanceof DOMException&&(s.name==="AbortError"||s.code===20);var Lx=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},Ir=(s,e)=>{for(let t of s)if(e(t))return t;return null},Bx=s=>{let e=!1,t=fV(()=>{e=!0},s);return()=>{try{return t(),e}finally{e=!1}}};var Dx=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},ki=(s,e)=>{let t=s;t=(0,rh.default)(t,"$$","$");let i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[r,a]of(0,Cx.default)(i)){let n=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=(0,rh.default)(t,n,(o,u)=>$x(a)?o:$x(u)?a:(0,Vx.default)(a,parseInt(u,10),"0"))}return t},_x=(s,e)=>{var $,w,F,M,j,N,K,P,L,R,A,O,de,Fe,ue,ee,Ee,we,Ae,Ne,At,Lt,Gt,ii,Li,Is,xs,Es,ws,As,Ps,ks,Rs,Ms,Ls,Bs,$s,Ds,Cs,Vs,Os,_s,Fs,Ns,Us,qs,js,Hs,zs,Qs,Gs,Ws,Ys,Ks,Xs,Js,Zs,ea,ta,ia,ra;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(fe=>{var q,Ge;return(Ge=(q=fe.textContent)==null?void 0:q.trim())!=null?Ge:""}),o=($=(0,Ox.default)(n,0))!=null?$:"",u=a.getAttribute("type")==="dynamic",l=a.getAttribute("availabilityStartTime"),d=a.getAttribute("publishTime"),c=a.getElementsByTagName("vk:Attrs")[0],f=c==null?void 0:c.getElementsByTagName("vk:XLatestSegmentPublishTime")[0].textContent,p=c==null?void 0:c.getElementsByTagName("vk:XStreamIsLive")[0].textContent,h=c==null?void 0:c.getElementsByTagName("vk:XStreamIsUnpublished")[0].textContent,m=c==null?void 0:c.getElementsByTagName("vk:XPlaybackDuration")[0].textContent,g;u&&(g={availabilityStartTime:l?new Date(l).getTime():0,publishTime:d?new Date(d).getTime():0,latestSegmentPublishTime:f?new Date(f).getTime():0,streamIsAlive:p==="yes",streamIsUnpublished:h==="yes"});let S,v=a.getAttribute("mediaPresentationDuration"),y=[...a.getElementsByTagName("Period")],T=y.reduce((fe,q)=>B(x({},fe),{[q.id]:q.children}),{}),I=y.reduce((fe,q)=>B(x({},fe),{[q.id]:q.getAttribute("duration")}),{});v?S=Dx(v):(0,sh.default)(I).filter(fe=>fe).length&&!u?S=(0,sh.default)(I).reduce((fe,q)=>{var Ge;return fe+((Ge=Dx(q))!=null?Ge:0)},0):m&&(S=parseInt(m,10));let k=0,C=(F=(w=a.getAttribute("profiles"))==null?void 0:w.split(","))!=null?F:[];for(let fe of y.map(q=>q.id))for(let q of T[fe]){let Ge=(M=q.getAttribute("id"))!=null?M:"id"+(k++).toString(10),Bt=(j=q.getAttribute("mimeType"))!=null?j:"",Wi=(N=q.getAttribute("codecs"))!=null?N:"",Yi=(K=q.getAttribute("contentType"))!=null?K:Bt==null?void 0:Bt.split("/")[0],Cl=(L=(P=q.getAttribute("profiles"))==null?void 0:P.split(","))!=null?L:[],sa=(A=Ax((R=q.getAttribute("lang"))!=null?R:""))!=null?A:{},ri=(Fe=(de=(O=q.querySelector("Label"))==null?void 0:O.textContent)==null?void 0:de.trim())!=null?Fe:void 0,Vl=q.querySelectorAll("Representation"),Ol=q.querySelector("SegmentTemplate"),_l=(ee=(ue=q.querySelector("Role"))==null?void 0:ue.getAttribute("value"))!=null?ee:void 0,ht=Yi,G={id:Ge,language:sa.language,isDefault:_l==="main",label:ri,codecs:Wi,hdr:ht==="video"&&as(Wi),mime:Bt,representations:[]};for(let U of Vl){let Re=(Ee=U.getAttribute("lang"))!=null?Ee:void 0,$t=(Ae=(we=ri!=null?ri:q.getAttribute("label"))!=null?we:U.getAttribute("label"))!=null?Ae:void 0,si=(Lt=(At=(Ne=U.querySelector("BaseURL"))==null?void 0:Ne.textContent)==null?void 0:At.trim())!=null?Lt:"",We=new URL(si||o,e).toString(),Me=(Gt=U.getAttribute("mimeType"))!=null?Gt:Bt,ai=(Li=(ii=U.getAttribute("codecs"))!=null?ii:Wi)!=null?Li:"",ni;if(Yi==="text"){let Le=U.getAttribute("id")||"",oi=((Is=sa.privateuse)==null?void 0:Is.includes("x-auto"))||Le.includes("_auto"),Ye=U.querySelector("SegmentTemplate");if(Ye){let Dt={representationId:(xs=U.getAttribute("id"))!=null?xs:void 0,bandwidth:(Es=U.getAttribute("bandwidth"))!=null?Es:void 0},ui=parseInt((ws=U.getAttribute("bandwidth"))!=null?ws:"",10)/1e3,li=(Ps=parseInt((As=Ye.getAttribute("startNumber"))!=null?As:"",10))!=null?Ps:1,ft=parseInt((ks=Ye.getAttribute("timescale"))!=null?ks:"",10),Ki=(Rs=Ye.querySelectorAll("SegmentTimeline S"))!=null?Rs:[],mt=Ye.getAttribute("media");if(!mt)continue;let ci=[],di=0,pi="",bt=0,Ct=li,se=0;for(let me of Ki){let Ke=parseInt((Ms=me.getAttribute("d"))!=null?Ms:"",10),ce=parseInt((Ls=me.getAttribute("r"))!=null?Ls:"",10)||0,Be=parseInt((Bs=me.getAttribute("t"))!=null?Bs:"",10);se=Number.isFinite(Be)?Be:se;let Xe=Ke/ft*1e3,$e=se/ft*1e3;for(let ve=0;ve<ce+1;ve++){let De=ki(mt,B(x({},Dt),{segmentNumber:Ct.toString(10),segmentTime:(se+ve*Ke).toString(10)})),gt=($e!=null?$e:0)+ve*Xe,Ot=gt+Xe;Ct++,ci.push({time:{from:gt,to:Ot},url:De})}se+=(ce+1)*Ke,di+=(ce+1)*Xe}bt=se/ft*1e3,pi=ki(mt,B(x({},Dt),{segmentNumber:Ct.toString(10),segmentTime:se.toString(10)}));let Vt={time:{from:bt,to:1/0},url:pi},Pe={type:"template",baseUrl:We,segmentTemplateUrl:mt,initUrl:"",totalSegmentsDurationMs:di,segments:ci,nextSegmentBeyondManifest:Vt,timescale:ft};ni={id:Le,kind:"text",segmentReference:Pe,profiles:[],duration:S,bitrate:ui,mime:"",codecs:"",width:0,height:0,isAuto:oi}}else ni={id:Le,isAuto:oi,kind:"text",url:We}}else{let Le=(Ds=($s=U.getAttribute("contentType"))!=null?$s:Me==null?void 0:Me.split("/")[0])!=null?Ds:Yi,oi=(Vs=(Cs=q.getAttribute("profiles"))==null?void 0:Cs.split(","))!=null?Vs:[],Ye=parseInt((Os=U.getAttribute("width"))!=null?Os:"",10),Dt=parseInt((_s=U.getAttribute("height"))!=null?_s:"",10),ui=parseInt((Fs=U.getAttribute("bandwidth"))!=null?Fs:"",10)/1e3,li=(Ns=U.getAttribute("frameRate"))!=null?Ns:"",ft=(Us=U.getAttribute("quality"))!=null?Us:void 0,Ki=li?_u(li):void 0,mt=(qs=U.getAttribute("id"))!=null?qs:"id"+(k++).toString(10),ci=Le==="video"?`${Dt}p`:Le==="audio"?`${ui}Kbps`:ai,di=`${mt}@${ci}`,pi=[...C,...Cl,...oi],bt,Ct=U.querySelector("SegmentBase"),se=(js=U.querySelector("SegmentTemplate"))!=null?js:Ol;if(Ct){let Pe=(zs=(Hs=U.querySelector("SegmentBase Initialization"))==null?void 0:Hs.getAttribute("range"))!=null?zs:"",[me,Ke]=Pe.split("-").map(De=>parseInt(De,10)),ce={from:me,to:Ke},Be=(Qs=U.querySelector("SegmentBase"))==null?void 0:Qs.getAttribute("indexRange"),[Xe,$e]=Be?Be.split("-").map(De=>parseInt(De,10)):[],ve=Be?{from:Xe,to:$e}:void 0;bt={type:"byteRange",url:We,initRange:ce,indexRange:ve}}else if(se){let Pe={representationId:(Gs=U.getAttribute("id"))!=null?Gs:void 0,bandwidth:(Ws=U.getAttribute("bandwidth"))!=null?Ws:void 0},me=parseInt((Ys=se.getAttribute("timescale"))!=null?Ys:"",10),Ke=(Ks=se.getAttribute("initialization"))!=null?Ks:"",ce=se.getAttribute("media"),Be=(Js=parseInt((Xs=se.getAttribute("startNumber"))!=null?Xs:"",10))!=null?Js:1,Xe=ki(Ke,Pe);if(!ce)throw new ReferenceError("No media attribute in SegmentTemplate");let $e=(Zs=se.querySelectorAll("SegmentTimeline S"))!=null?Zs:[],ve=[],De=0,gt="",Ot=0;if($e.length){let hi=Be,be=0;for(let St of $e){let ye=parseInt((ea=St.getAttribute("d"))!=null?ea:"",10),Je=parseInt((ta=St.getAttribute("r"))!=null?ta:"",10)||0,fi=parseInt((ia=St.getAttribute("t"))!=null?ia:"",10);be=Number.isFinite(fi)?fi:be;let Xi=ye/me*1e3,Ji=be/me*1e3;for(let mi=0;mi<Je+1;mi++){let Nl=ki(ce,B(x({},Pe),{segmentNumber:hi.toString(10),segmentTime:(be+mi*ye).toString(10)})),aa=(Ji!=null?Ji:0)+mi*Xi,Ul=aa+Xi;hi++,ve.push({time:{from:aa,to:Ul},url:Nl})}be+=(Je+1)*ye,De+=(Je+1)*Xi}Ot=be/me*1e3,gt=ki(ce,B(x({},Pe),{segmentNumber:hi.toString(10),segmentTime:be.toString(10)}))}else if(mV(S)){let be=parseInt((ra=se.getAttribute("duration"))!=null?ra:"",10)/me*1e3,St=Math.ceil(S/be),ye=0;for(let Je=1;Je<St;Je++){let fi=ki(ce,B(x({},Pe),{segmentNumber:Je.toString(10),segmentTime:ye.toString(10)}));ve.push({time:{from:ye,to:ye+be},url:fi}),ye+=be}Ot=ye,gt=ki(ce,B(x({},Pe),{segmentNumber:St.toString(10),segmentTime:ye.toString(10)}))}let Fl={time:{from:Ot,to:1/0},url:gt};bt={type:"template",baseUrl:We,segmentTemplateUrl:ce,initUrl:Xe,totalSegmentsDurationMs:De,segments:ve,nextSegmentBeyondManifest:Fl,timescale:me}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Le||!Me)continue;let Vt={video:"video",audio:"audio",text:"text"}[Le];if(!Vt)continue;ht||(ht=Vt),ni={id:di,kind:Vt,segmentReference:bt,profiles:pi,duration:S,bitrate:ui,mime:Me,codecs:ai,width:Ye,height:Dt,fps:Ki,quality:ft}}G.language||(G.language=Re),G.label||(G.label=$t),G.mime||(G.mime=Me),G.codecs||(G.codecs=ai),G.hdr||(G.hdr=ht==="video"&&as(ai)),G.representations.push(ni)}if(ht){let U=r[ht].find(Re=>Re.id===G.id);if(U&&G.representations.every(Re=>st(Re.segmentReference)))for(let Re of U.representations){let $t=G.representations.find(Me=>Me.id===Re.id),si=$t==null?void 0:$t.segmentReference,We=Re.segmentReference;We.segments.push(...si.segments),We.nextSegmentBeyondManifest=si.nextSegmentBeyondManifest}else r[ht].push(G)}}return{duration:S,streams:r,baseUrls:n,live:g}};import{fromEvent as bV,Subscription as gV}from"@vkontakte/videoplayer-shared/es2015";var ll=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 cl=class{constructor(e,t){this.lastUpdateTs=0;this.lastCallTs=0;this.prevRanges=[];this.subscription=new gV;this.mediaSource=e,this.sourceBuffer=t,this.subscription.add(bV(this.sourceBuffer,"updateend").subscribe(()=>this.updateend()))}updateend(){if(!z(this.mediaSource,this.sourceBuffer))return;let{prevRanges:e}=this,t=ll(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 no=class{constructor(e,t,i,{fetcher:r,tuning:a,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new Er(0);this.currentLowLatencySegmentLength$=new Er(0);this.currentSegmentLength$=new Er(0);this.onLastSegment$=new Er(!1);this.fullyBuffered$=new Er(!1);this.playingRepresentation$=new Er(void 0);this.playingRepresentationInit$=new Er(void 0);this.error$=new vV;this.gaps=[];this.subscription=new yV;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new le;this.switchAbortController=new le;this.destroyAbortController=new le;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=Hi(this.destroyAbortController.signal,function(e){return X(this,null,function*(){let t=this.representations.get(e);pt(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new Sx(this.sourceBuffer),this.sourceBufferBufferedDiff=new cl(this.mediaSource,this.sourceBuffer),this.subscription.add(nh(this.sourceBuffer,"updateend").subscribe(()=>{this.maintain()})),this.subscription.add(nh(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:xr.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o||!z(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,is(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=Oe(this.sourceBuffer.buffered,o),d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,n*2,l<d).catch(c=>{this.handleAsyncError(c,"pruneBuffer")})})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);let i=this.initData.get(t.id),r=this.segments.get(t.id),a=this.parsedInitData.get(t.id);pt(i,"No init buffer for starting representation"),pt(r,"No segments for starting representation"),i instanceof ArrayBuffer&&(this.searchGaps(r,t),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(a))})}.bind(this));this.switchTo=Hi(this.destroyAbortController.signal,function(e,t=!1){return X(this,null,function*(){if(!z(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);pt(i,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if(Qe(a)||Qe(r)?yield this.loadInit(i,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),pt(r,"No segments for starting representation"),a=this.initData.get(e),!(!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer||!z(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(a,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer();else{let n=this.getCurrentPosition();ms(n)&&!this.isLive&&(this.bufferLimit=1/0,yield new Zi(this.pruneBuffer(n,1/0,!0))),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}this.maintain()}})}.bind(this));this.switchToOld=Hi(this.destroyAbortController.signal,function(e,t=!1){return X(this,null,function*(){if(!z(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);pt(i,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if(Qe(a)||Qe(r)?yield this.loadInit(i,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),pt(r,"No segments for starting representation"),a=this.initData.get(e),!(!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer||!z(this.mediaSource,this.sourceBuffer)))if(yield this.abort(),yield this.sourceBufferTaskQueue.append(a,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let n=this.getCurrentPosition();ms(n)&&(this.isLive||(this.bufferLimit=1/0,yield new Zi(this.pruneBuffer(n,1/0,!0))),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}})}.bind(this));this.seekLive=Hi(this.destroyAbortController.signal,function(e){return X(this,null,function*(){var u,l;let t=(u=(0,hl.default)(e,d=>d.representations))!=null?u:[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let d of this.representations.keys()){let c=t.find(h=>h.id===d);c&&this.representations.set(d,c);let f=this.representations.get(d);if(!f||!st(f.segmentReference))return;let p=this.getActualLiveStartingSegments(f.segmentReference);this.segments.set(f.id,p)}let i=(l=this.switchingToRepresentationId)!=null?l:this.downloadingRepresentationId,r=this.representations.get(i);pt(r);let a=this.segments.get(i);pt(a,"No segments for starting representation");let n=this.initData.get(i);if(pt(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer))return;let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(a,r),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1})}.bind(this));var d;this.fetcher=r,this.tuning=a,this.compatibilityMode=u,this.forwardBufferTarget=a.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!(l!=null&&l.live),this.baseUrls=(d=l==null?void 0:l.baseUrls)!=null?d:[],this.initData=new Map(i.map(c=>[c.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(c=>[c.id,c])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchToWithPreviousAbort(e,t=!1){!z(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new le,Hi(this.switchAbortController.signal,function(i,r=!1){return X(this,null,function*(){this.switchingToRepresentationId=i;let a=this.representations.get(i);pt(a,`No such representation ${i}`);let n=this.segments.get(i),o=this.initData.get(i);if(Qe(o)||Qe(n)?yield this.loadInit(a,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(i),pt(n,"No segments for starting representation"),o=this.initData.get(i),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer||!z(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(o,this.downloadAbortController.signal),r)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=i,yield this.dropBuffer();else{let u=this.getCurrentPosition();ms(u)&&!this.isLive&&(this.bufferLimit=this.forwardBufferTarget,yield this.pruneBuffer(u,1/0,!0)),this.downloadingRepresentationId=i,this.switchingToRepresentationId=void 0}this.maintain()}})}.bind(this))(e,t))}warmUpMediaSource(){!Qe(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}abort(){return E(this,null,function*(){for(let e of this.activeSegments)this.abortSegment(e.segment);return this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new le,this.abortBuffer()})}maintain(e=this.getCurrentPosition()){if(Qe(e)||Qe(this.downloadingRepresentationId)||Qe(this.playingRepresentationId)||Qe(this.sourceBuffer)||!z(this.mediaSource,this.sourceBuffer)||ms(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(pt(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;let r=i.find(d=>e>=d.time.from&&e<d.time.to);ms(r)&&isFinite(r.time.from)&&isFinite(r.time.to)&&this.currentSegmentLength$.next((r==null?void 0:r.time.to)-r.time.from);let a=e,n=100;if(this.playingRepresentationId!==this.downloadingRepresentationId){let d=Oe(this.sourceBuffer.buffered,e),c=r?r.time.to+n:-1/0;r&&r.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&d>=r.time.to-e+n&&(a=c)}if(isFinite(this.bufferLimit)&&is(this.sourceBuffer.buffered)>=this.bufferLimit){let d=Oe(this.sourceBuffer.buffered,e),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,d<c).catch(f=>{this.handleAsyncError(f,"pruneBuffer")});return}let u=null;if(!this.activeSegments.size&&(u=this.selectForwardBufferSegments(i,t.segmentReference.type,a),u!=null&&u.length)){let d="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if((0,pl.default)(u,r))d="high";else{let c=(0,bs.default)(u,0);c&&c.time.from-r.time.to>=this.forwardBufferTarget/2&&(d="low")}this.loadSegments(u,t,d).catch(c=>{this.handleAsyncError(c,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&r&&r.status==="fed"&&!(u!=null&&u.length)&&Oe(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let l=(0,bs.default)(i,-1);!this.isLive&&l&&(this.fullyBuffered$.next(l.time.to-e-Oe(this.sourceBuffer.buffered,e)<n),this.onLastSegment$.next(e-l.time.from>0))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let i=0,r=this.isLive?this.liveInitialAdditionalOffset:0;for(let a of e)Math.trunc(a.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:a.time.from+r,persistent:!0}),i=a.time.to;ms(t.duration)&&t.duration-i>0&&!this.isLive&&this.gaps.push({representation:t.id,from:i,to:t.duration,persistent:!0})}getActualLiveStartingSegments(e){let t=e.segments,i=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,r=[],a=0,n=t.length-1;do r.unshift(t[n]),a+=t[n].time.to-t[n].time.from,n--;while(a<i&&n>=0);return this.liveInitialAdditionalOffset=a-i,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){let t=(0,hl.default)(e==null?void 0:e.streams[this.kind],r=>r.representations).find(r=>r.id===this.downloadingRepresentationId);if(!t)return;let i=this.segments.get(t.id);if(i!=null&&i.length)return{from:i[0].time.from,to:i[i.length-1].time.to}}updateLive(e){var i,r,a,n;let t=(i=(0,hl.default)(e==null?void 0:e.streams[this.kind],o=>o.representations))!=null?i:[];if(![...this.segments.values()].every(o=>!o.length))for(let o of t){if(!o||!st(o.segmentReference))return;let u=o.segmentReference.segments.map(p=>B(x({},p),{status:"none",size:void 0})),l=100,d=(r=this.segments.get(o.id))!=null?r:[],c=(n=(a=(0,bs.default)(d,-1))==null?void 0:a.time.to)!=null?n:0,f=u==null?void 0:u.findIndex(p=>c>=p.time.from+l&&c<=p.time.to+l);if(f===-1){this.liveUpdateSegmentIndex=0;let p=this.getActualLiveStartingSegments(o.segmentReference);this.segments.set(o.id,p)}else{let p=u.slice(f+1);this.segments.set(o.id,[...d,...p])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;pt(e);let t=this.segments.get(e);if(t!=null&&t.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}updateLowLatencyLiveIfNeeded(e){let t=0;for(let i of this.representations.values()){let r=i.segmentReference;if(!st(r))return;let a=this.segments.get(i.id);if(!a)continue;let n=a.find(u=>Math.floor(u.time.from)===Math.floor(e.time.from));if(n&&!isFinite(n.time.to)&&(n.time.to=e.time.to,t=n.time.to-n.time.from),!!!a.find(u=>Math.floor(u.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let u=Math.round(e.time.to*r.timescale/1e3).toString(10),l=ki(r.segmentTemplateUrl,{segmentTime:u});a.push({status:"none",time:{from:e.time.to,to:1/0},url:l})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){var a,n,o;let t=(n=(a=this.switchingToRepresentationId)!=null?a:this.downloadingRepresentationId)!=null?n:this.playingRepresentationId;if(!t)return;let i=this.segments.get(t);if(!i)return;let r=i.find(u=>u.time.from<=e&&u.time.to>=e);return(o=r==null?void 0:r.time.from)!=null?o:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e,t;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)==null||e.destroy(),(t=this.sourceBufferBufferedDiff)==null||t.destroy(),this.gapDetectionIdleCallback&&ei&&ei(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&ei&&ei(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:f,time:{from:p,to:h}},m)=>{let g=p<=i&&h>=i,S=p>i||g||m===0&&i===0,v=Math.min(this.forwardBufferTarget,this.bufferLimit),y=this.preloadOnly&&p<=i+v||r<v&&h-p>=v||h<=i+v;return(f==="none"||f==="partially_ejected"&&S&&y&&this.sourceBuffer&&z(this.mediaSource,this.sourceBuffer)&&!(He(this.sourceBuffer.buffered,p)&&He(this.sourceBuffer.buffered,h)))&&S&&y});if(a===-1)return null;if(t!=="byteRange")return e.slice(a,a+1);let n=e,o=0,u=0,l=[],d=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,c=this.preloadOnly?this.forwardBufferTarget:0;for(let f=a;f<n.length&&(o<=d||u<=c);f++){let p=n[f];if(o+=p.byte.to+1-p.byte.from,u+=p.time.to+1-p.time.from,p.status==="none"||p.status==="partially_ejected")l.push(p);else break}return l}loadSegments(e,t,i="auto"){return E(this,null,function*(){st(t.segmentReference)?yield this.loadTemplateSegment(e[0],t,i):yield this.loadByteRangeSegments(e,t,i)})}loadTemplateSegment(e,t,i="auto"){return E(this,null,function*(){e.status="downloading";let r={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(r);let{range:a,url:n,signal:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(yield Hi(o,function(){return X(this,null,function*(){let d=oh(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,d))})}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let d=yield this.fetcher.fetch(n,{range:a,signal:o,onProgress:u,priority:i,isLowLatency:this.isActiveLowLatency()});if(this.lastDataObtainedTimestampMs=dl(),!d)return;let c=new DataView(d),f=so(t.mime);if(!isFinite(r.segment.time.to)){let m=t.segmentReference.timescale;r.segment.time.to=f.getChunkEndTime(c,m)}u&&r.feedingBytes&&l?yield Promise.all(l):yield this.sourceBufferTaskQueue.append(c,o);let{serverDataReceivedTimestamp:p,serverDataPreparedTime:h}=f.getServerLatencyTimestamps(c);p&&h&&this.currentLiveSegmentServerLatency$.next(h-p),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(d){this.abortActiveSegments([e]),ao(d)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}})}updateRepresentationsBaseUrlIfNeeded(){if(!this.tuning.dash.enableBaseUrlSupport||!this.baseUrls.length||this.failedDownloads<=this.tuning.dash.maxSegmentRetryCount)return;this.baseUrlsIndex=(this.baseUrlsIndex+1)%this.baseUrls.length;let e=this.baseUrls[this.baseUrlsIndex];for(let t of this.representations.values())st(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}loadByteRangeSegments(e,t,i="auto"){return E(this,null,function*(){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&&(yield Hi(n,function(){return X(this,null,function*(){let u=oh(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),nh(window,"online").pipe(SV()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{yield this.fetcher.fetch(a,{range:r,onProgress:o,signal:n,priority:i}),this.lastDataObtainedTimestampMs=dl(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),ao(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}})}prepareByteRangeFetchSegmentParams(e,t){if(st(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:(0,bs.default)(e,0).byte.from,to:(0,bs.default)(e,-1).byte.to},{signal:a}=this.downloadAbortController;return{url:i,range:r,signal:a,onProgress:(o,u)=>E(this,null,function*(){if(!a.aborted)try{this.lastDataObtainedTimestampMs=dl(),yield this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:a,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:xr.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}})}}prepareTemplateFetchSegmentParams(e,t){if(!st(t.segmentReference))throw new Error("Representation is not template type");let i=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&i.searchParams.set("low-latency","yes");let r=i.toString(),{signal:a}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,d)=>{if(!a.aborted)try{this.lastDataObtainedTimestampMs=dl();let c=this.onSomeTemplateDataLoaded({dataView:l,loaded:d,signal:a,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(c)}catch(c){this.error$.next({id:"SegmentFeeding",category:xr.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}}:void 0;return{url:r,signal:a,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,pl.default)(e,t.segment)&&this.abortSegment(t.segment)}onSomeTemplateDataLoaded(n){return E(this,arguments,function*({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:a}){if(!this.activeSegments.size||!z(this.mediaSource,this.sourceBuffer))return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){let{segment:l}=u;if(u.representationId===t){if(a.aborted){r();continue}if(u.loadedBytes=i,u.loadedBytes>u.feedingBytes){let d=new DataView(e.buffer,e.byteOffset+u.feedingBytes,u.loadedBytes-u.feedingBytes),c=so(o.mime).parseFeedableSegmentChunk(d,this.isLive);c!=null&&c.byteLength&&(l.status="partially_fed",u.feedingBytes+=c.byteLength,yield this.sourceBufferTaskQueue.append(c),u.fedBytes+=c.byteLength)}}}})}onSomeByteRangesDataLoaded(o){return E(this,arguments,function*({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:a,onSegmentAppendFailed:n}){if(!this.activeSegments.size||!z(this.mediaSource,this.sourceBuffer))return;let u=this.representations.get(t);if(u)for(let l of this.activeSegments){if(l.representationId!==t)continue;if(a.aborted){yield n();continue}let{segment:d}=l,c=d.byte.from-i,f=d.byte.to-i,p=f-c+1,h=c<r,m=f<=r;if(h){if(d.status==="downloading"&&m){d.status="downloaded";let g=new DataView(e.buffer,e.byteOffset+c,p);(yield this.sourceBufferTaskQueue.append(g,a))&&!a.aborted?this.onSegmentFullyAppended(l,t):yield n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(d.status==="downloading"||d.status==="partially_fed")&&(l.loadedBytes=Math.min(p,r-c),l.loadedBytes>l.feedingBytes)){let g=new DataView(e.buffer,e.byteOffset+c+l.feedingBytes,l.loadedBytes-l.feedingBytes),S=l.loadedBytes===p?g:so(u.mime).parseFeedableSegmentChunk(g);S!=null&&S.byteLength&&(d.status="partially_fed",l.feedingBytes+=S.byteLength,(yield this.sourceBufferTaskQueue.append(S,a))&&!a.aborted?(l.fedBytes+=S.byteLength,l.fedBytes===p&&this.onSegmentFullyAppended(l,t)):yield n())}}}})}onSegmentFullyAppended(e,t){if(!(Qe(this.sourceBuffer)||!z(this.mediaSource,this.sourceBuffer))){!this.isLive&&Q.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(He(this.sourceBuffer.buffered,e.segment.time.from,100)&&He(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:xr.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",ih(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=ts(()=>(0,Fx.default)(this.loadInit(i,"low",!1),()=>this.initLoadIdleCallback=null)))}loadInit(e,t="auto",i=!1){return E(this,null,function*(){let r=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!i&&this.failedDownloads>0?Hi(this.destroyAbortController.signal,function(){return X(this,null,function*(){let o=oh(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))})}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,so(e.mime),r)).then(o=>{if(!o)return;let{init:u,dataView:l,segments:d}=o,c=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,c);let f=d;this.isLive&&st(e.segmentReference)&&(f=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,f),u&&this.parsedInitData.set(e.id,u)}).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:xr.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n})}dropBuffer(){return E(this,null,function*(){for(let e of this.segments.values())for(let t of e)t.status="none";yield this.pruneBuffer(0,1/0,!0)})}pruneBuffer(e,t,i=!1){return E(this,null,function*(){if(!this.sourceBuffer||!z(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||Qe(e))return!1;this.checkEjectedSegments();let r=[],a=0,n=o=>{var l;if(a>=t)return;r.push(x({},o.time));let u=ih(o)?(l=o.size)!=null?l:0:o.byte.to-o.byte.from;a+=u};for(let o of this.segments.values())for(let u of o){let l=u.time.to<=e-this.tuning.dash.bufferPruningSafeZone,d=u.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(l||d)&&u.status==="fed"&&n(u)}for(let o=0;o<this.sourceBuffer.buffered.length;o++){let u=this.sourceBuffer.buffered.start(o)*1e3,l=this.sourceBuffer.buffered.end(o)*1e3,d=0;for(let c of this.segments.values())for(let f of c)(0,pl.default)(["none","partially_ejected"],f.status)&&Math.round(f.time.from)<=Math.round(u)&&Math.round(f.time.to)>=Math.round(l)&&d++;if(d===this.segments.size){let c={time:{from:u,to:l},url:"",status:"none"};n(c)}}if(r.length&&i){let o=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let u of this.segments.values())for(let l of u)l.time.from>=e+o&&l.status==="fed"&&n(l)}return r.length?(r=Lx(r),(yield Promise.all(r.map(u=>this.sourceBufferTaskQueue.remove(u.from,u.to)))).reduce((u,l)=>u||l,!1)):!1})}abortBuffer(){return E(this,null,function*(){if(!this.sourceBuffer||!z(this.mediaSource,this.sourceBuffer))return!1;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;return this.sourceBufferTaskQueue.abort(t)})}getDebugBufferState(){if(!(!this.sourceBuffer||!z(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}getBufferedTo(){return!this.sourceBuffer||!z(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length?null:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}getForwardBufferDuration(e=this.getCurrentPosition()){return!this.sourceBuffer||!z(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||Qe(e)?0:Oe(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!this.sourceBuffer||!z(this.mediaSource,this.sourceBuffer))return;let{buffered:i}=this.sourceBuffer;this.tuning.useRefactoredSearchGap&&(this.gaps=this.gaps.filter(a=>{if(a.persistent)return!0;let n=Math.round(a.from),o=Math.round(a.to);for(let u=0;u<i.length;u++)if(n>=Math.round(i.start(u)*1e3)&&o<=Math.round(i.end(u)*1e3))return!1;return!0}));let r={representation:e,from:t.time.from,to:t.time.to,persistent:!1};for(let a=0;a<i.length;a++){let n=i.start(a)*1e3,o=i.end(a)*1e3;if(!(o<=t.time.from||n>=t.time.to)){if(n<=t.time.from&&o>=t.time.to){r=void 0;break}o>t.time.from&&o<t.time.to&&(r.from=o),n<t.time.to&&n>t.time.from&&(r.to=n)}}r&&r.to-r.from>1&&!this.gaps.some(a=>r&&a.from===r.from&&a.to===r.to)&&this.gaps.push(r)}detectGapsWhenIdle(e,t){if(!(this.gapDetectionIdleCallback||!this.sourceBuffer||!z(this.mediaSource,this.sourceBuffer))){if(!this.tuning.useRefactoredSearchGap)for(let i=0;i<this.sourceBuffer.buffered.length;i++)this.gaps=this.gaps.filter(r=>r.persistent||this.sourceBuffer&&(Math.round(r.from)<Math.round(this.sourceBuffer.buffered.start(i)*1e3)||Math.round(r.to)>Math.round(this.sourceBuffer.buffered.end(i)*1e3)));this.gapDetectionIdleCallback=ts(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:xr.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if(Qe(this.sourceBuffer)||!z(this.mediaSource,this.sourceBuffer)||Qe(this.playingRepresentationId)||this.sourceBufferBufferedDiff&&!this.sourceBufferBufferedDiff.wasUpdated())return;let e=ll(this.sourceBuffer.buffered),t=100;for(let i of this.segments.values())for(let r of i){let{status:a}=r;if(a!=="fed"&&a!=="partially_ejected")continue;let n=Math.floor(r.time.from),o=Math.ceil(r.time.to),u=!1,l=0;for(let d=0;d<e.length;d+=2){let c=e[d],f=e[d+1];u||(u=c-t<=n&&f+t>=o),(n>=c&&n<f-t||o>c+t&&o<=f)&&(l+=1)}u||(l===1?r.status="partially_ejected":this.gaps.some(d=>d.from===r.time.from||d.to===r.time.to)?r.status="partially_ejected":r.status="none")}}handleAsyncError(e,t){this.error$.next({id:t,category:xr.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}};import{abortable as oo,assertNever as Nx,fromEvent as Ux,merge as TV,now as uo,Subject as qx,ValueSubject as uh,flattenObject as gs,ErrorCategory as lo,SubscriptionRemovable as IV}from"@vkontakte/videoplayer-shared/es2015";var ml=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:a=!1}){this.lastConnectionType$=new uh(void 0);this.lastConnectionReused$=new uh(void 0);this.lastRequestFirstBytes$=new uh(void 0);this.recoverableError$=new qx;this.error$=new qx;this.abortAllController=new le;this.subscription=new IV;this.fetchManifest=oo(this.abortAllController.signal,function(e){return X(this,null,function*(){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=Ui(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=ju(i));let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(fl);return r?(t.log("success",gs({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(r.headers),r.text()):(t.error("error",gs({url:i,message:"No data in request manifest"})),t.end(),null)})}.bind(this));this.fetch=oo(this.abortAllController.signal,function(l){return X(this,arguments,function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:a="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1}={}){var j,N,K;let d=e,c=new Headers,f=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{c.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let P=new URL(d,location.href);P.searchParams.append("bytes",`${i.from}-${i.to}`),d=P.toString();break}default:Nx(t)}this.requestQuic&&(d=Ui(d));let p=this.abortAllController.signal,h;if(n){let P=new le;if(h=TV(Ux(this.abortAllController.signal,"abort"),Ux(n,"abort")).subscribe(()=>{try{P.abort()}catch(L){fl(L)}}),this.subscription.add(h),this.abortAllController.signal.aborted||n.aborted)try{P.abort()}catch(L){fl(L)}p=P.signal}let m=uo();f.log("startRequest",gs({url:d,priority:a,rangeMethod:t,range:i,isLowLatency:u,requestStartedAt:m}));let g=yield this.doFetch(d,{priority:a,headers:c,signal:p}),S=uo();if(!g)return f.error("error",{message:"No response in request"}),f.end(),this.unsubscribeAbortSubscription(h),null;if((j=this.throughputEstimator)==null||j.addRawRtt(S-m),!g.ok||!g.body){this.unsubscribeAbortSubscription(h);let P=`Fetch error ${g.status}: ${g.statusText}`;return f.error("error",{message:P}),f.end(),Promise.reject(new Error(`Fetch error ${g.status}: ${g.statusText}`))}if(this.onHeadersReceived(g.headers),!r&&!o){this.unsubscribeAbortSubscription(h);let P=uo(),L={requestStartedAt:m,requestEndedAt:P,duration:P-m};return f.log("endRequest",gs(L)),f.end(),g.arrayBuffer()}let v=g.body;if(o){let P;[v,P]=g.body.tee(),(N=this.throughputEstimator)==null||N.trackStream(P,u)}let y=v.getReader(),T,I=parseInt((K=g.headers.get("content-length"))!=null?K:"",10);Number.isFinite(I)&&(T=I),!T&&i&&(T=i.to-i.from+1);let k=0,C=T?new Uint8Array(T):new Uint8Array(0),V=!1,$=P=>{this.unsubscribeAbortSubscription(h),V=!0,fl(P)},w=oo(p,function(R){return X(this,arguments,function*({done:P,value:L}){if(k===0&&this.lastRequestFirstBytes$.next(uo()-m),p.aborted){this.unsubscribeAbortSubscription(h);return}if(!P&&L){if(T)C.set(L,k),k+=L.byteLength;else{let A=new Uint8Array(C.length+L.length);A.set(C),A.set(L,C.length),C=A,k+=L.byteLength}r==null||r(new DataView(C.buffer),k),yield y==null?void 0:y.read().then(w,$)}})}.bind(this));yield y==null?void 0:y.read().then(w,$),this.unsubscribeAbortSubscription(h);let F=uo(),M={failed:V,requestStartedAt:m,requestEndedAt:F,duration:F-m};return V?(f.error("endRequest",gs(M)),f.end(),null):(f.log("endRequest",gs(M)),f.end(),C.buffer)})}.bind(this));this.fetchByteRangeRepresentation=oo(this.abortAllController.signal,function(e,t,i){return X(this,null,function*(){var S;if(e.type!=="byteRange")return null;let{from:r,to:a}=e.initRange,n=r,o=a,u=!1,l,d;e.indexRange&&(l=e.indexRange.from,d=e.indexRange.to,u=a+1===l,u&&(n=Math.min(l,r),o=Math.max(d,a))),n=Math.min(n,0);let c=yield this.fetch(e.url,{range:{from:n,to:o},priority:i,measureThroughput:!1});if(!c)return null;let f=new DataView(c,r-n,a-n+1);if(!t.validateData(f))throw new Error("Invalid media file");let p=t.parseInit(f),h=(S=e.indexRange)!=null?S:t.getIndexRange(p);if(!h)throw new ReferenceError("No way to load representation index");let m;if(u)m=new DataView(c,h.from-n,h.to-h.from+1);else{let v=yield this.fetch(e.url,{range:h,priority:i,measureThroughput:!1});if(!v)return null;m=new DataView(v)}let g=t.parseSegments(m,p,h);return{init:p,dataView:new DataView(c),segments:g}})}.bind(this));this.fetchTemplateRepresentation=oo(this.abortAllController.signal,function(e,t){return X(this,null,function*(){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=>B(x({},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}=qu(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}fetchRepresentation(e,t,i="auto"){return E(this,null,function*(){var a,n;let{type:r}=e;switch(r){case"byteRange":return(a=yield this.fetchByteRangeRepresentation(e,t,i))!=null?a:null;case"template":return(n=yield this.fetchTemplateRepresentation(e,i))!=null?n:null;default:Nx(r)}})}destroy(){this.abortAllController.abort(),this.tracer.end(),this.subscription.unsubscribe()}doFetch(e,t){return E(this,null,function*(){let i=yield Mt(e,t);if(i.ok)return i;let r=yield i.text(),a=parseInt(r);if(!isNaN(a))switch(a){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:lo.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:lo.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:lo.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:lo.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${a})`,category:lo.FATAL})}})}unsubscribeAbortSubscription(e){e&&(e.unsubscribe(),this.subscription.remove(e))}},fl=s=>{if(!ao(s))throw s};import{isNullable as xV,ValueSubject as EV}from"@vkontakte/videoplayer-shared/es2015";var co=class s{constructor(e,t){this.currentRepresentation$=new EV(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(!xV(e))for(let i of this.representations)for(let r of i){let a=r.segmentReference,n=a.segments.length,o=a.segments[0].time.from,u=a.segments[n-1].time.to;if(e<o||e>u)continue;let l=a.segments.find(d=>d.time.from<=e&&d.time.to>=e);!l||((t=this.currentSegment)==null?void 0:t.time.from)===l.time.from&&this.currentSegment.time.to===l.time.to||(this.currentSegment=l,this.currentRepresentation$.next(B(x({},r),{label:"Live Text",language:"ru",isAuto:!0,url:new URL(l.url,a.baseUrl).toString()})))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e!=null?e:[]){let i=s.filterRepresentations(t.representations);if(i){this.representations[this.representationsCursor]=i,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!(e!=null&&e.some(t=>s.filterRepresentations(t.representations)))}static filterRepresentations(e){return e==null?void 0:e.filter(t=>t.kind==="text"&&"segmentReference"in t&&st(t.segmentReference))}};var RV=["progress","play","seeked","stalled","waiting"],MV=["timeupdate","progress","loadeddata","playing","seeked"];var Sl=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new hh;this.representationSubscription=new hh;this.state$=new Y("none");this.currentVideoRepresentation$=new Se(void 0);this.currentVideoRepresentationInit$=new Se(void 0);this.currentAudioRepresentation$=new Se(void 0);this.currentVideoSegmentLength$=new Se(0);this.currentAudioSegmentLength$=new Se(0);this.error$=new gl;this.lastConnectionType$=new Se(void 0);this.lastConnectionReused$=new Se(void 0);this.lastRequestFirstBytes$=new Se(void 0);this.currentLiveTextRepresentation$=new Se(null);this.isLive$=new Se(!1);this.isActiveLive$=new Se(!1);this.isLowLatency$=new Se(!1);this.liveDuration$=new Se(0);this.liveSeekableDuration$=new Se(0);this.liveAvailabilityStartTime$=new Se(0);this.liveStreamStatus$=new Se(void 0);this.bufferLength$=new Se(0);this.liveLatency$=new Se(void 0);this.liveLoadBufferLength$=new Se(0);this.livePositionFromPlayer$=new Se(0);this.currentStallDuration$=new Se(0);this.videoLastDataObtainedTimestamp$=new Se(0);this.fetcherRecoverableError$=new gl;this.fetcherError$=new gl;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new gl;this.gapWatchdogActive=!1;this.destroyController=new le;this.initManifest=ch(this.destroyController.signal,function(e,t,i){return X(this,null,function*(){var r;this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=Ie(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:Qt.PARSER,message:"No playable video representations"})})}.bind(this));this.updateManifest=ch(this.destroyController.signal,function(){return X(this,null,function*(){var n,o;this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(u=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:Qt.NETWORK,message:"Failed to load manifest",thrown:u})});if(!e)return null;let t=null;try{t=_x(e!=null?e:"",this.manifestUrlString)}catch(u){let l=(n=Ou(e))!=null?n:{id:"ManifestParsing",category:Qt.PARSER,message:"Failed to parse MPD manifest",thrown:u};this.error$.next(l)}if(!t)return null;let i=(u,l,d)=>{var c,f,p,h;return!!((f=(c=this.element)==null?void 0:c.canPlayType)!=null&&f.call(c,l)&&((h=(p=Et())==null?void 0:p.isTypeSupported)!=null&&h.call(p,`${l}; codecs="${d}"`))||u==="text")};if(t.live){this.isLive$.next(!!t.live);let{availabilityStartTime:u,latestSegmentPublishTime:l,streamIsUnpublished:d,streamIsAlive:c}=t.live,f=((o=t.duration)!=null?o:0)/1e3;this.liveSeekableDuration$.next(-1*f),this.liveDuration$.next((l-u)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let p="active";c||(p=d?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(p)}let r={text:t.streams.text,video:[],audio:[]};for(let u of["video","audio"]){let d=t.streams[u].filter(({mime:p,codecs:h})=>i(u,p,h)),c=new Set(d.map(({codecs:p})=>p)),f=Ju(c);if(f&&(r[u]=d.filter(({codecs:p})=>p.startsWith(f))),u==="video"){let p=this.tuning.preferHDR,h=r.video.some(g=>g.hdr),m=r.video.some(g=>!g.hdr);Q.display.isHDR&&p&&h?r.video=r.video.filter(g=>g.hdr):m&&(r.video=r.video.filter(g=>!g.hdr))}}let a=B(x({},t),{streams:r});return this.tracer.log("updateManifestEnd",ho(a)),a})}.bind(this));this.initRepresentations=ch(this.destroyController.signal,function(e,t,i){return X(this,null,function*(){var f;this.tracer.log("initRepresentationsStart",ho({initialVideo:e,initialAudio:t,sourceHls:i})),Ss(this.manifest),Ss(this.element),this.representationSubscription.unsubscribe(),this.representationSubscription=new hh,this.state$.startTransitionTo("representations_ready");let r=p=>{this.representationSubscription.add(ti(p,"error").pipe(bl(h=>{var m;return!!((m=this.element)!=null&&m.played.length)})).subscribe(h=>{this.error$.next({id:"VideoSource",category:Qt.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=this.tuning.useManagedMediaSource?hu():new MediaSource;let a=document.createElement("source");if(r(a),a.src=URL.createObjectURL(this.source),this.element.appendChild(a),this.tuning.useManagedMediaSource&&Gr())if(i){let p=document.createElement("source");r(p),p.type="application/x-mpegurl",p.src=i.url,this.element.appendChild(p)}else this.element.disableRemotePlayback=!0;this.isActiveLive$.next(this.isLive$.getValue());let n={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),manifest:this.manifest},o=this.manifest.streams.video.reduce((p,h)=>[...p,...h.representations],[]);if(this.videoBufferManager=new no("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],fo(t)){let p=this.manifest.streams.audio.reduce((h,m)=>[...h,...m.representations],[]);this.audioBufferManager=new no("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}co.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new co(this.manifest.streams.text,n)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$));let u=()=>{var p;(p=this.stallWatchdogSubscription)==null||p.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add(wr(...MV.map(p=>ti(this.element,p))).pipe(ys(p=>this.element?Oe(this.element.buffered,this.element.currentTime*1e3):0),po(),kV(p=>{p>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add(wr(ti(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe(po()).subscribe(h=>this.liveStreamEndTimestamp=ph())),this.subscription.add(ti(this.element,"pause").subscribe(()=>{this.livePauseWatchdogSubscription=dh(1e3).subscribe(h=>{let m=Ci(this.manifestUrlString,2);this.manifestUrlString=Ie(this.manifestUrlString,m+1e3,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add(ti(this.element,"play").subscribe(h=>{var m;return(m=this.livePauseWatchdogSubscription)==null?void 0:m.unsubscribe()})),this.representationSubscription.add(vs({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(ys(({isActiveLive:h,isLowLatency:m})=>h&&m),po()).subscribe(h=>{this.isManualDecreasePlaybackInLive()||ls(this.element,1)})),this.representationSubscription.add(vs({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(bl(({bufferLength:h,isActiveLive:m,isLowLatency:g})=>m&&g&&!!h)).subscribe(({bufferLength:h})=>this.liveBuffer.next(h))),this.representationSubscription.add(this.videoBufferManager.currentLowLatencySegmentLength$.subscribe(h=>{if(!this.isActiveLive$.getValue()&&!this.isLowLatency$.getValue()&&!h)return;let m=this.liveSeekableDuration$.getValue()-h/1e3;this.liveSeekableDuration$.next(Math.max(m,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+h/1e3)})),this.representationSubscription.add(vs({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(bl(({isLive:h})=>h),po((h,m)=>m.bufferLength<h.bufferLength),ys(({rtt:h,bufferLength:m,segmentServerLatency:g})=>{let S=Ci(this.manifestUrlString,2);return(h/2+m+g+S)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(vs({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:h,isActiveLive:m,isLowLatency:g})=>{if(!g||!m)return;let S=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,v=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,y=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,T=h-S;if(this.isManualDecreasePlaybackInLive())return;let I=1;Math.abs(T)>v&&(I=1+Math.sign(T)*y),ls(this.element,I)})),this.representationSubscription.add(this.bufferLength$.subscribe(h=>{var g,S;let m=0;if(h){let v=((S=(g=this.element)==null?void 0:g.currentTime)!=null?S:0)*1e3;m=Math.min(...this.bufferManagers.map(T=>{var I,k;return(k=(I=T.getLiveSegmentsToLoadState(this.manifest))==null?void 0:I.to)!=null?k:v}))-v}this.liveLoadBufferLength$.getValue()!==m&&this.liveLoadBufferLength$.next(m)}));let p=0;this.representationSubscription.add(vs({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(zx(1e3)).subscribe(g=>E(this,[g],function*({liveLoadBufferLength:h,bufferLength:m}){if(!this.element||this.isUpdatingLive)return;let S=this.element.playbackRate,v=Ci(this.manifestUrlString,2),y=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,T=Math.min(y,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*S),I=this.tuning.dashCmafLive.normalizedActualBufferOffset*S,k=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*S,C=isFinite(h)?h:m,V=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),$=y<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next($);let w="none";if(V?w="active_low_latency":this.isLowLatency$.getValue()&&$?(this.bufferManagers.forEach(F=>F.proceedLowLatencyLive()),w="active_low_latency"):v!==0&&C<T?w="live_forward_buffering":C<T+k&&(w="live_with_target_offset"),isFinite(h)&&(p=h>p?h:p),w==="live_forward_buffering"||w==="live_with_target_offset"){let F=p-(T+I),M=this.normolizeLiveOffset(Math.trunc(v+F/S)),j=Math.abs(M-v),N=0;!h||j<=this.tuning.dashCmafLive.offsetCalculationError?N=v:M>0&&j>this.tuning.dashCmafLive.offsetCalculationError&&(N=M),this.manifestUrlString=Ie(this.manifestUrlString,N,2)}(w==="live_with_target_offset"||w==="live_forward_buffering")&&(p=0,yield this.updateLive())}),h=>{this.error$.next({id:"updateLive",category:Qt.VIDEO_PIPELINE,thrown:h,message:"Failed to update live with subscription"})}))}let l=wr(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe(ys(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),d=wr(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe(ys(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue()))),c=vs({allBuffersFull:l,someBufferEnded:d}).pipe(po(),ys(({allBuffersFull:p,someBufferEnded:h})=>p&&h),bl(p=>p));if(this.representationSubscription.add(wr(this.forceEnded$,c).subscribe(()=>{var p;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(h=>!h.updating))try{(p=this.source)==null||p.endOfStream()}catch(h){this.error$.next({id:"EndOfStream",category:Qt.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:h})}})),this.representationSubscription.add(wr(...this.bufferManagers.map(p=>p.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.representationSubscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.representationSubscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.liveTextManager&&this.representationSubscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$)),this.source.readyState!=="open"){let p=this.tuning.dash.sourceOpenTimeout>=0;yield new Promise(h=>{var m;p&&(this.timeoutSourceOpenId=setTimeout(()=>{var g;if(((g=this.source)==null?void 0:g.readyState)==="open"){h();return}this.error$.next({id:"OpenOfStream",category:Qt.VIDEO_PIPELINE,message:"Failed to open MediaSource",thrown:new Error("Timeout reject when wait sourceopen event"),traceAsLog:!0})},this.tuning.dash.sourceOpenTimeout)),(m=this.source)==null||m.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),h()},{once:!0})})}if(!this.isLive$.getValue()){let p=[(f=this.manifest.duration)!=null?f:0,...(0,fh.default)((0,fh.default)([...this.manifest.streams.audio,...this.manifest.streams.video],h=>h.representations),h=>{let m=[];return h.duration&&m.push(h.duration),st(h.segmentReference)&&h.segmentReference.totalSegmentsDurationMs&&m.push(h.segmentReference.totalSegmentsDurationMs),m})];this.source.duration=Math.max(...p)/1e3}this.audioBufferManager&&fo(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")})}.bind(this));this.tick=()=>{var t,i,r,a;if(!this.element||!this.videoBufferManager||((t=this.source)==null?void 0:t.readyState)!=="open")return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),(i=this.audioBufferManager)==null||i.maintain(e),(r=this.liveTextManager)==null||r.maintain(e),(this.videoBufferManager.gaps.length||(a=this.audioBufferManager)!=null&&a.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=dh(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),n=>{this.error$.next({id:"GapWatchdog",category:Qt.WTF,message:"Error handling gaps",thrown:n})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.fetcher=new ml({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=wi.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,x({},e.tuning.dashCmafLive.lowLatency.bufferEstimator)),this.initTracerSubscription()}seekLive(e){return E(this,null,function*(){var r,a,n;Ss(this.element);let t=this.liveStreamStatus$.getValue()!=="active"?ph()-this.liveStreamEndTimestamp:0,i=this.normolizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=Ie(this.manifestUrlString,i,2),this.manifest=yield this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,yield(r=this.videoBufferManager)==null?void 0:r.seekLive(this.manifest.streams.video),yield(a=this.audioBufferManager)==null?void 0:a.seekLive(this.manifest.streams.audio),(n=this.liveTextManager)==null||n.seekLive(this.manifest.streams.text))})}initBuffer(){Ss(this.element),this.state$.setState("running");let e=ti(this.element,"timeupdate");this.tuning.dash.timeupdateEventTickThrottle&&(e=e.pipe(zx(this.tuning.dash.timeupdateEventTickThrottle))),this.subscription.add(wr(...RV.map(t=>ti(this.element,t)),ti(window,"online"),e).subscribe(()=>this.tick(),t=>{this.error$.next({id:"DashVKPlayer",category:Qt.WTF,message:"Internal logic error",thrown:t})})),this.subscription.add(ti(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(ti(this.element,"waiting").subscribe(()=>{var i;this.element&&this.element.readyState===HTMLMediaElement.HAVE_CURRENT_DATA&&!this.element.seeking&&He(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let t=()=>{var h,m,g,S,v,y,T,I,k,C,V;if(!this.element||((h=this.source)==null?void 0:h.readyState)!=="open")return;let r=this.currentStallDuration$.getValue();r+=50,this.currentStallDuration$.next(r);let a={timeInWaiting:r},n=ph(),o=100,u=(g=(m=this.videoBufferManager)==null?void 0:m.lastDataObtainedTimestamp)!=null?g:0;this.videoLastDataObtainedTimestamp$.next(u);let l=(v=(S=this.audioBufferManager)==null?void 0:S.lastDataObtainedTimestamp)!=null?v:0,d=(T=(y=this.videoBufferManager)==null?void 0:y.getForwardBufferDuration())!=null?T:0,c=(k=(I=this.audioBufferManager)==null?void 0:I.getForwardBufferDuration())!=null?k:0,f=d<o&&n-u>this.tuning.dash.crashOnStallTWithoutDataTimeout,p=this.audioBufferManager&&c<o&&n-l>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((f||p)&&r>this.tuning.dash.crashOnStallTWithoutDataTimeout||r>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${r} ms`);if(this.isLive$.getValue()&&r%2e3===0){let $=this.normolizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive($).catch(w=>{this.error$.next({id:"stallIntervalCallback",category:Qt.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:w})}),a.liveLastOffset=$}else{let $=this.element.currentTime*1e3;(C=this.videoBufferManager)==null||C.maintain($),(V=this.audioBufferManager)==null||V.maintain($),a.position=$}this.tracer.log("stallIntervalCallback",ho(a))};(i=this.stallWatchdogSubscription)==null||i.unsubscribe(),this.stallWatchdogSubscription=dh(50).subscribe(t,r=>{this.error$.next({id:"StallWatchdogCallback",category:Qt.NETWORK,message:"Can't restore DASH after stall.",thrown:r})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}switchRepresentation(e,t,i=!1){return E(this,null,function*(){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)})}seek(e,t){return E(this,null,function*(){var r,a,n,o,u;Ss(this.element),Ss(this.videoBufferManager);let i;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?i=e:i=Math.max((r=this.videoBufferManager.findSegmentStartTime(e))!=null?r:e,(n=(a=this.audioBufferManager)==null?void 0:a.findSegmentStartTime(e))!=null?n:e),this.warmUpMediaSourceIfNeeded(i),He(this.element.buffered,i)||(yield Promise.all([this.videoBufferManager.abort(),(o=this.audioBufferManager)==null?void 0:o.abort()])),!(Hx(this.element)||Hx(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),(u=this.audioBufferManager)==null||u.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",ho({requestedPosition:e,forcePrecise:t,position:i})))})}warmUpMediaSourceIfNeeded(e=(t=>(t=this.element)==null?void 0:t.currentTime)()){var i;fo(this.element)&&fo(this.source)&&fo(e)&&((i=this.source)==null?void 0:i.readyState)==="ended"&&this.element.duration*1e3-e>this.tuning.dash.seekBiasInTheEnd&&this.bufferManagers.forEach(r=>r.warmUpMediaSource())}get isStreamEnded(){var e;return((e=this.source)==null?void 0:e.readyState)==="ended"}stop(){var e,t,i;this.tracer.log("stop"),(e=this.element)==null||e.querySelectorAll("source").forEach(r=>{URL.revokeObjectURL(r.src),r.remove()}),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(t=this.videoBufferManager)==null||t.destroy(),this.videoBufferManager=null,(i=this.audioBufferManager)==null||i.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){var e;return(e=this.manifest)==null?void 0:e.streams}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){var e;this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),((e=this.source)==null?void 0:e.readyState)==="open"&&Array.from(this.source.sourceBuffers).every(t=>!t.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=PV(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}updateLive(){return E(this,null,function*(){var e,t;this.isUpdatingLive=!0,this.manifest=yield this.updateManifest(),this.manifest&&((e=this.bufferManagers)==null||e.forEach(i=>i.updateLive(this.manifest)),(t=this.liveTextManager)==null||t.updateLive(this.manifest)),this.isUpdatingLive=!1})}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getBufferedTo();if(e===null)return;let t=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),i=this.isJumpGapAfterSeekLive,r=this.element.currentTime;this.isJumpGapAfterSeekLive&&!t&&this.element.currentTime>e&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let a=this.element.currentTime*1e3,n=null,o=this.element.readyState===HTMLMediaElement.HAVE_METADATA?this.tuning.endGapTolerance:0;for(let u of this.bufferManagers)for(let l of u.gaps)(l.persistent||u.playingRepresentation$.getValue()===l.representation)&&l.from-o<=a&&l.to+o>a&&(this.element.duration*1e3-l.to<this.tuning.endGapTolerance?n=1/0:(n===null||l.to>n)&&(n=l.to));if(n!==null){let u=n+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,u===1/0?this.forceEnded$.next():(this.element.currentTime=u/1e3,this.tracer.log("jumpGap",ho({isJumpGapAfterSeekLive:i,isActiveLowLatency:t,initialCurrentTime:r,jumpTo:u,resultCurrentTime:this.element.currentTime})))}}};import{combine as LV,map as BV,observeElementSize as $V,Subscription as DV,ValueSubject as mh,noop as CV}from"@vkontakte/videoplayer-shared/es2015";var vl=class{constructor(){this.subscription=new DV;this.pipSize$=new mh(void 0);this.videoSize$=new mh(void 0);this.elementSize$=new mh(void 0);this.pictureInPictureWindowRemoveEventListener=CV}connect({observableVideo:e,video:t}){let i=r=>{let a=r.target;this.pipSize$.next({width:a.width,height:a.height})};this.subscription.add($V(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(LV({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(BV(({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 Ar=class{constructor(e){this.subscription=new qV;this.videoState=new Y("stopped");this.observableVideo=null;this.droppedFramesManager=new Zr;this.stallsManager=new al;this.elementSizeManager=new vl;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new _i;this.audioTrackSwitchHistory=new _i;this.selectedRepresentations={audio:null,video:null};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(r.state==="requested"&&(i==null?void 0:i.to)!=="paused"&&e!=="stopped"&&t!=="stopped"&&this.seek(r.position,r.forcePrecise),t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),D(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"),D(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="ready"&&D(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"&&D(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&D(this.params.desiredState.playbackState,"paused");return;default:return OV(e)}}};this.init3DScene=e=>{var i,r,a;if(this.scene3D)return;this.scene3D=new hs(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 kt(e.source.url),this.params=e,this.video=nt(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(je(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 Sl({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params;UV(this.observableVideo)&&(this.observableVideo=lt(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:Qx.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(bh(c=>!!c.length),Wx()).subscribe(c=>{this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:c})}));let n=this.params.desiredState.seekState.stateChangeEnded$.pipe(gh(c=>c.to.state!=="none"),yl());this.stallsManager.init({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$,videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,tuning:this.params.tuning.stallsManager,abrParams:this.params.tuning.autoTrackSelection,isBuffering$:i.isBuffering$,looped$:i.looped$,playing$:i.playing$}),a(i.ended$,e.endedEvent$),a(i.looped$,e.loopedEvent$),a(i.error$,e.error$),a(i.isBuffering$,e.isBuffering$),a(i.currentBuffer$,e.currentBuffer$),a(i.playing$,e.firstFrameEvent$),a(i.canplay$,e.canplay$),a(i.inPiP$,e.inPiP$),a(i.inFullscreen$,e.inFullscreen$),a(i.loadedMetadata$,e.loadedMetadataEvent$),a(this.player.error$,e.error$),a(this.player.fetcherRecoverableError$,e.fetcherRecoverableError$),a(this.player.fetcherError$,e.fetcherError$),a(this.player.lastConnectionType$,e.httpConnectionType$),a(this.player.lastConnectionReused$,e.httpConnectionReused$),a(this.player.isLive$,e.isLive$),a(this.player.lastRequestFirstBytes$.pipe(bh(Gx),Wx()),e.firstBytesEvent$),a(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),a(this.videoState.stateChangeEnded$.pipe(gh(c=>c.to)),this.params.output.playbackState$),this.subscription.add(i.looped$.subscribe(()=>this.player.warmUpMediaSourceIfNeeded(),r)),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(Kt(this.video,t.isLooped,r)),this.subscription.add(ut(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Pt(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),a(Rt(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),D(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),D(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:c})=>{if(c==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let f=this.player.getStreams();if(_V(f,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let h=[];for(let m of f.audio){h.push(eh(m));let g=[];for(let S of m.representations){let v=kx(S);g.push(v),this.audioTracksMap.set(v,{stream:m,representation:S})}this.audioStreamsMap.set(m,g)}this.params.output.availableAudioStreams$.next(h)}let p=[];for(let h of f.video){p.push(th(h));let m=[];for(let g of h.representations){let S=Px(B(x({},g),{streamId:h.id}));S&&(m.push(S),this.videoTracksMap.set(S,{stream:h,representation:g}))}this.videoStreamsMap.set(h,m)}this.params.output.availableVideoStreams$.next(p);for(let h of f.text)for(let m of h.representations){let g=Rx(h,m);this.textTracksMap.set(g,{stream:h,representation:m})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else c==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r));let{vktvAbrThrottle:o}=this.params.tuning.dash,u=o&&Bx(o)||null;this.subscription.add(Tl(this.player.currentStallDuration$,this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,this.elementSizeManager.getObservable(),this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,NV(this.video,"progress")).pipe(bh(()=>this.videoTracksMap.size>0)).subscribe(()=>E(this,null,function*(){let c=this.player.state$.getState(),f=this.player.state$.getTransition();if(c!=="manifest_ready"&&c!=="running"||f||c==="running"&&u&&!u())return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState()),this.selectVideoAudioRepresentations();let{video:p,audio:h}=this.selectedRepresentations;if(!p)return;let m=Ir(this.videoTracksMap.keys(),S=>{var v;return((v=this.videoTracksMap.get(S))==null?void 0:v.representation.id)===p.id});Gx(m)&&(this.stallsManager.lastVideoTrackSelected=m);let g=this.params.desiredState.autoVideoTrackLimits.getTransition();if(g&&this.params.output.autoVideoTrackLimits$.next(g.to),c==="manifest_ready")yield this.player.initRepresentations(p.id,h==null?void 0:h.id,this.params.sourceHls);else if(yield this.player.switchRepresentation("video",p.id),h){let S=!!t.audioStream.getTransition();yield this.player.switchRepresentation("audio",h.id,S)}}),r)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:c})=>{this.scene3D&&c&&this.scene3D.pointCameraTo(c.x,c.y)})),this.subscription.add(this.elementSizeManager.subscribe(c=>{this.scene3D&&c&&this.scene3D.setViewportSize(c.width,c.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(yl()).subscribe(c=>{let f=Ir(this.videoTracksMap.entries(),([,{representation:g}])=>g.id===c);if(!f){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[p,{stream:h}]=f,m=this.params.desiredState.videoStream.getTransition();m&&m.to&&m.to.id===h.id&&this.params.desiredState.videoStream.setState(m.to),e.currentVideoTrack$.next(p),e.currentVideoStream$.next(th(h))},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(yl()).subscribe(c=>{let f=Ir(this.audioTracksMap.entries(),([,{representation:g}])=>g.id===c);if(!f){e.currentAudioStream$.next(void 0);return}let[p,{stream:h}]=f,m=this.params.desiredState.audioStream.getTransition();m&&m.to&&m.to.id===h.id&&this.params.desiredState.audioStream.setState(m.to),e.currentAudioStream$.next(eh(h))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(c=>{var f,p;if(c!=null&&c.is3dVideo&&((f=this.params.tuning.spherical)!=null&&f.enabled))try{this.init3DScene(c),e.is3DVideo$.next(!0)}catch(h){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${h}`})}else this.destroy3DScene(),(p=this.params.tuning.spherical)!=null&&p.enabled&&e.is3DVideo$.next(!1)},r)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,r)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,r)),this.textTracksManager.connect(this.video,t,e);let l=t.playbackState.stateChangeStarted$.pipe(gh(({to:c})=>c==="ready"),yl());this.subscription.add(Tl(l,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,Sh(["init"])).subscribe(()=>{let c=t.autoVideoTrackSwitching.getState(),p=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:c?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(p)})),this.subscription.add(Tl(l,this.player.state$.stateChangeEnded$,Sh(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let d=Tl(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Sh(["init"])).pipe(FV(0));this.subscription.add(d.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){var V,$,w,F,M,j,N,K,P,L,R,A;if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?Va:Ca,t=this.params.tuning.useNewAutoSelectVideoTrack?Mu:Ru,i=this.params.tuning.useNewAutoSelectVideoTrack?Zt:ku,{desiredState:r,output:a}=this.params,n=r.autoVideoTrackSwitching.getState(),o=(V=r.videoTrack.getState())==null?void 0:V.id,u=Ir(this.videoTracksMap.keys(),O=>O.id===o),l=a.currentVideoTrack$.getValue(),d=((F=(w=r.videoStream.getState())!=null?w:u&&(($=this.videoTracksMap.get(u))==null?void 0:$.stream))!=null?F:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!d)return;let c=Ir(this.videoStreamsMap.keys(),O=>O.id===d.id),f=c&&this.videoStreamsMap.get(c);if(!f)return;let p=Oe(this.video.buffered,this.video.currentTime*1e3),h;this.player.isActiveLive$.getValue()?h=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?h=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:h=n?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let m=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,g=Math.min(p/Math.min(h,m||1/0),1),S=(M=r.audioStream.getState())!=null?M:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,v=(S==null?void 0:S.id)&&Ir(this.audioStreamsMap.keys(),O=>O.id===S.id)||this.audioStreamsMap.keys().next().value,y=0;if(v){if(u&&!n){let O=e(u,f,(j=this.audioStreamsMap.get(v))!=null?j:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);y=Math.max(y,(N=O==null?void 0:O.bitrate)!=null?N:-1/0)}if(l){let O=e(l,f,(K=this.audioStreamsMap.get(v))!=null?K:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);y=Math.max(y,(P=O==null?void 0:O.bitrate)!=null?P:-1/0)}}let T=u;(n||!T)&&(T=i(f,{container:this.elementSizeManager.getValue(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.stallsManager.abrTuningParams,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:y,forwardBufferHealth:g,current:l,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,stallsVideoMaxQualityLimit:this.stallsManager.videoMaxQualityLimit,stallsPredictedThroughput:this.stallsManager.predictedThroughput,abrLogger:this.params.dependencies.abrLogger}));let I=v&&t(T,f,(L=this.audioStreamsMap.get(v))!=null?L:[],{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}),k=(R=this.videoTracksMap.get(T))==null?void 0:R.representation,C=I&&((A=this.audioTracksMap.get(I))==null?void 0:A.representation);k&&C?(this.selectedRepresentations.video=k,this.selectedRepresentations.audio=C):k&&!C&&this.audioTracksMap.size===0&&(this.selectedRepresentations.video=k,this.selectedRepresentations.audio=null)}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){ct(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),D(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Qx.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),ot(this.video),this.tracer.end()}};var mo=class extends Ar{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 vh,merge as Yx,filter as Kx,filterChanged as jV,isNullable as yh,map as Xx,ValueSubject as Th,isNonNullable as HV}from"@vkontakte/videoplayer-shared/es2015";var bo=class extends Ar{constructor(e){super(e),this.textTracksManager.destroy()}subscribe(){super.subscribe();let e=-1,{output:t,observableVideo:i,desiredState:r,connect:a}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),a(i.timeUpdate$,t.liveBufferTime$),a(this.player.liveSeekableDuration$,t.duration$),a(this.player.liveLatency$,t.liveLatency$);let n=new Th(1);a(i.playbackRateState$,n),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(r.isLowLatency.stateChangeEnded$.pipe(Xx(o=>o.to)).subscribe(this.player.isLowLatency$)).add(vh({liveBufferTime:t.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(Xx(({liveBufferTime:o,liveAvailabilityStartTime:u})=>o&&u?o+u:void 0)).subscribe(t.liveTime$)).add(this.player.liveStreamStatus$.pipe(Kx(o=>HV(o))).subscribe(o=>t.isLiveEnded$.next(o!=="active"&&t.position$.getValue()===0))).add(vh({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:Yx(i.playbackRateState$,new Th(1))}).pipe(Kx(({liveStreamStatus:o,liveDuration:u})=>o==="active"&&!!u)).subscribe(({liveDuration:o,playbackRate:u})=>{let l=t.liveBufferTime$.getValue(),d=t.position$.getValue(),{playbackCatchupSpeedup:c}=this.params.tuning.dashCmafLive.lowLatency;d||u<1-c||this.video.paused||yh(l)||(e=o-l)})).add(vh({time:t.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:Yx(i.playbackRateState$,new Th(1))}).pipe(jV((o,u)=>this.player.liveStreamStatus$.getValue()==="active"?o.liveDuration===u.liveDuration:o.time===u.time)).subscribe(({time:o,liveDuration:u,playbackRate:l})=>{let d=t.position$.getValue(),{playbackCatchupSpeedup:c}=this.params.tuning.dashCmafLive.lowLatency;if(!d&&!this.video.paused&&l>=1-c||yh(o)||yh(u))return;let f=-1*(u-o-e);t.position$.next(Math.min(f,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(o=>{if(o){let u=Mx(o);this.params.output.availableTextTracks$.next([u])}}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=Math.trunc(t/1e3<=Math.abs(this.params.output.duration$.getValue())?t:0);this.player.seekLive(i).then(()=>{this.params.output.position$.next(e/1e3)})}};var Jx="X-Playback-Duration",Ih=s=>E(void 0,null,function*(){var r;let e=yield Mt(s),t=yield 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(Jx)?parseInt(e.headers.get(Jx),10):void 0});import{assertNever as tO,combine as iO,debounce as rO,ErrorCategory as El,filter as sO,filterChanged as aO,isNonNullable as tE,isNullable as wl,map as iE,merge as nO,observableFrom as oO,Subscription as uO,ValueSubject as wh,VideoQuality as lO}from"@vkontakte/videoplayer-shared/es2015";var Eh=H(Xc(),1);import{videoSizeToQuality as zV,getExponentialDelay as QV}from"@vkontakte/videoplayer-shared/es2015";var GV=s=>{let e=null;if(s.QUALITY&&(e=Oi(s.QUALITY)),!e&&s.RESOLUTION){let[t,i]=s.RESOLUTION.split("x").map(r=>parseInt(r,10));e=zV({width:t,height:i})}return e!=null?e:null},WV=(s,e)=>{var a,n;let t=s.split(`
|
|
186
|
+
`),i=[],r=[];for(let o=0;o<t.length;o++){let u=t[o],l=u.match(/^#EXT-X-STREAM-INF:(.+)/),d=u.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!l&&!d)){if(l){let c=(0,Eh.default)(l[1].split(",").map(v=>v.split("="))),f=(a=c.QUALITY)!=null?a:`stream-${c.BANDWIDTH}`,p=GV(c),h;c.BANDWIDTH&&(h=parseInt(c.BANDWIDTH,10)/1e3||void 0),!h&&c["AVERAGE-BANDWIDTH"]&&(h=parseInt(c["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let m=c["FRAME-RATE"]?parseFloat(c["FRAME-RATE"]):void 0,g;if(c.RESOLUTION){let[v,y]=c.RESOLUTION.split("x").map(T=>parseInt(T,10));v&&y&&(g={width:v,height:y})}let S=new URL(t[++o],e).toString();p&&i.push({id:f,quality:p,url:S,bandwidth:h,size:g,fps:m})}if(d){let c=(0,Eh.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,"")])),f=(n=c.URI)==null?void 0:n.replace(/playlist$/,"subtitles.vtt"),p=c.LANGUAGE,h=c.NAME;f&&p&&r.push({type:"internal",id:p,label:h,language:p,url:f,isAuto:!1})}}}if(!i.length)throw new Error("Empty manifest");return{qualityManifests:i,textTracks:r}},YV=s=>new Promise(e=>{setTimeout(()=>{e()},s)}),xh=0,Zx=(r,...a)=>E(void 0,[r,...a],function*(s,e=s,t,i){let o=yield(yield Mt(s,i)).text();xh+=1;try{let{qualityManifests:u,textTracks:l}=WV(o,e);return{qualityManifests:u,textTracks:l}}catch(u){if(xh<=t.manifestRetryMaxCount)return yield YV(QV(xh-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),Zx(s,e,t)}return{qualityManifests:[],textTracks:[]}}),Il=Zx;import{isNonNullable as KV,Subscription as XV,throttle as JV,ValueSubject as eE,Subject as ZV,ErrorCategory as eO}from"@vkontakte/videoplayer-shared/es2015";var xl=class{constructor(e,t,i,r,a){this.subscription=new XV;this.abortControllers={destroy:new le,nextManifest:null};this.prepareUrl=void 0;this.currentTextTrackData=null;this.availableTextTracks$=new eE(null);this.getCurrentTime$=new eE(null);this.error$=new ZV;this.params={fetchManifestData:i,sourceUrl:r,downloadThreshold:a},this.subscription.add(e.pipe(JV(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()}prepare(e){return E(this,null,function*(){try{let t=new URL(e);t.searchParams.set("enable-subtitles","yes"),this.prepareUrl=t.toString();let{textTracks:i}=yield this.fetchManifestData();yield this.processTextTracks(i,this.params.sourceUrl)}catch(t){this.error("prepare",t)}})}processTextTracks(e,t){return E(this,null,function*(){try{let i=yield this.parseTextTracks(e,t);i&&(this.currentTextTrackData=i)}catch(i){this.error("processTextTracks",i)}})}parseTextTracks(e,t){return E(this,null,function*(){for(let i of e){let r=new URL(i.url,t).toString(),n=yield(yield Mt(r,{signal:this.abortControllers.destroy.signal})).text(),o=this.parsePlaylist(n,r);return{textTrack:i,playlist:o}}})}parsePlaylist(e,t){let i={mediaSequence:0,programDateTime:"",segments:[],targetDuration:0,vkPlaybackDuration:0,segmentStartTime:0,vkStartTime:""},r=e.split(`
|
|
187
|
+
`),a=0;for(let n=0;n<r.length;++n){let o=r[n];switch(!0){case o.startsWith("#EXTINF:"):{let u=r[++n],l=new URL(u,t).toString(),d=Number(this.extractPlaylistRowValue("#EXTINF:",o))*1e3;if(i.segments.push({time:{from:a,to:a+d},url:l}),a=a+d,!i.segmentStartTime){let c=new Date(i.vkStartTime).valueOf(),f=new Date(i.programDateTime).valueOf();i.segmentStartTime=f-c}break}case o.startsWith("#EXT-X-TARGETDURATION:"):i.targetDuration=Number(this.extractPlaylistRowValue("#EXT-X-TARGETDURATION:",o));break;case o.startsWith("#EXT-X-MEDIA-SEQUENCE:"):i.mediaSequence=Number(this.extractPlaylistRowValue("#EXT-X-MEDIA-SEQUENCE:",o));break;case o.startsWith("#EXT-X-VK-PLAYBACK-DURATION:"):i.vkPlaybackDuration=Number(this.extractPlaylistRowValue("#EXT-X-VK-PLAYBACK-DURATION:",o));break;case o.startsWith("#EXT-X-PROGRAM-DATE-TIME:"):{let u=this.extractPlaylistRowValue("#EXT-X-PROGRAM-DATE-TIME:",o);i.programDateTime=u;let l=new Date(u);l.setMilliseconds(0),a=l.valueOf();break}case o.startsWith("#EXT-X-VK-START-TIME:"):i.vkStartTime=this.extractPlaylistRowValue("#EXT-X-VK-START-TIME:",o);break}}return i}extractPlaylistRowValue(e,t){switch(e){case"#EXTINF:":return t.substring(e.length,t.length-1);default:return t.substring(e.length)}}processLiveTime(e){if(KV(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([B(x({},this.currentTextTrackData.textTrack),{url:n.url,isAuto:!0})]);break}}}fetchNextManifestData(){return E(this,null,function*(){try{if(this.abortControllers.nextManifest)return;this.abortControllers.nextManifest=new le;let{textTracks:e}=yield this.fetchManifestData(),t=yield 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}})}fetchManifestData(){return E(this,null,function*(){var t;let e=(t=this.prepareUrl)!=null?t:this.params.sourceUrl;return yield this.params.fetchManifestData(e,{signal:this.abortControllers.destroy.signal})})}error(e,t){this.error$.next({id:"[LiveTextManager][HLS_LIVE_CMAF]",category:eO.WTF,thrown:t,message:e})}};var go=class{constructor(e){this.subscription=new uO;this.videoState=new Y("stopped");this.textTracksManager=null;this.liveTextManager=null;this.manifests$=new wh([]);this.liveOffset=new hr;this.manifestStartTime$=new wh(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"),D(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(a||n||o){let d=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(d),this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((r==null?void 0:r.to)!=="paused"&&l.state==="requested"){this.videoState.startTransitionTo("ready"),this.seek(l.position&&l.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":i==="ready"?D(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),D(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"&&D(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"&&(D(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return tO(t)}};var i;this.params=e,this.video=nt(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:lO.INVARIANT,url:this.params.source.url};let t=(r,a)=>Il(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 xl(this.params.output.liveTime$,this.video,t,this.params.source.url,this.params.tuning.hlsLiveNewTextManagerDownloadThreshold):this.textTracksManager=new kt(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:El.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:El.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(je(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new wh((i=e.source.maxSeekBackTime)!=null?i:1/0),this.subscribe()}selectManifest(){var u,l,d,c;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),a=(c=(d=(u=r==null?void 0:r.to)==null?void 0:u.id)!=null?d:(l=t.getState())==null?void 0:l.id)!=null?c:"master",n=this.manifests$.getValue();if(!n.length)return;let o=i?"master":a;return i&&!r&&t.startTransitionTo(this.masterManifest),n.find(f=>f.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsLiveProvider",category:El.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},r=lt(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(ut(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Pt(this.video,t.playbackRate,r.playbackRateState$,i)),a(Rt(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"),D(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),D(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(aO(),iE(o=>-o/1e3)).subscribe(this.params.output.duration$,i)),this.subscription.add(r.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&tE(l.to)){let c=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let f=this.manifests$.getValue().find(p=>p.id===c);f&&(this.params.output.currentVideoTrack$.next(f),this.params.output.hostname$.next(je(f.url)))}d&&this.params.desiredState.autoVideoTrackSwitching.setState(d.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o&&o.state==="requested"&&this.seek(o.position)},i)),this.subscription.add(r.loadedData$.subscribe(()=>{var u,l,d;let o=(d=(l=(u=this.video)==null?void 0:u.getStartDate)==null?void 0:l.call(u))==null?void 0:d.getTime();this.manifestStartTime$.next(o||void 0)},i)),this.subscription.add(iO({startTime:this.manifestStartTime$.pipe(sO(tE)),currentTime:r.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),i)),this.subscription.add(this.manifests$.pipe(iE(o=>o.map(({id:u,quality:l,size:d,bandwidth:c,fps:f})=>({id:u,quality:l,size:d,fps:f,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,i));let n=nO(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,oO(["init"])).pipe(rO(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){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),ot(this.video)}prepare(){var o,u,l;let e=this.selectManifest();if(wl(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:d,min:c}=(u=(o=t==null?void 0:t.to)!=null?o:i)!=null?u:{};for(let[f,p]of[[d,"mq"],[c,"lq"]]){let h=String(parseFloat(f||""));p&&f&&r.searchParams.set(p,h)}}let a=this.params.format==="HLS_LIVE_CMAF"?2:0,n=Ie(r.toString(),this.liveOffset.getTotalOffset(),a);(l=this.liveTextManager)==null||l.prepare(n),this.video.setAttribute("src",n),this.video.load(),Ih(n).then(d=>{var c;if(!wl(d))this.maxSeekBackTime$.next(d);else{let f=(c=this.params.source.maxSeekBackTime)!=null?c:this.maxSeekBackTime$.getValue();(wl(f)||!isFinite(f))&&Mt(n).then(p=>p.text()).then(p=>{var m;let h=(m=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(p))==null?void 0:m[1];if(h){let g=new URL(h,n).toString();Ih(g).then(S=>{wl(S)||this.maxSeekBackTime$.next(S)})}}).catch(()=>{})}})}playIfAllowed(){ct(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),D(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:El.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=Ie(this.params.source.url);if(this.params.tuning.useHlsLiveNewTextManager){let t=new URL(e);t.searchParams.set("enable-subtitles","yes"),e=t.toString()}return e}};import{assertNever as cO,debounce as dO,ErrorCategory as Ah,fromEvent as Ph,isNonNullable as pO,isNullable as hO,map as rE,merge as sE,observableFrom as aE,Subscription as fO,ValueSubject as mO,VideoQuality as bO}from"@vkontakte/videoplayer-shared/es2015";var So=class{constructor(e){this.subscription=new fO;this.videoState=new Y("stopped");this.manifests$=new mO([]);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"),D(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(a||n||o){let d=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(d);let{currentTime:c}=this.video;this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:c*1e3,forcePrecise:!0});return}switch((r==null?void 0:r.to)!=="paused"&&l.state==="requested"&&this.seek(l.position),t){case"ready":i==="ready"?D(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),D(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"&&D(this.params.desiredState.playbackState,"playing");return;case"paused":i==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&D(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return cO(t)}};this.textTracksManager=new kt(e.source.url),this.params=e,this.video=nt(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:bO.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(je(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),Il(Ie(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:t,textTracks:i})=>{this.manifests$.next([this.masterManifest,...t]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(i)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:Ah.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){var u,l,d,c;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),a=(c=(d=(u=r==null?void 0:r.to)==null?void 0:u.id)!=null?d:(l=t.getState())==null?void 0:l.id)!=null?c:"master",n=this.manifests$.getValue();if(!n.length)return;let o=i?"master":a;return i&&(!r||!r.from)&&t.startTransitionTo(this.masterManifest),n.find(f=>f.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsProvider",category:Ah.WTF,message:"HlsProvider internal logic error",thrown:o})},r=lt(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(rE(o=>o.to)),this.params.output.playbackState$),this.subscription.add(Kt(this.video,t.isLooped,i)),this.subscription.add(ut(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Pt(this.video,t.playbackRate,r.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),D(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),D(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i).add(r.loadedMetadata$.subscribe(()=>{var p;let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&pO(l.to)){let h=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let m=this.manifests$.getValue().find(g=>g.id===h);m&&(this.params.output.currentVideoTrack$.next(m),this.params.output.hostname$.next(je(m.url)))}let c=this.params.desiredState.playbackRate.getState(),f=(p=this.params.output.element$.getValue())==null?void 0:p.playbackRate;if(c!==f){let h=this.params.output.element$.getValue();h&&(this.params.desiredState.playbackRate.setState(c),h.playbackRate=c)}d&&this.params.desiredState.autoVideoTrackSwitching.setState(d.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o.state==="requested"&&this.seek(o.position)},i))),this.subscription.add(this.manifests$.pipe(rE(o=>o.map(({id:u,quality:l,size:d,bandwidth:c,fps:f})=>({id:u,quality:l,size:d,fps:f,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,i)),!Q.device.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(sE(Ph(o,"addtrack"),Ph(o,"removetrack"),Ph(o,"change"),aE(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},i))}let n=sE(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,aE(["init"])).pipe(dO(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),ot(this.video)}prepare(){var a,n;let e=this.selectManifest();if(hO(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:o,min:u}=(n=(a=t==null?void 0:t.to)!=null?a:i)!=null?n:{};for(let[l,d]of[[o,"mq"],[u,"lq"]]){let c=String(parseFloat(l||""));d&&l&&r.searchParams.set(d,c)}}this.video.setAttribute("src",r.toString()),this.video.load()}playIfAllowed(){ct(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),D(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Ah.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var uE=H(sr(),1),kh=H(pr(),1),lE=H(qt(),1);import{assertNever as gO,assertNonNullable as nE,debounce as SO,ErrorCategory as oE,isHigherOrEqual as vO,isLowerOrEqual as yO,isNonNullable as TO,merge as IO,observableFrom as xO,Subscription as EO,map as wO}from"@vkontakte/videoplayer-shared/es2015";var vo=class{constructor(e){this.subscription=new EO;this.videoState=new Y("stopped");this.trackUrls={};this.textTracksManager=new kt;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"),D(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"?D(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),D(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"&&D(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&D(this.params.desiredState.playbackState,"paused");return;default:return gO(e)}};this.params=e,this.video=nt(e.container,e.tuning),this.params.output.element$.next(this.video),(0,uE.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,kh.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:oE.WTF,message:"MpegProvider internal logic error",thrown:o})},r=lt(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(wO(o=>o.to)),this.params.output.playbackState$),this.subscription.add(Kt(this.video,t.isLooped,i)),this.subscription.add(ut(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Pt(this.video,t.playbackRate,r.playbackRateState$,i)),a(Rt(this.video),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),D(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),D(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&&TO(o.to)){this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to.id].track);let d=this.params.desiredState.playbackRate.getState(),c=(l=this.params.output.element$.getValue())==null?void 0:l.playbackRate;if(d!==c){let f=this.params.output.element$.getValue();f&&(this.params.desiredState.playbackRate.setState(d),f.playbackRate=d)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.textTracksManager.connect(this.video,t,e);let n=IO(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,xO(["init"])).pipe(SO(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),ot(this.video)}prepare(){var i;let e=(i=this.params.desiredState.videoTrack.getState())==null?void 0:i.id;nE(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];nE(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=Ui(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(je(t))}playIfAllowed(){ct(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),D(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:oE.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){var l,d;this.params.output.autoVideoTrackLimits$.next(e);let t=c=>{this.params.output.currentVideoTrack$.next(c),this.params.desiredState.videoTrack.startTransitionTo(c)},i=c=>{let f=Zt(n,{container:this.video.getBoundingClientRect(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,limits:c,abrLogger:this.params.dependencies.abrLogger});t(f)},r=(l=this.params.output.currentVideoTrack$.getValue())==null?void 0:l.quality,a=!!(e.max||e.min),n=(0,kh.default)(this.trackUrls).map(c=>c.track);if(!r||!a||Wr(e,n[0].quality,(d=(0,lE.default)(n,-1))==null?void 0:d.quality)){i();return}let o=e.max?yO(r,e.max):!0,u=e.min?vO(r,e.min):!0;o&&u||i(e)}};import{assertNever as dE,debounce as RO,merge as pE,observableFrom as MO,Subscription as LO,map as hE,ValueSubject as BO,ErrorCategory as Mh,VideoQuality as $O}from"@vkontakte/videoplayer-shared/es2015";import{ErrorCategory as AO}from"@vkontakte/videoplayer-shared/es2015";var cE=["stun:videostun.mycdn.me:80"],PO=1e3,kO=3,Rh=()=>null,Al=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=Rh;this.externalStopCallback=Rh;this.externalErrorCallback=Rh;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}}handleUpdateMessage(e){return E(this,null,function*(){try{let t=yield this.createOffer();this.peerConnection&&(yield this.peerConnection.setLocalDescription(t)),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}})}handleLogin(){return E(this,null,function*(){try{let e={iceServers:[{urls:cE}]};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=yield this.createOffer();yield this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}})}handleAnswer(e){return E(this,null,function*(){try{this.peerConnection&&(yield this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e})))}catch(t){this.handleRTCError(t)}})}handleCandidate(e){return E(this,null,function*(){if(e)try{this.peerConnection&&(yield 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:AO.WTF,message:e.message})}onPeerConnectionStream(e){return E(this,null,function*(){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()))}}createOffer(){return E(this,null,function*(){let e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");let t=yield 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),PO)}normalizeOptions(e={}){let t={stunServerList:cE,maxRetryNumber:kO,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var yo=class{constructor(e){this.videoState=new Y("stopped");this.maxSeekBackTime$=new BO(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"),D(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"),D(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"&&D(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&D(this.params.desiredState.playbackState,"paused");return;default:return dE(e)}};this.subscription=new LO,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=nt(e.container,e.tuning),this.liveStreamClient=new Al(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),ot(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,i=n=>{e.error$.next({id:"WebRTCLiveProvider",category:Mh.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};this.subscription.add(pE(this.videoState.stateChangeStarted$.pipe(hE(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(hE(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})}));let r=lt(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(Rt(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(ut(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 dE(n.to)}},i)).add(pE(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,MO(["init"])).pipe(RO(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(je(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:$O.INVARIANT}),this.video.srcObject=e,D(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:Mh.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){ct(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),D(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Mh.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var To=class{constructor(e){this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next()}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return!!this.current.done}};import{assertNever as xo,assertNonNullable as zi,ErrorCategory as Pl,filter as vE,isNonNullable as yE,isNullable as NO,map as UO,merge as qO,once as jO,Subject as _e,Subscription as TE,ValueSubject as J,flattenObject as Lh}from"@vkontakte/videoplayer-shared/es2015";import{Observable as DO,map as fE,Subscription as CO,Subject as VO}from"@vkontakte/videoplayer-shared/es2015";var mE=s=>new DO(e=>{let t=new CO,i=s.desiredPlaybackState$.stateChangeStarted$.pipe(fE(({from:l,to:d})=>`${l}-${d}`)),r=s.desiredPlaybackState$.stateChangeEnded$,a=s.providerChanged$.pipe(fE(({type:l})=>l!==void 0)),n=new VO,o=0,u="unknown";return t.add(i.subscribe(l=>{o&&window.clearTimeout(o),u=l,o=window.setTimeout(()=>n.next(l),s.maxTransitionInterval)})),t.add(r.subscribe(()=>{window.clearTimeout(o),u="unknown",o=0})),t.add(a.subscribe(l=>{o&&(window.clearTimeout(o),o=0,l&&(o=window.setTimeout(()=>n.next(u),s.maxTransitionInterval)))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});import{ErrorCategory as OO,Subscription as _O,combine as FO,filter as gE,once as SE}from"@vkontakte/videoplayer-shared/es2015";function bE(){return new(window.AudioContext||window.webkitAudioContext)}var Io=class Io{constructor(e,t,i,r){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=i;this.volumeMultiplier=r;this.destroyController=new le;this.subscriptions=new _O;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe(gE(a=>!!a.type),SE()).subscribe(({type:a})=>this.subscribe(a)))}subscribe(e){Q.browser.isSafari&&e!=="MPEG"||this.subscriptions.add(FO({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(gE(({playbackState:t,video:i,volume:{muted:r,volume:a}})=>t==="playing"&&!!i&&!r&&!!a),SE()).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}initAudioContextOnce(e){return E(this,null,function*(){let{volumeMultiplier:t}=this,i=bE();this.audioContext=i;let r=i.createGain();if(this.gainNode=r,r.gain.value=t,r.connect(i.destination),i.state==="suspended"&&(yield 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:Io.errorId,category:OO.VIDEO_PIPELINE,message:(t=e==null?void 0:e.message)!=null?t:`${Io.errorId} exception`,thrown:e})}};Io.errorId="VolumeMultiplierManager";var Ts=Io;var HO={chunkDuration:5e3,maxParallelRequests:5},Eo=class{constructor(e){this.current$=new J({type:void 0});this.providerError$=new _e;this.noAvailableProvidersError$=new _e;this.volumeMultiplierError$=new _e;this.providerOutput={position$:new J(0),duration$:new J(1/0),volume$:new J({muted:!1,volume:1}),availableVideoStreams$:new J([]),currentVideoStream$:new J(void 0),availableVideoTracks$:new J([]),currentVideoTrack$:new J(void 0),availableAudioStreams$:new J([]),currentAudioStream$:new J(void 0),availableAudioTracks$:new J([]),currentVideoSegmentLength$:new J(0),currentAudioSegmentLength$:new J(0),isAudioAvailable$:new J(!0),autoVideoTrackLimitingAvailable$:new J(!1),autoVideoTrackLimits$:new J(void 0),currentBuffer$:new J(void 0),isBuffering$:new J(!0),error$:new _e,fetcherError$:new _e,fetcherRecoverableError$:new _e,warning$:new _e,willSeekEvent$:new _e,soundProhibitedEvent$:new _e,seekedEvent$:new _e,loopedEvent$:new _e,endedEvent$:new _e,firstBytesEvent$:new _e,loadedMetadataEvent$:new _e,firstFrameEvent$:new _e,canplay$:new _e,isLive$:new J(void 0),isLiveEnded$:new J(null),isLowLatency$:new J(!1),canChangePlaybackSpeed$:new J(!0),liveTime$:new J(void 0),liveBufferTime$:new J(void 0),liveLatency$:new J(void 0),severeStallOccurred$:new _e,availableTextTracks$:new J([]),currentTextTrack$:new J(void 0),hostname$:new J(void 0),httpConnectionType$:new J(void 0),httpConnectionReused$:new J(void 0),inPiP$:new J(!1),inFullscreen$:new J(!1),element$:new J(void 0),elementVisible$:new J(!0),availableSources$:new J(void 0),is3DVideo$:new J(!1),playbackState$:new J(""),getCurrentTime$:new J(null)};this.subscription=new TE;this.volumeMultiplierManager=null;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer"),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name);let t=JI([...ex(this.params.tuning),...ZI(this.params.tuning)],this.params.tuning).filter(l=>yE(e.sources[l])),{forceFormat:i,formatsToAvoid:r}=this.params.tuning,a=[];i?a=[i]:r.length?a=[...t.filter(l=>!(0,Bh.default)(r,l)),...t.filter(l=>(0,Bh.default)(r,l))]:a=t,this.log({message:`Selected formats: ${a.join(" > ")}`}),this.tracer.log("Selected formats",Lh(a)),this.screenFormatsIterator=new To(a);let n=[...Bp(!0),...Bp(!1)];this.chromecastFormatsIterator=new To(n.filter(l=>yE(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:o=1,tuning:{useVolumeMultiplier:u}}=this.params;u&&o!==1&&Ts.isSupported()&&(this.volumeMultiplierManager=new Ts(this.providerOutput,this.current$,this.volumeMultiplierError$,o))}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()}))}destroy(){var e;this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe(),(e=this.volumeMultiplierManager)==null||e.destroy(),this.volumeMultiplierManager=null,this.tracer.end()}initProvider(){let e=this.chooseDestination(),t=this.chooseFormat(e);if(NO(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:Pl.WTF,message:"Failed to create provider",thrown:r})}i?this.current$.next({type:t,provider:i,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.tracer.log("reinitProvider"),this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.tracer.log("switchToNextProvider",{destination:e}),this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}destroyProvider(){let e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"}),this.tracer.log("destroyProvider"),e.destroy();let t=this.providerOutput.position$.getValue()*1e3,i=this.params.desiredState.seekState.getState(),r=i.state!=="none";if(this.params.desiredState.seekState.setState({state:"requested",position:r?i.position:t,forcePrecise:r?i.forcePrecise:!1}),e.scene3D){let n=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:n.x,y:n.y})}let a=this.providerOutput.isBuffering$;a.getValue()||a.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),this.tracer.log("createProvider",{destination:e,format:t}),e){case"SCREEN":return this.createScreenProvider(t);case"CHROMECAST":return this.createChromecastProvider(t);default:return xo(e)}}createScreenProvider(e){let{sources:t,container:i,desiredState:r,panelSize:a}=this.params,n=this.providerOutput,o={container:i,source:null,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning,panelSize:a};switch(e){case"DASH_SEP":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_ONDEMAND":case"DASH_STREAMS":{let u=this.applyFailoverHost(t[e]),l=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return zi(u),this.params.tuning.useNewDashProvider?new mo(B(x({},o),{source:u,sourceHls:l})):new Ln(B(x({},o),{source:u,sourceHls:l}))}case"DASH_LIVE_CMAF":{let u=this.applyFailoverHost(t[e]);return zi(u),this.params.tuning.useNewDashProvider?new bo(B(x({},o),{source:u})):new Bn(B(x({},o),{source:u}))}case"HLS":case"HLS_ONDEMAND":{let u=this.applyFailoverHost(t[e]);return zi(u),new So(B(x({},o),{source:u}))}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let u=this.applyFailoverHost(t[e]);return zi(u),new go(B(x({},o),{source:u,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e}))}case"MPEG":{let u=this.applyFailoverHost(t[e]);return zi(u),new vo(B(x({},o),{source:u}))}case"DASH_LIVE":{let u=this.applyFailoverHost(t[e]);return zi(u),new Jy(B(x({},o),{source:u,config:B(x({},HO),{maxPausedTime:this.params.tuning.live.maxPausedTime})}))}case"WEB_RTC_LIVE":{let u=this.applyFailoverHost(t[e]);return zi(u),new yo({container:i,source:u,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return xo(e)}}createChromecastProvider(e){let{sources:t,container:i,desiredState:r,meta:a}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return zi(o),new Ra({connection:o,meta:a,container:i,source:t,format:e,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?"CHROMECAST":"SCREEN"}chooseFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case"CHROMECAST":return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return xo(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return xo(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 xo(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 B(x({},e),{url:i(e.url)})}return(0,xE.default)((0,IE.default)(e).map(([r,a])=>[r,i(a)]))}initProviderErrorHandling(){let e=new TE,t=!1,i=0;return e.add(qO(this.providerOutput.error$.pipe(vE(r=>!this.params.tuning.ignoreAudioRendererError||!r.message||!/AUDIO_RENDERER_ERROR/ig.test(r.message))),mE({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(UO(r=>({id:`ProviderHangup:${r}`,category:Pl.WTF,message:`A ${r} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.providerOutput.fetcherError$.subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;let r=this.params.desiredState.playbackState.transitionEnded$.pipe(vE(({to:a})=>a==="playing"),jO()).subscribe(()=>t=!0);e.add(r)})),e.add(this.providerError$.subscribe(r=>{let a=this.current$.getValue().destination,n={error:r,currentDestination:a};if(a==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("SCREEN"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let o=r.category===Pl.NETWORK,u=r.category===Pl.FATAL,l=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),d=i<this.params.tuning.providerErrorLimit&&!u,c=l&&!u&&(o&&t||!d);n=B(x({},n),{isNetworkError:o,isFatalError:u,haveFailoverHost:l,tryFailover:c,canReinitProvider:d}),d?(i++,this.reinitProvider()):c?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):(i=0,this.switchToNextProvider(a!=null?a:"SCREEN"))}r.traceAsLog?this.tracer.log("providerInfo",Lh(n)):this.tracer.error("providerError",Lh(n))})),e}};import{fromEvent as kl,once as zO,combine as QO,Subscription as EE,ValueSubject as $h,map as GO,filter as WO,isNonNullable as Rl,now as wt,safeStorage as Dh}from"@vkontakte/videoplayer-shared/es2015";var YO=5e3,wE="one_video_throughput",AE="one_video_rtt",Ri=window.navigator.connection,PE=()=>{let s=Ri==null?void 0:Ri.downlink;if(Rl(s)&&s!==10)return s*1e3},kE=()=>{let s=Ri==null?void 0:Ri.rtt;if(Rl(s)&&s!==3e3)return s},RE=(s,e,t)=>{let i=t*8,r=i/s;return i/(r+e)},Ch=class s{constructor(e){this.subscription=new EE;this.concurrentDownloads=new Set;var r,a;this.tuningConfig=e;let t=s.load(wE)||(e.useBrowserEstimation?PE():void 0)||YO,i=(a=(r=s.load(AE))!=null?r:e.useBrowserEstimation?kE():void 0)!=null?a:0;if(this.throughput$=new $h(t),this.rtt$=new $h(i),this.rttAdjustedThroughput$=new $h(RE(t,i,e.rttPenaltyRequestSize)),this.throughput=wi.getSmoothedValue(t,-1,e),this.rtt=wi.getSmoothedValue(i,1,e),e.useBrowserEstimation){let n=()=>{let u=PE();u&&this.throughput.next(u);let l=kE();Rl(l)&&this.rtt.next(l)};Ri&&"onchange"in Ri&&this.subscription.add(kl(Ri,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{Dh.set(wE,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{Dh.set(AE,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(QO({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(GO(({throughput:n,rtt:o})=>RE(n,o,e.rttPenaltyRequestSize)),WO(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=wt(),r=new EE;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add(kl(e,"progress").pipe(zO()).subscribe(a=>{t=a.loaded,i=wt()}));break;case 1:case 0:r.add(kl(e,"loadstart").subscribe(()=>{t=0,i=wt()}));break}r.add(kl(e,"loadend").subscribe(a=>{if(e.status===200){let n=a.loaded,o=wt(),u=n-t,l=o-i;this.addRawSpeed(u,l,1)}this.concurrentDownloads.delete(e),r.unsubscribe()}))}trackStream(e,t=!1){let i=e.getReader();if(!i){e.cancel("Could not get reader");return}let r=0,a=wt(),n=0,o=wt(),u=d=>{this.concurrentDownloads.delete(e),i.releaseLock(),e.cancel(`Throughput Estimator error: ${d}`).catch(()=>{})},l=f=>E(this,[f],function*({done:d,value:c}){if(d)!t&&this.addRawSpeed(r,wt()-a,1),this.concurrentDownloads.delete(e);else if(c){if(t){let p=wt();if(p-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||p-a>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let m=o-a;m&&this.addRawSpeed(n,m,1,t),n=c.byteLength,a=wt()}else n+=c.byteLength;o=wt()}else r+=c.byteLength,n+=c.byteLength,n>=this.tuningConfig.streamMinSampleSize&&wt()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,wt()-o,this.concurrentDownloads.size),n=0,o=wt());yield i==null?void 0:i.read().then(l,u)}});this.concurrentDownloads.add(e),i==null||i.read().then(l,u)}addRawSpeed(e,t,i=1,r=!1){if(s.sanityCheck(e,t,r)){let a=e*8/t;this.throughput.next(a*i)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,i=!1){let r=e*8/t;return!(!r||!isFinite(r)||r>1e6||r<30||i&&e<1e4||!i&&e<10*1024||!i&&t<=20)}static load(e){var i;let t=Dh.get(e);if(Rl(t))return(i=parseInt(t,10))!=null?i:void 0}},ME=Ch;import{fillWithDefault as KO,VideoQuality as Ml}from"@vkontakte/videoplayer-shared/es2015";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:Ml.Q_4320P,activeVideoAreaThreshold:.1,highQualityLimit:Ml.Q_720P,trafficSavingLimit:Ml.Q_480P},stallsManager:{enabled:!1,stallDurationNoDataBeforeQualityDecrease:500,stallDurationToBeCount:100,stallCountBeforeQualityDecrease:3,resetQualityRestrictionTimeout:1e4,ignoreStallsOnSeek:!0,stallsMetricsHistoryLength:5,maxPossibleStallDuration:3e4,minTvtToBeCounted:5,maxTvtToBeCounted:10800,significantTvt:600,targetStallsDurationPerTvt:1,deviationStallsDurationPerTvt:.5,criticalStallsDurationPerTvt:6,abrAdjustingSpeed:.1,emaAlpha:.6,useTotalStallsDurationPerTvt:!0,useAverageStallsDurationPerTvt:!0,useEmaStallsDurationPerTvt:!0},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:Ml.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,seekBiasInTheEnd:2e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,crashOnStallTimeout:25e3,crashOnStallTWithoutDataTimeout:5e3,enableSubSegmentBufferFeeding:!0,bufferEmptinessTolerance:100,useFetchPriorityHints:!0,enableBaseUrlSupport:!0,maxSegmentRetryCount:5,sourceOpenTimeout:1e3,vktvAbrThrottle:0,timeupdateEventTickThrottle:300},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,maxLiveDuration:7200,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:250,playbackCatchupSpeedup:.05,isActiveOnDefault:!1,bufferEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:"07A4434E",useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"dash",preferCMAF:!1,preferWebRTC:!1,preferMultiStream:!1,preferHDR:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,seekNearDurationBias:1,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useHlsJs:!1,useNativeHLSTextTracks:!1,useManagedMediaSource:!0,useNewSwitchTo:!1,useNewDashProvider:!1,useNewAutoSelectVideoTrack:!1,useSafariEndlessRequestBugfix:!0,useRefactoredSearchGap:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,audioVideoSyncRate:20,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50},useVolumeMultiplier:!1,ignoreAudioRendererError:!1,useEnableSubtitlesParam:!1,useOldMSEDetection:!1,useHlsLiveNewTextManager:!1,exposeInternalsToGlobal:!1,hlsLiveNewTextManagerDownloadThreshold:4e3,disableYandexPiP:!1,asyncResolveClientChecker:!1,autostartOnlyIfVisible:!1},BE=s=>{var e;return B(x({},KO(s,LE)),{configName:[...(e=s.configName)!=null?e:[],...LE.configName]})};import{assertNonNullable as Ll,combine as Mi,ErrorCategory as Bl,filter as W,filterChanged as ae,fromEvent as Oh,isNonNullable as VE,isNullable as r_,Logger as s_,map as re,mapTo as OE,merge as Qi,now as $l,once as Z,Subject as ne,Subscription as _E,tap as _h,ValueSubject as _,isHigher as a_,isInvariantQuality as FE,flattenObject as Gi,throttle as Fh,getTraceSubscriptionMethod as NE,TracerFactory as n_,InternalsExposure as o_}from"@vkontakte/videoplayer-shared/es2015";import{merge as XO,map as JO,filter as $E,isNonNullable as ZO}from"@vkontakte/videoplayer-shared/es2015";var Vh=({seekState:s,position$:e})=>XO(s.stateChangeEnded$.pipe(JO(({to:t})=>{var i;return t.state==="none"?void 0:((i=t.position)!=null?i:NaN)/1e3}),$E(ZO)),e.pipe($E(()=>s.getState().state==="none")));import{assertNonNullable as e_}from"@vkontakte/videoplayer-shared/es2015";var DE=s=>{let e=typeof s.container=="string"?document.getElementById(s.container):s.container;return e_(e,`Wrong container or containerId {${s.container}}`),e};import{filter as t_,once as i_}from"@vkontakte/videoplayer-shared/es2015";var CE=(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(t_(r=>r.length>0),i_()).subscribe(r=>{r.find(i)&&e.startTransitionTo(s)}):(s===void 0||t!=null&&t.getValue().find(i))&&e.startTransitionTo(s)};var Dl=class{constructor(e={configName:[]},t=n_.createRootTracer(!1)){this.subscription=new _E;this.logger=new s_;this.abrLogger=this.logger.createComponentLog("ABR");this.internalsExposure=null;this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new _(!1);this.hasLiveOffsetByPausedTimer=0;this.playerInitRequest=0;this.playerInited=new _(!1);this.wasSetStartedQuality=!1;this.desiredState={playbackState:new Y("stopped"),seekState:new Y({state:"none"}),volume:new Y({volume:1,muted:!1}),videoTrack:new Y(void 0),videoStream:new Y(void 0),audioStream:new Y(void 0),autoVideoTrackSwitching:new Y(!0),autoVideoTrackLimits:new Y({}),isLooped:new Y(!1),isLowLatency:new Y(!1),playbackRate:new Y(1),externalTextTracks:new Y([]),internalTextTracks:new Y([]),currentTextTrack:new Y(void 0),textTrackCuesSettings:new Y({}),cameraOrientation:new Y({x:0,y:0})};this.info={playbackState$:new _(void 0),position$:new _(0),duration$:new _(1/0),muted$:new _(!1),volume$:new _(1),availableVideoStreams$:new _([]),currentVideoStream$:new _(void 0),availableQualities$:new _([]),availableQualitiesFps$:new _({}),currentQuality$:new _(void 0),isAutoQualityEnabled$:new _(!0),autoQualityLimitingAvailable$:new _(!1),autoQualityLimits$:new _({}),predefinedQualityLimitType$:new _("unknown"),availableAudioStreams$:new _([]),currentAudioStream$:new _(void 0),availableAudioTracks$:new _([]),isAudioAvailable$:new _(!0),currentPlaybackRate$:new _(1),currentBuffer$:new _({start:0,end:0}),isBuffering$:new _(!0),isStalled$:new _(!1),isEnded$:new _(!1),isLooped$:new _(!1),isLive$:new _(void 0),isLiveEnded$:new _(null),canChangePlaybackSpeed$:new _(void 0),atLiveEdge$:new _(void 0),atLiveDurationEdge$:new _(void 0),liveTime$:new _(void 0),liveBufferTime$:new _(void 0),liveLatency$:new _(void 0),currentFormat$:new _(void 0),availableTextTracks$:new _([]),currentTextTrack$:new _(void 0),throughputEstimation$:new _(void 0),rttEstimation$:new _(void 0),videoBitrate$:new _(void 0),hostname$:new _(void 0),httpConnectionType$:new _(void 0),httpConnectionReused$:new _(void 0),surface$:new _("none"),chromecastState$:new _("NOT_AVAILABLE"),chromecastDeviceName$:new _(void 0),intrinsicVideoSize$:new _(void 0),availableSources$:new _(void 0),is3DVideo$:new _(!1),currentVideoSegmentLength$:new _(0),currentAudioSegmentLength$:new _(0)};this.events={inited$:new ne,ready$:new ne,started$:new ne,playing$:new ne,paused$:new ne,stopped$:new ne,willReady$:new ne,willStart$:new ne,willResume$:new ne,willPause$:new ne,willStop$:new ne,willDestruct$:new ne,watchCoverageRecord$:new ne,watchCoverageLive$:new ne,managedError$:new ne,fatalError$:new ne,fetcherRecoverableError$:new ne,ended$:new ne,looped$:new ne,seeked$:new ne,willSeek$:new ne,autoplaySoundProhibited$:new ne,firstBytes$:new ne,loadedMetadata$:new ne,firstFrame$:new ne,canplay$:new ne,log$:new ne,fetcherError$:new ne,severeStallOccured$:new ne};this.experimental={element$:new _(void 0),tuningConfigName$:new _([]),enableDebugTelemetry$:new _(!1),dumpTelemetry:Ey,getCurrentTime$:new _(null)};if(this.initLogs(),this.tuning=BE(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new $o({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new ME(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new o_("CORE"),this.internalsExposure.expose({player:this})),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(i,r,a)=>{let n=Reflect.get(i,r,a);return typeof n!="function"?n:(...o)=>{try{return n.apply(i,o)}catch(u){let l=o.map(f=>JSON.stringify(f,(p,h)=>{let m=typeof h;return(0,UE.default)(["number","string","boolean"],m)?h:h===null?null:`<${m}>`})),d=`Player.${String(r)}`,c=`Exception calling ${d} (${l.join(", ")})`;throw this.events.fatalError$.next({id:d,category:Bl.WTF,message:c,thrown:u}),u}}}})}initVideo(e){var a;this.config=e,(a=this.internalsExposure)==null||a.expose({config:e,logger:this.logger,tuning:this.tuning}),this.setMuted(this.tuning.isAudioDisabled);let t=()=>{var l,d,c;let u=e,{container:n}=u,o=qh(u,["container"]);this.tracer.log("initVideo",Gi(o)),this.domContainer=DE(e),this.chromecastInitializer.contentId=(l=e.meta)==null?void 0:l.videoId,this.providerContainer=new Eo({sources:e.sources,meta:(d=e.meta)!=null?d:{},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?Q.isInited$.pipe(W(n=>!!n),Z()).subscribe(()=>{console.log("Core SDK async start"),i()}):i()};return this.isNotActiveTabCase()?(this.tracer.log("request play from hidden tab"),Oh(document,"visibilitychange").pipe(Z()).subscribe(r)):r(),this}destroy(){var e,t;this.tracer.log("destroy"),window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.playerInitRequest&&window.cancelAnimationFrame(this.playerInitRequest),this.events.willDestruct$.next(),this.stop(),(e=this.providerContainer)==null||e.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe(),this.tracer.end(),(t=this.internalsExposure)==null||t.destroy()}prepare(){return this.subscription.add(this.playerInited.pipe(W(e=>!!e),Z()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("prepare",{currentPlayBackState:e.getState()}),e.getState()==="stopped"&&e.startTransitionTo("ready")})),this}play(){return this.subscription.add(this.playerInited.pipe(W(e=>!!e),Z()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("play",{currentPlayBackState:e.getState()}),e.getState()!=="playing"&&e.startTransitionTo("playing")})),this}pause(){return this.subscription.add(this.playerInited.pipe(W(e=>!!e),Z()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("pause",{currentPlayBackState:e.getState()}),e.getState()!=="paused"&&e.startTransitionTo("paused")})),this}stop(){return this.subscription.add(this.playerInited.pipe(W(e=>!!e),Z()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("stop",{currentPlayBackState:e.getState()}),e.getState()!=="stopped"&&e.startTransitionTo("stopped")})),this}seekTime(e,t=!0){return this.subscription.add(this.playerInited.pipe(W(i=>!!i),Z()).subscribe(()=>{let i=this.info.duration$.getValue(),r=this.info.isLive$.getValue(),a=e;e>=i&&!r&&(a=i-this.tuning.seekNearDurationBias),this.tracer.log("seekTime",{duration:i,isLive:r,time:e,calculatedTime:a,forcePrecise:t}),Number.isFinite(a)&&(this.events.willSeek$.next({from:this.getExactTime(),to:a}),this.desiredState.seekState.setState({state:"requested",position:a*1e3,forcePrecise:t}))})),this}seekPercent(e){return this.subscription.add(this.playerInited.pipe(W(t=>!!t),Z()).subscribe(()=>{let t=this.info.duration$.getValue();this.tracer.log("seekPercent",{percent:e,duration:t}),isFinite(t)&&this.seekTime(Math.abs(t)*e,!1)})),this}setVolume(e,t){return this.subscription.add(this.playerInited.pipe(W(i=>!!i),Z()).subscribe(()=>{var o;let i=this.desiredState.volume,r=i.getTransition(),a=(o=r==null?void 0:r.to.muted)!=null?o:this.info.muted$.getValue(),n=t!=null?t:this.tuning.isAudioDisabled||a;this.tracer.log("setVolume",{volume:e,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:n}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setVolume(e):i.startTransitionTo({volume:e,muted:n})})),this}setMuted(e,t=!1){return this.subscription.add(this.playerInited.pipe(W(i=>!!i),Z()).subscribe(()=>{var o;let i=this.desiredState.volume,r=this.tuning.isAudioDisabled&&!t||e,a=i.getTransition(),n=(o=a==null?void 0:a.to.volume)!=null?o:this.info.volume$.getValue();this.tracer.log("setMuted",{isMuted:e,nextMuted:r,volume:n,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue()}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setMuted(r):i.startTransitionTo({volume:n,muted:r})})),this}setVideoStream(e){return this.subscription.add(this.playerInited.pipe(W(t=>!!t),Z()).subscribe(()=>{this.desiredState.videoStream.startTransitionTo(e)})),this}setAudioStream(e){return this.subscription.add(this.playerInited.pipe(W(t=>!!t),Z()).subscribe(()=>{this.desiredState.audioStream.startTransitionTo(e)})),this}setQuality(e){return this.subscription.add(this.playerInited.pipe(W(t=>!!t),Z()).subscribe(()=>{Ll(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(W(i=>i.length>0),Z()).subscribe(i=>{this.setVideoTrackIdByQuality(i,e)}):this.explicitInitialQuality=e:t.length>0&&this.setVideoTrackIdByQuality(t,e)})),this}setAutoQuality(e){return this.subscription.add(this.playerInited.pipe(W(t=>!!t),Z()).subscribe(()=>{this.tracer.log("setAutoQuality",{enable:e}),this.desiredState.autoVideoTrackSwitching.startTransitionTo(e)})),this}setAutoQualityLimits(e){return this.subscription.add(this.playerInited.pipe(W(t=>!!t),Z()).subscribe(()=>{this.tracer.log("setAutoQualityLimits",Gi(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e)})),this}setPredefinedQualityLimits(e){return this.subscription.add(this.playerInited.pipe(W(t=>!!t),Z()).subscribe(()=>{if(this.info.predefinedQualityLimitType$.getValue()===e)return this;let{highQualityLimit:t,trafficSavingLimit:i}=this.tuning.autoTrackSelection,r;switch(e){case"high_quality":r={min:t,max:void 0};break;case"traffic_saving":r={max:i,min:void 0};break;default:r={max:void 0,min:void 0}}this.setAutoQualityLimits(r)})),this}setPlaybackRate(e){return this.subscription.add(this.playerInited.pipe(W(t=>!!t),Z()).subscribe(()=>{var i;Ll(this.providerContainer);let t=(i=this.providerContainer)==null?void 0:i.providerOutput.element$.getValue();this.tracer.log("setPlaybackRate",{playbackRate:e,isVideoElementAvailable:!!t}),t&&(this.desiredState.playbackRate.setState(e),t.playbackRate=e)})),this}setExternalTextTracks(e){return this.subscription.add(this.playerInited.pipe(W(t=>!!t),Z()).subscribe(()=>{e.length&&this.tracer.log("setExternalTextTracks",Gi(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>x({type:"external"},t)))})),this}selectTextTrack(e){return this.subscription.add(this.playerInited.pipe(W(t=>!!t),Z()).subscribe(()=>{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.subscription.add(this.playerInited.pipe(W(t=>!!t),Z()).subscribe(()=>{this.tracer.log("setTextTrackCueSettings",x({},e)),this.desiredState.textTrackCuesSettings.startTransitionTo(e)})),this}setLiveLowLatency(e){let t=this.info.isLive$.getValue(),i=this.desiredState.isLowLatency.getState();return!t||i===e?this:(this.tracer.log("live switch to low latency "+e),this.desiredState.isLowLatency.setState(e),this.seekTime(0))}setLooped(e){return this.subscription.add(this.playerInited.pipe(W(t=>!!t),Z()).subscribe(()=>{this.tracer.log("setLooped",{isLooped:e}),this.desiredState.isLooped.startTransitionTo(e)})),this}toggleChromecast(){this.tracer.log("toggleChromecast"),this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){return this.subscription.add(this.playerInited.pipe(W(i=>!!i),Z()).subscribe(()=>{let i=this.getScene3D();this.tracer.log("startCameraManualRotation",{isScene3DAvailable:!!i,mx:e,my:t}),i&&i.startCameraManualRotation(e,t)})),this}stopCameraManualRotation(e=!1){return this.subscription.add(this.playerInited.pipe(W(t=>!!t),Z()).subscribe(()=>{let t=this.getScene3D();this.tracer.log("stopCameraManualRotation",{isScene3DAvailable:!!t,immediate:e}),t&&t.stopCameraManualRotation(e)})),this}moveCameraFocusPX(e,t){return this.subscription.add(this.playerInited.pipe(W(i=>!!i),Z()).subscribe(()=>{let i=this.getScene3D();if(this.tracer.log("moveCameraFocusPX",{isScene3DAvailable:!!i,dxpx:e,dypx:t}),i){let r=i.getCameraRotation(),a=i.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:r.x+a.x,y:r.y+a.y})}})),this}holdCamera(){return this.subscription.add(this.playerInited.pipe(W(e=>e),Z()).subscribe(()=>{let e=this.getScene3D();e&&e.holdCamera()})),this}releaseCamera(){return this.subscription.add(this.playerInited.pipe(W(e=>!!e),Z()).subscribe(()=>{let e=this.getScene3D();e&&e.releaseCamera()})),this}getExactTime(){if(!this.providerContainer)return 0;let e=this.providerContainer.providerOutput.element$.getValue();if(r_(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),i=t.state==="none"?void 0:t.position;return VE(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(Qi(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(re(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(re(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(re(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(re(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(re(e=>e.to)).subscribe(e=>{this.info.autoQualityLimits$.next(e);let{highQualityLimit:t,trafficSavingLimit:i}=this.tuning.autoTrackSelection;this.info.predefinedQualityLimitType$.next(Yd(e,t,i))})),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(W(({from:e})=>e==="stopped"),Z()).subscribe(()=>{this.initedAt=$l(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case"ready":this.events.ready$.next();break;case"playing":this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case"paused":this.events.paused$.next();break;case"stopped":this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case"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",Gi(n)),n.state==="requested"?this.desiredState.seekState.setState(B(x({},n),{state:"applying"})):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:Bl.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe(Z()).subscribe(this.events.autoplaySoundProhibited$)).add(e.providerOutput.severeStallOccurred$.subscribe(this.events.severeStallOccured$)).add(e.providerOutput.seekedEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("seekedEvent",Gi(n)),n.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe(re(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(re(n=>n.destination),ae()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(Mi({availableVideoTracks:e.providerOutput.availableVideoTracks$,currentVideoStream:e.providerOutput.currentVideoStream$}).pipe(re(({availableVideoTracks:n,currentVideoStream:o})=>n.filter(u=>o?o.id===u.streamId:!0).map(({quality:u})=>u).sort((u,l)=>FE(u)?1:FE(l)?-1:a_(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(ae()).subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.pipe(W(n=>VE(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(ae((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe(ae((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(ae()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(ae()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(ae()).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(re(n=>n?{start:n.from,end:n.to}:{start:0,end:0})).subscribe(this.info.currentBuffer$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.isLiveEnded$.pipe(_h(n=>n&&this.stop())).subscribe(this.info.isLiveEnded$)).add(e.providerOutput.canChangePlaybackSpeed$.subscribe(this.info.canChangePlaybackSpeed$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.liveBufferTime$.subscribe(this.info.liveBufferTime$)).add(e.providerOutput.liveLatency$.subscribe(this.info.liveLatency$)).add(Mi({hasLiveOffsetByPaused:Qi(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(re(n=>n.to),ae(),re(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(Mi({atLiveEdge:Mi({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Vh({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(re(({isLive:n,position:o,isLowLatency:u})=>{let l=this.getActiveLiveDelay(u);return n&&Math.abs(o)<l/1e3}),ae(),_h(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(re(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add(Mi({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(re(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),ae(),_h(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(re(n=>n.muted),ae()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(re(n=>n.volume),ae()).subscribe(this.info.volume$)).add(Vh({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(Qi(e.providerOutput.endedEvent$.pipe(OE(!0)),e.providerOutput.seekedEvent$.pipe(OE(!1))).pipe(ae()).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(re(n=>({id:n?`No${n}`:"NoProviders",category:Bl.VIDEO_PIPELINE,message:n?`${n} was forced but failed or not available`:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.getCurrentTime$.subscribe(this.experimental.getCurrentTime$)).add(e.providerOutput.firstBytesEvent$.pipe(Z(),re(n=>n!=null?n:$l()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(Z(),re(()=>$l()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(Z(),re(()=>$l()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$)).add(e.providerOutput.availableSources$.subscribe(this.info.availableSources$));let t=new _(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let i=new _(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(W(({to:n})=>n==="playing"),Z()).subscribe(()=>i.next(!1)));let r=0,a=Qi(e.providerOutput.isBuffering$,t,i).pipe(re(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||i.getValue();return n&&!o}),ae());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(Qi(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(Qi(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,e.providerOutput.elementVisible$,this.chromecastInitializer.castState$).subscribe(()=>{let n=e.providerOutput.inPiP$.getValue(),o=e.providerOutput.inFullscreen$.getValue(),u=e.providerOutput.element$.getValue(),l=e.providerOutput.elementVisible$.getValue(),d=this.chromecastInitializer.castState$.getValue(),c;d==="CONNECTED"?c="second_screen":u?l?n?c="pip":o?c="fullscreen":c="inline":c="invisible":c="none",this.info.surface$.getValue()!==c&&this.info.surface$.next(c)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(re(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(ae((i,r)=>i.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(W(i=>i.length>0),Z()).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=Zt(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(Qi(this.desiredState.videoTrack.stateChangeStarted$.pipe(re(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(re(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(re(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(re(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(re(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(re(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(re(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(re(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(re(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;Ll(this.providerContainer),Ll(e),xy(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(i=>Iy(i)),this.providerContainer.current$.subscribe(({type:i})=>Da("provider",i)),e.duration$.subscribe(i=>Da("duration",i)),e.availableVideoTracks$.pipe(W(i=>!!i.length),Z()).subscribe(i=>Da("tracks",i)),this.events.fatalError$.subscribe(new tt("fatalError")),this.events.managedError$.subscribe(new tt("managedError")),e.position$.subscribe(new tt("position")),e.currentVideoTrack$.pipe(re(i=>i==null?void 0:i.quality)).subscribe(new tt("quality")),this.info.currentBuffer$.subscribe(new tt("buffer")),e.isBuffering$.subscribe(new tt("isBuffering"))].forEach(i=>this.subscription.add(i)),Da("codecs",Q.video.supportedCodecs)}initTracerSubscription(){let e=NE(this.tracer.log.bind(this.tracer)),t=NE(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(ae()).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(Mi({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe(W(({currentQuality:i,videoBitrate:r})=>!!i&&!!r),ae((i,r)=>i.currentQuality===r.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe(W(i=>i>0),ae()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe(W(i=>i>0),ae()).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(Mi({currentBuffer:this.info.currentBuffer$.pipe(W(i=>i.end>0),ae((i,r)=>i.end===r.end&&i.start===r.start)),position:this.info.position$.pipe(ae())}).pipe(Fh(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe(ae()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe(ae()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe(ae()).subscribe(e("canChangePlaybackSpeed"))).add(Mi({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(W(({liveTime:i,liveBufferTime:r})=>!!i&&!!r),Fh(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(ae(),W(i=>i===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(ae(),W(i=>i===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe(ae()).subscribe(e("muted"))).add(this.info.volume$.pipe(ae()).subscribe(e("volume"))).add(this.info.isEnded$.pipe(ae(),W(i=>i===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add(Mi({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(W(({throughputEstimation:i,rtt:r})=>!!i&&!!r),Fh(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(ae(),W(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=()=>E(this,null,function*(){t(),e=yield window.navigator.wakeLock.request("screen").catch(r=>{r instanceof DOMException&&r.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:Bl.DOM,message:String(r)})})});this.subscription.add(Qi(Oh(document,"visibilitychange"),Oh(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let r=document.visibilityState==="visible",a=this.desiredState.playbackState.getState()==="playing",n=!!e&&!(e!=null&&e.released);r&&a?n||i():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let i=e.find(r=>r.quality===t);this.tracer.log("setVideoTrackIdByQuality",Gi({quality:t,availableTracks:Gi(e),track:Gi(i),isAutoQuality:!i})),i?this.desiredState.videoTrack.startTransitionTo(i):this.setAutoQuality(!0)}getActiveLiveDelay(e=!1){return e?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay}isNotActiveTabCase(){return document.hidden&&this.tuning.autoplayOnlyInActiveTab&&!Ua()}};import{Subscription as bte,Observable as gte,Subject as Ste,ValueSubject as vte,VideoQuality as yte}from"@vkontakte/videoplayer-shared/es2015";var Tte=`@vkontakte/videoplayer-core@${jh}`;export{Ao as ChromecastState,Hl as HttpConnectionType,gte as Observable,at as PlaybackState,Dl as Player,Po as PredefinedQualityLimits,Tte as SDK_VERSION,Ste as Subject,bte as Subscription,zl as Surface,jh as VERSION,vte as ValueSubject,bi as VideoFormat,yte as VideoQuality,Q as clientChecker,$a as isMobile};
|