@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/es2018.esm.js CHANGED
@@ -1,19 +1,19 @@
1
1
  /**
2
- * @vkontakte/videoplayer-core v2.0.135-dev.de6f0c74.0
3
- * Tue, 24 Jun 2025 23:52:58 GMT
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 LE=Object.create;var Lh=Object.defineProperty;var BE=Object.getOwnPropertyDescriptor;var $E=Object.getOwnPropertyNames;var DE=Object.getPrototypeOf,CE=Object.prototype.hasOwnProperty;var b=(s,e)=>()=>(e||s((e={exports:{}}).exports,e),e.exports);var VE=(s,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of $E(e))!CE.call(s,r)&&r!==t&&Lh(s,r,{get:()=>e[r],enumerable:!(i=BE(e,r))||i.enumerable});return s};var N=(s,e,t)=>(t=s!=null?LE(DE(s)):{},VE(e||!s||!s.__esModule?Lh(t,"default",{value:s,enumerable:!0}):t,s));var ve=b((Ol,$h)=>{"use strict";var ea=function(s){return s&&s.Math===Math&&s};$h.exports=ea(typeof globalThis=="object"&&globalThis)||ea(typeof window=="object"&&window)||ea(typeof self=="object"&&self)||ea(typeof global=="object"&&global)||ea(typeof Ol=="object"&&Ol)||function(){return this}()||Function("return this")()});var Oe=b((KO,Dh)=>{"use strict";Dh.exports=function(s){try{return!!s()}catch(e){return!0}}});var ta=b((XO,Ch)=>{"use strict";var OE=Oe();Ch.exports=!OE(function(){var s=function(){}.bind();return typeof s!="function"||s.hasOwnProperty("prototype")})});var _l=b((JO,Fh)=>{"use strict";var _E=ta(),_h=Function.prototype,Vh=_h.apply,Oh=_h.call;Fh.exports=typeof Reflect=="object"&&Reflect.apply||(_E?Oh.bind(Vh):function(){return Oh.apply(Vh,arguments)})});var Le=b((ZO,qh)=>{"use strict";var Nh=ta(),Uh=Function.prototype,Fl=Uh.call,FE=Nh&&Uh.bind.bind(Fl,Fl);qh.exports=Nh?FE:function(s){return function(){return Fl.apply(s,arguments)}}});var Wi=b((e_,Hh)=>{"use strict";var jh=Le(),NE=jh({}.toString),UE=jh("".slice);Hh.exports=function(s){return UE(NE(s),8,-1)}});var Nl=b((t_,zh)=>{"use strict";var qE=Wi(),jE=Le();zh.exports=function(s){if(qE(s)==="Function")return jE(s)}});var ge=b((i_,Qh)=>{"use strict";var Ul=typeof document=="object"&&document.all;Qh.exports=typeof Ul=="undefined"&&Ul!==void 0?function(s){return typeof s=="function"||s===Ul}:function(s){return typeof s=="function"}});var ft=b((r_,Gh)=>{"use strict";var HE=Oe();Gh.exports=!HE(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var mt=b((s_,Wh)=>{"use strict";var zE=ta(),To=Function.prototype.call;Wh.exports=zE?To.bind(To):function(){return To.apply(To,arguments)}});var ql=b(Xh=>{"use strict";var Yh={}.propertyIsEnumerable,Kh=Object.getOwnPropertyDescriptor,QE=Kh&&!Yh.call({1:2},1);Xh.f=QE?function(e){var t=Kh(this,e);return!!t&&t.enumerable}:Yh});var ia=b((n_,Jh)=>{"use strict";Jh.exports=function(s,e){return{enumerable:!(s&1),configurable:!(s&2),writable:!(s&4),value:e}}});var ef=b((o_,Zh)=>{"use strict";var GE=Le(),WE=Oe(),YE=Wi(),jl=Object,KE=GE("".split);Zh.exports=WE(function(){return!jl("z").propertyIsEnumerable(0)})?function(s){return YE(s)==="String"?KE(s,""):jl(s)}:jl});var Tr=b((u_,tf)=>{"use strict";tf.exports=function(s){return s==null}});var Pi=b((l_,rf)=>{"use strict";var XE=Tr(),JE=TypeError;rf.exports=function(s){if(XE(s))throw new JE("Can't call method on "+s);return s}});var Yi=b((c_,sf)=>{"use strict";var ZE=ef(),ew=Pi();sf.exports=function(s){return ZE(ew(s))}});var bt=b((d_,af)=>{"use strict";var tw=ge();af.exports=function(s){return typeof s=="object"?s!==null:tw(s)}});var Ir=b((p_,nf)=>{"use strict";nf.exports={}});var pi=b((h_,uf)=>{"use strict";var Hl=Ir(),zl=ve(),iw=ge(),of=function(s){return iw(s)?s:void 0};uf.exports=function(s,e){return arguments.length<2?of(Hl[s])||of(zl[s]):Hl[s]&&Hl[s][e]||zl[s]&&zl[s][e]}});var ra=b((f_,lf)=>{"use strict";var rw=Le();lf.exports=rw({}.isPrototypeOf)});var Ki=b((m_,pf)=>{"use strict";var sw=ve(),cf=sw.navigator,df=cf&&cf.userAgent;pf.exports=df?String(df):""});var Gl=b((b_,Sf)=>{"use strict";var gf=ve(),Ql=Ki(),hf=gf.process,ff=gf.Deno,mf=hf&&hf.versions||ff&&ff.version,bf=mf&&mf.v8,$t,Io;bf&&($t=bf.split("."),Io=$t[0]>0&&$t[0]<4?1:+($t[0]+$t[1]));!Io&&Ql&&($t=Ql.match(/Edge\/(\d+)/),(!$t||$t[1]>=74)&&($t=Ql.match(/Chrome\/(\d+)/),$t&&(Io=+$t[1])));Sf.exports=Io});var Wl=b((g_,yf)=>{"use strict";var vf=Gl(),aw=Oe(),nw=ve(),ow=nw.String;yf.exports=!!Object.getOwnPropertySymbols&&!aw(function(){var s=Symbol("symbol detection");return!ow(s)||!(Object(s)instanceof Symbol)||!Symbol.sham&&vf&&vf<41})});var Yl=b((S_,Tf)=>{"use strict";var uw=Wl();Tf.exports=uw&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var Kl=b((v_,If)=>{"use strict";var lw=pi(),cw=ge(),dw=ra(),pw=Yl(),hw=Object;If.exports=pw?function(s){return typeof s=="symbol"}:function(s){var e=lw("Symbol");return cw(e)&&dw(e.prototype,hw(s))}});var sa=b((y_,xf)=>{"use strict";var fw=String;xf.exports=function(s){try{return fw(s)}catch(e){return"Object"}}});var jt=b((T_,Ef)=>{"use strict";var mw=ge(),bw=sa(),gw=TypeError;Ef.exports=function(s){if(mw(s))return s;throw new gw(bw(s)+" is not a function")}});var aa=b((I_,wf)=>{"use strict";var Sw=jt(),vw=Tr();wf.exports=function(s,e){var t=s[e];return vw(t)?void 0:Sw(t)}});var Pf=b((x_,Af)=>{"use strict";var Xl=mt(),Jl=ge(),Zl=bt(),yw=TypeError;Af.exports=function(s,e){var t,i;if(e==="string"&&Jl(t=s.toString)&&!Zl(i=Xl(t,s))||Jl(t=s.valueOf)&&!Zl(i=Xl(t,s))||e!=="string"&&Jl(t=s.toString)&&!Zl(i=Xl(t,s)))return i;throw new yw("Can't convert object to primitive value")}});var Dt=b((E_,Rf)=>{"use strict";Rf.exports=!0});var Lf=b((w_,Mf)=>{"use strict";var kf=ve(),Tw=Object.defineProperty;Mf.exports=function(s,e){try{Tw(kf,s,{value:e,configurable:!0,writable:!0})}catch(t){kf[s]=e}return e}});var na=b((A_,Df)=>{"use strict";var Iw=Dt(),xw=ve(),Ew=Lf(),Bf="__core-js_shared__",$f=Df.exports=xw[Bf]||Ew(Bf,{});($f.versions||($f.versions=[])).push({version:"3.38.0",mode:Iw?"pure":"global",copyright:"\xA9 2014-2024 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.38.0/LICENSE",source:"https://github.com/zloirock/core-js"})});var ec=b((P_,Vf)=>{"use strict";var Cf=na();Vf.exports=function(s,e){return Cf[s]||(Cf[s]=e||{})}});var xr=b((R_,Of)=>{"use strict";var ww=Pi(),Aw=Object;Of.exports=function(s){return Aw(ww(s))}});var Ct=b((k_,_f)=>{"use strict";var Pw=Le(),Rw=xr(),kw=Pw({}.hasOwnProperty);_f.exports=Object.hasOwn||function(e,t){return kw(Rw(e),t)}});var tc=b((M_,Ff)=>{"use strict";var Mw=Le(),Lw=0,Bw=Math.random(),$w=Mw(1 .toString);Ff.exports=function(s){return"Symbol("+(s===void 0?"":s)+")_"+$w(++Lw+Bw,36)}});var _e=b((L_,Uf)=>{"use strict";var Dw=ve(),Cw=ec(),Nf=Ct(),Vw=tc(),Ow=Wl(),_w=Yl(),Er=Dw.Symbol,ic=Cw("wks"),Fw=_w?Er.for||Er:Er&&Er.withoutSetter||Vw;Uf.exports=function(s){return Nf(ic,s)||(ic[s]=Ow&&Nf(Er,s)?Er[s]:Fw("Symbol."+s)),ic[s]}});var zf=b((B_,Hf)=>{"use strict";var Nw=mt(),qf=bt(),jf=Kl(),Uw=aa(),qw=Pf(),jw=_e(),Hw=TypeError,zw=jw("toPrimitive");Hf.exports=function(s,e){if(!qf(s)||jf(s))return s;var t=Uw(s,zw),i;if(t){if(e===void 0&&(e="default"),i=Nw(t,s,e),!qf(i)||jf(i))return i;throw new Hw("Can't convert object to primitive value")}return e===void 0&&(e="number"),qw(s,e)}});var rc=b(($_,Qf)=>{"use strict";var Qw=zf(),Gw=Kl();Qf.exports=function(s){var e=Qw(s,"string");return Gw(e)?e:e+""}});var xo=b((D_,Wf)=>{"use strict";var Ww=ve(),Gf=bt(),sc=Ww.document,Yw=Gf(sc)&&Gf(sc.createElement);Wf.exports=function(s){return Yw?sc.createElement(s):{}}});var ac=b((C_,Yf)=>{"use strict";var Kw=ft(),Xw=Oe(),Jw=xo();Yf.exports=!Kw&&!Xw(function(){return Object.defineProperty(Jw("div"),"a",{get:function(){return 7}}).a!==7})});var Jf=b(Xf=>{"use strict";var Zw=ft(),eA=mt(),tA=ql(),iA=ia(),rA=Yi(),sA=rc(),aA=Ct(),nA=ac(),Kf=Object.getOwnPropertyDescriptor;Xf.f=Zw?Kf:function(e,t){if(e=rA(e),t=sA(t),nA)try{return Kf(e,t)}catch(i){}if(aA(e,t))return iA(!eA(tA.f,e,t),e[t])}});var nc=b((O_,Zf)=>{"use strict";var oA=Oe(),uA=ge(),lA=/#|\.prototype\./,oa=function(s,e){var t=dA[cA(s)];return t===hA?!0:t===pA?!1:uA(e)?oA(e):!!e},cA=oa.normalize=function(s){return String(s).replace(lA,".").toLowerCase()},dA=oa.data={},pA=oa.NATIVE="N",hA=oa.POLYFILL="P";Zf.exports=oa});var wr=b((__,tm)=>{"use strict";var em=Nl(),fA=jt(),mA=ta(),bA=em(em.bind);tm.exports=function(s,e){return fA(s),e===void 0?s:mA?bA(s,e):function(){return s.apply(e,arguments)}}});var oc=b((F_,im)=>{"use strict";var gA=ft(),SA=Oe();im.exports=gA&&SA(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var Ht=b((N_,rm)=>{"use strict";var vA=bt(),yA=String,TA=TypeError;rm.exports=function(s){if(vA(s))return s;throw new TA(yA(s)+" is not an object")}});var Xi=b(am=>{"use strict";var IA=ft(),xA=ac(),EA=oc(),Eo=Ht(),sm=rc(),wA=TypeError,uc=Object.defineProperty,AA=Object.getOwnPropertyDescriptor,lc="enumerable",cc="configurable",dc="writable";am.f=IA?EA?function(e,t,i){if(Eo(e),t=sm(t),Eo(i),typeof e=="function"&&t==="prototype"&&"value"in i&&dc in i&&!i[dc]){var r=AA(e,t);r&&r[dc]&&(e[t]=i.value,i={configurable:cc in i?i[cc]:r[cc],enumerable:lc in i?i[lc]:r[lc],writable:!1})}return uc(e,t,i)}:uc:function(e,t,i){if(Eo(e),t=sm(t),Eo(i),xA)try{return uc(e,t,i)}catch(r){}if("get"in i||"set"in i)throw new wA("Accessors not supported");return"value"in i&&(e[t]=i.value),e}});var Ar=b((q_,nm)=>{"use strict";var PA=ft(),RA=Xi(),kA=ia();nm.exports=PA?function(s,e,t){return RA.f(s,e,kA(1,t))}:function(s,e,t){return s[e]=t,s}});var Ee=b((j_,um)=>{"use strict";var ua=ve(),MA=_l(),LA=Nl(),BA=ge(),$A=Jf().f,DA=nc(),Pr=Ir(),CA=wr(),Rr=Ar(),om=Ct();na();var VA=function(s){var e=function(t,i,r){if(this instanceof e){switch(arguments.length){case 0:return new s;case 1:return new s(t);case 2:return new s(t,i)}return new s(t,i,r)}return MA(s,this,arguments)};return e.prototype=s.prototype,e};um.exports=function(s,e){var t=s.target,i=s.global,r=s.stat,a=s.proto,n=i?ua:r?ua[t]:ua[t]&&ua[t].prototype,o=i?Pr:Pr[t]||Rr(Pr,t,{})[t],u=o.prototype,l,d,c,h,p,f,m,g,S;for(h in e)l=DA(i?h:t+(r?".":"#")+h,s.forced),d=!l&&n&&om(n,h),f=o[h],d&&(s.dontCallGetSet?(S=$A(n,h),m=S&&S.value):m=n[h]),p=d&&m?m:e[h],!(!l&&!a&&typeof f==typeof p)&&(s.bind&&d?g=CA(p,ua):s.wrap&&d?g=VA(p):a&&BA(p)?g=LA(p):g=p,(s.sham||p&&p.sham||f&&f.sham)&&Rr(g,"sham",!0),Rr(o,h,g),a&&(c=t+"Prototype",om(Pr,c)||Rr(Pr,c,{}),Rr(Pr[c],h,p),s.real&&u&&(l||!u[h])&&Rr(u,h,p)))}});var cm=b((H_,lm)=>{"use strict";var OA=Math.ceil,_A=Math.floor;lm.exports=Math.trunc||function(e){var t=+e;return(t>0?_A:OA)(t)}});var la=b((z_,dm)=>{"use strict";var FA=cm();dm.exports=function(s){var e=+s;return e!==e||e===0?0:FA(e)}});var hm=b((Q_,pm)=>{"use strict";var NA=la(),UA=Math.max,qA=Math.min;pm.exports=function(s,e){var t=NA(s);return t<0?UA(t+e,0):qA(t,e)}});var pc=b((G_,fm)=>{"use strict";var jA=la(),HA=Math.min;fm.exports=function(s){var e=jA(s);return e>0?HA(e,9007199254740991):0}});var kr=b((W_,mm)=>{"use strict";var zA=pc();mm.exports=function(s){return zA(s.length)}});var hc=b((Y_,gm)=>{"use strict";var QA=Yi(),GA=hm(),WA=kr(),bm=function(s){return function(e,t,i){var r=QA(e),a=WA(r);if(a===0)return!s&&-1;var n=GA(i,a),o;if(s&&t!==t){for(;a>n;)if(o=r[n++],o!==o)return!0}else for(;a>n;n++)if((s||n in r)&&r[n]===t)return s||n||0;return!s&&-1}};gm.exports={includes:bm(!0),indexOf:bm(!1)}});var ca=b((K_,Sm)=>{"use strict";Sm.exports=function(){}});var vm=b(()=>{"use strict";var YA=Ee(),KA=hc().includes,XA=Oe(),JA=ca(),ZA=XA(function(){return!Array(1).includes()});YA({target:"Array",proto:!0,forced:ZA},{includes:function(e){return KA(this,e,arguments.length>1?arguments[1]:void 0)}});JA("includes")});var Ri=b((Z_,ym)=>{"use strict";var eP=pi();ym.exports=eP});var Im=b((eF,Tm)=>{"use strict";vm();var tP=Ri();Tm.exports=tP("Array","includes")});var Em=b((tF,xm)=>{"use strict";var iP=Im();xm.exports=iP});var gt=b((iF,wm)=>{"use strict";var rP=Em();wm.exports=rP});var Po=b((fF,$m)=>{"use strict";var dP=ec(),pP=tc(),Bm=dP("keys");$m.exports=function(s){return Bm[s]||(Bm[s]=pP(s))}});var Cm=b((mF,Dm)=>{"use strict";var hP=Oe();Dm.exports=!hP(function(){function s(){}return s.prototype.constructor=null,Object.getPrototypeOf(new s)!==s.prototype})});var Ro=b((bF,Om)=>{"use strict";var fP=Ct(),mP=ge(),bP=xr(),gP=Po(),SP=Cm(),Vm=gP("IE_PROTO"),bc=Object,vP=bc.prototype;Om.exports=SP?bc.getPrototypeOf:function(s){var e=bP(s);if(fP(e,Vm))return e[Vm];var t=e.constructor;return mP(t)&&e instanceof t?t.prototype:e instanceof bc?vP:null}});var ko=b((gF,_m)=>{"use strict";_m.exports={}});var Um=b((SF,Nm)=>{"use strict";var yP=Le(),gc=Ct(),TP=Yi(),IP=hc().indexOf,xP=ko(),Fm=yP([].push);Nm.exports=function(s,e){var t=TP(s),i=0,r=[],a;for(a in t)!gc(xP,a)&&gc(t,a)&&Fm(r,a);for(;e.length>i;)gc(t,a=e[i++])&&(~IP(r,a)||Fm(r,a));return r}});var Sc=b((vF,qm)=>{"use strict";qm.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var vc=b((yF,jm)=>{"use strict";var EP=Um(),wP=Sc();jm.exports=Object.keys||function(e){return EP(e,wP)}});var yc=b((TF,Wm)=>{"use strict";var zm=ft(),AP=Oe(),Qm=Le(),PP=Ro(),RP=vc(),kP=Yi(),MP=ql().f,Gm=Qm(MP),LP=Qm([].push),BP=zm&&AP(function(){var s=Object.create(null);return s[2]=2,!Gm(s,2)}),Hm=function(s){return function(e){for(var t=kP(e),i=RP(t),r=BP&&PP(t)===null,a=i.length,n=0,o=[],u;a>n;)u=i[n++],(!zm||(r?u in t:Gm(t,u)))&&LP(o,s?[u,t[u]]:t[u]);return o}};Wm.exports={entries:Hm(!0),values:Hm(!1)}});var Ym=b(()=>{"use strict";var $P=Ee(),DP=yc().entries;$P({target:"Object",stat:!0},{entries:function(e){return DP(e)}})});var Xm=b((EF,Km)=>{"use strict";Ym();var CP=Ir();Km.exports=CP.Object.entries});var Zm=b((wF,Jm)=>{"use strict";var VP=Xm();Jm.exports=VP});var Ji=b((AF,eb)=>{"use strict";var OP=Zm();eb.exports=OP});var Zi=b((PF,tb)=>{"use strict";tb.exports={}});var sb=b((RF,rb)=>{"use strict";var _P=ve(),FP=ge(),ib=_P.WeakMap;rb.exports=FP(ib)&&/native code/.test(String(ib))});var Ec=b((kF,ob)=>{"use strict";var NP=sb(),nb=ve(),UP=bt(),qP=Ar(),Tc=Ct(),Ic=na(),jP=Po(),HP=ko(),ab="Object already initialized",xc=nb.TypeError,zP=nb.WeakMap,Mo,da,Lo,QP=function(s){return Lo(s)?da(s):Mo(s,{})},GP=function(s){return function(e){var t;if(!UP(e)||(t=da(e)).type!==s)throw new xc("Incompatible receiver, "+s+" required");return t}};NP||Ic.state?(Vt=Ic.state||(Ic.state=new zP),Vt.get=Vt.get,Vt.has=Vt.has,Vt.set=Vt.set,Mo=function(s,e){if(Vt.has(s))throw new xc(ab);return e.facade=s,Vt.set(s,e),e},da=function(s){return Vt.get(s)||{}},Lo=function(s){return Vt.has(s)}):(er=jP("state"),HP[er]=!0,Mo=function(s,e){if(Tc(s,er))throw new xc(ab);return e.facade=s,qP(s,er,e),e},da=function(s){return Tc(s,er)?s[er]:{}},Lo=function(s){return Tc(s,er)});var Vt,er;ob.exports={set:Mo,get:da,has:Lo,enforce:QP,getterFor:GP}});var Pc=b((MF,lb)=>{"use strict";var wc=ft(),WP=Ct(),ub=Function.prototype,YP=wc&&Object.getOwnPropertyDescriptor,Ac=WP(ub,"name"),KP=Ac&&function(){}.name==="something",XP=Ac&&(!wc||wc&&YP(ub,"name").configurable);lb.exports={EXISTS:Ac,PROPER:KP,CONFIGURABLE:XP}});var db=b(cb=>{"use strict";var JP=ft(),ZP=oc(),eR=Xi(),tR=Ht(),iR=Yi(),rR=vc();cb.f=JP&&!ZP?Object.defineProperties:function(e,t){tR(e);for(var i=iR(t),r=rR(t),a=r.length,n=0,o;a>n;)eR.f(e,o=r[n++],i[o]);return e}});var Rc=b((BF,pb)=>{"use strict";var sR=pi();pb.exports=sR("document","documentElement")});var Bc=b(($F,vb)=>{"use strict";var aR=Ht(),nR=db(),hb=Sc(),oR=ko(),uR=Rc(),lR=xo(),cR=Po(),fb=">",mb="<",Mc="prototype",Lc="script",gb=cR("IE_PROTO"),kc=function(){},Sb=function(s){return mb+Lc+fb+s+mb+"/"+Lc+fb},bb=function(s){s.write(Sb("")),s.close();var e=s.parentWindow.Object;return s=null,e},dR=function(){var s=lR("iframe"),e="java"+Lc+":",t;return s.style.display="none",uR.appendChild(s),s.src=String(e),t=s.contentWindow.document,t.open(),t.write(Sb("document.F=Object")),t.close(),t.F},Bo,$o=function(){try{Bo=new ActiveXObject("htmlfile")}catch(e){}$o=typeof document!="undefined"?document.domain&&Bo?bb(Bo):dR():bb(Bo);for(var s=hb.length;s--;)delete $o[Mc][hb[s]];return $o()};oR[gb]=!0;vb.exports=Object.create||function(e,t){var i;return e!==null?(kc[Mc]=aR(e),i=new kc,kc[Mc]=null,i[gb]=e):i=$o(),t===void 0?i:nR.f(i,t)}});var Mr=b((DF,yb)=>{"use strict";var pR=Ar();yb.exports=function(s,e,t,i){return i&&i.enumerable?s[e]=t:pR(s,e,t),s}});var Vc=b((CF,xb)=>{"use strict";var hR=Oe(),fR=ge(),mR=bt(),bR=Bc(),Tb=Ro(),gR=Mr(),SR=_e(),vR=Dt(),Cc=SR("iterator"),Ib=!1,hi,$c,Dc;[].keys&&(Dc=[].keys(),"next"in Dc?($c=Tb(Tb(Dc)),$c!==Object.prototype&&(hi=$c)):Ib=!0);var yR=!mR(hi)||hR(function(){var s={};return hi[Cc].call(s)!==s});yR?hi={}:vR&&(hi=bR(hi));fR(hi[Cc])||gR(hi,Cc,function(){return this});xb.exports={IteratorPrototype:hi,BUGGY_SAFARI_ITERATORS:Ib}});var Do=b((VF,wb)=>{"use strict";var TR=_e(),IR=TR("toStringTag"),Eb={};Eb[IR]="z";wb.exports=String(Eb)==="[object z]"});var pa=b((OF,Ab)=>{"use strict";var xR=Do(),ER=ge(),Co=Wi(),wR=_e(),AR=wR("toStringTag"),PR=Object,RR=Co(function(){return arguments}())==="Arguments",kR=function(s,e){try{return s[e]}catch(t){}};Ab.exports=xR?Co:function(s){var e,t,i;return s===void 0?"Undefined":s===null?"Null":typeof(t=kR(e=PR(s),AR))=="string"?t:RR?Co(e):(i=Co(e))==="Object"&&ER(e.callee)?"Arguments":i}});var Rb=b((_F,Pb)=>{"use strict";var MR=Do(),LR=pa();Pb.exports=MR?{}.toString:function(){return"[object "+LR(this)+"]"}});var ha=b((FF,Mb)=>{"use strict";var BR=Do(),$R=Xi().f,DR=Ar(),CR=Ct(),VR=Rb(),OR=_e(),kb=OR("toStringTag");Mb.exports=function(s,e,t,i){var r=t?s:s&&s.prototype;r&&(CR(r,kb)||$R(r,kb,{configurable:!0,value:e}),i&&!BR&&DR(r,"toString",VR))}});var Bb=b((NF,Lb)=>{"use strict";var _R=Vc().IteratorPrototype,FR=Bc(),NR=ia(),UR=ha(),qR=Zi(),jR=function(){return this};Lb.exports=function(s,e,t,i){var r=e+" Iterator";return s.prototype=FR(_R,{next:NR(+!i,t)}),UR(s,r,!1,!0),qR[r]=jR,s}});var Db=b((UF,$b)=>{"use strict";var HR=Le(),zR=jt();$b.exports=function(s,e,t){try{return HR(zR(Object.getOwnPropertyDescriptor(s,e)[t]))}catch(i){}}});var Vb=b((qF,Cb)=>{"use strict";var QR=bt();Cb.exports=function(s){return QR(s)||s===null}});var _b=b((jF,Ob)=>{"use strict";var GR=Vb(),WR=String,YR=TypeError;Ob.exports=function(s){if(GR(s))return s;throw new YR("Can't set "+WR(s)+" as a prototype")}});var Oc=b((HF,Fb)=>{"use strict";var KR=Db(),XR=bt(),JR=Pi(),ZR=_b();Fb.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var s=!1,e={},t;try{t=KR(Object.prototype,"__proto__","set"),t(e,[]),s=e instanceof Array}catch(i){}return function(r,a){return JR(r),ZR(a),XR(r)&&(s?t(r,a):r.__proto__=a),r}}():void 0)});var Kb=b((zF,Yb)=>{"use strict";var ek=Ee(),tk=mt(),Vo=Dt(),Gb=Pc(),ik=ge(),rk=Bb(),Nb=Ro(),Ub=Oc(),sk=ha(),ak=Ar(),_c=Mr(),nk=_e(),qb=Zi(),Wb=Vc(),ok=Gb.PROPER,uk=Gb.CONFIGURABLE,jb=Wb.IteratorPrototype,Oo=Wb.BUGGY_SAFARI_ITERATORS,fa=nk("iterator"),Hb="keys",ma="values",zb="entries",Qb=function(){return this};Yb.exports=function(s,e,t,i,r,a,n){rk(t,e,i);var o=function(S){if(S===r&&h)return h;if(!Oo&&S&&S in d)return d[S];switch(S){case Hb:return function(){return new t(this,S)};case ma:return function(){return new t(this,S)};case zb:return function(){return new t(this,S)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,d=s.prototype,c=d[fa]||d["@@iterator"]||r&&d[r],h=!Oo&&c||o(r),p=e==="Array"&&d.entries||c,f,m,g;if(p&&(f=Nb(p.call(new s)),f!==Object.prototype&&f.next&&(!Vo&&Nb(f)!==jb&&(Ub?Ub(f,jb):ik(f[fa])||_c(f,fa,Qb)),sk(f,u,!0,!0),Vo&&(qb[u]=Qb))),ok&&r===ma&&c&&c.name!==ma&&(!Vo&&uk?ak(d,"name",ma):(l=!0,h=function(){return tk(c,this)})),r)if(m={values:o(ma),keys:a?h:o(Hb),entries:o(zb)},n)for(g in m)(Oo||l||!(g in d))&&_c(d,g,m[g]);else ek({target:e,proto:!0,forced:Oo||l},m);return(!Vo||n)&&d[fa]!==h&&_c(d,fa,h,{name:r}),qb[e]=h,m}});var Jb=b((QF,Xb)=>{"use strict";Xb.exports=function(s,e){return{value:s,done:e}}});var Nc=b((GF,rg)=>{"use strict";var lk=Yi(),Fc=ca(),Zb=Zi(),tg=Ec(),ck=Xi().f,dk=Kb(),_o=Jb(),pk=Dt(),hk=ft(),ig="Array Iterator",fk=tg.set,mk=tg.getterFor(ig);rg.exports=dk(Array,"Array",function(s,e){fk(this,{type:ig,target:lk(s),index:0,kind:e})},function(){var s=mk(this),e=s.target,t=s.index++;if(!e||t>=e.length)return s.target=void 0,_o(void 0,!0);switch(s.kind){case"keys":return _o(t,!1);case"values":return _o(e[t],!1)}return _o([t,e[t]],!1)},"values");var eg=Zb.Arguments=Zb.Array;Fc("keys");Fc("values");Fc("entries");if(!pk&&hk&&eg.name!=="values")try{ck(eg,"name",{value:"values"})}catch(s){}});var ag=b((WF,sg)=>{"use strict";var bk=_e(),gk=Zi(),Sk=bk("iterator"),vk=Array.prototype;sg.exports=function(s){return s!==void 0&&(gk.Array===s||vk[Sk]===s)}});var Uc=b((YF,og)=>{"use strict";var yk=pa(),ng=aa(),Tk=Tr(),Ik=Zi(),xk=_e(),Ek=xk("iterator");og.exports=function(s){if(!Tk(s))return ng(s,Ek)||ng(s,"@@iterator")||Ik[yk(s)]}});var lg=b((KF,ug)=>{"use strict";var wk=mt(),Ak=jt(),Pk=Ht(),Rk=sa(),kk=Uc(),Mk=TypeError;ug.exports=function(s,e){var t=arguments.length<2?kk(s):e;if(Ak(t))return Pk(wk(t,s));throw new Mk(Rk(s)+" is not iterable")}});var pg=b((XF,dg)=>{"use strict";var Lk=mt(),cg=Ht(),Bk=aa();dg.exports=function(s,e,t){var i,r;cg(s);try{if(i=Bk(s,"return"),!i){if(e==="throw")throw t;return t}i=Lk(i,s)}catch(a){r=!0,i=a}if(e==="throw")throw t;if(r)throw i;return cg(i),t}});var No=b((JF,bg)=>{"use strict";var $k=wr(),Dk=mt(),Ck=Ht(),Vk=sa(),Ok=ag(),_k=kr(),hg=ra(),Fk=lg(),Nk=Uc(),fg=pg(),Uk=TypeError,Fo=function(s,e){this.stopped=s,this.result=e},mg=Fo.prototype;bg.exports=function(s,e,t){var i=t&&t.that,r=!!(t&&t.AS_ENTRIES),a=!!(t&&t.IS_RECORD),n=!!(t&&t.IS_ITERATOR),o=!!(t&&t.INTERRUPTED),u=$k(e,i),l,d,c,h,p,f,m,g=function(v){return l&&fg(l,"normal",v),new Fo(!0,v)},S=function(v){return r?(Ck(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=Nk(s),!d)throw new Uk(Vk(s)+" is not iterable");if(Ok(d)){for(c=0,h=_k(s);h>c;c++)if(p=S(s[c]),p&&hg(mg,p))return p;return new Fo(!1)}l=Fk(s,d)}for(f=a?s.next:l.next;!(m=Dk(f,l)).done;){try{p=S(m.value)}catch(v){fg(l,"throw",v)}if(typeof p=="object"&&p&&hg(mg,p))return p}return new Fo(!1)}});var Sg=b((ZF,gg)=>{"use strict";var qk=ft(),jk=Xi(),Hk=ia();gg.exports=function(s,e,t){qk?jk.f(s,e,Hk(0,t)):s[e]=t}});var vg=b(()=>{"use strict";var zk=Ee(),Qk=No(),Gk=Sg();zk({target:"Object",stat:!0},{fromEntries:function(e){var t={};return Qk(e,function(i,r){Gk(t,i,r)},{AS_ENTRIES:!0}),t}})});var Tg=b((iN,yg)=>{"use strict";Nc();vg();var Wk=Ir();yg.exports=Wk.Object.fromEntries});var xg=b((rN,Ig)=>{"use strict";Ig.exports={CSSRuleList:0,CSSStyleDeclaration:0,CSSValueList:0,ClientRectList:0,DOMRectList:0,DOMStringList:0,DOMTokenList:1,DataTransferItemList:0,FileList:0,HTMLAllCollection:0,HTMLCollection:0,HTMLFormElement:0,HTMLSelectElement:0,MediaList:0,MimeTypeArray:0,NamedNodeMap:0,NodeList:1,PaintRequestList:0,Plugin:0,PluginArray:0,SVGLengthList:0,SVGNumberList:0,SVGPathSegList:0,SVGPointList:0,SVGStringList:0,SVGTransformList:0,SourceBufferList:0,StyleSheetList:0,TextTrackCueList:0,TextTrackList:0,TouchList:0}});var wg=b(()=>{"use strict";Nc();var Yk=xg(),Kk=ve(),Xk=ha(),Eg=Zi();for(Uo in Yk)Xk(Kk[Uo],Uo),Eg[Uo]=Eg.Array;var Uo});var Pg=b((nN,Ag)=>{"use strict";var Jk=Tg();wg();Ag.exports=Jk});var qc=b((oN,Rg)=>{"use strict";var Zk=Pg();Rg.exports=Zk});var kg=b(()=>{"use strict"});var jc=b((cN,Mg)=>{"use strict";var ba=ve(),eM=Ki(),tM=Wi(),qo=function(s){return eM.slice(0,s.length)===s};Mg.exports=function(){return qo("Bun/")?"BUN":qo("Cloudflare-Workers")?"CLOUDFLARE":qo("Deno/")?"DENO":qo("Node.js/")?"NODE":ba.Bun&&typeof Bun.version=="string"?"BUN":ba.Deno&&typeof Deno.version=="object"?"DENO":tM(ba.process)==="process"?"NODE":ba.window&&ba.document?"BROWSER":"REST"}()});var jo=b((dN,Lg)=>{"use strict";var iM=jc();Lg.exports=iM==="NODE"});var $g=b((pN,Bg)=>{"use strict";var rM=Xi();Bg.exports=function(s,e,t){return rM.f(s,e,t)}});var Vg=b((hN,Cg)=>{"use strict";var sM=pi(),aM=$g(),nM=_e(),oM=ft(),Dg=nM("species");Cg.exports=function(s){var e=sM(s);oM&&e&&!e[Dg]&&aM(e,Dg,{configurable:!0,get:function(){return this}})}});var _g=b((fN,Og)=>{"use strict";var uM=ra(),lM=TypeError;Og.exports=function(s,e){if(uM(e,s))return s;throw new lM("Incorrect invocation")}});var zc=b((mN,Fg)=>{"use strict";var cM=Le(),dM=ge(),Hc=na(),pM=cM(Function.toString);dM(Hc.inspectSource)||(Hc.inspectSource=function(s){return pM(s)});Fg.exports=Hc.inspectSource});var Gc=b((bN,Hg)=>{"use strict";var hM=Le(),fM=Oe(),Ng=ge(),mM=pa(),bM=pi(),gM=zc(),Ug=function(){},qg=bM("Reflect","construct"),Qc=/^\s*(?:class|function)\b/,SM=hM(Qc.exec),vM=!Qc.test(Ug),ga=function(e){if(!Ng(e))return!1;try{return qg(Ug,[],e),!0}catch(t){return!1}},jg=function(e){if(!Ng(e))return!1;switch(mM(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return vM||!!SM(Qc,gM(e))}catch(t){return!0}};jg.sham=!0;Hg.exports=!qg||fM(function(){var s;return ga(ga.call)||!ga(Object)||!ga(function(){s=!0})||s})?jg:ga});var Qg=b((gN,zg)=>{"use strict";var yM=Gc(),TM=sa(),IM=TypeError;zg.exports=function(s){if(yM(s))return s;throw new IM(TM(s)+" is not a constructor")}});var Wc=b((SN,Wg)=>{"use strict";var Gg=Ht(),xM=Qg(),EM=Tr(),wM=_e(),AM=wM("species");Wg.exports=function(s,e){var t=Gg(s).constructor,i;return t===void 0||EM(i=Gg(t)[AM])?e:xM(i)}});var Kg=b((vN,Yg)=>{"use strict";var PM=Le();Yg.exports=PM([].slice)});var Jg=b((yN,Xg)=>{"use strict";var RM=TypeError;Xg.exports=function(s,e){if(s<e)throw new RM("Not enough arguments");return s}});var Yc=b((TN,Zg)=>{"use strict";var kM=Ki();Zg.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(kM)});var sd=b((IN,uS)=>{"use strict";var St=ve(),MM=_l(),LM=wr(),eS=ge(),BM=Ct(),oS=Oe(),tS=Rc(),$M=Kg(),iS=xo(),DM=Jg(),CM=Yc(),VM=jo(),td=St.setImmediate,id=St.clearImmediate,OM=St.process,Kc=St.Dispatch,_M=St.Function,rS=St.MessageChannel,FM=St.String,Xc=0,Sa={},sS="onreadystatechange",va,tr,Jc,Zc;oS(function(){va=St.location});var rd=function(s){if(BM(Sa,s)){var e=Sa[s];delete Sa[s],e()}},ed=function(s){return function(){rd(s)}},aS=function(s){rd(s.data)},nS=function(s){St.postMessage(FM(s),va.protocol+"//"+va.host)};(!td||!id)&&(td=function(e){DM(arguments.length,1);var t=eS(e)?e:_M(e),i=$M(arguments,1);return Sa[++Xc]=function(){MM(t,void 0,i)},tr(Xc),Xc},id=function(e){delete Sa[e]},VM?tr=function(s){OM.nextTick(ed(s))}:Kc&&Kc.now?tr=function(s){Kc.now(ed(s))}:rS&&!CM?(Jc=new rS,Zc=Jc.port2,Jc.port1.onmessage=aS,tr=LM(Zc.postMessage,Zc)):St.addEventListener&&eS(St.postMessage)&&!St.importScripts&&va&&va.protocol!=="file:"&&!oS(nS)?(tr=nS,St.addEventListener("message",aS,!1)):sS in iS("script")?tr=function(s){tS.appendChild(iS("script"))[sS]=function(){tS.removeChild(this),rd(s)}}:tr=function(s){setTimeout(ed(s),0)});uS.exports={set:td,clear:id}});var dS=b((xN,cS)=>{"use strict";var lS=ve(),NM=ft(),UM=Object.getOwnPropertyDescriptor;cS.exports=function(s){if(!NM)return lS[s];var e=UM(lS,s);return e&&e.value}});var ad=b((EN,hS)=>{"use strict";var pS=function(){this.head=null,this.tail=null};pS.prototype={add:function(s){var e={item:s,next:null},t=this.tail;t?t.next=e:this.head=e,this.tail=e},get:function(){var s=this.head;if(s){var e=this.head=s.next;return e===null&&(this.tail=null),s.item}}};hS.exports=pS});var mS=b((wN,fS)=>{"use strict";var qM=Ki();fS.exports=/ipad|iphone|ipod/i.test(qM)&&typeof Pebble!="undefined"});var gS=b((AN,bS)=>{"use strict";var jM=Ki();bS.exports=/web0s(?!.*chrome)/i.test(jM)});var ES=b((PN,xS)=>{"use strict";var Br=ve(),HM=dS(),SS=wr(),nd=sd().set,zM=ad(),QM=Yc(),GM=mS(),WM=gS(),od=jo(),vS=Br.MutationObserver||Br.WebKitMutationObserver,yS=Br.document,TS=Br.process,Ho=Br.Promise,cd=HM("queueMicrotask"),Lr,ud,ld,zo,IS;cd||(ya=new zM,Ta=function(){var s,e;for(od&&(s=TS.domain)&&s.exit();e=ya.get();)try{e()}catch(t){throw ya.head&&Lr(),t}s&&s.enter()},!QM&&!od&&!WM&&vS&&yS?(ud=!0,ld=yS.createTextNode(""),new vS(Ta).observe(ld,{characterData:!0}),Lr=function(){ld.data=ud=!ud}):!GM&&Ho&&Ho.resolve?(zo=Ho.resolve(void 0),zo.constructor=Ho,IS=SS(zo.then,zo),Lr=function(){IS(Ta)}):od?Lr=function(){TS.nextTick(Ta)}:(nd=SS(nd,Br),Lr=function(){nd(Ta)}),cd=function(s){ya.head||Lr(),ya.add(s)});var ya,Ta;xS.exports=cd});var AS=b((RN,wS)=>{"use strict";wS.exports=function(s,e){try{arguments.length===1?console.error(s):console.error(s,e)}catch(t){}}});var Qo=b((kN,PS)=>{"use strict";PS.exports=function(s){try{return{error:!1,value:s()}}catch(e){return{error:!0,value:e}}}});var ir=b((MN,RS)=>{"use strict";var YM=ve();RS.exports=YM.Promise});var $r=b((LN,BS)=>{"use strict";var KM=ve(),Ia=ir(),XM=ge(),JM=nc(),ZM=zc(),eL=_e(),kS=jc(),tL=Dt(),dd=Gl(),MS=Ia&&Ia.prototype,iL=eL("species"),pd=!1,LS=XM(KM.PromiseRejectionEvent),rL=JM("Promise",function(){var s=ZM(Ia),e=s!==String(Ia);if(!e&&dd===66||tL&&!(MS.catch&&MS.finally))return!0;if(!dd||dd<51||!/native code/.test(s)){var t=new Ia(function(a){a(1)}),i=function(a){a(function(){},function(){})},r=t.constructor={};if(r[iL]=i,pd=t.then(function(){})instanceof i,!pd)return!0}return!e&&(kS==="BROWSER"||kS==="DENO")&&!LS});BS.exports={CONSTRUCTOR:rL,REJECTION_EVENT:LS,SUBCLASSING:pd}});var Dr=b((BN,DS)=>{"use strict";var $S=jt(),sL=TypeError,aL=function(s){var e,t;this.promise=new s(function(i,r){if(e!==void 0||t!==void 0)throw new sL("Bad Promise constructor");e=i,t=r}),this.resolve=$S(e),this.reject=$S(t)};DS.exports.f=function(s){return new aL(s)}});var ZS=b(()=>{"use strict";var nL=Ee(),oL=Dt(),Ko=jo(),ki=ve(),_r=mt(),CS=Mr(),VS=Oc(),uL=ha(),lL=Vg(),cL=jt(),Yo=ge(),dL=bt(),pL=_g(),hL=Wc(),US=sd().set,gd=ES(),fL=AS(),mL=Qo(),bL=ad(),qS=Ec(),Xo=ir(),Sd=$r(),jS=Dr(),Jo="Promise",HS=Sd.CONSTRUCTOR,gL=Sd.REJECTION_EVENT,SL=Sd.SUBCLASSING,hd=qS.getterFor(Jo),vL=qS.set,Cr=Xo&&Xo.prototype,rr=Xo,Go=Cr,zS=ki.TypeError,fd=ki.document,vd=ki.process,md=jS.f,yL=md,TL=!!(fd&&fd.createEvent&&ki.dispatchEvent),QS="unhandledrejection",IL="rejectionhandled",OS=0,GS=1,xL=2,yd=1,WS=2,Wo,_S,EL,FS,YS=function(s){var e;return dL(s)&&Yo(e=s.then)?e:!1},KS=function(s,e){var t=e.value,i=e.state===GS,r=i?s.ok:s.fail,a=s.resolve,n=s.reject,o=s.domain,u,l,d;try{r?(i||(e.rejection===WS&&AL(e),e.rejection=yd),r===!0?u=t:(o&&o.enter(),u=r(t),o&&(o.exit(),d=!0)),u===s.promise?n(new zS("Promise-chain cycle")):(l=YS(u))?_r(l,u,a,n):a(u)):n(t)}catch(c){o&&!d&&o.exit(),n(c)}},XS=function(s,e){s.notified||(s.notified=!0,gd(function(){for(var t=s.reactions,i;i=t.get();)KS(i,s);s.notified=!1,e&&!s.rejection&&wL(s)}))},JS=function(s,e,t){var i,r;TL?(i=fd.createEvent("Event"),i.promise=e,i.reason=t,i.initEvent(s,!1,!0),ki.dispatchEvent(i)):i={promise:e,reason:t},!gL&&(r=ki["on"+s])?r(i):s===QS&&fL("Unhandled promise rejection",t)},wL=function(s){_r(US,ki,function(){var e=s.facade,t=s.value,i=NS(s),r;if(i&&(r=mL(function(){Ko?vd.emit("unhandledRejection",t,e):JS(QS,e,t)}),s.rejection=Ko||NS(s)?WS:yd,r.error))throw r.value})},NS=function(s){return s.rejection!==yd&&!s.parent},AL=function(s){_r(US,ki,function(){var e=s.facade;Ko?vd.emit("rejectionHandled",e):JS(IL,e,s.value)})},Vr=function(s,e,t){return function(i){s(e,i,t)}},Or=function(s,e,t){s.done||(s.done=!0,t&&(s=t),s.value=e,s.state=xL,XS(s,!0))},bd=function(s,e,t){if(!s.done){s.done=!0,t&&(s=t);try{if(s.facade===e)throw new zS("Promise can't be resolved itself");var i=YS(e);i?gd(function(){var r={done:!1};try{_r(i,e,Vr(bd,r,s),Vr(Or,r,s))}catch(a){Or(r,a,s)}}):(s.value=e,s.state=GS,XS(s,!1))}catch(r){Or({done:!1},r,s)}}};if(HS&&(rr=function(e){pL(this,Go),cL(e),_r(Wo,this);var t=hd(this);try{e(Vr(bd,t),Vr(Or,t))}catch(i){Or(t,i)}},Go=rr.prototype,Wo=function(e){vL(this,{type:Jo,done:!1,notified:!1,parent:!1,reactions:new bL,rejection:!1,state:OS,value:void 0})},Wo.prototype=CS(Go,"then",function(e,t){var i=hd(this),r=md(hL(this,rr));return i.parent=!0,r.ok=Yo(e)?e:!0,r.fail=Yo(t)&&t,r.domain=Ko?vd.domain:void 0,i.state===OS?i.reactions.add(r):gd(function(){KS(r,i)}),r.promise}),_S=function(){var s=new Wo,e=hd(s);this.promise=s,this.resolve=Vr(bd,e),this.reject=Vr(Or,e)},jS.f=md=function(s){return s===rr||s===EL?new _S(s):yL(s)},!oL&&Yo(Xo)&&Cr!==Object.prototype)){FS=Cr.then,SL||CS(Cr,"then",function(e,t){var i=this;return new rr(function(r,a){_r(FS,i,r,a)}).then(e,t)},{unsafe:!0});try{delete Cr.constructor}catch(s){}VS&&VS(Cr,Go)}nL({global:!0,constructor:!0,wrap:!0,forced:HS},{Promise:rr});uL(rr,Jo,!1,!0);lL(Jo)});var sv=b((CN,rv)=>{"use strict";var PL=_e(),tv=PL("iterator"),iv=!1;try{ev=0,Td={next:function(){return{done:!!ev++}},return:function(){iv=!0}},Td[tv]=function(){return this},Array.from(Td,function(){throw 2})}catch(s){}var ev,Td;rv.exports=function(s,e){try{if(!e&&!iv)return!1}catch(r){return!1}var t=!1;try{var i={};i[tv]=function(){return{next:function(){return{done:t=!0}}}},s(i)}catch(r){}return t}});var Id=b((VN,av)=>{"use strict";var RL=ir(),kL=sv(),ML=$r().CONSTRUCTOR;av.exports=ML||!kL(function(s){RL.all(s).then(void 0,function(){})})});var nv=b(()=>{"use strict";var LL=Ee(),BL=mt(),$L=jt(),DL=Dr(),CL=Qo(),VL=No(),OL=Id();LL({target:"Promise",stat:!0,forced:OL},{all:function(e){var t=this,i=DL.f(t),r=i.resolve,a=i.reject,n=CL(function(){var o=$L(t.resolve),u=[],l=0,d=1;VL(e,function(c){var h=l++,p=!1;d++,BL(o,t,c).then(function(f){p||(p=!0,u[h]=f,--d||r(u))},a)}),--d||r(u)});return n.error&&a(n.value),i.promise}})});var uv=b(()=>{"use strict";var _L=Ee(),FL=Dt(),NL=$r().CONSTRUCTOR,Ed=ir(),UL=pi(),qL=ge(),jL=Mr(),ov=Ed&&Ed.prototype;_L({target:"Promise",proto:!0,forced:NL,real:!0},{catch:function(s){return this.then(void 0,s)}});!FL&&qL(Ed)&&(xd=UL("Promise").prototype.catch,ov.catch!==xd&&jL(ov,"catch",xd,{unsafe:!0}));var xd});var lv=b(()=>{"use strict";var HL=Ee(),zL=mt(),QL=jt(),GL=Dr(),WL=Qo(),YL=No(),KL=Id();HL({target:"Promise",stat:!0,forced:KL},{race:function(e){var t=this,i=GL.f(t),r=i.reject,a=WL(function(){var n=QL(t.resolve);YL(e,function(o){zL(n,t,o).then(i.resolve,r)})});return a.error&&r(a.value),i.promise}})});var cv=b(()=>{"use strict";var XL=Ee(),JL=Dr(),ZL=$r().CONSTRUCTOR;XL({target:"Promise",stat:!0,forced:ZL},{reject:function(e){var t=JL.f(this),i=t.reject;return i(e),t.promise}})});var wd=b((zN,dv)=>{"use strict";var eB=Ht(),tB=bt(),iB=Dr();dv.exports=function(s,e){if(eB(s),tB(e)&&e.constructor===s)return e;var t=iB.f(s),i=t.resolve;return i(e),t.promise}});var fv=b(()=>{"use strict";var rB=Ee(),sB=pi(),pv=Dt(),aB=ir(),hv=$r().CONSTRUCTOR,nB=wd(),oB=sB("Promise"),uB=pv&&!hv;rB({target:"Promise",stat:!0,forced:pv||hv},{resolve:function(e){return nB(uB&&this===oB?aB:this,e)}})});var mv=b(()=>{"use strict";ZS();nv();uv();lv();cv();fv()});var vv=b(()=>{"use strict";var lB=Ee(),cB=Dt(),Zo=ir(),dB=Oe(),gv=pi(),Sv=ge(),pB=Wc(),bv=wd(),hB=Mr(),Pd=Zo&&Zo.prototype,fB=!!Zo&&dB(function(){Pd.finally.call({then:function(){}},function(){})});lB({target:"Promise",proto:!0,real:!0,forced:fB},{finally:function(s){var e=pB(this,gv("Promise")),t=Sv(s);return this.then(t?function(i){return bv(e,s()).then(function(){return i})}:s,t?function(i){return bv(e,s()).then(function(){throw i})}:s)}});!cB&&Sv(Zo)&&(Ad=gv("Promise").prototype.finally,Pd.finally!==Ad&&hB(Pd,"finally",Ad,{unsafe:!0}));var Ad});var Tv=b((JN,yv)=>{"use strict";kg();mv();vv();var mB=Ri();yv.exports=mB("Promise","finally")});var xv=b((ZN,Iv)=>{"use strict";var bB=Tv();Iv.exports=bB});var eu=b((eU,Ev)=>{"use strict";var gB=xv();Ev.exports=gB});var Ov=b(()=>{"use strict";var LB=Ee(),BB=yc().values;LB({target:"Object",stat:!0},{values:function(e){return BB(e)}})});var Fv=b((_U,_v)=>{"use strict";Ov();var $B=Ir();_v.exports=$B.Object.values});var Uv=b((FU,Nv)=>{"use strict";var DB=Fv();Nv.exports=DB});var nr=b((NU,qv)=>{"use strict";var CB=Uv();qv.exports=CB});var ay=b(()=>{"use strict";var s$=Ee(),a$=xr(),n$=kr(),o$=la(),u$=ca();s$({target:"Array",proto:!0},{at:function(e){var t=a$(this),i=n$(t),r=o$(e),a=r>=0?r:i+r;return a<0||a>=i?void 0:t[a]}});u$("at")});var oy=b((Y1,ny)=>{"use strict";ay();var l$=Ri();ny.exports=l$("Array","at")});var ly=b((K1,uy)=>{"use strict";var c$=oy();uy.exports=c$});var Ot=b((X1,cy)=>{"use strict";var d$=ly();cy.exports=d$});var Kd=b((Oj,jy)=>{"use strict";var z$=Wi();jy.exports=Array.isArray||function(e){return z$(e)==="Array"}});var zy=b((_j,Hy)=>{"use strict";var Q$=TypeError,G$=9007199254740991;Hy.exports=function(s){if(s>G$)throw Q$("Maximum allowed index exceeded");return s}});var Wy=b((Fj,Gy)=>{"use strict";var W$=Kd(),Y$=kr(),K$=zy(),X$=wr(),Qy=function(s,e,t,i,r,a,n,o){for(var u=r,l=0,d=n?X$(n,o):!1,c,h;l<i;)l in t&&(c=d?d(t[l],l,e):t[l],a>0&&W$(c)?(h=Y$(c),u=Qy(s,e,c,h,u,a-1)-1):(K$(u+1),s[u]=c),u++),l++;return u};Gy.exports=Qy});var Jy=b((Nj,Xy)=>{"use strict";var Yy=Kd(),J$=Gc(),Z$=bt(),eD=_e(),tD=eD("species"),Ky=Array;Xy.exports=function(s){var e;return Yy(s)&&(e=s.constructor,J$(e)&&(e===Ky||Yy(e.prototype))?e=void 0:Z$(e)&&(e=e[tD],e===null&&(e=void 0))),e===void 0?Ky:e}});var eT=b((Uj,Zy)=>{"use strict";var iD=Jy();Zy.exports=function(s,e){return new(iD(s))(e===0?0:e)}});var tT=b(()=>{"use strict";var rD=Ee(),sD=Wy(),aD=jt(),nD=xr(),oD=kr(),uD=eT();rD({target:"Array",proto:!0},{flatMap:function(e){var t=nD(this),i=oD(t),r;return aD(e),r=uD(t,0),r.length=sD(r,t,t,i,0,1,e,arguments.length>1?arguments[1]:void 0),r}})});var iT=b(()=>{"use strict";var lD=ca();lD("flatMap")});var sT=b((Qj,rT)=>{"use strict";tT();iT();var cD=Ri();rT.exports=cD("Array","flatMap")});var nT=b((Gj,aT)=>{"use strict";var dD=sT();aT.exports=dD});var Fa=b((Wj,oT)=>{"use strict";var pD=nT();oT.exports=pD});var Na=b((Yj,uT)=>{"use strict";var hD=pa(),fD=String;uT.exports=function(s){if(hD(s)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return fD(s)}});var Xd=b((Kj,lT)=>{"use strict";lT.exports=`
7
- \v\f\r \xA0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF`});var pT=b((Xj,dT)=>{"use strict";var mD=Le(),bD=Pi(),gD=Na(),Zd=Xd(),cT=mD("".replace),SD=RegExp("^["+Zd+"]+"),vD=RegExp("(^|[^"+Zd+"])["+Zd+"]+$"),Jd=function(s){return function(e){var t=gD(bD(e));return s&1&&(t=cT(t,SD,"")),s&2&&(t=cT(t,vD,"$1")),t}};dT.exports={start:Jd(1),end:Jd(2),trim:Jd(3)}});var bT=b((Jj,mT)=>{"use strict";var yD=Pc().PROPER,TD=Oe(),hT=Xd(),fT="\u200B\x85\u180E";mT.exports=function(s){return TD(function(){return!!hT[s]()||fT[s]()!==fT||yD&&hT[s].name!==s})}});var ep=b((Zj,gT)=>{"use strict";var ID=pT().start,xD=bT();gT.exports=xD("trimStart")?function(){return ID(this)}:"".trimStart});var vT=b(()=>{"use strict";var ED=Ee(),ST=ep();ED({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==ST},{trimLeft:ST})});var TT=b(()=>{"use strict";vT();var wD=Ee(),yT=ep();wD({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==yT},{trimStart:yT})});var xT=b((sH,IT)=>{"use strict";TT();var AD=Ri();IT.exports=AD("String","trimLeft")});var wT=b((aH,ET)=>{"use strict";var PD=xT();ET.exports=PD});var PT=b((nH,AT)=>{"use strict";var RD=wT();AT.exports=RD});var qT=b(()=>{"use strict"});var jT=b(()=>{"use strict"});var zT=b((N3,HT)=>{"use strict";var XD=bt(),JD=Wi(),ZD=_e(),e0=ZD("match");HT.exports=function(s){var e;return XD(s)&&((e=s[e0])!==void 0?!!e:JD(s)==="RegExp")}});var GT=b((U3,QT)=>{"use strict";var t0=Ht();QT.exports=function(){var s=t0(this),e="";return s.hasIndices&&(e+="d"),s.global&&(e+="g"),s.ignoreCase&&(e+="i"),s.multiline&&(e+="m"),s.dotAll&&(e+="s"),s.unicode&&(e+="u"),s.unicodeSets&&(e+="v"),s.sticky&&(e+="y"),e}});var KT=b((q3,YT)=>{"use strict";var i0=mt(),r0=Ct(),s0=ra(),a0=GT(),WT=RegExp.prototype;YT.exports=function(s){var e=s.flags;return e===void 0&&!("flags"in WT)&&!r0(s,"flags")&&s0(WT,s)?i0(a0,s):e}});var JT=b((j3,XT)=>{"use strict";var np=Le(),n0=xr(),o0=Math.floor,sp=np("".charAt),u0=np("".replace),ap=np("".slice),l0=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,c0=/\$([$&'`]|\d{1,2})/g;XT.exports=function(s,e,t,i,r,a){var n=t+s.length,o=i.length,u=c0;return r!==void 0&&(r=n0(r),u=l0),u0(a,u,function(l,d){var c;switch(sp(d,0)){case"$":return"$";case"&":return s;case"`":return ap(e,0,t);case"'":return ap(e,n);case"<":c=r[ap(d,1,-1)];break;default:var h=+d;if(h===0)return l;if(h>o){var p=o0(h/10);return p===0?l:p<=o?i[p-1]===void 0?sp(d,1):i[p-1]+sp(d,1):l}c=i[h-1]}return c===void 0?"":c})}});var tI=b(()=>{"use strict";var d0=Ee(),p0=mt(),up=Le(),ZT=Pi(),h0=ge(),f0=Tr(),m0=zT(),Jr=Na(),b0=aa(),g0=KT(),S0=JT(),v0=_e(),y0=Dt(),T0=v0("replace"),I0=TypeError,op=up("".indexOf),x0=up("".replace),eI=up("".slice),E0=Math.max;d0({target:"String",proto:!0},{replaceAll:function(e,t){var i=ZT(this),r,a,n,o,u,l,d,c,h,p,f=0,m="";if(!f0(e)){if(r=m0(e),r&&(a=Jr(ZT(g0(e))),!~op(a,"g")))throw new I0("`.replaceAll` does not allow non-global regexes");if(n=b0(e,T0),n)return p0(n,e,i,t);if(y0&&r)return x0(Jr(i),e,t)}for(o=Jr(i),u=Jr(e),l=h0(t),l||(t=Jr(t)),d=u.length,c=E0(1,d),h=op(o,u);h!==-1;)p=l?Jr(t(u,h,o)):S0(u,o,h,[],void 0,t),m+=eI(o,f,h)+p,f=h+d,h=h+c>o.length?-1:op(o,u,h+c);return f<o.length&&(m+=eI(o,f)),m}})});var rI=b((Q3,iI)=>{"use strict";qT();jT();tI();var w0=Ri();iI.exports=w0("String","replaceAll")});var aI=b((G3,sI)=>{"use strict";var A0=rI();sI.exports=A0});var lp=b((W3,nI)=>{"use strict";var P0=aI();nI.exports=P0});var uI=b((Y3,oI)=>{"use strict";var R0=la(),k0=Na(),M0=Pi(),L0=RangeError;oI.exports=function(e){var t=k0(M0(this)),i="",r=R0(e);if(r<0||r===1/0)throw new L0("Wrong number of repetitions");for(;r>0;(r>>>=1)&&(t+=t))r&1&&(i+=t);return i}});var hI=b((K3,pI)=>{"use strict";var dI=Le(),B0=pc(),lI=Na(),$0=uI(),D0=Pi(),C0=dI($0),V0=dI("".slice),O0=Math.ceil,cI=function(s){return function(e,t,i){var r=lI(D0(e)),a=B0(t),n=r.length,o=i===void 0?" ":lI(i),u,l;return a<=n||o===""?r:(u=a-n,l=C0(o,O0(u/o.length)),l.length>u&&(l=V0(l,0,u)),s?r+l:l+r)}};pI.exports={start:cI(!1),end:cI(!0)}});var mI=b((X3,fI)=>{"use strict";var _0=Ki();fI.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(_0)});var bI=b(()=>{"use strict";var F0=Ee(),N0=hI().start,U0=mI();F0({target:"String",proto:!0,forced:U0},{padStart:function(e){return N0(this,e,arguments.length>1?arguments[1]:void 0)}})});var SI=b((ez,gI)=>{"use strict";bI();var q0=Ri();gI.exports=q0("String","padStart")});var yI=b((tz,vI)=>{"use strict";var j0=SI();vI.exports=j0});var cp=b((iz,TI)=>{"use strict";var H0=yI();TI.exports=H0});var Bh="2.0.135-dev.de6f0c74.0";var et=(r=>(r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused",r))(et||{}),di=(y=>(y.MPEG="MPEG",y.DASH="DASH",y.DASH_SEP="DASH_SEP",y.DASH_SEP_VK="DASH_SEP",y.DASH_WEBM="DASH_WEBM",y.DASH_WEBM_AV1="DASH_WEBM_AV1",y.DASH_STREAMS="DASH_STREAMS",y.DASH_WEBM_VK="DASH_WEBM",y.DASH_ONDEMAND="DASH_ONDEMAND",y.DASH_ONDEMAND_VK="DASH_ONDEMAND",y.DASH_LIVE="DASH_LIVE",y.DASH_LIVE_CMAF="DASH_LIVE_CMAF",y.DASH_LIVE_WEBM="DASH_LIVE_WEBM",y.HLS="HLS",y.HLS_ONDEMAND="HLS_ONDEMAND",y.HLS_JS="HLS",y.HLS_LIVE="HLS_LIVE",y.HLS_LIVE_CMAF="HLS_LIVE_CMAF",y.WEB_RTC_LIVE="WEB_RTC_LIVE",y))(di||{});var vo=(r=>(r.NOT_AVAILABLE="NOT_AVAILABLE",r.AVAILABLE="AVAILABLE",r.CONNECTING="CONNECTING",r.CONNECTED="CONNECTED",r))(vo||{}),Cl=(i=>(i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic",i))(Cl||{});var Vl=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(Vl||{}),yo=(i=>(i.TRAFFIC_SAVING="traffic_saving",i.HIGH_QUALITY="high_quality",i.UNKNOWN="unknown",i))(yo||{});var ME=N(gt(),1);import{assertNever as Lm,assertNonNullable as sP,isNonNullable as wo,ValueSubject as fc,Subject as aP,Subscription as nP,merge as oP,observableFrom as uP,fromEvent as Pm,map as Rm,tap as km,filterChanged as lP,isNullable as mc,ErrorCategory as Mm}from"@vkontakte/videoplayer-shared/es2018";var Am=s=>new Promise((e,t)=>{let i=document.createElement("script");i.setAttribute("src",s),i.onload=()=>e(),i.onerror=r=>t(r),document.body.appendChild(i)});var Ao=class{constructor(e){this.connection$=new fc(void 0);this.castState$=new fc("NOT_AVAILABLE");this.errorEvent$=new aP;this.realCastState$=new fc("NOT_AVAILABLE");this.subscription=new nP;this.isDestroyed=!1;var a;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");let t="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${t}`}),e.isDisabled||!t)return;let i=wo((a=window.chrome)==null?void 0:a.cast),r=!!window.__onGCastApiAvailable;i?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&!this.isDestroyed&&this.initializeCastApi()},r||Am("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:Mm.NETWORK,message:"Script loading failed!"})))}connect(){var e;(e=cast.framework.CastContext.getInstance())==null||e.requestSession()}disconnect(){var e,t;(t=(e=cast.framework.CastContext.getInstance())==null?void 0:e.getCurrentSession())==null||t.endSession(!0)}stopMedia(){return new Promise((e,t)=>{var i,r,a;(a=(r=(i=cast.framework.CastContext.getInstance())==null?void 0:i.getCurrentSession())==null?void 0:r.getMediaSession())==null||a.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){wo(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();mc(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();mc(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.isDestroyed=!0,this.subscription.unsubscribe()}initListeners(){let e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),i=cast.framework.CastContext.getInstance();this.subscription.add(Pm(i,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(r=>{var a,n,o;switch(r.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(o=(n=(a=i.getCurrentSession())==null?void 0:a.getMediaSession())==null?void 0:n.media)==null?void 0:o.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return Lm(r.sessionState)}})).add(oP(Pm(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(km(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),Rm(r=>r.castState)),uP([i.getCastState()])).pipe(lP(),Rm(cP),km(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{var o,u;let a=r==="CONNECTED",n=wo(this.connection$.getValue());if(a&&!n){let l=i.getCurrentSession();sP(l);let d=l.getCastDevice(),c=(u=(o=l.getMediaSession())==null?void 0:o.media)==null?void 0:u.contentId;(mc(c)||c===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:l,castDevice:d}))}else!a&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(r==="CONNECTED"?wo(this.connection$.getValue())?"CONNECTED":"AVAILABLE":r)}))}initializeCastApi(){var r;let e,t,i;try{e=cast.framework.CastContext.getInstance(),t=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,i=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(a){return}try{e.setOptions({receiverApplicationId:(r=this.params.receiverApplicationId)!=null?r:t,autoJoinPolicy:i}),this.initListeners()}catch(a){this.errorEvent$.next({id:"ChromecastInitializer",category:Mm.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:a})}}},cP=s=>{switch(s){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return"NOT_AVAILABLE";case cast.framework.CastState.NOT_CONNECTED:return"AVAILABLE";case cast.framework.CastState.CONNECTING:return"CONNECTING";case cast.framework.CastState.CONNECTED:return"CONNECTED";default:return Lm(s)}};var xh=N(gt(),1),dE=N(Ji(),1),pE=N(qc(),1);var Dv=N(eu(),1);import{assertNever as wv}from"@vkontakte/videoplayer-shared/es2018";var Se=(s,e=0,t=0)=>{switch(t){case 0:return s.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case 1:{if(e===0)return s;let i=new URL(s);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}case 2:{let i=new URL(s);return!i.searchParams.get("offset_p")&&e===0?s:(i.searchParams.set("offset_p",e.toFixed(0)),i.toString())}default:wv(t)}return s},Mi=(s,e)=>{var t;switch(e){case 0:return NaN;case 1:{let i=new URL(s);return Number(i.searchParams.get("playback_shift"))}case 2:{let i=new URL(s);return Number((t=i.searchParams.get("offset_p"))!=null?t:0)}default:wv(e)}};var B=(s,e,t=!1)=>{let i=s.getTransition();(t||!i||i.to===e)&&s.setState(e)};import{isNonNullable as SB,Subject as tu,merge as Av}from"@vkontakte/videoplayer-shared/es2018";var G=class{constructor(e){this.transitionStarted$=new tu;this.transitionEnded$=new tu;this.transitionUpdated$=new tu;this.forceChanged$=new tu;this.stateChangeStarted$=Av(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=Av(this.transitionEnded$,this.forceChanged$);this.state=e,this.prevState=void 0}setState(e){let t=this.transition,i=this.state;this.transition=void 0,this.prevState=i,this.state=e,t?t.to===e?this.transitionEnded$.next(t):this.forceChanged$.next({from:t.from,to:e,canceledTransition:t}):this.forceChanged$.next({from:i,to:e,canceledTransition:t})}startTransitionTo(e){let t=this.transition,i=this.state;i===e||SB(t)&&t.to===e||(this.prevState=i,this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:i,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}getPrevState(){return this.prevState}};import{assertNever as vB}from"@vkontakte/videoplayer-shared/es2018";var Pv=s=>{switch(s){case"MPEG":case"DASH":case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":case"HLS":case"HLS_ONDEMAND":return!1;case"DASH_LIVE":case"DASH_LIVE_CMAF":case"HLS_LIVE":case"HLS_LIVE_CMAF":case"DASH_LIVE_WEBM":case"WEB_RTC_LIVE":return!0;default:return vB(s)}};import{assertNever as Fr,assertNonNullable as sr,debounce as Rv,ErrorCategory as kv,fromEvent as ar,isNonNullable as Mv,map as Lv,merge as Bv,observableFrom as yB,Subject as TB,Subscription as Rd,timeout as IB,getHighestQuality as xB}from"@vkontakte/videoplayer-shared/es2018";var EB=5,wB=5,AB=500,$v=7e3,xa=class{constructor(e){this.subscription=new Rd;this.loadMediaTimeoutSubscription=new Rd;this.videoState=new G("stopped");this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(a)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.stop());return}if(!t){if((r==null?void 0:r.to)!=="paused"&&a.state==="requested"&&e!=="stopped"){this.seek(a.position/1e3);return}switch(i){case"ready":{switch(e){case"playing":case"paused":case"ready":break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:Fr(e)}break}case"playing":{switch(e){case"playing":break;case"paused":this.videoState.startTransitionTo("playing"),this.params.connection.remotePlayerController.playOrPause();break;case"ready":this.videoState.startTransitionTo("playing"),this.params.connection.remotePlayerController.playOrPause();break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:Fr(e)}break}case"paused":{switch(e){case"playing":this.videoState.startTransitionTo("paused"),this.params.connection.remotePlayerController.playOrPause();break;case"paused":break;case"ready":this.videoState.startTransitionTo("paused"),this.videoState.setState("paused");break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:Fr(e)}break}default:Fr(i)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(Pv(e.format)),this.params.output.isAudioAvailable$.next(!0),this.handleRemoteVolumeChange({volume:this.params.connection.remotePlayer.volumeLevel,muted:this.params.connection.remotePlayer.isMuted});let t=this.params.connection.session.getMediaSession();t&&this.restoreSession(t),this.subscribe()}destroy(){this.log({message:"[destroy]"}),this.subscription.unsubscribe()}subscribe(){this.subscription.add(this.loadMediaTimeoutSubscription);let e=new Rd;this.subscription.add(e),this.subscription.add(Bv(this.videoState.stateChangeStarted$.pipe(Lv(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe(Lv(r=>`stateChangeEnded$ ${JSON.stringify(r)}`))).subscribe(r=>this.log({message:`[videoState] ${r}`})));let t=(r,a)=>this.subscription.add(r.subscribe(a));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{let r=new TB;e.add(r.pipe(Rv(AB)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let a=NaN;e.add(ar(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(n=>{this.logRemoteEvent(n);let o=n.value;this.params.output.position$.next(o),(this.params.desiredState.seekState.getState().state==="applying"||Math.abs(o-a)>EB)&&r.next(o),a=o})),e.add(ar(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(ar(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(ar(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t(ar(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),r=>{this.logRemoteEvent(r);let{remotePlayer:a}=this.params.connection,n=r.value,o=this.params.output.isBuffering$.getValue(),u=n===chrome.cast.media.PlayerState.BUFFERING;switch(o!==u&&this.params.output.isBuffering$.next(u),n){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&a.duration-a.currentTime<wB&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),B(this.params.desiredState.playbackState,"stopped");break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:Fr(n)}}),t(ar(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t(ar(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});let i=Bv(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,yB(["init"])).pipe(Rv(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"),B(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),B(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"),B(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"),B(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"&&B(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){var r,a;let t=this.params.output.volume$.getValue(),i={volume:(r=e.volume)!=null?r:t.volume,muted:(a=e.muted)!=null?a:t.muted};(i.volume!==t.volume||i.muted!==i.muted)&&this.params.output.volume$.next(i)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:i}=this.params.connection;t.currentTime=e,i.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){var l;let t=this.params.source,i,r,a;switch(e){case"MPEG":{let d=t[e];sr(d);let c=xB(Object.keys(d));sr(c);let h=d[c];sr(h),i=h,r="video/mp4",a=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let d=t[e];sr(d),i=d.url,r="application/x-mpegurl",a=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":{let d=t[e];sr(d),i=d.url,r="application/dash+xml",a=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let d=t[e];sr(d),i=d.url,r="application/dash+xml",a=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let d=t[e];sr(d),i=Se(d.url),r="application/x-mpegurl",a=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let d="Unsupported format for Chromecast",c=new Error(d);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:kv.VIDEO_PIPELINE,message:d,thrown:c}),c}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return Fr(e)}let n=new chrome.cast.media.MediaInfo((l=this.params.meta.videoId)!=null?l:i,r);n.contentUrl=i,n.streamType=a,n.metadata=new chrome.cast.media.GenericMediaMetadata;let{title:o,subtitle:u}=this.params.meta;return Mv(o)&&(n.metadata.title=o),Mv(u)&&(n.metadata.subtitle=u),n}createLoadRequest(e){let t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;let i=this.params.desiredState.seekState.getState();return i.state==="applying"||i.state==="requested"?t.currentTime=this.params.output.isLive$.getValue()?0:i.position/1e3:t.currentTime=0,t}loadMedia(e){let t=this.params.connection.session.loadMedia(e),i=new Promise((r,a)=>{this.loadMediaTimeoutSubscription.add(IB($v).subscribe(()=>a(`timeout(${$v})`)))});(0,Dv.default)(Promise.race([t,i]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},r=>{let a=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${r}`;this.log({message:a}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:kv.VIDEO_PIPELINE,message:a,thrown:r})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var Wd=N(gt(),1);import{clearVideoElement as Vv}from"@vkontakte/videoplayer-shared/es2018";import{clearVideoElement as PB}from"@vkontakte/videoplayer-shared/es2018";var Cv=s=>{try{s.pause(),s.playbackRate=0,PB(s),s.remove()}catch(e){console.error(e)}};import{fromEvent as RB,Subscription as kB}from"@vkontakte/videoplayer-shared/es2018";var kd=class{constructor(){this.attribute="data-pool-reused"}get(e){return e.hasAttribute(this.attribute)}set(e,t){e.toggleAttribute(this.attribute,t)}delete(e){e.removeAttribute(this.attribute)}},Md=window.WeakMap?new WeakMap:new kd,Ld=window.WeakMap?new WeakMap:new Map,MB=(s,e=20)=>{let t=0;return RB(s,"ratechange").subscribe(i=>{t++,t>=e&&(s.currentTime=s.currentTime,t=0)})},tt=(s,{audioVideoSyncRate:e,disableYandexPiP:t})=>{let i=s.querySelector("video"),r=!!i;i?Vv(i):(i=document.createElement("video"),s.appendChild(i)),Md.set(i,r);let a=new kB;return a.add(MB(i,e)),Ld.set(i,a),i.setAttribute("crossorigin","anonymous"),i.setAttribute("playsinline","playsinline"),t&&i.setAttribute("x-yandex-pip","false"),i.controls=!1,i.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),i},it=s=>{let e=Ld.get(s);e==null||e.unsubscribe(),Ld.delete(s);let t=Md.get(s);Md.delete(s),t?Vv(s):Cv(s)};var $d=N(nr(),1);import{assertNonNullable as wa,isNonNullable as Qt,isNullable as _B,fromEvent as Nr,merge as jv,observableFrom as Hv,filterChanged as zv,map as Aa,Subject as Qv,Subscription as FB,ValueSubject as NB,ErrorCategory as UB}from"@vkontakte/videoplayer-shared/es2018";import{isNonNullable as Bd,isNullable as VB,Subscription as OB}from"@vkontakte/videoplayer-shared/es2018";var iu=(s,e,t,{equal:i=(n,o)=>n===o,changed$:r,onError:a}={})=>{let n=s.getState(),o=e(),u=VB(r),l=new OB;return r&&l.add(r.subscribe(d=>{let c=s.getState();i(d,c)&&s.setState(d)},a)),i(o,n)||(t(n),u&&s.setState(n)),l.add(s.stateChangeStarted$.subscribe(d=>{t(d.to),u&&s.setState(d.to)},a)),l},zt=(s,e,t)=>iu(e,()=>s.loop,i=>{Bd(i)&&(s.loop=i)},{onError:t}),rt=(s,e,t,i)=>iu(e,()=>({muted:s.muted,volume:s.volume}),r=>{Bd(r)&&(s.muted=r.muted,s.volume=r.volume)},{equal:(r,a)=>r===a||(r==null?void 0:r.muted)===(a==null?void 0:a.muted)&&(r==null?void 0:r.volume)===(a==null?void 0:a.volume),changed$:t,onError:i}),It=(s,e,t,i)=>iu(e,()=>s.playbackRate,r=>{Bd(r)&&(s.playbackRate=r)},{changed$:t,onError:i}),Ea=iu;var qB=s=>["__",s.language,s.label].join("|"),jB=(s,e)=>{if(s.id===e)return!0;let[t,i,r]=e.split("|");return s.language===i&&s.label===r},Dd=class s{constructor(e){this.available$=new Qv;this.current$=new NB(void 0);this.error$=new Qv;this.subscription=new FB;this.externalTracks=new Map;this.internalTracks=new Map;this.baseURL=e}connect(e,t,i){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();let r=a=>{this.error$.next({id:"TextTracksManager",category:UB.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:a})};this.subscription.add(this.available$.subscribe(i.availableTextTracks$)),this.subscription.add(this.current$.subscribe(i.currentTextTrack$)),this.subscription.add(this.error$.subscribe(i.error$)),this.subscription.add(Ea(t.internalTextTracks,()=>(0,$d.default)(this.internalTracks),a=>{Qt(a)&&this.setInternal(a)},{equal:(a,n)=>Qt(a)&&Qt(n)&&a.length===n.length&&a.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(Aa(a=>a.filter(({type:n})=>n==="internal"))),onError:r})),this.subscription.add(Ea(t.externalTextTracks,()=>(0,$d.default)(this.externalTracks),a=>{Qt(a)&&this.setExternal(a)},{equal:(a,n)=>Qt(a)&&Qt(n)&&a.length===n.length&&a.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(Aa(a=>a.filter(({type:n})=>n==="external"))),onError:r})),this.subscription.add(Ea(t.currentTextTrack,()=>{if(this.video)return;let a=this.htmlTextTracksAsArray().find(({mode:n})=>n==="showing");return a&&this.htmlTextTrackToITextTrack(a).id},a=>this.select(a),{changed$:this.current$,onError:r})),this.subscription.add(Ea(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let a of this.htmlTextTracksAsArray())this.applyCueSettings(a.cues),this.applyCueSettings(a.activeCues)}))}subscribe(){wa(this.video);let{textTracks:e}=this.video;this.subscription.add(Nr(e,"addtrack").subscribe(()=>{let i=this.current$.getValue();i&&this.select(i)})),this.subscription.add(jv(Nr(e,"addtrack"),Nr(e,"removetrack"),Hv(["init"])).pipe(Aa(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),zv((i,r)=>i.length===r.length&&i.every(({id:a},n)=>a===r[n].id))).subscribe(this.available$)),this.subscription.add(jv(Nr(e,"change"),Hv(["init"])).pipe(Aa(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),Aa(i=>i&&this.htmlTextTrackToITextTrack(i).id),zv()).subscribe(this.current$));let t=i=>{var r,a;return this.applyCueSettings((a=(r=i.target)==null?void 0:r.activeCues)!=null?a:null)};this.subscription.add(Nr(e,"addtrack").subscribe(i=>{var a,n;(a=i.track)==null||a.addEventListener("cuechange",t);let r=o=>{var l,d,c,h,p;let u=(d=(l=o.target)==null?void 0:l.cues)!=null?d:null;u&&u.length&&(this.applyCueSettings((h=(c=o.target)==null?void 0:c.cues)!=null?h:null),(p=o.target)==null||p.removeEventListener("cuechange",r))};(n=i.track)==null||n.addEventListener("cuechange",r)})),this.subscription.add(Nr(e,"removetrack").subscribe(i=>{var r;(r=i.track)==null||r.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;let t=this.cueSettings.getState();for(let i of Array.from(e)){let r=i;Qt(t.align)&&(r.align=t.align),Qt(t.position)&&(r.position=t.position),Qt(t.size)&&(r.size=t.size),Qt(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){wa(this.video);let t=[...this.video.textTracks];return e?t:t.filter(s.isHealthyTrack)}htmlTextTrackToITextTrack(e){var o,u,l,d,c;let{language:t,label:i}=e,r=e.id?e.id:qB(e),a=this.externalTracks.has(r),n=(l=a?(o=this.externalTracks.get(r))==null?void 0:o.isAuto:(u=this.internalTracks.get(r))==null?void 0:u.isAuto)!=null?l:r.includes("auto");return a?{id:r,type:"external",isAuto:n,language:t,label:i,url:(d=this.externalTracks.get(r))==null?void 0:d.url}:{id:r,type:"internal",isAuto:n,language:t,label:i,url:(c=this.internalTracks.get(r))==null?void 0:c.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(i=>i.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){let t=[...this.externalTracks];e.filter(({id:i,language:r,isAuto:a})=>!this.internalTracks.has(i)&&!t.some(([,n])=>n.language===r&&n.isAuto===a)).forEach(i=>this.attach(i)),Array.from(this.internalTracks).filter(([i])=>!e.find(r=>r.id===i)).forEach(([,i])=>this.detach(i))}select(e){wa(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(_B(e)||!jB(t,e))&&(t.mode="disabled")}destroy(){if(this.subscription.unsubscribe(),this.video)for(let e of Array.from(this.video.getElementsByTagName("track"))){let t=e.getAttribute("id");t&&this.externalTracks.has(t)&&this.video.removeChild(e)}this.externalTracks.clear()}attach(e){wa(this.video);let t=document.createElement("track");this.baseURL?t.setAttribute("src",new URL(e.url,this.baseURL).toString()):t.setAttribute("src",e.url),t.setAttribute("id",e.id),e.label&&t.setAttribute("label",e.label),e.language&&t.setAttribute("srclang",e.language),e.type==="external"?this.externalTracks.set(e.id,e):e.type==="internal"&&this.internalTracks.set(e.id,e),this.video.appendChild(t)}detach(e){wa(this.video);let t=Array.prototype.find.call(this.video.getElementsByTagName("track"),i=>i.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}},xt=Dd;var or=class{constructor(){this.pausedTime=0;this.streamOffset=0;this.pauseTimestamp=0}getTotalPausedTime(){return this.pausedTime+this.getCurrentPausedTime()}getCurrentPausedTime(){return this.pauseTimestamp>0?Date.now()-this.pauseTimestamp:0}getStreamOffset(){return this.streamOffset}getTotalOffset(){return this.getTotalPausedTime()+this.streamOffset}pause(){this.pauseTimestamp===0&&(this.pauseTimestamp=Date.now())}resume(){this.pauseTimestamp>0&&(this.pausedTime+=this.getCurrentPausedTime(),this.pauseTimestamp=0)}resetTo(e,t=!1){this.streamOffset=e,this.pauseTimestamp=0,this.pausedTime=0,t&&this.pause()}};var Gv=s=>{let e=s;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e==null?void 0:e.parentNode;return e!=null?e:void 0},Cd=s=>{let e=Gv(s);return!!(e&&e.fullscreenElement&&e.fullscreenElement===s)},Wv=s=>{let e=Gv(s);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===s)};import{fromEvent as Ye,map as Gt,merge as lu,filterChanged as iy,isNonNullable as ry,Subject as JB,filter as Od,mapTo as _d,combine as ZB,once as e$,throttle as t$,ErrorCategory as i$,ValueSubject as sy,Subscription as r$}from"@vkontakte/videoplayer-shared/es2018";var HB=3,Yv=(s,e,t=HB)=>{let i=0,r=0;for(let a=0;a<s.length;a++){let n=s.start(a),o=s.end(a);if(n<=e&&e<=o){if(i=n,r=o,!t)return{from:i,to:r};for(let u=a-1;u>=0;u--)s.end(u)+t>=i&&(i=s.start(u));for(let u=a+1;u<s.length;u++)s.start(u)-t<=r&&(r=s.end(u))}}return{from:i,to:r}};var ru=class{constructor(){this._isMiuiBrowser=!1}get current(){return this._current}get isChrome(){return this.current==="Chrome"}get isFirefox(){return this.current==="Firefox"}get isSafari(){return this.current==="Safari"}get isOpera(){return this.current==="Opera"}get isEdge(){return this.current==="Edge"}get isYandex(){return this.current==="Yandex"}get isSamsungBrowser(){return this.current==="SamsungBrowser"}get currentVersion(){return this._current_version}get chromeVersion(){return this._chromeVersion}get firefoxVersion(){return this._firefoxVersion}get safariVersion(){return this._safariVersion}get operaVersion(){return this._operaVersion}get edgeVersion(){return this._edgeVersion}get yandexVersion(){return this._yandexVersion}get isMiuiBrowser(){return this._isMiuiBrowser}detect(){let{userAgent:e}=navigator;try{let t=/yabrowser/i.test(e)?"Yandex":void 0,i=/samsungbrowser/i.test(e)?"SamsungBrowser":void 0,r=/chrome|crios/i.test(e)?"Chrome":void 0,a=/chromium/i.test(e)?"Chromium":void 0,n=/firefox|fxios/i.test(e)?"Firefox":void 0,o=/webkit|safari|khtml/i.test(e)?"Safari":void 0,u=/opr\//i.test(e)?"Opera":void 0,l=/edg/i.test(e)?"Edge":void 0;this._isMiuiBrowser=/(XiaoMi)|(MiuiBrowser)/i.test(e),this._current=t||i||n||u||l||r||a||o||"Rest"}catch(t){console.error(t)}this.isChrome&&this.detectChromeVersion(),this.isFirefox&&this.detectFirefoxVersion(),this.isSafari&&this.detectSafariVersion(),this.isOpera&&this.detectOperaVersion(),this.isEdge&&this.detectEdgeVersion(),this.isYandex&&this.detectYandexVersion()}detectVersion(e){try{let{userAgent:t}=window.navigator,i=t.match(e);if(!i)return;let r=i[1],a=parseInt(r,10);if(!isNaN(a))return this._current_version=a,a}catch(t){console.error(t)}}detectChromeVersion(){this._chromeVersion=this.detectVersion(/Chrome\/(\d+\.\d+)/)}detectFirefoxVersion(){this._firefoxVersion=this.detectVersion(/Firefox\/(\d+\.\d+)/)}detectSafariVersion(){this._safariVersion=this.detectVersion(/Version\/(\d+)/)}detectOperaVersion(){this._operaVersion=this.detectVersion(/OPR\/(\d+\.\d+)/)}detectEdgeVersion(){this._edgeVersion=this.detectVersion(/Edg\/(\d+\.\d+)/)}detectYandexVersion(){this._yandexVersion=this.detectVersion(/YaBrowser\/(\d+\.\d+\.\d+)/)}};var Kv=N(gt(),1);var Pa=()=>{var s,e;return/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test((s=navigator.appVersion)!=null?s:navigator.userAgent)||((e=navigator==null?void 0:navigator.userAgentData)==null?void 0:e.mobile)};var su=class{constructor(e){this._highEntropyValues={};this._displayChecker=e}get current(){return this._current}get isIOS(){let e=["iPhone","iPad","iPod"];return this._highEntropyValues.platform==="iOS"||(0,Kv.default)(e,this.current)}get isMac(){return this._highEntropyValues.platform==="macOS"||this.current==="Mac"}get isApple(){return this.isIOS||this.isMac}get isIphoneOrOldIpad(){if(!this.isApple||!this._displayChecker.isTouch)return!1;let e=this.current==="iPad"||this._displayChecker.width>700,t=this._iosVersion;return!e||e&&!!t&&t<16}get isAndroid(){return this._highEntropyValues.platform==="Android"||this.current==="Android"}get isMobile(){return this._highEntropyValues.mobile||this._isMobile}get iOSVersion(){return this._iosVersion}detect(){let{userAgent:e}=navigator;try{this._isMobile=Pa()}catch(t){console.error(t)}this.detectDevice(e),this.detectHighEntropyValues(),this.isIOS&&this.detectIOSVersion()}async detectHighEntropyValues(){let{userAgentData:e}=navigator;if(e!=null&&e.getHighEntropyValues){let t=await e.getHighEntropyValues(["architecture","bitness","brands","mobile","platform","formFactor","model","platformVersion","wow64"]);this._highEntropyValues=t}}detectDevice(e){try{let t=/android/i.test(e)?"Android":void 0,i=/iphone/i.test(e)?"iPhone":void 0,r=/ipad/i.test(e)?"iPad":void 0,a=/ipod/i.test(e)?"iPod":void 0,n=/mac/i.test(e)?"Mac":void 0,o=/webOS|BlackBerry|IEMobile|Opera Mini/i.test(e)?"RestMobile":void 0;this._current=t||i||r||a||o||n||"Desktop"}catch(t){console.error(t)}}detectIOSVersion(){try{if(this._highEntropyValues.platformVersion){let a=this._highEntropyValues.platformVersion.split(".").slice(0,2).join("."),n=parseFloat(a);this._iosVersion=n;return}let{userAgent:e}=window.navigator,t=e.match(/OS (\d+(_\d+)?)/i);if(!t)return;let i=t[1].replace(/_/g,".");if(!i)return;let r=parseFloat(i);if(isNaN(r))return;this._iosVersion=r}catch(e){console.error(e)}}};var au=class{get isTouch(){return typeof this._maxTouchPoints=="number"?this._maxTouchPoints>1:"ontouchstart"in window}get maxTouchPoints(){return this._maxTouchPoints}get height(){return this._height}get width(){return this._width}get screenHeight(){return this._screenHeight}get screenWidth(){return this._screenWidth}get pixelRatio(){return this._pixelRatio}get isHDR(){return this._isHdr}get colorDepth(){return this._colorDepth}detect(){var t;let{maxTouchPoints:e}=navigator;try{this._maxTouchPoints=e!=null?e:0,this._isHdr=!!((t=matchMedia("(dynamic-range: high)"))!=null&&t.matches),this._colorDepth=screen.colorDepth}catch(i){console.error(i)}try{this._pixelRatio=window.devicePixelRatio||1,this._height=screen.height,this._width=screen.width,this._height=screen.height,this._screenHeight=this._height*this._pixelRatio,this._screenWidth=this._width*this._pixelRatio}catch(i){console.error(i)}}};var vt=()=>window.ManagedMediaSource||window.MediaSource,Ur=()=>{var s,e;return!!(window.ManagedMediaSource&&((e=(s=window.ManagedSourceBuffer)==null?void 0:s.prototype)!=null&&e.appendBuffer))},Xv=()=>{var s,e;return!!(window.MediaSource&&((e=(s=window.SourceBuffer)==null?void 0:s.prototype)!=null&&e.appendBuffer))},nu=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var zB=document.createElement("video"),QB='video/mp4; codecs="avc1.42000a,mp4a.40.2"',GB='video/mp4; codecs="hev1.1.6.L93.B0"',Jv='video/webm; codecs="vp09.00.10.08"',Zv='video/webm; codecs="av01.0.00M.08"',WB='audio/mp4; codecs="mp4a.40.2"',YB='audio/webm; codecs="opus"',ey,KB=async()=>{if(!window.navigator.mediaCapabilities)return;let s={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=await Promise.all([window.navigator.mediaCapabilities.decodingInfo({...s,video:{...s.video,contentType:Zv}}),window.navigator.mediaCapabilities.decodingInfo({...s,video:{...s.video,contentType:Jv}})]);ey={DASH_WEBM_AV1:e,DASH_WEBM:t}};KB().catch(s=>{console.log(zB),console.error(s)});var ou=class{constructor(e,t){this._deviceChecker=e,this._browserChecker=t}get protocols(){return this._protocols}get containers(){return this._containers}get codecs(){return this._codecs}get webmDecodingInfo(){return ey}get supportedCodecs(){return Object.keys(this._codecs).filter(e=>this._codecs[e])}get nativeHlsSupported(){return this._nativeHlsSupported}detect(){var e,t,i,r,a,n,o,u,l,d,c,h,p,f,m,g,S,v,y,I;this._video=document.createElement("video");try{this._protocols={mms:Ur(),mse:Xv(),hls:!!((t=(e=this._video).canPlayType)!=null&&t.call(e,"application/x-mpegurl")||(r=(i=this._video).canPlayType)!=null&&r.call(i,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},this._containers={mp4:!!((n=(a=this._video).canPlayType)!=null&&n.call(a,"video/mp4")),webm:!!((u=(o=this._video).canPlayType)!=null&&u.call(o,"video/webm")),cmaf:!0};let T=!!((d=(l=vt())==null?void 0:l.isTypeSupported)!=null&&d.call(l,QB)),E=!!((h=(c=vt())==null?void 0:c.isTypeSupported)!=null&&h.call(c,GB)),O=!!((f=(p=vt())==null?void 0:p.isTypeSupported)!=null&&f.call(p,WB));this._codecs={h264:T,h265:E,vp9:!!((g=(m=vt())==null?void 0:m.isTypeSupported)!=null&&g.call(m,Jv)),av1:!!((v=(S=vt())==null?void 0:S.isTypeSupported)!=null&&v.call(S,Zv)),aac:O,opus:!!((I=(y=vt())==null?void 0:y.isTypeSupported)!=null&&I.call(y,YB)),mpeg:(T||E)&&O},this._nativeHlsSupported=this._protocols.hls&&this._containers.mp4}catch(T){console.error(T)}try{this.destroyVideoElement()}catch(T){console.error("Error destroying video element:",T)}}destroyVideoElement(){var t;if(!this._video)return;if(this._video.pause(),this._video.currentTime=0,this._video.removeAttribute("src"),this._video.src="",this._video.load(),this._video.remove){this._video.remove(),this._video=null;return}this._video.parentNode&&this._video.parentNode.removeChild(this._video);let e=this._video.cloneNode(!1);(t=this._video.parentNode)==null||t.replaceChild(e,this._video),this._video=null}};var ty="audio/mpeg",uu=class{supportMp3(){return this._codecs.mp3&&this._containers.mpeg}detect(){var e,t,i,r;this._audio=document.createElement("audio");try{this._containers={mpeg:!!((t=(e=this._audio).canPlayType)!=null&&t.call(e,ty))},this._codecs={mp3:!!((r=(i=vt())==null?void 0:i.isTypeSupported)!=null&&r.call(i,ty))}}catch(a){console.error(a)}try{this.destroyAudioElement()}catch(a){console.error("Error destroying audio element:",a)}}destroyAudioElement(){var t;if(!this._audio)return;if(this._audio.pause(),this._audio.currentTime=0,this._audio.removeAttribute("src"),this._audio.src="",this._audio.load(),this._audio.remove){this._audio.remove(),this._audio=null;return}this._audio.parentNode&&this._audio.parentNode.removeChild(this._audio);let e=this._audio.cloneNode(!1);(t=this._audio.parentNode)==null||t.replaceChild(e,this._audio),this._audio=null}};import{ValueSubject as XB}from"@vkontakte/videoplayer-shared/es2018";var Vd=class{constructor(){this.isInited$=new XB(!1);this._displayChecker=new au,this._deviceChecker=new su(this._displayChecker),this._browserChecker=new ru,this._videoChecker=new ou(this._deviceChecker,this._browserChecker),this._audioChecker=new uu,this.detect()}get display(){return this._displayChecker}get device(){return this._deviceChecker}get browser(){return this._browserChecker}get video(){return this._videoChecker}get audio(){return this._audioChecker}async detect(){this._displayChecker.detect(),this._deviceChecker.detect(),this._browserChecker.detect(),this._videoChecker.detect(),this._audioChecker.detect(),this.isInited$.next(!0)}},j=new Vd;var st=s=>{let e=P=>Ye(s,P).pipe(_d(void 0)),t=new r$,i=()=>t.unsubscribe(),r=lu(Ye(s,"progress"),Ye(s,"timeupdate")).pipe(Gt(()=>Yv(s.buffered,s.currentTime))),a=j.browser.isSafari?ZB({play:e("play").pipe(e$()),playing:e("playing")}).pipe(_d(void 0)):e("playing"),n=Ye(s,"volumechange").pipe(Gt(()=>({muted:s.muted,volume:s.volume}))),o=Ye(s,"ratechange").pipe(Gt(()=>s.playbackRate)),u=Ye(s,"error").pipe(Od(()=>!!(s.error||s.played.length)),Gt(()=>{var C;let P=s.error;return{id:P?`MediaError#${P.code}`:"HtmlVideoError",category:i$.VIDEO_PIPELINE,message:P?P.message:"Error event from HTML video element",thrown:(C=s.error)!=null?C:void 0}})),l=Ye(s,"timeupdate").pipe(Gt(()=>s.currentTime)),d=["waiting","seeking","seeked","timeupdate"],c=new JB,h=.3,p;t.add(lu(...d.map(P=>Ye(s,P))).subscribe(P=>{let C=s.currentTime;s.loop&&ry(p)&&ry(C)&&p>=s.duration-h&&C<=h&&c.next(p),p=C}));let f=e("pause").pipe(Od(()=>!s.error&&p!==s.duration)),m=Ye(s,"enterpictureinpicture"),g=Ye(s,"leavepictureinpicture"),S=new sy(Wv(s));t.add(m.subscribe(()=>S.next(!0))),t.add(g.subscribe(()=>S.next(!1)));let v=new sy(Cd(s)),y=Ye(s,"fullscreenchange");t.add(y.pipe(Gt(()=>Cd(s))).subscribe(v));let I=.1,T=1e3,E=Ye(s,"timeupdate").pipe(Gt(P=>s.duration-s.currentTime<I),iy()),O=lu(E.pipe(Od(P=>!s.loop&&P)),Ye(s,"ended")).pipe(t$(T),_d(void 0)),w=lu(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(P=>Ye(s,P)),E.pipe(Gt(P=>({type:P?"ended":"unknown"})))).pipe(Gt(P=>j.browser.isFirefox&&P.type==="ended"?s.readyState<2:s.readyState<3),iy());return{playing$:a,pause$:f,canplay$:e("canplay"),ended$:O,looped$:c,error$:u,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:l,durationChange$:Ye(s,"durationchange").pipe(Gt(()=>s.duration)),isBuffering$:w,currentBuffer$:r,volumeState$:n,playbackRateState$:o,inPiP$:S,inFullscreen$:v,enterPip$:m,leavePip$:g,destroy:i}};import{VideoQuality as Li}from"@vkontakte/videoplayer-shared/es2018";var Bi=s=>{switch(s){case"mobile":return Li.Q_144P;case"lowest":return Li.Q_240P;case"low":return Li.Q_360P;case"sd":case"medium":return Li.Q_480P;case"hd":case"high":return Li.Q_720P;case"fullhd":case"full":return Li.Q_1080P;case"quadhd":case"quad":return Li.Q_1440P;case"ultrahd":case"ultra":return Li.Q_2160P}};var Xe=N(Ot(),1),Ud=N(gt(),1),ur=N(Ji(),1);import{isNonNullable as re,isNullable as fu,now as yy,isHigher as mu,isHigherOrEqual as jr,isInvariantQuality as bu,isLowerOrEqual as Hr,videoSizeToQuality as Ty,assertNotEmptyArray as gu,assertNonNullable as Iy}from"@vkontakte/videoplayer-shared/es2018";var Fd=!1,mi={},dy=s=>{Fd=s},py=()=>{mi={}},hy=s=>{s(mi)},Ra=(s,e)=>{var t;Fd&&(mi.meta=(t=mi.meta)!=null?t:{},mi.meta[s]=e)},Ke=class{constructor(e){this.name=e}next(e){var i,r;if(!Fd)return;mi.series=(i=mi.series)!=null?i:{};let t=(r=mi.series[this.name])!=null?r:[];t.push([Date.now(),e]),mi.series[this.name]=t}};import{isHigher as p$,isHigherOrEqual as rq,isLower as fy,isLowerOrEqual as sq,isNonNullable as cu,isNullable as h$,videoHeightToQuality as du}from"@vkontakte/videoplayer-shared/es2018";function Nd(s,e,t){return!s.max&&s.min===e?"high_quality":!s.min&&s.max===t?"traffic_saving":"unknown"}function pu(s,e,t){return!!s&&Nd(s,e,t)==="high_quality"}function qr(s,e,t){return h$(s)||cu(s.min)&&cu(s.max)&&fy(s.max,s.min)||cu(s.min)&&e&&p$(s.min,e)||cu(s.max)&&t&&fy(s.max,t)}function my({limits:s,highestAvailableHeight:e,lowestAvailableHeight:t}){return qr({max:s!=null&&s.max?du(s.max):void 0,min:s!=null&&s.min?du(s.min):void 0},e?du(e):void 0,t?du(t):void 0)}var xy=new Ke("best_bitrate"),Su=(s,e,t)=>(e-t)*Math.pow(2,-10*s)+t;var zr=s=>(e,t)=>s*(Number(e.bitrate)-Number(t.bitrate)),$i=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=yy()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},vu='Assertion "ABR Tracks is empty array" failed',hu=new WeakMap,by=new WeakMap,gy=new WeakMap,ka=(s,e,t,i)=>{var u;let r=[...e].sort(zr(1)),a=[...t].sort(zr(1)),n=a.filter(l=>re(l.bitrate)&&re(s.bitrate)?s.bitrate/l.bitrate>i:!0),o=(u=(0,Xe.default)(a,Math.round(a.length*r.indexOf(s)/(r.length+1))))!=null?u:(0,Xe.default)(a,-1);return o&&(0,Ud.default)(n,o)?o:n.length?(0,Xe.default)(n,-1):(0,Xe.default)(a,0)},Ma=(s,e,t,i)=>{var u;let r=hu.get(e);r||(r=[...e].sort(zr(1)),hu.set(e,r));let a=hu.get(t);a||(a=[...t].sort(zr(1)),hu.set(t,a));let n=gy.get(s);n||(n=a.filter(l=>re(l.bitrate)&&re(s.bitrate)?s.bitrate/l.bitrate>i:!0),gy.set(s,n));let o=(u=(0,Xe.default)(a,Math.round(a.length*r.indexOf(s)/(r.length+1))))!=null?u:(0,Xe.default)(a,-1);return o&&(0,Ud.default)(n,o)?o:n.length?(0,Xe.default)(n,-1):(0,Xe.default)(a,0)},Sy=s=>"quality"in s,yu=(s,e,t,i)=>{var n;let r=re((n=i==null?void 0:i.last)==null?void 0:n.bitrate)&&re(t==null?void 0:t.bitrate)&&i.last.bitrate<t.bitrate?s.trackCooldownIncreaseQuality:s.trackCooldownDecreaseQuality,a=t&&i&&i.history[t.id]&&yy()-i.history[t.id]<=r&&(!i.last||t.id!==i.last.id);if(t!=null&&t.id&&i&&!a&&i.recordSelection(t),a&&(i!=null&&i.last)){let o=i.last;i==null||i.recordSwitch(o);let u=Sy(o)?"video":"audio",l=Sy(o)?o.quality:o.bitrate;return e({message:`
6
+ var LE=Object.create;var Lh=Object.defineProperty;var BE=Object.getOwnPropertyDescriptor;var $E=Object.getOwnPropertyNames;var DE=Object.getPrototypeOf,CE=Object.prototype.hasOwnProperty;var b=(s,e)=>()=>(e||s((e={exports:{}}).exports,e),e.exports);var VE=(s,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of $E(e))!CE.call(s,r)&&r!==t&&Lh(s,r,{get:()=>e[r],enumerable:!(i=BE(e,r))||i.enumerable});return s};var N=(s,e,t)=>(t=s!=null?LE(DE(s)):{},VE(e||!s||!s.__esModule?Lh(t,"default",{value:s,enumerable:!0}):t,s));var ve=b((Ol,$h)=>{"use strict";var ea=function(s){return s&&s.Math===Math&&s};$h.exports=ea(typeof globalThis=="object"&&globalThis)||ea(typeof window=="object"&&window)||ea(typeof self=="object"&&self)||ea(typeof global=="object"&&global)||ea(typeof Ol=="object"&&Ol)||function(){return this}()||Function("return this")()});var Oe=b((JO,Dh)=>{"use strict";Dh.exports=function(s){try{return!!s()}catch(e){return!0}}});var ta=b((ZO,Ch)=>{"use strict";var OE=Oe();Ch.exports=!OE(function(){var s=function(){}.bind();return typeof s!="function"||s.hasOwnProperty("prototype")})});var _l=b((e_,Fh)=>{"use strict";var _E=ta(),_h=Function.prototype,Vh=_h.apply,Oh=_h.call;Fh.exports=typeof Reflect=="object"&&Reflect.apply||(_E?Oh.bind(Vh):function(){return Oh.apply(Vh,arguments)})});var Le=b((t_,qh)=>{"use strict";var Nh=ta(),Uh=Function.prototype,Fl=Uh.call,FE=Nh&&Uh.bind.bind(Fl,Fl);qh.exports=Nh?FE:function(s){return function(){return Fl.apply(s,arguments)}}});var Wi=b((i_,Hh)=>{"use strict";var jh=Le(),NE=jh({}.toString),UE=jh("".slice);Hh.exports=function(s){return UE(NE(s),8,-1)}});var Nl=b((r_,zh)=>{"use strict";var qE=Wi(),jE=Le();zh.exports=function(s){if(qE(s)==="Function")return jE(s)}});var ge=b((s_,Qh)=>{"use strict";var Ul=typeof document=="object"&&document.all;Qh.exports=typeof Ul=="undefined"&&Ul!==void 0?function(s){return typeof s=="function"||s===Ul}:function(s){return typeof s=="function"}});var ft=b((a_,Gh)=>{"use strict";var HE=Oe();Gh.exports=!HE(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var mt=b((n_,Wh)=>{"use strict";var zE=ta(),To=Function.prototype.call;Wh.exports=zE?To.bind(To):function(){return To.apply(To,arguments)}});var ql=b(Xh=>{"use strict";var Yh={}.propertyIsEnumerable,Kh=Object.getOwnPropertyDescriptor,QE=Kh&&!Yh.call({1:2},1);Xh.f=QE?function(e){var t=Kh(this,e);return!!t&&t.enumerable}:Yh});var ia=b((u_,Jh)=>{"use strict";Jh.exports=function(s,e){return{enumerable:!(s&1),configurable:!(s&2),writable:!(s&4),value:e}}});var ef=b((l_,Zh)=>{"use strict";var GE=Le(),WE=Oe(),YE=Wi(),jl=Object,KE=GE("".split);Zh.exports=WE(function(){return!jl("z").propertyIsEnumerable(0)})?function(s){return YE(s)==="String"?KE(s,""):jl(s)}:jl});var Tr=b((c_,tf)=>{"use strict";tf.exports=function(s){return s==null}});var Pi=b((d_,rf)=>{"use strict";var XE=Tr(),JE=TypeError;rf.exports=function(s){if(XE(s))throw new JE("Can't call method on "+s);return s}});var Yi=b((p_,sf)=>{"use strict";var ZE=ef(),ew=Pi();sf.exports=function(s){return ZE(ew(s))}});var bt=b((h_,af)=>{"use strict";var tw=ge();af.exports=function(s){return typeof s=="object"?s!==null:tw(s)}});var Ir=b((f_,nf)=>{"use strict";nf.exports={}});var pi=b((m_,uf)=>{"use strict";var Hl=Ir(),zl=ve(),iw=ge(),of=function(s){return iw(s)?s:void 0};uf.exports=function(s,e){return arguments.length<2?of(Hl[s])||of(zl[s]):Hl[s]&&Hl[s][e]||zl[s]&&zl[s][e]}});var ra=b((b_,lf)=>{"use strict";var rw=Le();lf.exports=rw({}.isPrototypeOf)});var Ki=b((g_,pf)=>{"use strict";var sw=ve(),cf=sw.navigator,df=cf&&cf.userAgent;pf.exports=df?String(df):""});var Gl=b((S_,Sf)=>{"use strict";var gf=ve(),Ql=Ki(),hf=gf.process,ff=gf.Deno,mf=hf&&hf.versions||ff&&ff.version,bf=mf&&mf.v8,$t,Io;bf&&($t=bf.split("."),Io=$t[0]>0&&$t[0]<4?1:+($t[0]+$t[1]));!Io&&Ql&&($t=Ql.match(/Edge\/(\d+)/),(!$t||$t[1]>=74)&&($t=Ql.match(/Chrome\/(\d+)/),$t&&(Io=+$t[1])));Sf.exports=Io});var Wl=b((v_,yf)=>{"use strict";var vf=Gl(),aw=Oe(),nw=ve(),ow=nw.String;yf.exports=!!Object.getOwnPropertySymbols&&!aw(function(){var s=Symbol("symbol detection");return!ow(s)||!(Object(s)instanceof Symbol)||!Symbol.sham&&vf&&vf<41})});var Yl=b((y_,Tf)=>{"use strict";var uw=Wl();Tf.exports=uw&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var Kl=b((T_,If)=>{"use strict";var lw=pi(),cw=ge(),dw=ra(),pw=Yl(),hw=Object;If.exports=pw?function(s){return typeof s=="symbol"}:function(s){var e=lw("Symbol");return cw(e)&&dw(e.prototype,hw(s))}});var sa=b((I_,xf)=>{"use strict";var fw=String;xf.exports=function(s){try{return fw(s)}catch(e){return"Object"}}});var jt=b((x_,Ef)=>{"use strict";var mw=ge(),bw=sa(),gw=TypeError;Ef.exports=function(s){if(mw(s))return s;throw new gw(bw(s)+" is not a function")}});var aa=b((E_,wf)=>{"use strict";var Sw=jt(),vw=Tr();wf.exports=function(s,e){var t=s[e];return vw(t)?void 0:Sw(t)}});var Pf=b((w_,Af)=>{"use strict";var Xl=mt(),Jl=ge(),Zl=bt(),yw=TypeError;Af.exports=function(s,e){var t,i;if(e==="string"&&Jl(t=s.toString)&&!Zl(i=Xl(t,s))||Jl(t=s.valueOf)&&!Zl(i=Xl(t,s))||e!=="string"&&Jl(t=s.toString)&&!Zl(i=Xl(t,s)))return i;throw new yw("Can't convert object to primitive value")}});var Dt=b((A_,kf)=>{"use strict";kf.exports=!0});var Lf=b((P_,Mf)=>{"use strict";var Rf=ve(),Tw=Object.defineProperty;Mf.exports=function(s,e){try{Tw(Rf,s,{value:e,configurable:!0,writable:!0})}catch(t){Rf[s]=e}return e}});var na=b((k_,Df)=>{"use strict";var Iw=Dt(),xw=ve(),Ew=Lf(),Bf="__core-js_shared__",$f=Df.exports=xw[Bf]||Ew(Bf,{});($f.versions||($f.versions=[])).push({version:"3.38.0",mode:Iw?"pure":"global",copyright:"\xA9 2014-2024 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.38.0/LICENSE",source:"https://github.com/zloirock/core-js"})});var ec=b((R_,Vf)=>{"use strict";var Cf=na();Vf.exports=function(s,e){return Cf[s]||(Cf[s]=e||{})}});var xr=b((M_,Of)=>{"use strict";var ww=Pi(),Aw=Object;Of.exports=function(s){return Aw(ww(s))}});var Ct=b((L_,_f)=>{"use strict";var Pw=Le(),kw=xr(),Rw=Pw({}.hasOwnProperty);_f.exports=Object.hasOwn||function(e,t){return Rw(kw(e),t)}});var tc=b((B_,Ff)=>{"use strict";var Mw=Le(),Lw=0,Bw=Math.random(),$w=Mw(1 .toString);Ff.exports=function(s){return"Symbol("+(s===void 0?"":s)+")_"+$w(++Lw+Bw,36)}});var _e=b(($_,Uf)=>{"use strict";var Dw=ve(),Cw=ec(),Nf=Ct(),Vw=tc(),Ow=Wl(),_w=Yl(),Er=Dw.Symbol,ic=Cw("wks"),Fw=_w?Er.for||Er:Er&&Er.withoutSetter||Vw;Uf.exports=function(s){return Nf(ic,s)||(ic[s]=Ow&&Nf(Er,s)?Er[s]:Fw("Symbol."+s)),ic[s]}});var zf=b((D_,Hf)=>{"use strict";var Nw=mt(),qf=bt(),jf=Kl(),Uw=aa(),qw=Pf(),jw=_e(),Hw=TypeError,zw=jw("toPrimitive");Hf.exports=function(s,e){if(!qf(s)||jf(s))return s;var t=Uw(s,zw),i;if(t){if(e===void 0&&(e="default"),i=Nw(t,s,e),!qf(i)||jf(i))return i;throw new Hw("Can't convert object to primitive value")}return e===void 0&&(e="number"),qw(s,e)}});var rc=b((C_,Qf)=>{"use strict";var Qw=zf(),Gw=Kl();Qf.exports=function(s){var e=Qw(s,"string");return Gw(e)?e:e+""}});var xo=b((V_,Wf)=>{"use strict";var Ww=ve(),Gf=bt(),sc=Ww.document,Yw=Gf(sc)&&Gf(sc.createElement);Wf.exports=function(s){return Yw?sc.createElement(s):{}}});var ac=b((O_,Yf)=>{"use strict";var Kw=ft(),Xw=Oe(),Jw=xo();Yf.exports=!Kw&&!Xw(function(){return Object.defineProperty(Jw("div"),"a",{get:function(){return 7}}).a!==7})});var Jf=b(Xf=>{"use strict";var Zw=ft(),eA=mt(),tA=ql(),iA=ia(),rA=Yi(),sA=rc(),aA=Ct(),nA=ac(),Kf=Object.getOwnPropertyDescriptor;Xf.f=Zw?Kf:function(e,t){if(e=rA(e),t=sA(t),nA)try{return Kf(e,t)}catch(i){}if(aA(e,t))return iA(!eA(tA.f,e,t),e[t])}});var nc=b((F_,Zf)=>{"use strict";var oA=Oe(),uA=ge(),lA=/#|\.prototype\./,oa=function(s,e){var t=dA[cA(s)];return t===hA?!0:t===pA?!1:uA(e)?oA(e):!!e},cA=oa.normalize=function(s){return String(s).replace(lA,".").toLowerCase()},dA=oa.data={},pA=oa.NATIVE="N",hA=oa.POLYFILL="P";Zf.exports=oa});var wr=b((N_,tm)=>{"use strict";var em=Nl(),fA=jt(),mA=ta(),bA=em(em.bind);tm.exports=function(s,e){return fA(s),e===void 0?s:mA?bA(s,e):function(){return s.apply(e,arguments)}}});var oc=b((U_,im)=>{"use strict";var gA=ft(),SA=Oe();im.exports=gA&&SA(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var Ht=b((q_,rm)=>{"use strict";var vA=bt(),yA=String,TA=TypeError;rm.exports=function(s){if(vA(s))return s;throw new TA(yA(s)+" is not an object")}});var Xi=b(am=>{"use strict";var IA=ft(),xA=ac(),EA=oc(),Eo=Ht(),sm=rc(),wA=TypeError,uc=Object.defineProperty,AA=Object.getOwnPropertyDescriptor,lc="enumerable",cc="configurable",dc="writable";am.f=IA?EA?function(e,t,i){if(Eo(e),t=sm(t),Eo(i),typeof e=="function"&&t==="prototype"&&"value"in i&&dc in i&&!i[dc]){var r=AA(e,t);r&&r[dc]&&(e[t]=i.value,i={configurable:cc in i?i[cc]:r[cc],enumerable:lc in i?i[lc]:r[lc],writable:!1})}return uc(e,t,i)}:uc:function(e,t,i){if(Eo(e),t=sm(t),Eo(i),xA)try{return uc(e,t,i)}catch(r){}if("get"in i||"set"in i)throw new wA("Accessors not supported");return"value"in i&&(e[t]=i.value),e}});var Ar=b((H_,nm)=>{"use strict";var PA=ft(),kA=Xi(),RA=ia();nm.exports=PA?function(s,e,t){return kA.f(s,e,RA(1,t))}:function(s,e,t){return s[e]=t,s}});var Ee=b((z_,um)=>{"use strict";var ua=ve(),MA=_l(),LA=Nl(),BA=ge(),$A=Jf().f,DA=nc(),Pr=Ir(),CA=wr(),kr=Ar(),om=Ct();na();var VA=function(s){var e=function(t,i,r){if(this instanceof e){switch(arguments.length){case 0:return new s;case 1:return new s(t);case 2:return new s(t,i)}return new s(t,i,r)}return MA(s,this,arguments)};return e.prototype=s.prototype,e};um.exports=function(s,e){var t=s.target,i=s.global,r=s.stat,a=s.proto,n=i?ua:r?ua[t]:ua[t]&&ua[t].prototype,o=i?Pr:Pr[t]||kr(Pr,t,{})[t],u=o.prototype,l,d,c,h,p,f,m,g,S;for(h in e)l=DA(i?h:t+(r?".":"#")+h,s.forced),d=!l&&n&&om(n,h),f=o[h],d&&(s.dontCallGetSet?(S=$A(n,h),m=S&&S.value):m=n[h]),p=d&&m?m:e[h],!(!l&&!a&&typeof f==typeof p)&&(s.bind&&d?g=CA(p,ua):s.wrap&&d?g=VA(p):a&&BA(p)?g=LA(p):g=p,(s.sham||p&&p.sham||f&&f.sham)&&kr(g,"sham",!0),kr(o,h,g),a&&(c=t+"Prototype",om(Pr,c)||kr(Pr,c,{}),kr(Pr[c],h,p),s.real&&u&&(l||!u[h])&&kr(u,h,p)))}});var cm=b((Q_,lm)=>{"use strict";var OA=Math.ceil,_A=Math.floor;lm.exports=Math.trunc||function(e){var t=+e;return(t>0?_A:OA)(t)}});var la=b((G_,dm)=>{"use strict";var FA=cm();dm.exports=function(s){var e=+s;return e!==e||e===0?0:FA(e)}});var hm=b((W_,pm)=>{"use strict";var NA=la(),UA=Math.max,qA=Math.min;pm.exports=function(s,e){var t=NA(s);return t<0?UA(t+e,0):qA(t,e)}});var pc=b((Y_,fm)=>{"use strict";var jA=la(),HA=Math.min;fm.exports=function(s){var e=jA(s);return e>0?HA(e,9007199254740991):0}});var Rr=b((K_,mm)=>{"use strict";var zA=pc();mm.exports=function(s){return zA(s.length)}});var hc=b((X_,gm)=>{"use strict";var QA=Yi(),GA=hm(),WA=Rr(),bm=function(s){return function(e,t,i){var r=QA(e),a=WA(r);if(a===0)return!s&&-1;var n=GA(i,a),o;if(s&&t!==t){for(;a>n;)if(o=r[n++],o!==o)return!0}else for(;a>n;n++)if((s||n in r)&&r[n]===t)return s||n||0;return!s&&-1}};gm.exports={includes:bm(!0),indexOf:bm(!1)}});var ca=b((J_,Sm)=>{"use strict";Sm.exports=function(){}});var vm=b(()=>{"use strict";var YA=Ee(),KA=hc().includes,XA=Oe(),JA=ca(),ZA=XA(function(){return!Array(1).includes()});YA({target:"Array",proto:!0,forced:ZA},{includes:function(e){return KA(this,e,arguments.length>1?arguments[1]:void 0)}});JA("includes")});var ki=b((tF,ym)=>{"use strict";var eP=pi();ym.exports=eP});var Im=b((iF,Tm)=>{"use strict";vm();var tP=ki();Tm.exports=tP("Array","includes")});var Em=b((rF,xm)=>{"use strict";var iP=Im();xm.exports=iP});var gt=b((sF,wm)=>{"use strict";var rP=Em();wm.exports=rP});var Po=b((bF,$m)=>{"use strict";var dP=ec(),pP=tc(),Bm=dP("keys");$m.exports=function(s){return Bm[s]||(Bm[s]=pP(s))}});var Cm=b((gF,Dm)=>{"use strict";var hP=Oe();Dm.exports=!hP(function(){function s(){}return s.prototype.constructor=null,Object.getPrototypeOf(new s)!==s.prototype})});var ko=b((SF,Om)=>{"use strict";var fP=Ct(),mP=ge(),bP=xr(),gP=Po(),SP=Cm(),Vm=gP("IE_PROTO"),bc=Object,vP=bc.prototype;Om.exports=SP?bc.getPrototypeOf:function(s){var e=bP(s);if(fP(e,Vm))return e[Vm];var t=e.constructor;return mP(t)&&e instanceof t?t.prototype:e instanceof bc?vP:null}});var Ro=b((vF,_m)=>{"use strict";_m.exports={}});var Um=b((yF,Nm)=>{"use strict";var yP=Le(),gc=Ct(),TP=Yi(),IP=hc().indexOf,xP=Ro(),Fm=yP([].push);Nm.exports=function(s,e){var t=TP(s),i=0,r=[],a;for(a in t)!gc(xP,a)&&gc(t,a)&&Fm(r,a);for(;e.length>i;)gc(t,a=e[i++])&&(~IP(r,a)||Fm(r,a));return r}});var Sc=b((TF,qm)=>{"use strict";qm.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var vc=b((IF,jm)=>{"use strict";var EP=Um(),wP=Sc();jm.exports=Object.keys||function(e){return EP(e,wP)}});var yc=b((xF,Wm)=>{"use strict";var zm=ft(),AP=Oe(),Qm=Le(),PP=ko(),kP=vc(),RP=Yi(),MP=ql().f,Gm=Qm(MP),LP=Qm([].push),BP=zm&&AP(function(){var s=Object.create(null);return s[2]=2,!Gm(s,2)}),Hm=function(s){return function(e){for(var t=RP(e),i=kP(t),r=BP&&PP(t)===null,a=i.length,n=0,o=[],u;a>n;)u=i[n++],(!zm||(r?u in t:Gm(t,u)))&&LP(o,s?[u,t[u]]:t[u]);return o}};Wm.exports={entries:Hm(!0),values:Hm(!1)}});var Ym=b(()=>{"use strict";var $P=Ee(),DP=yc().entries;$P({target:"Object",stat:!0},{entries:function(e){return DP(e)}})});var Xm=b((AF,Km)=>{"use strict";Ym();var CP=Ir();Km.exports=CP.Object.entries});var Zm=b((PF,Jm)=>{"use strict";var VP=Xm();Jm.exports=VP});var Ji=b((kF,eb)=>{"use strict";var OP=Zm();eb.exports=OP});var Zi=b((RF,tb)=>{"use strict";tb.exports={}});var sb=b((MF,rb)=>{"use strict";var _P=ve(),FP=ge(),ib=_P.WeakMap;rb.exports=FP(ib)&&/native code/.test(String(ib))});var Ec=b((LF,ob)=>{"use strict";var NP=sb(),nb=ve(),UP=bt(),qP=Ar(),Tc=Ct(),Ic=na(),jP=Po(),HP=Ro(),ab="Object already initialized",xc=nb.TypeError,zP=nb.WeakMap,Mo,da,Lo,QP=function(s){return Lo(s)?da(s):Mo(s,{})},GP=function(s){return function(e){var t;if(!UP(e)||(t=da(e)).type!==s)throw new xc("Incompatible receiver, "+s+" required");return t}};NP||Ic.state?(Vt=Ic.state||(Ic.state=new zP),Vt.get=Vt.get,Vt.has=Vt.has,Vt.set=Vt.set,Mo=function(s,e){if(Vt.has(s))throw new xc(ab);return e.facade=s,Vt.set(s,e),e},da=function(s){return Vt.get(s)||{}},Lo=function(s){return Vt.has(s)}):(er=jP("state"),HP[er]=!0,Mo=function(s,e){if(Tc(s,er))throw new xc(ab);return e.facade=s,qP(s,er,e),e},da=function(s){return Tc(s,er)?s[er]:{}},Lo=function(s){return Tc(s,er)});var Vt,er;ob.exports={set:Mo,get:da,has:Lo,enforce:QP,getterFor:GP}});var Pc=b((BF,lb)=>{"use strict";var wc=ft(),WP=Ct(),ub=Function.prototype,YP=wc&&Object.getOwnPropertyDescriptor,Ac=WP(ub,"name"),KP=Ac&&function(){}.name==="something",XP=Ac&&(!wc||wc&&YP(ub,"name").configurable);lb.exports={EXISTS:Ac,PROPER:KP,CONFIGURABLE:XP}});var db=b(cb=>{"use strict";var JP=ft(),ZP=oc(),ek=Xi(),tk=Ht(),ik=Yi(),rk=vc();cb.f=JP&&!ZP?Object.defineProperties:function(e,t){tk(e);for(var i=ik(t),r=rk(t),a=r.length,n=0,o;a>n;)ek.f(e,o=r[n++],i[o]);return e}});var kc=b((DF,pb)=>{"use strict";var sk=pi();pb.exports=sk("document","documentElement")});var Bc=b((CF,vb)=>{"use strict";var ak=Ht(),nk=db(),hb=Sc(),ok=Ro(),uk=kc(),lk=xo(),ck=Po(),fb=">",mb="<",Mc="prototype",Lc="script",gb=ck("IE_PROTO"),Rc=function(){},Sb=function(s){return mb+Lc+fb+s+mb+"/"+Lc+fb},bb=function(s){s.write(Sb("")),s.close();var e=s.parentWindow.Object;return s=null,e},dk=function(){var s=lk("iframe"),e="java"+Lc+":",t;return s.style.display="none",uk.appendChild(s),s.src=String(e),t=s.contentWindow.document,t.open(),t.write(Sb("document.F=Object")),t.close(),t.F},Bo,$o=function(){try{Bo=new ActiveXObject("htmlfile")}catch(e){}$o=typeof document!="undefined"?document.domain&&Bo?bb(Bo):dk():bb(Bo);for(var s=hb.length;s--;)delete $o[Mc][hb[s]];return $o()};ok[gb]=!0;vb.exports=Object.create||function(e,t){var i;return e!==null?(Rc[Mc]=ak(e),i=new Rc,Rc[Mc]=null,i[gb]=e):i=$o(),t===void 0?i:nk.f(i,t)}});var Mr=b((VF,yb)=>{"use strict";var pk=Ar();yb.exports=function(s,e,t,i){return i&&i.enumerable?s[e]=t:pk(s,e,t),s}});var Vc=b((OF,xb)=>{"use strict";var hk=Oe(),fk=ge(),mk=bt(),bk=Bc(),Tb=ko(),gk=Mr(),Sk=_e(),vk=Dt(),Cc=Sk("iterator"),Ib=!1,hi,$c,Dc;[].keys&&(Dc=[].keys(),"next"in Dc?($c=Tb(Tb(Dc)),$c!==Object.prototype&&(hi=$c)):Ib=!0);var yk=!mk(hi)||hk(function(){var s={};return hi[Cc].call(s)!==s});yk?hi={}:vk&&(hi=bk(hi));fk(hi[Cc])||gk(hi,Cc,function(){return this});xb.exports={IteratorPrototype:hi,BUGGY_SAFARI_ITERATORS:Ib}});var Do=b((_F,wb)=>{"use strict";var Tk=_e(),Ik=Tk("toStringTag"),Eb={};Eb[Ik]="z";wb.exports=String(Eb)==="[object z]"});var pa=b((FF,Ab)=>{"use strict";var xk=Do(),Ek=ge(),Co=Wi(),wk=_e(),Ak=wk("toStringTag"),Pk=Object,kk=Co(function(){return arguments}())==="Arguments",Rk=function(s,e){try{return s[e]}catch(t){}};Ab.exports=xk?Co:function(s){var e,t,i;return s===void 0?"Undefined":s===null?"Null":typeof(t=Rk(e=Pk(s),Ak))=="string"?t:kk?Co(e):(i=Co(e))==="Object"&&Ek(e.callee)?"Arguments":i}});var kb=b((NF,Pb)=>{"use strict";var Mk=Do(),Lk=pa();Pb.exports=Mk?{}.toString:function(){return"[object "+Lk(this)+"]"}});var ha=b((UF,Mb)=>{"use strict";var Bk=Do(),$k=Xi().f,Dk=Ar(),Ck=Ct(),Vk=kb(),Ok=_e(),Rb=Ok("toStringTag");Mb.exports=function(s,e,t,i){var r=t?s:s&&s.prototype;r&&(Ck(r,Rb)||$k(r,Rb,{configurable:!0,value:e}),i&&!Bk&&Dk(r,"toString",Vk))}});var Bb=b((qF,Lb)=>{"use strict";var _k=Vc().IteratorPrototype,Fk=Bc(),Nk=ia(),Uk=ha(),qk=Zi(),jk=function(){return this};Lb.exports=function(s,e,t,i){var r=e+" Iterator";return s.prototype=Fk(_k,{next:Nk(+!i,t)}),Uk(s,r,!1,!0),qk[r]=jk,s}});var Db=b((jF,$b)=>{"use strict";var Hk=Le(),zk=jt();$b.exports=function(s,e,t){try{return Hk(zk(Object.getOwnPropertyDescriptor(s,e)[t]))}catch(i){}}});var Vb=b((HF,Cb)=>{"use strict";var Qk=bt();Cb.exports=function(s){return Qk(s)||s===null}});var _b=b((zF,Ob)=>{"use strict";var Gk=Vb(),Wk=String,Yk=TypeError;Ob.exports=function(s){if(Gk(s))return s;throw new Yk("Can't set "+Wk(s)+" as a prototype")}});var Oc=b((QF,Fb)=>{"use strict";var Kk=Db(),Xk=bt(),Jk=Pi(),Zk=_b();Fb.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var s=!1,e={},t;try{t=Kk(Object.prototype,"__proto__","set"),t(e,[]),s=e instanceof Array}catch(i){}return function(r,a){return Jk(r),Zk(a),Xk(r)&&(s?t(r,a):r.__proto__=a),r}}():void 0)});var Kb=b((GF,Yb)=>{"use strict";var eR=Ee(),tR=mt(),Vo=Dt(),Gb=Pc(),iR=ge(),rR=Bb(),Nb=ko(),Ub=Oc(),sR=ha(),aR=Ar(),_c=Mr(),nR=_e(),qb=Zi(),Wb=Vc(),oR=Gb.PROPER,uR=Gb.CONFIGURABLE,jb=Wb.IteratorPrototype,Oo=Wb.BUGGY_SAFARI_ITERATORS,fa=nR("iterator"),Hb="keys",ma="values",zb="entries",Qb=function(){return this};Yb.exports=function(s,e,t,i,r,a,n){rR(t,e,i);var o=function(S){if(S===r&&h)return h;if(!Oo&&S&&S in d)return d[S];switch(S){case Hb:return function(){return new t(this,S)};case ma:return function(){return new t(this,S)};case zb:return function(){return new t(this,S)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,d=s.prototype,c=d[fa]||d["@@iterator"]||r&&d[r],h=!Oo&&c||o(r),p=e==="Array"&&d.entries||c,f,m,g;if(p&&(f=Nb(p.call(new s)),f!==Object.prototype&&f.next&&(!Vo&&Nb(f)!==jb&&(Ub?Ub(f,jb):iR(f[fa])||_c(f,fa,Qb)),sR(f,u,!0,!0),Vo&&(qb[u]=Qb))),oR&&r===ma&&c&&c.name!==ma&&(!Vo&&uR?aR(d,"name",ma):(l=!0,h=function(){return tR(c,this)})),r)if(m={values:o(ma),keys:a?h:o(Hb),entries:o(zb)},n)for(g in m)(Oo||l||!(g in d))&&_c(d,g,m[g]);else eR({target:e,proto:!0,forced:Oo||l},m);return(!Vo||n)&&d[fa]!==h&&_c(d,fa,h,{name:r}),qb[e]=h,m}});var Jb=b((WF,Xb)=>{"use strict";Xb.exports=function(s,e){return{value:s,done:e}}});var Nc=b((YF,rg)=>{"use strict";var lR=Yi(),Fc=ca(),Zb=Zi(),tg=Ec(),cR=Xi().f,dR=Kb(),_o=Jb(),pR=Dt(),hR=ft(),ig="Array Iterator",fR=tg.set,mR=tg.getterFor(ig);rg.exports=dR(Array,"Array",function(s,e){fR(this,{type:ig,target:lR(s),index:0,kind:e})},function(){var s=mR(this),e=s.target,t=s.index++;if(!e||t>=e.length)return s.target=void 0,_o(void 0,!0);switch(s.kind){case"keys":return _o(t,!1);case"values":return _o(e[t],!1)}return _o([t,e[t]],!1)},"values");var eg=Zb.Arguments=Zb.Array;Fc("keys");Fc("values");Fc("entries");if(!pR&&hR&&eg.name!=="values")try{cR(eg,"name",{value:"values"})}catch(s){}});var ag=b((KF,sg)=>{"use strict";var bR=_e(),gR=Zi(),SR=bR("iterator"),vR=Array.prototype;sg.exports=function(s){return s!==void 0&&(gR.Array===s||vR[SR]===s)}});var Uc=b((XF,og)=>{"use strict";var yR=pa(),ng=aa(),TR=Tr(),IR=Zi(),xR=_e(),ER=xR("iterator");og.exports=function(s){if(!TR(s))return ng(s,ER)||ng(s,"@@iterator")||IR[yR(s)]}});var lg=b((JF,ug)=>{"use strict";var wR=mt(),AR=jt(),PR=Ht(),kR=sa(),RR=Uc(),MR=TypeError;ug.exports=function(s,e){var t=arguments.length<2?RR(s):e;if(AR(t))return PR(wR(t,s));throw new MR(kR(s)+" is not iterable")}});var pg=b((ZF,dg)=>{"use strict";var LR=mt(),cg=Ht(),BR=aa();dg.exports=function(s,e,t){var i,r;cg(s);try{if(i=BR(s,"return"),!i){if(e==="throw")throw t;return t}i=LR(i,s)}catch(a){r=!0,i=a}if(e==="throw")throw t;if(r)throw i;return cg(i),t}});var No=b((eN,bg)=>{"use strict";var $R=wr(),DR=mt(),CR=Ht(),VR=sa(),OR=ag(),_R=Rr(),hg=ra(),FR=lg(),NR=Uc(),fg=pg(),UR=TypeError,Fo=function(s,e){this.stopped=s,this.result=e},mg=Fo.prototype;bg.exports=function(s,e,t){var i=t&&t.that,r=!!(t&&t.AS_ENTRIES),a=!!(t&&t.IS_RECORD),n=!!(t&&t.IS_ITERATOR),o=!!(t&&t.INTERRUPTED),u=$R(e,i),l,d,c,h,p,f,m,g=function(v){return l&&fg(l,"normal",v),new Fo(!0,v)},S=function(v){return r?(CR(v),o?u(v[0],v[1],g):u(v[0],v[1])):o?u(v,g):u(v)};if(a)l=s.iterator;else if(n)l=s;else{if(d=NR(s),!d)throw new UR(VR(s)+" is not iterable");if(OR(d)){for(c=0,h=_R(s);h>c;c++)if(p=S(s[c]),p&&hg(mg,p))return p;return new Fo(!1)}l=FR(s,d)}for(f=a?s.next:l.next;!(m=DR(f,l)).done;){try{p=S(m.value)}catch(v){fg(l,"throw",v)}if(typeof p=="object"&&p&&hg(mg,p))return p}return new Fo(!1)}});var Sg=b((tN,gg)=>{"use strict";var qR=ft(),jR=Xi(),HR=ia();gg.exports=function(s,e,t){qR?jR.f(s,e,HR(0,t)):s[e]=t}});var vg=b(()=>{"use strict";var zR=Ee(),QR=No(),GR=Sg();zR({target:"Object",stat:!0},{fromEntries:function(e){var t={};return QR(e,function(i,r){GR(t,i,r)},{AS_ENTRIES:!0}),t}})});var Tg=b((sN,yg)=>{"use strict";Nc();vg();var WR=Ir();yg.exports=WR.Object.fromEntries});var xg=b((aN,Ig)=>{"use strict";Ig.exports={CSSRuleList:0,CSSStyleDeclaration:0,CSSValueList:0,ClientRectList:0,DOMRectList:0,DOMStringList:0,DOMTokenList:1,DataTransferItemList:0,FileList:0,HTMLAllCollection:0,HTMLCollection:0,HTMLFormElement:0,HTMLSelectElement:0,MediaList:0,MimeTypeArray:0,NamedNodeMap:0,NodeList:1,PaintRequestList:0,Plugin:0,PluginArray:0,SVGLengthList:0,SVGNumberList:0,SVGPathSegList:0,SVGPointList:0,SVGStringList:0,SVGTransformList:0,SourceBufferList:0,StyleSheetList:0,TextTrackCueList:0,TextTrackList:0,TouchList:0}});var wg=b(()=>{"use strict";Nc();var YR=xg(),KR=ve(),XR=ha(),Eg=Zi();for(Uo in YR)XR(KR[Uo],Uo),Eg[Uo]=Eg.Array;var Uo});var Pg=b((uN,Ag)=>{"use strict";var JR=Tg();wg();Ag.exports=JR});var qc=b((lN,kg)=>{"use strict";var ZR=Pg();kg.exports=ZR});var Rg=b(()=>{"use strict"});var jc=b((pN,Mg)=>{"use strict";var ba=ve(),eM=Ki(),tM=Wi(),qo=function(s){return eM.slice(0,s.length)===s};Mg.exports=function(){return qo("Bun/")?"BUN":qo("Cloudflare-Workers")?"CLOUDFLARE":qo("Deno/")?"DENO":qo("Node.js/")?"NODE":ba.Bun&&typeof Bun.version=="string"?"BUN":ba.Deno&&typeof Deno.version=="object"?"DENO":tM(ba.process)==="process"?"NODE":ba.window&&ba.document?"BROWSER":"REST"}()});var jo=b((hN,Lg)=>{"use strict";var iM=jc();Lg.exports=iM==="NODE"});var $g=b((fN,Bg)=>{"use strict";var rM=Xi();Bg.exports=function(s,e,t){return rM.f(s,e,t)}});var Vg=b((mN,Cg)=>{"use strict";var sM=pi(),aM=$g(),nM=_e(),oM=ft(),Dg=nM("species");Cg.exports=function(s){var e=sM(s);oM&&e&&!e[Dg]&&aM(e,Dg,{configurable:!0,get:function(){return this}})}});var _g=b((bN,Og)=>{"use strict";var uM=ra(),lM=TypeError;Og.exports=function(s,e){if(uM(e,s))return s;throw new lM("Incorrect invocation")}});var zc=b((gN,Fg)=>{"use strict";var cM=Le(),dM=ge(),Hc=na(),pM=cM(Function.toString);dM(Hc.inspectSource)||(Hc.inspectSource=function(s){return pM(s)});Fg.exports=Hc.inspectSource});var Gc=b((SN,Hg)=>{"use strict";var hM=Le(),fM=Oe(),Ng=ge(),mM=pa(),bM=pi(),gM=zc(),Ug=function(){},qg=bM("Reflect","construct"),Qc=/^\s*(?:class|function)\b/,SM=hM(Qc.exec),vM=!Qc.test(Ug),ga=function(e){if(!Ng(e))return!1;try{return qg(Ug,[],e),!0}catch(t){return!1}},jg=function(e){if(!Ng(e))return!1;switch(mM(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return vM||!!SM(Qc,gM(e))}catch(t){return!0}};jg.sham=!0;Hg.exports=!qg||fM(function(){var s;return ga(ga.call)||!ga(Object)||!ga(function(){s=!0})||s})?jg:ga});var Qg=b((vN,zg)=>{"use strict";var yM=Gc(),TM=sa(),IM=TypeError;zg.exports=function(s){if(yM(s))return s;throw new IM(TM(s)+" is not a constructor")}});var Wc=b((yN,Wg)=>{"use strict";var Gg=Ht(),xM=Qg(),EM=Tr(),wM=_e(),AM=wM("species");Wg.exports=function(s,e){var t=Gg(s).constructor,i;return t===void 0||EM(i=Gg(t)[AM])?e:xM(i)}});var Kg=b((TN,Yg)=>{"use strict";var PM=Le();Yg.exports=PM([].slice)});var Jg=b((IN,Xg)=>{"use strict";var kM=TypeError;Xg.exports=function(s,e){if(s<e)throw new kM("Not enough arguments");return s}});var Yc=b((xN,Zg)=>{"use strict";var RM=Ki();Zg.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(RM)});var sd=b((EN,uS)=>{"use strict";var St=ve(),MM=_l(),LM=wr(),eS=ge(),BM=Ct(),oS=Oe(),tS=kc(),$M=Kg(),iS=xo(),DM=Jg(),CM=Yc(),VM=jo(),td=St.setImmediate,id=St.clearImmediate,OM=St.process,Kc=St.Dispatch,_M=St.Function,rS=St.MessageChannel,FM=St.String,Xc=0,Sa={},sS="onreadystatechange",va,tr,Jc,Zc;oS(function(){va=St.location});var rd=function(s){if(BM(Sa,s)){var e=Sa[s];delete Sa[s],e()}},ed=function(s){return function(){rd(s)}},aS=function(s){rd(s.data)},nS=function(s){St.postMessage(FM(s),va.protocol+"//"+va.host)};(!td||!id)&&(td=function(e){DM(arguments.length,1);var t=eS(e)?e:_M(e),i=$M(arguments,1);return Sa[++Xc]=function(){MM(t,void 0,i)},tr(Xc),Xc},id=function(e){delete Sa[e]},VM?tr=function(s){OM.nextTick(ed(s))}:Kc&&Kc.now?tr=function(s){Kc.now(ed(s))}:rS&&!CM?(Jc=new rS,Zc=Jc.port2,Jc.port1.onmessage=aS,tr=LM(Zc.postMessage,Zc)):St.addEventListener&&eS(St.postMessage)&&!St.importScripts&&va&&va.protocol!=="file:"&&!oS(nS)?(tr=nS,St.addEventListener("message",aS,!1)):sS in iS("script")?tr=function(s){tS.appendChild(iS("script"))[sS]=function(){tS.removeChild(this),rd(s)}}:tr=function(s){setTimeout(ed(s),0)});uS.exports={set:td,clear:id}});var dS=b((wN,cS)=>{"use strict";var lS=ve(),NM=ft(),UM=Object.getOwnPropertyDescriptor;cS.exports=function(s){if(!NM)return lS[s];var e=UM(lS,s);return e&&e.value}});var ad=b((AN,hS)=>{"use strict";var pS=function(){this.head=null,this.tail=null};pS.prototype={add:function(s){var e={item:s,next:null},t=this.tail;t?t.next=e:this.head=e,this.tail=e},get:function(){var s=this.head;if(s){var e=this.head=s.next;return e===null&&(this.tail=null),s.item}}};hS.exports=pS});var mS=b((PN,fS)=>{"use strict";var qM=Ki();fS.exports=/ipad|iphone|ipod/i.test(qM)&&typeof Pebble!="undefined"});var gS=b((kN,bS)=>{"use strict";var jM=Ki();bS.exports=/web0s(?!.*chrome)/i.test(jM)});var ES=b((RN,xS)=>{"use strict";var Br=ve(),HM=dS(),SS=wr(),nd=sd().set,zM=ad(),QM=Yc(),GM=mS(),WM=gS(),od=jo(),vS=Br.MutationObserver||Br.WebKitMutationObserver,yS=Br.document,TS=Br.process,Ho=Br.Promise,cd=HM("queueMicrotask"),Lr,ud,ld,zo,IS;cd||(ya=new zM,Ta=function(){var s,e;for(od&&(s=TS.domain)&&s.exit();e=ya.get();)try{e()}catch(t){throw ya.head&&Lr(),t}s&&s.enter()},!QM&&!od&&!WM&&vS&&yS?(ud=!0,ld=yS.createTextNode(""),new vS(Ta).observe(ld,{characterData:!0}),Lr=function(){ld.data=ud=!ud}):!GM&&Ho&&Ho.resolve?(zo=Ho.resolve(void 0),zo.constructor=Ho,IS=SS(zo.then,zo),Lr=function(){IS(Ta)}):od?Lr=function(){TS.nextTick(Ta)}:(nd=SS(nd,Br),Lr=function(){nd(Ta)}),cd=function(s){ya.head||Lr(),ya.add(s)});var ya,Ta;xS.exports=cd});var AS=b((MN,wS)=>{"use strict";wS.exports=function(s,e){try{arguments.length===1?console.error(s):console.error(s,e)}catch(t){}}});var Qo=b((LN,PS)=>{"use strict";PS.exports=function(s){try{return{error:!1,value:s()}}catch(e){return{error:!0,value:e}}}});var ir=b((BN,kS)=>{"use strict";var YM=ve();kS.exports=YM.Promise});var $r=b(($N,BS)=>{"use strict";var KM=ve(),Ia=ir(),XM=ge(),JM=nc(),ZM=zc(),eL=_e(),RS=jc(),tL=Dt(),dd=Gl(),MS=Ia&&Ia.prototype,iL=eL("species"),pd=!1,LS=XM(KM.PromiseRejectionEvent),rL=JM("Promise",function(){var s=ZM(Ia),e=s!==String(Ia);if(!e&&dd===66||tL&&!(MS.catch&&MS.finally))return!0;if(!dd||dd<51||!/native code/.test(s)){var t=new Ia(function(a){a(1)}),i=function(a){a(function(){},function(){})},r=t.constructor={};if(r[iL]=i,pd=t.then(function(){})instanceof i,!pd)return!0}return!e&&(RS==="BROWSER"||RS==="DENO")&&!LS});BS.exports={CONSTRUCTOR:rL,REJECTION_EVENT:LS,SUBCLASSING:pd}});var Dr=b((DN,DS)=>{"use strict";var $S=jt(),sL=TypeError,aL=function(s){var e,t;this.promise=new s(function(i,r){if(e!==void 0||t!==void 0)throw new sL("Bad Promise constructor");e=i,t=r}),this.resolve=$S(e),this.reject=$S(t)};DS.exports.f=function(s){return new aL(s)}});var ZS=b(()=>{"use strict";var nL=Ee(),oL=Dt(),Ko=jo(),Ri=ve(),_r=mt(),CS=Mr(),VS=Oc(),uL=ha(),lL=Vg(),cL=jt(),Yo=ge(),dL=bt(),pL=_g(),hL=Wc(),US=sd().set,gd=ES(),fL=AS(),mL=Qo(),bL=ad(),qS=Ec(),Xo=ir(),Sd=$r(),jS=Dr(),Jo="Promise",HS=Sd.CONSTRUCTOR,gL=Sd.REJECTION_EVENT,SL=Sd.SUBCLASSING,hd=qS.getterFor(Jo),vL=qS.set,Cr=Xo&&Xo.prototype,rr=Xo,Go=Cr,zS=Ri.TypeError,fd=Ri.document,vd=Ri.process,md=jS.f,yL=md,TL=!!(fd&&fd.createEvent&&Ri.dispatchEvent),QS="unhandledrejection",IL="rejectionhandled",OS=0,GS=1,xL=2,yd=1,WS=2,Wo,_S,EL,FS,YS=function(s){var e;return dL(s)&&Yo(e=s.then)?e:!1},KS=function(s,e){var t=e.value,i=e.state===GS,r=i?s.ok:s.fail,a=s.resolve,n=s.reject,o=s.domain,u,l,d;try{r?(i||(e.rejection===WS&&AL(e),e.rejection=yd),r===!0?u=t:(o&&o.enter(),u=r(t),o&&(o.exit(),d=!0)),u===s.promise?n(new zS("Promise-chain cycle")):(l=YS(u))?_r(l,u,a,n):a(u)):n(t)}catch(c){o&&!d&&o.exit(),n(c)}},XS=function(s,e){s.notified||(s.notified=!0,gd(function(){for(var t=s.reactions,i;i=t.get();)KS(i,s);s.notified=!1,e&&!s.rejection&&wL(s)}))},JS=function(s,e,t){var i,r;TL?(i=fd.createEvent("Event"),i.promise=e,i.reason=t,i.initEvent(s,!1,!0),Ri.dispatchEvent(i)):i={promise:e,reason:t},!gL&&(r=Ri["on"+s])?r(i):s===QS&&fL("Unhandled promise rejection",t)},wL=function(s){_r(US,Ri,function(){var e=s.facade,t=s.value,i=NS(s),r;if(i&&(r=mL(function(){Ko?vd.emit("unhandledRejection",t,e):JS(QS,e,t)}),s.rejection=Ko||NS(s)?WS:yd,r.error))throw r.value})},NS=function(s){return s.rejection!==yd&&!s.parent},AL=function(s){_r(US,Ri,function(){var e=s.facade;Ko?vd.emit("rejectionHandled",e):JS(IL,e,s.value)})},Vr=function(s,e,t){return function(i){s(e,i,t)}},Or=function(s,e,t){s.done||(s.done=!0,t&&(s=t),s.value=e,s.state=xL,XS(s,!0))},bd=function(s,e,t){if(!s.done){s.done=!0,t&&(s=t);try{if(s.facade===e)throw new zS("Promise can't be resolved itself");var i=YS(e);i?gd(function(){var r={done:!1};try{_r(i,e,Vr(bd,r,s),Vr(Or,r,s))}catch(a){Or(r,a,s)}}):(s.value=e,s.state=GS,XS(s,!1))}catch(r){Or({done:!1},r,s)}}};if(HS&&(rr=function(e){pL(this,Go),cL(e),_r(Wo,this);var t=hd(this);try{e(Vr(bd,t),Vr(Or,t))}catch(i){Or(t,i)}},Go=rr.prototype,Wo=function(e){vL(this,{type:Jo,done:!1,notified:!1,parent:!1,reactions:new bL,rejection:!1,state:OS,value:void 0})},Wo.prototype=CS(Go,"then",function(e,t){var i=hd(this),r=md(hL(this,rr));return i.parent=!0,r.ok=Yo(e)?e:!0,r.fail=Yo(t)&&t,r.domain=Ko?vd.domain:void 0,i.state===OS?i.reactions.add(r):gd(function(){KS(r,i)}),r.promise}),_S=function(){var s=new Wo,e=hd(s);this.promise=s,this.resolve=Vr(bd,e),this.reject=Vr(Or,e)},jS.f=md=function(s){return s===rr||s===EL?new _S(s):yL(s)},!oL&&Yo(Xo)&&Cr!==Object.prototype)){FS=Cr.then,SL||CS(Cr,"then",function(e,t){var i=this;return new rr(function(r,a){_r(FS,i,r,a)}).then(e,t)},{unsafe:!0});try{delete Cr.constructor}catch(s){}VS&&VS(Cr,Go)}nL({global:!0,constructor:!0,wrap:!0,forced:HS},{Promise:rr});uL(rr,Jo,!1,!0);lL(Jo)});var sv=b((ON,rv)=>{"use strict";var PL=_e(),tv=PL("iterator"),iv=!1;try{ev=0,Td={next:function(){return{done:!!ev++}},return:function(){iv=!0}},Td[tv]=function(){return this},Array.from(Td,function(){throw 2})}catch(s){}var ev,Td;rv.exports=function(s,e){try{if(!e&&!iv)return!1}catch(r){return!1}var t=!1;try{var i={};i[tv]=function(){return{next:function(){return{done:t=!0}}}},s(i)}catch(r){}return t}});var Id=b((_N,av)=>{"use strict";var kL=ir(),RL=sv(),ML=$r().CONSTRUCTOR;av.exports=ML||!RL(function(s){kL.all(s).then(void 0,function(){})})});var nv=b(()=>{"use strict";var LL=Ee(),BL=mt(),$L=jt(),DL=Dr(),CL=Qo(),VL=No(),OL=Id();LL({target:"Promise",stat:!0,forced:OL},{all:function(e){var t=this,i=DL.f(t),r=i.resolve,a=i.reject,n=CL(function(){var o=$L(t.resolve),u=[],l=0,d=1;VL(e,function(c){var h=l++,p=!1;d++,BL(o,t,c).then(function(f){p||(p=!0,u[h]=f,--d||r(u))},a)}),--d||r(u)});return n.error&&a(n.value),i.promise}})});var uv=b(()=>{"use strict";var _L=Ee(),FL=Dt(),NL=$r().CONSTRUCTOR,Ed=ir(),UL=pi(),qL=ge(),jL=Mr(),ov=Ed&&Ed.prototype;_L({target:"Promise",proto:!0,forced:NL,real:!0},{catch:function(s){return this.then(void 0,s)}});!FL&&qL(Ed)&&(xd=UL("Promise").prototype.catch,ov.catch!==xd&&jL(ov,"catch",xd,{unsafe:!0}));var xd});var lv=b(()=>{"use strict";var HL=Ee(),zL=mt(),QL=jt(),GL=Dr(),WL=Qo(),YL=No(),KL=Id();HL({target:"Promise",stat:!0,forced:KL},{race:function(e){var t=this,i=GL.f(t),r=i.reject,a=WL(function(){var n=QL(t.resolve);YL(e,function(o){zL(n,t,o).then(i.resolve,r)})});return a.error&&r(a.value),i.promise}})});var cv=b(()=>{"use strict";var XL=Ee(),JL=Dr(),ZL=$r().CONSTRUCTOR;XL({target:"Promise",stat:!0,forced:ZL},{reject:function(e){var t=JL.f(this),i=t.reject;return i(e),t.promise}})});var wd=b((GN,dv)=>{"use strict";var eB=Ht(),tB=bt(),iB=Dr();dv.exports=function(s,e){if(eB(s),tB(e)&&e.constructor===s)return e;var t=iB.f(s),i=t.resolve;return i(e),t.promise}});var fv=b(()=>{"use strict";var rB=Ee(),sB=pi(),pv=Dt(),aB=ir(),hv=$r().CONSTRUCTOR,nB=wd(),oB=sB("Promise"),uB=pv&&!hv;rB({target:"Promise",stat:!0,forced:pv||hv},{resolve:function(e){return nB(uB&&this===oB?aB:this,e)}})});var mv=b(()=>{"use strict";ZS();nv();uv();lv();cv();fv()});var vv=b(()=>{"use strict";var lB=Ee(),cB=Dt(),Zo=ir(),dB=Oe(),gv=pi(),Sv=ge(),pB=Wc(),bv=wd(),hB=Mr(),Pd=Zo&&Zo.prototype,fB=!!Zo&&dB(function(){Pd.finally.call({then:function(){}},function(){})});lB({target:"Promise",proto:!0,real:!0,forced:fB},{finally:function(s){var e=pB(this,gv("Promise")),t=Sv(s);return this.then(t?function(i){return bv(e,s()).then(function(){return i})}:s,t?function(i){return bv(e,s()).then(function(){throw i})}:s)}});!cB&&Sv(Zo)&&(Ad=gv("Promise").prototype.finally,Pd.finally!==Ad&&hB(Pd,"finally",Ad,{unsafe:!0}));var Ad});var Tv=b((eU,yv)=>{"use strict";Rg();mv();vv();var mB=ki();yv.exports=mB("Promise","finally")});var xv=b((tU,Iv)=>{"use strict";var bB=Tv();Iv.exports=bB});var eu=b((iU,Ev)=>{"use strict";var gB=xv();Ev.exports=gB});var Ov=b(()=>{"use strict";var LB=Ee(),BB=yc().values;LB({target:"Object",stat:!0},{values:function(e){return BB(e)}})});var Fv=b((NU,_v)=>{"use strict";Ov();var $B=Ir();_v.exports=$B.Object.values});var Uv=b((UU,Nv)=>{"use strict";var DB=Fv();Nv.exports=DB});var nr=b((qU,qv)=>{"use strict";var CB=Uv();qv.exports=CB});var ay=b(()=>{"use strict";var s$=Ee(),a$=xr(),n$=Rr(),o$=la(),u$=ca();s$({target:"Array",proto:!0},{at:function(e){var t=a$(this),i=n$(t),r=o$(e),a=r>=0?r:i+r;return a<0||a>=i?void 0:t[a]}});u$("at")});var oy=b((X1,ny)=>{"use strict";ay();var l$=ki();ny.exports=l$("Array","at")});var ly=b((J1,uy)=>{"use strict";var c$=oy();uy.exports=c$});var Ot=b((Z1,cy)=>{"use strict";var d$=ly();cy.exports=d$});var Kd=b((Fj,jy)=>{"use strict";var z$=Wi();jy.exports=Array.isArray||function(e){return z$(e)==="Array"}});var zy=b((Nj,Hy)=>{"use strict";var Q$=TypeError,G$=9007199254740991;Hy.exports=function(s){if(s>G$)throw Q$("Maximum allowed index exceeded");return s}});var Wy=b((Uj,Gy)=>{"use strict";var W$=Kd(),Y$=Rr(),K$=zy(),X$=wr(),Qy=function(s,e,t,i,r,a,n,o){for(var u=r,l=0,d=n?X$(n,o):!1,c,h;l<i;)l in t&&(c=d?d(t[l],l,e):t[l],a>0&&W$(c)?(h=Y$(c),u=Qy(s,e,c,h,u,a-1)-1):(K$(u+1),s[u]=c),u++),l++;return u};Gy.exports=Qy});var Jy=b((qj,Xy)=>{"use strict";var Yy=Kd(),J$=Gc(),Z$=bt(),eD=_e(),tD=eD("species"),Ky=Array;Xy.exports=function(s){var e;return Yy(s)&&(e=s.constructor,J$(e)&&(e===Ky||Yy(e.prototype))?e=void 0:Z$(e)&&(e=e[tD],e===null&&(e=void 0))),e===void 0?Ky:e}});var eT=b((jj,Zy)=>{"use strict";var iD=Jy();Zy.exports=function(s,e){return new(iD(s))(e===0?0:e)}});var tT=b(()=>{"use strict";var rD=Ee(),sD=Wy(),aD=jt(),nD=xr(),oD=Rr(),uD=eT();rD({target:"Array",proto:!0},{flatMap:function(e){var t=nD(this),i=oD(t),r;return aD(e),r=uD(t,0),r.length=sD(r,t,t,i,0,1,e,arguments.length>1?arguments[1]:void 0),r}})});var iT=b(()=>{"use strict";var lD=ca();lD("flatMap")});var sT=b((Wj,rT)=>{"use strict";tT();iT();var cD=ki();rT.exports=cD("Array","flatMap")});var nT=b((Yj,aT)=>{"use strict";var dD=sT();aT.exports=dD});var Fa=b((Kj,oT)=>{"use strict";var pD=nT();oT.exports=pD});var Na=b((Xj,uT)=>{"use strict";var hD=pa(),fD=String;uT.exports=function(s){if(hD(s)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return fD(s)}});var Xd=b((Jj,lT)=>{"use strict";lT.exports=`
7
+ \v\f\r \xA0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF`});var pT=b((Zj,dT)=>{"use strict";var mD=Le(),bD=Pi(),gD=Na(),Zd=Xd(),cT=mD("".replace),SD=RegExp("^["+Zd+"]+"),vD=RegExp("(^|[^"+Zd+"])["+Zd+"]+$"),Jd=function(s){return function(e){var t=gD(bD(e));return s&1&&(t=cT(t,SD,"")),s&2&&(t=cT(t,vD,"$1")),t}};dT.exports={start:Jd(1),end:Jd(2),trim:Jd(3)}});var bT=b((eH,mT)=>{"use strict";var yD=Pc().PROPER,TD=Oe(),hT=Xd(),fT="\u200B\x85\u180E";mT.exports=function(s){return TD(function(){return!!hT[s]()||fT[s]()!==fT||yD&&hT[s].name!==s})}});var ep=b((tH,gT)=>{"use strict";var ID=pT().start,xD=bT();gT.exports=xD("trimStart")?function(){return ID(this)}:"".trimStart});var vT=b(()=>{"use strict";var ED=Ee(),ST=ep();ED({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==ST},{trimLeft:ST})});var TT=b(()=>{"use strict";vT();var wD=Ee(),yT=ep();wD({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==yT},{trimStart:yT})});var xT=b((nH,IT)=>{"use strict";TT();var AD=ki();IT.exports=AD("String","trimLeft")});var wT=b((oH,ET)=>{"use strict";var PD=xT();ET.exports=PD});var PT=b((uH,AT)=>{"use strict";var kD=wT();AT.exports=kD});var qT=b(()=>{"use strict"});var jT=b(()=>{"use strict"});var zT=b((q3,HT)=>{"use strict";var XD=bt(),JD=Wi(),ZD=_e(),e0=ZD("match");HT.exports=function(s){var e;return XD(s)&&((e=s[e0])!==void 0?!!e:JD(s)==="RegExp")}});var GT=b((j3,QT)=>{"use strict";var t0=Ht();QT.exports=function(){var s=t0(this),e="";return s.hasIndices&&(e+="d"),s.global&&(e+="g"),s.ignoreCase&&(e+="i"),s.multiline&&(e+="m"),s.dotAll&&(e+="s"),s.unicode&&(e+="u"),s.unicodeSets&&(e+="v"),s.sticky&&(e+="y"),e}});var KT=b((H3,YT)=>{"use strict";var i0=mt(),r0=Ct(),s0=ra(),a0=GT(),WT=RegExp.prototype;YT.exports=function(s){var e=s.flags;return e===void 0&&!("flags"in WT)&&!r0(s,"flags")&&s0(WT,s)?i0(a0,s):e}});var JT=b((z3,XT)=>{"use strict";var np=Le(),n0=xr(),o0=Math.floor,sp=np("".charAt),u0=np("".replace),ap=np("".slice),l0=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,c0=/\$([$&'`]|\d{1,2})/g;XT.exports=function(s,e,t,i,r,a){var n=t+s.length,o=i.length,u=c0;return r!==void 0&&(r=n0(r),u=l0),u0(a,u,function(l,d){var c;switch(sp(d,0)){case"$":return"$";case"&":return s;case"`":return ap(e,0,t);case"'":return ap(e,n);case"<":c=r[ap(d,1,-1)];break;default:var h=+d;if(h===0)return l;if(h>o){var p=o0(h/10);return p===0?l:p<=o?i[p-1]===void 0?sp(d,1):i[p-1]+sp(d,1):l}c=i[h-1]}return c===void 0?"":c})}});var tI=b(()=>{"use strict";var d0=Ee(),p0=mt(),up=Le(),ZT=Pi(),h0=ge(),f0=Tr(),m0=zT(),Jr=Na(),b0=aa(),g0=KT(),S0=JT(),v0=_e(),y0=Dt(),T0=v0("replace"),I0=TypeError,op=up("".indexOf),x0=up("".replace),eI=up("".slice),E0=Math.max;d0({target:"String",proto:!0},{replaceAll:function(e,t){var i=ZT(this),r,a,n,o,u,l,d,c,h,p,f=0,m="";if(!f0(e)){if(r=m0(e),r&&(a=Jr(ZT(g0(e))),!~op(a,"g")))throw new I0("`.replaceAll` does not allow non-global regexes");if(n=b0(e,T0),n)return p0(n,e,i,t);if(y0&&r)return x0(Jr(i),e,t)}for(o=Jr(i),u=Jr(e),l=h0(t),l||(t=Jr(t)),d=u.length,c=E0(1,d),h=op(o,u);h!==-1;)p=l?Jr(t(u,h,o)):S0(u,o,h,[],void 0,t),m+=eI(o,f,h)+p,f=h+d,h=h+c>o.length?-1:op(o,u,h+c);return f<o.length&&(m+=eI(o,f)),m}})});var rI=b((W3,iI)=>{"use strict";qT();jT();tI();var w0=ki();iI.exports=w0("String","replaceAll")});var aI=b((Y3,sI)=>{"use strict";var A0=rI();sI.exports=A0});var lp=b((K3,nI)=>{"use strict";var P0=aI();nI.exports=P0});var uI=b((X3,oI)=>{"use strict";var k0=la(),R0=Na(),M0=Pi(),L0=RangeError;oI.exports=function(e){var t=R0(M0(this)),i="",r=k0(e);if(r<0||r===1/0)throw new L0("Wrong number of repetitions");for(;r>0;(r>>>=1)&&(t+=t))r&1&&(i+=t);return i}});var hI=b((J3,pI)=>{"use strict";var dI=Le(),B0=pc(),lI=Na(),$0=uI(),D0=Pi(),C0=dI($0),V0=dI("".slice),O0=Math.ceil,cI=function(s){return function(e,t,i){var r=lI(D0(e)),a=B0(t),n=r.length,o=i===void 0?" ":lI(i),u,l;return a<=n||o===""?r:(u=a-n,l=C0(o,O0(u/o.length)),l.length>u&&(l=V0(l,0,u)),s?r+l:l+r)}};pI.exports={start:cI(!1),end:cI(!0)}});var mI=b((Z3,fI)=>{"use strict";var _0=Ki();fI.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(_0)});var bI=b(()=>{"use strict";var F0=Ee(),N0=hI().start,U0=mI();F0({target:"String",proto:!0,forced:U0},{padStart:function(e){return N0(this,e,arguments.length>1?arguments[1]:void 0)}})});var SI=b((iz,gI)=>{"use strict";bI();var q0=ki();gI.exports=q0("String","padStart")});var yI=b((rz,vI)=>{"use strict";var j0=SI();vI.exports=j0});var cp=b((sz,TI)=>{"use strict";var H0=yI();TI.exports=H0});var Bh="2.0.135-dev.ee4a31cc.0";var et=(r=>(r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused",r))(et||{}),di=(y=>(y.MPEG="MPEG",y.DASH="DASH",y.DASH_SEP="DASH_SEP",y.DASH_SEP_VK="DASH_SEP",y.DASH_WEBM="DASH_WEBM",y.DASH_WEBM_AV1="DASH_WEBM_AV1",y.DASH_STREAMS="DASH_STREAMS",y.DASH_WEBM_VK="DASH_WEBM",y.DASH_ONDEMAND="DASH_ONDEMAND",y.DASH_ONDEMAND_VK="DASH_ONDEMAND",y.DASH_LIVE="DASH_LIVE",y.DASH_LIVE_CMAF="DASH_LIVE_CMAF",y.DASH_LIVE_WEBM="DASH_LIVE_WEBM",y.HLS="HLS",y.HLS_ONDEMAND="HLS_ONDEMAND",y.HLS_JS="HLS",y.HLS_LIVE="HLS_LIVE",y.HLS_LIVE_CMAF="HLS_LIVE_CMAF",y.WEB_RTC_LIVE="WEB_RTC_LIVE",y))(di||{});var vo=(r=>(r.NOT_AVAILABLE="NOT_AVAILABLE",r.AVAILABLE="AVAILABLE",r.CONNECTING="CONNECTING",r.CONNECTED="CONNECTED",r))(vo||{}),Cl=(i=>(i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic",i))(Cl||{});var Vl=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(Vl||{}),yo=(i=>(i.TRAFFIC_SAVING="traffic_saving",i.HIGH_QUALITY="high_quality",i.UNKNOWN="unknown",i))(yo||{});var ME=N(gt(),1);import{assertNever as Lm,assertNonNullable as sP,isNonNullable as wo,ValueSubject as fc,Subject as aP,Subscription as nP,merge as oP,observableFrom as uP,fromEvent as Pm,map as km,tap as Rm,filterChanged as lP,isNullable as mc,ErrorCategory as Mm}from"@vkontakte/videoplayer-shared/es2018";var Am=s=>new Promise((e,t)=>{let i=document.createElement("script");i.setAttribute("src",s),i.onload=()=>e(),i.onerror=r=>t(r),document.body.appendChild(i)});var Ao=class{constructor(e){this.connection$=new fc(void 0);this.castState$=new fc("NOT_AVAILABLE");this.errorEvent$=new aP;this.realCastState$=new fc("NOT_AVAILABLE");this.subscription=new nP;this.isDestroyed=!1;var a;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");let t="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${t}`}),e.isDisabled||!t)return;let i=wo((a=window.chrome)==null?void 0:a.cast),r=!!window.__onGCastApiAvailable;i?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&!this.isDestroyed&&this.initializeCastApi()},r||Am("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:Mm.NETWORK,message:"Script loading failed!"})))}connect(){var e;(e=cast.framework.CastContext.getInstance())==null||e.requestSession()}disconnect(){var e,t;(t=(e=cast.framework.CastContext.getInstance())==null?void 0:e.getCurrentSession())==null||t.endSession(!0)}stopMedia(){return new Promise((e,t)=>{var i,r,a;(a=(r=(i=cast.framework.CastContext.getInstance())==null?void 0:i.getCurrentSession())==null?void 0:r.getMediaSession())==null||a.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){wo(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();mc(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();mc(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.isDestroyed=!0,this.subscription.unsubscribe()}initListeners(){let e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),i=cast.framework.CastContext.getInstance();this.subscription.add(Pm(i,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(r=>{var a,n,o;switch(r.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(o=(n=(a=i.getCurrentSession())==null?void 0:a.getMediaSession())==null?void 0:n.media)==null?void 0:o.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return Lm(r.sessionState)}})).add(oP(Pm(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(Rm(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),km(r=>r.castState)),uP([i.getCastState()])).pipe(lP(),km(cP),Rm(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{var o,u;let a=r==="CONNECTED",n=wo(this.connection$.getValue());if(a&&!n){let l=i.getCurrentSession();sP(l);let d=l.getCastDevice(),c=(u=(o=l.getMediaSession())==null?void 0:o.media)==null?void 0:u.contentId;(mc(c)||c===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:l,castDevice:d}))}else!a&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(r==="CONNECTED"?wo(this.connection$.getValue())?"CONNECTED":"AVAILABLE":r)}))}initializeCastApi(){var r;let e,t,i;try{e=cast.framework.CastContext.getInstance(),t=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,i=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(a){return}try{e.setOptions({receiverApplicationId:(r=this.params.receiverApplicationId)!=null?r:t,autoJoinPolicy:i}),this.initListeners()}catch(a){this.errorEvent$.next({id:"ChromecastInitializer",category:Mm.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:a})}}},cP=s=>{switch(s){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return"NOT_AVAILABLE";case cast.framework.CastState.NOT_CONNECTED:return"AVAILABLE";case cast.framework.CastState.CONNECTING:return"CONNECTING";case cast.framework.CastState.CONNECTED:return"CONNECTED";default:return Lm(s)}};var xh=N(gt(),1),dE=N(Ji(),1),pE=N(qc(),1);var Dv=N(eu(),1);import{assertNever as wv}from"@vkontakte/videoplayer-shared/es2018";var Se=(s,e=0,t=0)=>{switch(t){case 0:return s.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case 1:{if(e===0)return s;let i=new URL(s);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}case 2:{let i=new URL(s);return!i.searchParams.get("offset_p")&&e===0?s:(i.searchParams.set("offset_p",e.toFixed(0)),i.toString())}default:wv(t)}return s},Mi=(s,e)=>{var t;switch(e){case 0:return NaN;case 1:{let i=new URL(s);return Number(i.searchParams.get("playback_shift"))}case 2:{let i=new URL(s);return Number((t=i.searchParams.get("offset_p"))!=null?t:0)}default:wv(e)}};var B=(s,e,t=!1)=>{let i=s.getTransition();(t||!i||i.to===e)&&s.setState(e)};import{isNonNullable as SB,Subject as tu,merge as Av}from"@vkontakte/videoplayer-shared/es2018";var G=class{constructor(e){this.transitionStarted$=new tu;this.transitionEnded$=new tu;this.transitionUpdated$=new tu;this.forceChanged$=new tu;this.stateChangeStarted$=Av(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=Av(this.transitionEnded$,this.forceChanged$);this.state=e,this.prevState=void 0}setState(e){let t=this.transition,i=this.state;this.transition=void 0,this.prevState=i,this.state=e,t?t.to===e?this.transitionEnded$.next(t):this.forceChanged$.next({from:t.from,to:e,canceledTransition:t}):this.forceChanged$.next({from:i,to:e,canceledTransition:t})}startTransitionTo(e){let t=this.transition,i=this.state;i===e||SB(t)&&t.to===e||(this.prevState=i,this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:i,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}getPrevState(){return this.prevState}};import{assertNever as vB}from"@vkontakte/videoplayer-shared/es2018";var Pv=s=>{switch(s){case"MPEG":case"DASH":case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":case"HLS":case"HLS_ONDEMAND":return!1;case"DASH_LIVE":case"DASH_LIVE_CMAF":case"HLS_LIVE":case"HLS_LIVE_CMAF":case"DASH_LIVE_WEBM":case"WEB_RTC_LIVE":return!0;default:return vB(s)}};import{assertNever as Fr,assertNonNullable as sr,debounce as kv,ErrorCategory as Rv,fromEvent as ar,isNonNullable as Mv,map as Lv,merge as Bv,observableFrom as yB,Subject as TB,Subscription as kd,timeout as IB,getHighestQuality as xB}from"@vkontakte/videoplayer-shared/es2018";var EB=5,wB=5,AB=500,$v=7e3,xa=class{constructor(e){this.subscription=new kd;this.loadMediaTimeoutSubscription=new kd;this.videoState=new G("stopped");this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(a)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.stop());return}if(!t){if((r==null?void 0:r.to)!=="paused"&&a.state==="requested"&&e!=="stopped"){this.seek(a.position/1e3);return}switch(i){case"ready":{switch(e){case"playing":case"paused":case"ready":break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:Fr(e)}break}case"playing":{switch(e){case"playing":break;case"paused":this.videoState.startTransitionTo("playing"),this.params.connection.remotePlayerController.playOrPause();break;case"ready":this.videoState.startTransitionTo("playing"),this.params.connection.remotePlayerController.playOrPause();break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:Fr(e)}break}case"paused":{switch(e){case"playing":this.videoState.startTransitionTo("paused"),this.params.connection.remotePlayerController.playOrPause();break;case"paused":break;case"ready":this.videoState.startTransitionTo("paused"),this.videoState.setState("paused");break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:Fr(e)}break}default:Fr(i)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(Pv(e.format)),this.params.output.isAudioAvailable$.next(!0),this.handleRemoteVolumeChange({volume:this.params.connection.remotePlayer.volumeLevel,muted:this.params.connection.remotePlayer.isMuted});let t=this.params.connection.session.getMediaSession();t&&this.restoreSession(t),this.subscribe()}destroy(){this.log({message:"[destroy]"}),this.subscription.unsubscribe()}subscribe(){this.subscription.add(this.loadMediaTimeoutSubscription);let e=new kd;this.subscription.add(e),this.subscription.add(Bv(this.videoState.stateChangeStarted$.pipe(Lv(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe(Lv(r=>`stateChangeEnded$ ${JSON.stringify(r)}`))).subscribe(r=>this.log({message:`[videoState] ${r}`})));let t=(r,a)=>this.subscription.add(r.subscribe(a));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{let r=new TB;e.add(r.pipe(kv(AB)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let a=NaN;e.add(ar(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(n=>{this.logRemoteEvent(n);let o=n.value;this.params.output.position$.next(o),(this.params.desiredState.seekState.getState().state==="applying"||Math.abs(o-a)>EB)&&r.next(o),a=o})),e.add(ar(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(ar(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(ar(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t(ar(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),r=>{this.logRemoteEvent(r);let{remotePlayer:a}=this.params.connection,n=r.value,o=this.params.output.isBuffering$.getValue(),u=n===chrome.cast.media.PlayerState.BUFFERING;switch(o!==u&&this.params.output.isBuffering$.next(u),n){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&a.duration-a.currentTime<wB&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),B(this.params.desiredState.playbackState,"stopped");break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:Fr(n)}}),t(ar(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t(ar(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});let i=Bv(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,yB(["init"])).pipe(kv(0));t(i,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});let{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState("paused"),B(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),B(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"),B(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"),B(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"&&B(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){var r,a;let t=this.params.output.volume$.getValue(),i={volume:(r=e.volume)!=null?r:t.volume,muted:(a=e.muted)!=null?a:t.muted};(i.volume!==t.volume||i.muted!==i.muted)&&this.params.output.volume$.next(i)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:i}=this.params.connection;t.currentTime=e,i.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){var l;let t=this.params.source,i,r,a;switch(e){case"MPEG":{let d=t[e];sr(d);let c=xB(Object.keys(d));sr(c);let h=d[c];sr(h),i=h,r="video/mp4",a=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let d=t[e];sr(d),i=d.url,r="application/x-mpegurl",a=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":{let d=t[e];sr(d),i=d.url,r="application/dash+xml",a=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let d=t[e];sr(d),i=d.url,r="application/dash+xml",a=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let d=t[e];sr(d),i=Se(d.url),r="application/x-mpegurl",a=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let d="Unsupported format for Chromecast",c=new Error(d);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:Rv.VIDEO_PIPELINE,message:d,thrown:c}),c}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return Fr(e)}let n=new chrome.cast.media.MediaInfo((l=this.params.meta.videoId)!=null?l:i,r);n.contentUrl=i,n.streamType=a,n.metadata=new chrome.cast.media.GenericMediaMetadata;let{title:o,subtitle:u}=this.params.meta;return Mv(o)&&(n.metadata.title=o),Mv(u)&&(n.metadata.subtitle=u),n}createLoadRequest(e){let t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;let i=this.params.desiredState.seekState.getState();return i.state==="applying"||i.state==="requested"?t.currentTime=this.params.output.isLive$.getValue()?0:i.position/1e3:t.currentTime=0,t}loadMedia(e){let t=this.params.connection.session.loadMedia(e),i=new Promise((r,a)=>{this.loadMediaTimeoutSubscription.add(IB($v).subscribe(()=>a(`timeout(${$v})`)))});(0,Dv.default)(Promise.race([t,i]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},r=>{let a=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${r}`;this.log({message:a}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:Rv.VIDEO_PIPELINE,message:a,thrown:r})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var Wd=N(gt(),1);import{clearVideoElement as Vv}from"@vkontakte/videoplayer-shared/es2018";import{clearVideoElement as PB}from"@vkontakte/videoplayer-shared/es2018";var Cv=s=>{try{s.pause(),s.playbackRate=0,PB(s),s.remove()}catch(e){console.error(e)}};import{fromEvent as kB,Subscription as RB}from"@vkontakte/videoplayer-shared/es2018";var Rd=class{constructor(){this.attribute="data-pool-reused"}get(e){return e.hasAttribute(this.attribute)}set(e,t){e.toggleAttribute(this.attribute,t)}delete(e){e.removeAttribute(this.attribute)}},Md=window.WeakMap?new WeakMap:new Rd,Ld=window.WeakMap?new WeakMap:new Map,MB=(s,e=20)=>{let t=0;return kB(s,"ratechange").subscribe(i=>{t++,t>=e&&(s.currentTime=s.currentTime,t=0)})},tt=(s,{audioVideoSyncRate:e,disableYandexPiP:t})=>{let i=s.querySelector("video"),r=!!i;i?Vv(i):(i=document.createElement("video"),s.appendChild(i)),Md.set(i,r);let a=new RB;return a.add(MB(i,e)),Ld.set(i,a),i.setAttribute("crossorigin","anonymous"),i.setAttribute("playsinline","playsinline"),t&&i.setAttribute("x-yandex-pip","false"),i.controls=!1,i.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),i},it=s=>{let e=Ld.get(s);e==null||e.unsubscribe(),Ld.delete(s);let t=Md.get(s);Md.delete(s),t?Vv(s):Cv(s)};var $d=N(nr(),1);import{assertNonNullable as wa,isNonNullable as Qt,isNullable as _B,fromEvent as Nr,merge as jv,observableFrom as Hv,filterChanged as zv,map as Aa,Subject as Qv,Subscription as FB,ValueSubject as NB,ErrorCategory as UB}from"@vkontakte/videoplayer-shared/es2018";import{isNonNullable as Bd,isNullable as VB,Subscription as OB}from"@vkontakte/videoplayer-shared/es2018";var iu=(s,e,t,{equal:i=(n,o)=>n===o,changed$:r,onError:a}={})=>{let n=s.getState(),o=e(),u=VB(r),l=new OB;return r&&l.add(r.subscribe(d=>{let c=s.getState();i(d,c)&&s.setState(d)},a)),i(o,n)||(t(n),u&&s.setState(n)),l.add(s.stateChangeStarted$.subscribe(d=>{t(d.to),u&&s.setState(d.to)},a)),l},zt=(s,e,t)=>iu(e,()=>s.loop,i=>{Bd(i)&&(s.loop=i)},{onError:t}),rt=(s,e,t,i)=>iu(e,()=>({muted:s.muted,volume:s.volume}),r=>{Bd(r)&&(s.muted=r.muted,s.volume=r.volume)},{equal:(r,a)=>r===a||(r==null?void 0:r.muted)===(a==null?void 0:a.muted)&&(r==null?void 0:r.volume)===(a==null?void 0:a.volume),changed$:t,onError:i}),It=(s,e,t,i)=>iu(e,()=>s.playbackRate,r=>{Bd(r)&&(s.playbackRate=r)},{changed$:t,onError:i}),Ea=iu;var qB=s=>["__",s.language,s.label].join("|"),jB=(s,e)=>{if(s.id===e)return!0;let[t,i,r]=e.split("|");return s.language===i&&s.label===r},Dd=class s{constructor(e){this.available$=new Qv;this.current$=new NB(void 0);this.error$=new Qv;this.subscription=new FB;this.externalTracks=new Map;this.internalTracks=new Map;this.baseURL=e}connect(e,t,i){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();let r=a=>{this.error$.next({id:"TextTracksManager",category:UB.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:a})};this.subscription.add(this.available$.subscribe(i.availableTextTracks$)),this.subscription.add(this.current$.subscribe(i.currentTextTrack$)),this.subscription.add(this.error$.subscribe(i.error$)),this.subscription.add(Ea(t.internalTextTracks,()=>(0,$d.default)(this.internalTracks),a=>{Qt(a)&&this.setInternal(a)},{equal:(a,n)=>Qt(a)&&Qt(n)&&a.length===n.length&&a.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(Aa(a=>a.filter(({type:n})=>n==="internal"))),onError:r})),this.subscription.add(Ea(t.externalTextTracks,()=>(0,$d.default)(this.externalTracks),a=>{Qt(a)&&this.setExternal(a)},{equal:(a,n)=>Qt(a)&&Qt(n)&&a.length===n.length&&a.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(Aa(a=>a.filter(({type:n})=>n==="external"))),onError:r})),this.subscription.add(Ea(t.currentTextTrack,()=>{if(this.video)return;let a=this.htmlTextTracksAsArray().find(({mode:n})=>n==="showing");return a&&this.htmlTextTrackToITextTrack(a).id},a=>this.select(a),{changed$:this.current$,onError:r})),this.subscription.add(Ea(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let a of this.htmlTextTracksAsArray())this.applyCueSettings(a.cues),this.applyCueSettings(a.activeCues)}))}subscribe(){wa(this.video);let{textTracks:e}=this.video;this.subscription.add(Nr(e,"addtrack").subscribe(()=>{let i=this.current$.getValue();i&&this.select(i)})),this.subscription.add(jv(Nr(e,"addtrack"),Nr(e,"removetrack"),Hv(["init"])).pipe(Aa(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),zv((i,r)=>i.length===r.length&&i.every(({id:a},n)=>a===r[n].id))).subscribe(this.available$)),this.subscription.add(jv(Nr(e,"change"),Hv(["init"])).pipe(Aa(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),Aa(i=>i&&this.htmlTextTrackToITextTrack(i).id),zv()).subscribe(this.current$));let t=i=>{var r,a;return this.applyCueSettings((a=(r=i.target)==null?void 0:r.activeCues)!=null?a:null)};this.subscription.add(Nr(e,"addtrack").subscribe(i=>{var a,n;(a=i.track)==null||a.addEventListener("cuechange",t);let r=o=>{var l,d,c,h,p;let u=(d=(l=o.target)==null?void 0:l.cues)!=null?d:null;u&&u.length&&(this.applyCueSettings((h=(c=o.target)==null?void 0:c.cues)!=null?h:null),(p=o.target)==null||p.removeEventListener("cuechange",r))};(n=i.track)==null||n.addEventListener("cuechange",r)})),this.subscription.add(Nr(e,"removetrack").subscribe(i=>{var r;(r=i.track)==null||r.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;let t=this.cueSettings.getState();for(let i of Array.from(e)){let r=i;Qt(t.align)&&(r.align=t.align),Qt(t.position)&&(r.position=t.position),Qt(t.size)&&(r.size=t.size),Qt(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){wa(this.video);let t=[...this.video.textTracks];return e?t:t.filter(s.isHealthyTrack)}htmlTextTrackToITextTrack(e){var o,u,l,d,c;let{language:t,label:i}=e,r=e.id?e.id:qB(e),a=this.externalTracks.has(r),n=(l=a?(o=this.externalTracks.get(r))==null?void 0:o.isAuto:(u=this.internalTracks.get(r))==null?void 0:u.isAuto)!=null?l:r.includes("auto");return a?{id:r,type:"external",isAuto:n,language:t,label:i,url:(d=this.externalTracks.get(r))==null?void 0:d.url}:{id:r,type:"internal",isAuto:n,language:t,label:i,url:(c=this.internalTracks.get(r))==null?void 0:c.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(i=>i.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){let t=[...this.externalTracks];e.filter(({id:i,language:r,isAuto:a})=>!this.internalTracks.has(i)&&!t.some(([,n])=>n.language===r&&n.isAuto===a)).forEach(i=>this.attach(i)),Array.from(this.internalTracks).filter(([i])=>!e.find(r=>r.id===i)).forEach(([,i])=>this.detach(i))}select(e){wa(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(_B(e)||!jB(t,e))&&(t.mode="disabled")}destroy(){if(this.subscription.unsubscribe(),this.video)for(let e of Array.from(this.video.getElementsByTagName("track"))){let t=e.getAttribute("id");t&&this.externalTracks.has(t)&&this.video.removeChild(e)}this.externalTracks.clear()}attach(e){wa(this.video);let t=document.createElement("track");this.baseURL?t.setAttribute("src",new URL(e.url,this.baseURL).toString()):t.setAttribute("src",e.url),t.setAttribute("id",e.id),e.label&&t.setAttribute("label",e.label),e.language&&t.setAttribute("srclang",e.language),e.type==="external"?this.externalTracks.set(e.id,e):e.type==="internal"&&this.internalTracks.set(e.id,e),this.video.appendChild(t)}detach(e){wa(this.video);let t=Array.prototype.find.call(this.video.getElementsByTagName("track"),i=>i.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}},xt=Dd;var or=class{constructor(){this.pausedTime=0;this.streamOffset=0;this.pauseTimestamp=0}getTotalPausedTime(){return this.pausedTime+this.getCurrentPausedTime()}getCurrentPausedTime(){return this.pauseTimestamp>0?Date.now()-this.pauseTimestamp:0}getStreamOffset(){return this.streamOffset}getTotalOffset(){return this.getTotalPausedTime()+this.streamOffset}pause(){this.pauseTimestamp===0&&(this.pauseTimestamp=Date.now())}resume(){this.pauseTimestamp>0&&(this.pausedTime+=this.getCurrentPausedTime(),this.pauseTimestamp=0)}resetTo(e,t=!1){this.streamOffset=e,this.pauseTimestamp=0,this.pausedTime=0,t&&this.pause()}};var Gv=s=>{let e=s;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e==null?void 0:e.parentNode;return e!=null?e:void 0},Cd=s=>{let e=Gv(s);return!!(e&&e.fullscreenElement&&e.fullscreenElement===s)},Wv=s=>{let e=Gv(s);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===s)};import{fromEvent as Ye,map as Gt,merge as lu,filterChanged as iy,isNonNullable as ry,Subject as JB,filter as Od,mapTo as _d,combine as ZB,once as e$,throttle as t$,ErrorCategory as i$,ValueSubject as sy,Subscription as r$}from"@vkontakte/videoplayer-shared/es2018";var HB=3,Yv=(s,e,t=HB)=>{let i=0,r=0;for(let a=0;a<s.length;a++){let n=s.start(a),o=s.end(a);if(n<=e&&e<=o){if(i=n,r=o,!t)return{from:i,to:r};for(let u=a-1;u>=0;u--)s.end(u)+t>=i&&(i=s.start(u));for(let u=a+1;u<s.length;u++)s.start(u)-t<=r&&(r=s.end(u))}}return{from:i,to:r}};var ru=class{constructor(){this._isMiuiBrowser=!1}get current(){return this._current}get isChrome(){return this.current==="Chrome"}get isFirefox(){return this.current==="Firefox"}get isSafari(){return this.current==="Safari"}get isOpera(){return this.current==="Opera"}get isEdge(){return this.current==="Edge"}get isYandex(){return this.current==="Yandex"}get isSamsungBrowser(){return this.current==="SamsungBrowser"}get currentVersion(){return this._current_version}get chromeVersion(){return this._chromeVersion}get firefoxVersion(){return this._firefoxVersion}get safariVersion(){return this._safariVersion}get operaVersion(){return this._operaVersion}get edgeVersion(){return this._edgeVersion}get yandexVersion(){return this._yandexVersion}get isMiuiBrowser(){return this._isMiuiBrowser}detect(){let{userAgent:e}=navigator;try{let t=/yabrowser/i.test(e)?"Yandex":void 0,i=/samsungbrowser/i.test(e)?"SamsungBrowser":void 0,r=/chrome|crios/i.test(e)?"Chrome":void 0,a=/chromium/i.test(e)?"Chromium":void 0,n=/firefox|fxios/i.test(e)?"Firefox":void 0,o=/webkit|safari|khtml/i.test(e)?"Safari":void 0,u=/opr\//i.test(e)?"Opera":void 0,l=/edg/i.test(e)?"Edge":void 0;this._isMiuiBrowser=/(XiaoMi)|(MiuiBrowser)/i.test(e),this._current=t||i||n||u||l||r||a||o||"Rest"}catch(t){console.error(t)}this.isChrome&&this.detectChromeVersion(),this.isFirefox&&this.detectFirefoxVersion(),this.isSafari&&this.detectSafariVersion(),this.isOpera&&this.detectOperaVersion(),this.isEdge&&this.detectEdgeVersion(),this.isYandex&&this.detectYandexVersion()}detectVersion(e){try{let{userAgent:t}=window.navigator,i=t.match(e);if(!i)return;let r=i[1],a=parseInt(r,10);if(!isNaN(a))return this._current_version=a,a}catch(t){console.error(t)}}detectChromeVersion(){this._chromeVersion=this.detectVersion(/Chrome\/(\d+\.\d+)/)}detectFirefoxVersion(){this._firefoxVersion=this.detectVersion(/Firefox\/(\d+\.\d+)/)}detectSafariVersion(){this._safariVersion=this.detectVersion(/Version\/(\d+)/)}detectOperaVersion(){this._operaVersion=this.detectVersion(/OPR\/(\d+\.\d+)/)}detectEdgeVersion(){this._edgeVersion=this.detectVersion(/Edg\/(\d+\.\d+)/)}detectYandexVersion(){this._yandexVersion=this.detectVersion(/YaBrowser\/(\d+\.\d+\.\d+)/)}};var Kv=N(gt(),1);var Pa=()=>{var s,e;return/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test((s=navigator.appVersion)!=null?s:navigator.userAgent)||((e=navigator==null?void 0:navigator.userAgentData)==null?void 0:e.mobile)};var su=class{constructor(e){this._highEntropyValues={};this._displayChecker=e}get current(){return this._current}get isIOS(){let e=["iPhone","iPad","iPod"];return this._highEntropyValues.platform==="iOS"||(0,Kv.default)(e,this.current)}get isMac(){return this._highEntropyValues.platform==="macOS"||this.current==="Mac"}get isApple(){return this.isIOS||this.isMac}get isIphoneOrOldIpad(){if(!this.isApple||!this._displayChecker.isTouch)return!1;let e=this.current==="iPad"||this._displayChecker.width>700,t=this._iosVersion;return!e||e&&!!t&&t<16}get isAndroid(){return this._highEntropyValues.platform==="Android"||this.current==="Android"}get isMobile(){return this._highEntropyValues.mobile||this._isMobile}get iOSVersion(){return this._iosVersion}detect(){let{userAgent:e}=navigator;try{this._isMobile=Pa()}catch(t){console.error(t)}this.detectDevice(e),this.detectHighEntropyValues(),this.isIOS&&this.detectIOSVersion()}async detectHighEntropyValues(){let{userAgentData:e}=navigator;if(e!=null&&e.getHighEntropyValues){let t=await e.getHighEntropyValues(["architecture","bitness","brands","mobile","platform","formFactor","model","platformVersion","wow64"]);this._highEntropyValues=t}}detectDevice(e){try{let t=/android/i.test(e)?"Android":void 0,i=/iphone/i.test(e)?"iPhone":void 0,r=/ipad/i.test(e)?"iPad":void 0,a=/ipod/i.test(e)?"iPod":void 0,n=/mac/i.test(e)?"Mac":void 0,o=/webOS|BlackBerry|IEMobile|Opera Mini/i.test(e)?"RestMobile":void 0;this._current=t||i||r||a||o||n||"Desktop"}catch(t){console.error(t)}}detectIOSVersion(){try{if(this._highEntropyValues.platformVersion){let a=this._highEntropyValues.platformVersion.split(".").slice(0,2).join("."),n=parseFloat(a);this._iosVersion=n;return}let{userAgent:e}=window.navigator,t=e.match(/OS (\d+(_\d+)?)/i);if(!t)return;let i=t[1].replace(/_/g,".");if(!i)return;let r=parseFloat(i);if(isNaN(r))return;this._iosVersion=r}catch(e){console.error(e)}}};var au=class{get isTouch(){return typeof this._maxTouchPoints=="number"?this._maxTouchPoints>1:"ontouchstart"in window}get maxTouchPoints(){return this._maxTouchPoints}get height(){return this._height}get width(){return this._width}get screenHeight(){return this._screenHeight}get screenWidth(){return this._screenWidth}get pixelRatio(){return this._pixelRatio}get isHDR(){return this._isHdr}get colorDepth(){return this._colorDepth}detect(){var t;let{maxTouchPoints:e}=navigator;try{this._maxTouchPoints=e!=null?e:0,this._isHdr=!!((t=matchMedia("(dynamic-range: high)"))!=null&&t.matches),this._colorDepth=screen.colorDepth}catch(i){console.error(i)}try{this._pixelRatio=window.devicePixelRatio||1,this._height=screen.height,this._width=screen.width,this._height=screen.height,this._screenHeight=this._height*this._pixelRatio,this._screenWidth=this._width*this._pixelRatio}catch(i){console.error(i)}}};var vt=()=>window.ManagedMediaSource||window.MediaSource,Ur=()=>{var s,e;return!!(window.ManagedMediaSource&&((e=(s=window.ManagedSourceBuffer)==null?void 0:s.prototype)!=null&&e.appendBuffer))},Xv=()=>{var s,e;return!!(window.MediaSource&&((e=(s=window.SourceBuffer)==null?void 0:s.prototype)!=null&&e.appendBuffer))},nu=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var zB=document.createElement("video"),QB='video/mp4; codecs="avc1.42000a,mp4a.40.2"',GB='video/mp4; codecs="hev1.1.6.L93.B0"',Jv='video/webm; codecs="vp09.00.10.08"',Zv='video/webm; codecs="av01.0.00M.08"',WB='audio/mp4; codecs="mp4a.40.2"',YB='audio/webm; codecs="opus"',ey,KB=async()=>{if(!window.navigator.mediaCapabilities)return;let s={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=await Promise.all([window.navigator.mediaCapabilities.decodingInfo({...s,video:{...s.video,contentType:Zv}}),window.navigator.mediaCapabilities.decodingInfo({...s,video:{...s.video,contentType:Jv}})]);ey={DASH_WEBM_AV1:e,DASH_WEBM:t}};KB().catch(s=>{console.log(zB),console.error(s)});var ou=class{constructor(e,t){this._deviceChecker=e,this._browserChecker=t}get protocols(){return this._protocols}get containers(){return this._containers}get codecs(){return this._codecs}get webmDecodingInfo(){return ey}get supportedCodecs(){return Object.keys(this._codecs).filter(e=>this._codecs[e])}get nativeHlsSupported(){return this._nativeHlsSupported}detect(){var e,t,i,r,a,n,o,u,l,d,c,h,p,f,m,g,S,v,y,I;this._video=document.createElement("video");try{this._protocols={mms:Ur(),mse:Xv(),hls:!!((t=(e=this._video).canPlayType)!=null&&t.call(e,"application/x-mpegurl")||(r=(i=this._video).canPlayType)!=null&&r.call(i,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},this._containers={mp4:!!((n=(a=this._video).canPlayType)!=null&&n.call(a,"video/mp4")),webm:!!((u=(o=this._video).canPlayType)!=null&&u.call(o,"video/webm")),cmaf:!0};let T=!!((d=(l=vt())==null?void 0:l.isTypeSupported)!=null&&d.call(l,QB)),E=!!((h=(c=vt())==null?void 0:c.isTypeSupported)!=null&&h.call(c,GB)),O=!!((f=(p=vt())==null?void 0:p.isTypeSupported)!=null&&f.call(p,WB));this._codecs={h264:T,h265:E,vp9:!!((g=(m=vt())==null?void 0:m.isTypeSupported)!=null&&g.call(m,Jv)),av1:!!((v=(S=vt())==null?void 0:S.isTypeSupported)!=null&&v.call(S,Zv)),aac:O,opus:!!((I=(y=vt())==null?void 0:y.isTypeSupported)!=null&&I.call(y,YB)),mpeg:(T||E)&&O},this._nativeHlsSupported=this._protocols.hls&&this._containers.mp4}catch(T){console.error(T)}try{this.destroyVideoElement()}catch(T){console.error("Error destroying video element:",T)}}destroyVideoElement(){var t;if(!this._video)return;if(this._video.pause(),this._video.currentTime=0,this._video.removeAttribute("src"),this._video.src="",this._video.load(),this._video.remove){this._video.remove(),this._video=null;return}this._video.parentNode&&this._video.parentNode.removeChild(this._video);let e=this._video.cloneNode(!1);(t=this._video.parentNode)==null||t.replaceChild(e,this._video),this._video=null}};var ty="audio/mpeg",uu=class{supportMp3(){return this._codecs.mp3&&this._containers.mpeg}detect(){var e,t,i,r;this._audio=document.createElement("audio");try{this._containers={mpeg:!!((t=(e=this._audio).canPlayType)!=null&&t.call(e,ty))},this._codecs={mp3:!!((r=(i=vt())==null?void 0:i.isTypeSupported)!=null&&r.call(i,ty))}}catch(a){console.error(a)}try{this.destroyAudioElement()}catch(a){console.error("Error destroying audio element:",a)}}destroyAudioElement(){var t;if(!this._audio)return;if(this._audio.pause(),this._audio.currentTime=0,this._audio.removeAttribute("src"),this._audio.src="",this._audio.load(),this._audio.remove){this._audio.remove(),this._audio=null;return}this._audio.parentNode&&this._audio.parentNode.removeChild(this._audio);let e=this._audio.cloneNode(!1);(t=this._audio.parentNode)==null||t.replaceChild(e,this._audio),this._audio=null}};import{ValueSubject as XB}from"@vkontakte/videoplayer-shared/es2018";var Vd=class{constructor(){this.isInited$=new XB(!1);this._displayChecker=new au,this._deviceChecker=new su(this._displayChecker),this._browserChecker=new ru,this._videoChecker=new ou(this._deviceChecker,this._browserChecker),this._audioChecker=new uu,this.detect()}get display(){return this._displayChecker}get device(){return this._deviceChecker}get browser(){return this._browserChecker}get video(){return this._videoChecker}get audio(){return this._audioChecker}async detect(){this._displayChecker.detect(),this._deviceChecker.detect(),this._browserChecker.detect(),this._videoChecker.detect(),this._audioChecker.detect(),this.isInited$.next(!0)}},j=new Vd;var st=s=>{let e=P=>Ye(s,P).pipe(_d(void 0)),t=new r$,i=()=>t.unsubscribe(),r=lu(Ye(s,"progress"),Ye(s,"timeupdate")).pipe(Gt(()=>Yv(s.buffered,s.currentTime))),a=j.browser.isSafari?ZB({play:e("play").pipe(e$()),playing:e("playing")}).pipe(_d(void 0)):e("playing"),n=Ye(s,"volumechange").pipe(Gt(()=>({muted:s.muted,volume:s.volume}))),o=Ye(s,"ratechange").pipe(Gt(()=>s.playbackRate)),u=Ye(s,"error").pipe(Od(()=>!!(s.error||s.played.length)),Gt(()=>{var C;let P=s.error;return{id:P?`MediaError#${P.code}`:"HtmlVideoError",category:i$.VIDEO_PIPELINE,message:P?P.message:"Error event from HTML video element",thrown:(C=s.error)!=null?C:void 0}})),l=Ye(s,"timeupdate").pipe(Gt(()=>s.currentTime)),d=["waiting","seeking","seeked","timeupdate"],c=new JB,h=.3,p;t.add(lu(...d.map(P=>Ye(s,P))).subscribe(P=>{let C=s.currentTime;s.loop&&ry(p)&&ry(C)&&p>=s.duration-h&&C<=h&&c.next(p),p=C}));let f=e("pause").pipe(Od(()=>!s.error&&p!==s.duration)),m=Ye(s,"enterpictureinpicture"),g=Ye(s,"leavepictureinpicture"),S=new sy(Wv(s));t.add(m.subscribe(()=>S.next(!0))),t.add(g.subscribe(()=>S.next(!1)));let v=new sy(Cd(s)),y=Ye(s,"fullscreenchange");t.add(y.pipe(Gt(()=>Cd(s))).subscribe(v));let I=.1,T=1e3,E=Ye(s,"timeupdate").pipe(Gt(P=>s.duration-s.currentTime<I),iy()),O=lu(E.pipe(Od(P=>!s.loop&&P)),Ye(s,"ended")).pipe(t$(T),_d(void 0)),w=lu(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(P=>Ye(s,P)),E.pipe(Gt(P=>({type:P?"ended":"unknown"})))).pipe(Gt(P=>j.browser.isFirefox&&P.type==="ended"?s.readyState<2:s.readyState<3),iy());return{playing$:a,pause$:f,canplay$:e("canplay"),ended$:O,looped$:c,error$:u,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:l,durationChange$:Ye(s,"durationchange").pipe(Gt(()=>s.duration)),isBuffering$:w,currentBuffer$:r,volumeState$:n,playbackRateState$:o,inPiP$:S,inFullscreen$:v,enterPip$:m,leavePip$:g,destroy:i}};import{VideoQuality as Li}from"@vkontakte/videoplayer-shared/es2018";var Bi=s=>{switch(s){case"mobile":return Li.Q_144P;case"lowest":return Li.Q_240P;case"low":return Li.Q_360P;case"sd":case"medium":return Li.Q_480P;case"hd":case"high":return Li.Q_720P;case"fullhd":case"full":return Li.Q_1080P;case"quadhd":case"quad":return Li.Q_1440P;case"ultrahd":case"ultra":return Li.Q_2160P}};var Xe=N(Ot(),1),Ud=N(gt(),1),ur=N(Ji(),1);import{isNonNullable as re,isNullable as fu,now as yy,isHigher as mu,isHigherOrEqual as jr,isInvariantQuality as bu,isLowerOrEqual as Hr,videoSizeToQuality as Ty,assertNotEmptyArray as gu,assertNonNullable as Iy}from"@vkontakte/videoplayer-shared/es2018";var Fd=!1,mi={},dy=s=>{Fd=s},py=()=>{mi={}},hy=s=>{s(mi)},ka=(s,e)=>{var t;Fd&&(mi.meta=(t=mi.meta)!=null?t:{},mi.meta[s]=e)},Ke=class{constructor(e){this.name=e}next(e){var i,r;if(!Fd)return;mi.series=(i=mi.series)!=null?i:{};let t=(r=mi.series[this.name])!=null?r:[];t.push([Date.now(),e]),mi.series[this.name]=t}};import{isHigher as p$,isHigherOrEqual as aq,isLower as fy,isLowerOrEqual as nq,isNonNullable as cu,isNullable as h$,videoHeightToQuality as du}from"@vkontakte/videoplayer-shared/es2018";function Nd(s,e,t){return!s.max&&s.min===e?"high_quality":!s.min&&s.max===t?"traffic_saving":"unknown"}function pu(s,e,t){return!!s&&Nd(s,e,t)==="high_quality"}function qr(s,e,t){return h$(s)||cu(s.min)&&cu(s.max)&&fy(s.max,s.min)||cu(s.min)&&e&&p$(s.min,e)||cu(s.max)&&t&&fy(s.max,t)}function my({limits:s,highestAvailableHeight:e,lowestAvailableHeight:t}){return qr({max:s!=null&&s.max?du(s.max):void 0,min:s!=null&&s.min?du(s.min):void 0},e?du(e):void 0,t?du(t):void 0)}var xy=new Ke("best_bitrate"),Su=(s,e,t)=>(e-t)*Math.pow(2,-10*s)+t;var zr=s=>(e,t)=>s*(Number(e.bitrate)-Number(t.bitrate)),$i=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=yy()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},vu='Assertion "ABR Tracks is empty array" failed',hu=new WeakMap,by=new WeakMap,gy=new WeakMap,Ra=(s,e,t,i)=>{var u;let r=[...e].sort(zr(1)),a=[...t].sort(zr(1)),n=a.filter(l=>re(l.bitrate)&&re(s.bitrate)?s.bitrate/l.bitrate>i:!0),o=(u=(0,Xe.default)(a,Math.round(a.length*r.indexOf(s)/(r.length+1))))!=null?u:(0,Xe.default)(a,-1);return o&&(0,Ud.default)(n,o)?o:n.length?(0,Xe.default)(n,-1):(0,Xe.default)(a,0)},Ma=(s,e,t,i)=>{var u;let r=hu.get(e);r||(r=[...e].sort(zr(1)),hu.set(e,r));let a=hu.get(t);a||(a=[...t].sort(zr(1)),hu.set(t,a));let n=gy.get(s);n||(n=a.filter(l=>re(l.bitrate)&&re(s.bitrate)?s.bitrate/l.bitrate>i:!0),gy.set(s,n));let o=(u=(0,Xe.default)(a,Math.round(a.length*r.indexOf(s)/(r.length+1))))!=null?u:(0,Xe.default)(a,-1);return o&&(0,Ud.default)(n,o)?o:n.length?(0,Xe.default)(n,-1):(0,Xe.default)(a,0)},Sy=s=>"quality"in s,yu=(s,e,t,i)=>{var n;let r=re((n=i==null?void 0:i.last)==null?void 0:n.bitrate)&&re(t==null?void 0:t.bitrate)&&i.last.bitrate<t.bitrate?s.trackCooldownIncreaseQuality:s.trackCooldownDecreaseQuality,a=t&&i&&i.history[t.id]&&yy()-i.history[t.id]<=r&&(!i.last||t.id!==i.last.id);if(t!=null&&t.id&&i&&!a&&i.recordSelection(t),a&&(i!=null&&i.last)){let o=i.last;i==null||i.recordSwitch(o);let u=Sy(o)?"video":"audio",l=Sy(o)?o.quality:o.bitrate;return e({message:`
8
8
  [last ${u} selected] ${l}
9
- `}),o}return i==null||i.recordSwitch(t),t},f$=(s,e)=>Math.log(e)/Math.log(s),Ey=({tuning:s,container:e,limits:t,panelSize:i})=>{let r=s.containerSizeFactor;if(i)return{containerSizeLimit:i,containerSizeFactor:r};if(s.usePixelRatio&&j.display.pixelRatio){let a=j.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=f$(n,o*a+u)+l;Number.isFinite(d)&&(r*=d)}}return pu(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}},vy=new WeakMap,Wt=(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:h,stallsPredictedThroughput:p,abrLogger:f,panelSize:m})=>{var k,Q,U,A,F;gu(s,vu);let{containerSizeFactor:g,containerSizeLimit:S}=Ey({container:e,tuning:i,limits:r,panelSize:m}),v=i.considerPlaybackRate&&re(o)?o:1,y=vy.get(s);y||(y=s.filter(R=>!bu(R.quality)).sort((R,x)=>mu(R.quality,x.quality)?-1:1),vy.set(s,y));let I=(k=(0,Xe.default)(y,-1))==null?void 0:k.quality,T=(Q=(0,Xe.default)(y,0))==null?void 0:Q.quality,E=qr(r,T,I),O=v*Su(n!=null?n:.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),L={},w=null;for(let R of y){let x=!0;if(S)if(R.size)x=R.size.width<=S.width&&R.size.height<=S.height;else{let Ve=S&&Ty(S);x=Ve?Hr(R.quality,Ve):!0}if(!x){L[R.quality]="FitsContainer";continue}let $=p||t,oe=re($)&&isFinite($)&&re(R.bitrate)?$-a>=R.bitrate*O:!0,Ce=pu(r,i.highQualityLimit,i.trafficSavingLimit)&&(r==null?void 0:r.min)===R.quality;if(!oe&&!Ce){L[R.quality]="FitsThroughput";continue}if(i.lazyQualitySwitch&&re(i.minBufferToSwitchUp)&&u&&!bu(u.quality)&&(n!=null?n:0)<i.minBufferToSwitchUp&&mu(R.quality,u.quality)){L[R.quality]="Buffer";continue}if(!!c&&jr(R.quality,c)&&!Ce){L[R.quality]="DroppedFramesLimit";continue}if(!!h&&jr(R.quality,h)&&!Ce){L[R.quality]="StallsLimit";continue}let Te=E||(fu(r==null?void 0:r.max)||Hr(R.quality,r.max))&&(fu(r==null?void 0:r.min)||jr(R.quality,r.min)),Ie=re(d)&&!d?Hr(R.quality,i.backgroundVideoQualityLimit):!0;if(!Te||!Ie){L[R.quality]="FitsQualityLimits";continue}w||(w=R)}w&&w.bitrate&&xy.next(w.bitrate);let P=(U=w!=null?w:(0,Xe.default)(y,-1))!=null?U:s[0],C=l==null?void 0:l.last,M=yu(i,f,P,l);return re(l)&&M.quality!==(C==null?void 0:C.quality)&&f({message:`
9
+ `}),o}return i==null||i.recordSwitch(t),t},f$=(s,e)=>Math.log(e)/Math.log(s),Ey=({tuning:s,container:e,limits:t,panelSize:i})=>{let r=s.containerSizeFactor;if(i)return{containerSizeLimit:i,containerSizeFactor:r};if(s.usePixelRatio&&j.display.pixelRatio){let a=j.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=f$(n,o*a+u)+l;Number.isFinite(d)&&(r*=d)}}return pu(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}},vy=new WeakMap,Wt=(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:h,stallsPredictedThroughput:p,abrLogger:f,panelSize:m})=>{var R,Q,U,A,F;gu(s,vu);let{containerSizeFactor:g,containerSizeLimit:S}=Ey({container:e,tuning:i,limits:r,panelSize:m}),v=i.considerPlaybackRate&&re(o)?o:1,y=vy.get(s);y||(y=s.filter(k=>!bu(k.quality)).sort((k,x)=>mu(k.quality,x.quality)?-1:1),vy.set(s,y));let I=(R=(0,Xe.default)(y,-1))==null?void 0:R.quality,T=(Q=(0,Xe.default)(y,0))==null?void 0:Q.quality,E=qr(r,T,I),O=v*Su(n!=null?n:.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),L={},w=null;for(let k of y){let x=!0;if(S)if(k.size)x=k.size.width<=S.width&&k.size.height<=S.height;else{let Ve=S&&Ty(S);x=Ve?Hr(k.quality,Ve):!0}if(!x){L[k.quality]="FitsContainer";continue}let $=p||t,oe=re($)&&isFinite($)&&re(k.bitrate)?$-a>=k.bitrate*O:!0,Ce=pu(r,i.highQualityLimit,i.trafficSavingLimit)&&(r==null?void 0:r.min)===k.quality;if(!oe&&!Ce){L[k.quality]="FitsThroughput";continue}if(i.lazyQualitySwitch&&re(i.minBufferToSwitchUp)&&u&&!bu(u.quality)&&(n!=null?n:0)<i.minBufferToSwitchUp&&mu(k.quality,u.quality)){L[k.quality]="Buffer";continue}if(!!c&&jr(k.quality,c)&&!Ce){L[k.quality]="DroppedFramesLimit";continue}if(!!h&&jr(k.quality,h)&&!Ce){L[k.quality]="StallsLimit";continue}let Te=E||(fu(r==null?void 0:r.max)||Hr(k.quality,r.max))&&(fu(r==null?void 0:r.min)||jr(k.quality,r.min)),Ie=re(d)&&!d?Hr(k.quality,i.backgroundVideoQualityLimit):!0;if(!Te||!Ie){L[k.quality]="FitsQualityLimits";continue}w||(w=k)}w&&w.bitrate&&xy.next(w.bitrate);let P=(U=w!=null?w:(0,Xe.default)(y,-1))!=null?U:s[0],C=l==null?void 0:l.last,M=yu(i,f,P,l);return re(l)&&M.quality!==(C==null?void 0:C.quality)&&f({message:`
10
10
  [VIDEO TRACKS ABR]
11
11
  [available video tracks]
12
- ${s.map(R=>{var x,$;return`{ id: ${R.id}, quality: ${R.quality}, bitrate: ${R.bitrate}, size: ${(x=R.size)==null?void 0:x.width}:${($=R.size)==null?void 0:$.height} }`}).join(`
12
+ ${s.map(k=>{var x,$;return`{ id: ${k.id}, quality: ${k.quality}, bitrate: ${k.bitrate}, size: ${(x=k.size)==null?void 0:x.width}:${($=k.size)==null?void 0:$.height} }`}).join(`
13
13
  `)}
14
14
 
15
15
  [tuning]
16
- ${(0,ur.default)(i!=null?i:{}).map(([R,x])=>`${R}: ${x}`).join(`
16
+ ${(0,ur.default)(i!=null?i:{}).map(([k,x])=>`${k}: ${x}`).join(`
17
17
  `)}
18
18
 
19
19
  [limit params]
@@ -34,12 +34,12 @@ var LE=Object.create;var Lh=Object.defineProperty;var BE=Object.getOwnPropertyDe
34
34
  minQualityLimit: ${r==null?void 0:r.min},
35
35
 
36
36
  [limited video tracks]
37
- ${(0,ur.default)(L).map(([R,x])=>`${R}: ${x}`).join(`
37
+ ${(0,ur.default)(L).map(([k,x])=>`${k}: ${x}`).join(`
38
38
  `)||"All tracks are available"}
39
39
 
40
40
  [best video track] ${w==null?void 0:w.quality}
41
41
  [selected video track] ${M==null?void 0:M.quality}
42
- `}),M},Tu=(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:h,stallsPredictedThroughput:p,abrLogger:f,panelSize:m})=>{var Q,U,A,F,R;gu(s,vu);let{containerSizeFactor:g,containerSizeLimit:S}=Ey({container:e,tuning:i,limits:r,panelSize:m}),v=i.considerPlaybackRate&&re(o)?o:1,y=s.filter(x=>!bu(x.quality)).sort((x,$)=>mu(x.quality,$.quality)?-1:1),I=(Q=(0,Xe.default)(y,-1))==null?void 0:Q.quality,T=(U=(0,Xe.default)(y,0))==null?void 0:U.quality,E=qr(r,T,I),O=v*Su(n!=null?n:.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),L={},P=y.filter(x=>{let $=!0;if(S)if(x.size)$=x.size.width<=S.width&&x.size.height<=S.height;else{let Tt=S&&Ty(S);$=Tt?Hr(x.quality,Tt):!0}if(!$)return L[x.quality]="FitsContainer",!1;let oe=p||t,Ce=re(oe)&&isFinite(oe)&&re(x.bitrate)?oe-a>=x.bitrate*O:!0,se=pu(r,i.highQualityLimit,i.trafficSavingLimit)&&(r==null?void 0:r.min)===x.quality;if(!Ce&&!se)return L[x.quality]="FitsThroughput",!1;if(i.lazyQualitySwitch&&re(i.minBufferToSwitchUp)&&u&&!bu(u.quality)&&(n!=null?n:0)<i.minBufferToSwitchUp&&mu(x.quality,u.quality))return L[x.quality]="Buffer",!1;if(!!c&&jr(x.quality,c)&&!se)return L[x.quality]="DroppedFramesLimit",!1;if(!!h&&jr(x.quality,h)&&!se)return L[x.quality]="StallsLimit",!1;let Ie=E||(fu(r==null?void 0:r.max)||Hr(x.quality,r.max))&&(fu(r==null?void 0:r.min)||jr(x.quality,r.min)),Ve=re(d)&&!d?Hr(x.quality,i.backgroundVideoQualityLimit):!0;return!Ie||!Ve?(L[x.quality]="FitsQualityLimits",!1):!0})[0];P&&P.bitrate&&xy.next(P.bitrate);let C=(A=P!=null?P:(0,Xe.default)(y,-1))!=null?A:s[0],M=l==null?void 0:l.last,k=yu(i,f,C,l);return re(l)&&k.quality!==(M==null?void 0:M.quality)&&f({message:`
42
+ `}),M},Tu=(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:h,stallsPredictedThroughput:p,abrLogger:f,panelSize:m})=>{var Q,U,A,F,k;gu(s,vu);let{containerSizeFactor:g,containerSizeLimit:S}=Ey({container:e,tuning:i,limits:r,panelSize:m}),v=i.considerPlaybackRate&&re(o)?o:1,y=s.filter(x=>!bu(x.quality)).sort((x,$)=>mu(x.quality,$.quality)?-1:1),I=(Q=(0,Xe.default)(y,-1))==null?void 0:Q.quality,T=(U=(0,Xe.default)(y,0))==null?void 0:U.quality,E=qr(r,T,I),O=v*Su(n!=null?n:.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),L={},P=y.filter(x=>{let $=!0;if(S)if(x.size)$=x.size.width<=S.width&&x.size.height<=S.height;else{let Tt=S&&Ty(S);$=Tt?Hr(x.quality,Tt):!0}if(!$)return L[x.quality]="FitsContainer",!1;let oe=p||t,Ce=re(oe)&&isFinite(oe)&&re(x.bitrate)?oe-a>=x.bitrate*O:!0,se=pu(r,i.highQualityLimit,i.trafficSavingLimit)&&(r==null?void 0:r.min)===x.quality;if(!Ce&&!se)return L[x.quality]="FitsThroughput",!1;if(i.lazyQualitySwitch&&re(i.minBufferToSwitchUp)&&u&&!bu(u.quality)&&(n!=null?n:0)<i.minBufferToSwitchUp&&mu(x.quality,u.quality))return L[x.quality]="Buffer",!1;if(!!c&&jr(x.quality,c)&&!se)return L[x.quality]="DroppedFramesLimit",!1;if(!!h&&jr(x.quality,h)&&!se)return L[x.quality]="StallsLimit",!1;let Ie=E||(fu(r==null?void 0:r.max)||Hr(x.quality,r.max))&&(fu(r==null?void 0:r.min)||jr(x.quality,r.min)),Ve=re(d)&&!d?Hr(x.quality,i.backgroundVideoQualityLimit):!0;return!Ie||!Ve?(L[x.quality]="FitsQualityLimits",!1):!0})[0];P&&P.bitrate&&xy.next(P.bitrate);let C=(A=P!=null?P:(0,Xe.default)(y,-1))!=null?A:s[0],M=l==null?void 0:l.last,R=yu(i,f,C,l);return re(l)&&R.quality!==(M==null?void 0:M.quality)&&f({message:`
43
43
  [VIDEO TRACKS ABR]
44
44
  [available video tracks]
45
45
  ${s.map(x=>{var $,oe;return`{ id: ${x.id}, quality: ${x.quality}, bitrate: ${x.bitrate}, size: ${($=x.size)==null?void 0:$.width}:${(oe=x.size)==null?void 0:oe.height} }`}).join(`
@@ -51,7 +51,7 @@ var LE=Object.create;var Lh=Object.defineProperty;var BE=Object.getOwnPropertyDe
51
51
 
52
52
  [limit params]
53
53
  containerSizeFactor: ${g},
54
- containerSizeLimit: ${(F=S==null?void 0:S.width)!=null?F:0} x ${(R=S==null?void 0:S.height)!=null?R:0},
54
+ containerSizeLimit: ${(F=S==null?void 0:S.width)!=null?F:0} x ${(k=S==null?void 0:S.height)!=null?k:0},
55
55
  estimatedThroughput: ${t},
56
56
  stallsPredictedThroughput: ${p},
57
57
  reserve: ${a},
@@ -71,8 +71,8 @@ var LE=Object.create;var Lh=Object.defineProperty;var BE=Object.getOwnPropertyDe
71
71
  `)||"All tracks are available"}
72
72
 
73
73
  [best video track] ${P==null?void 0:P.quality}
74
- [selected video track] ${k==null?void 0:k.quality}
75
- `}),k},Iu=(s,e,t,{estimatedThroughput:i,tuning:r,playbackRate:a,forwardBufferHealth:n,history:o,abrLogger:u,stallsPredictedThroughput:l})=>{gu(t,vu);let d=r.considerPlaybackRate&&re(a)?a:1,c=[...t].sort(zr(-1)),h=s.bitrate;Iy(h);let p=d*Su(n!=null?n:.5,r.bitrateAudioFactorAtEmptyBuffer,r.bitrateAudioFactorAtFullBuffer),f,m=ka(s,e,t,r.minVideoAudioRatio),g=l||i;re(g)&&isFinite(g)&&(f=c.find(y=>re(y.bitrate)&&re(m==null?void 0:m.bitrate)?g-h>=y.bitrate*p&&y.bitrate>=m.bitrate:!1)),f||(f=m);let S=o==null?void 0:o.last,v=f&&yu(r,u,f,o);return re(o)&&(v==null?void 0:v.bitrate)!==(S==null?void 0:S.bitrate)&&u({message:`
74
+ [selected video track] ${R==null?void 0:R.quality}
75
+ `}),R},Iu=(s,e,t,{estimatedThroughput:i,tuning:r,playbackRate:a,forwardBufferHealth:n,history:o,abrLogger:u,stallsPredictedThroughput:l})=>{gu(t,vu);let d=r.considerPlaybackRate&&re(a)?a:1,c=[...t].sort(zr(-1)),h=s.bitrate;Iy(h);let p=d*Su(n!=null?n:.5,r.bitrateAudioFactorAtEmptyBuffer,r.bitrateAudioFactorAtFullBuffer),f,m=Ra(s,e,t,r.minVideoAudioRatio),g=l||i;re(g)&&isFinite(g)&&(f=c.find(y=>re(y.bitrate)&&re(m==null?void 0:m.bitrate)?g-h>=y.bitrate*p&&y.bitrate>=m.bitrate:!1)),f||(f=m);let S=o==null?void 0:o.last,v=f&&yu(r,u,f,o);return re(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(`
@@ -114,14 +114,14 @@ var LE=Object.create;var Lh=Object.defineProperty;var BE=Object.getOwnPropertyDe
114
114
  minBufferToSwitchUp: ${r.minBufferToSwitchUp},
115
115
 
116
116
  [selected audio track] ${v==null?void 0:v.id}
117
- `}),v};var Fe=s=>new URL(s).hostname;import{assertNever as Cy,assertNonNullable as Vy,combine as C$,debounce as V$,ErrorCategory as Oy,filter as _y,filterChanged as O$,isNonNullable as Qd,map as Pu,merge as Fy,observableFrom as _$,once as F$,Subscription as N$,ValueSubject as Gd,videoQualityToHeight as Ny,videoSizeToQuality as U$}from"@vkontakte/videoplayer-shared/es2018";var Ly=N(Ot(),1);var Ay=N(gt(),1),wy=s=>{if(s instanceof DOMException&&(0,Ay.default)(["Failed to load because no supported source was found.","The element has no supported sources."],s.message))throw s;return!(s instanceof DOMException&&(s.code===20||s.name==="AbortError"))},at=async(s,e)=>{let t=s.muted;try{await s.play()}catch(i){if(!wy(i))return!1;if(e&&e(),t)return console.warn(i),!1;s.muted=!0;try{await s.play()}catch(r){return wy(r)&&(s.muted=!1,console.warn(r)),!1}}return!0};import{isNonNullable as wu,isNullable as g$,assertNonNullable as $a}from"@vkontakte/videoplayer-shared/es2018";var Ry=N(nr(),1);import{isNonNullable as Py,assertNonNullable as Eu,now as m$}from"@vkontakte/videoplayer-shared/es2018";function Be(){return m$()}function qd(s){return Be()-s}function jd(s){let e=s.split("/"),t=e.slice(0,e.length-1).join("/"),i=/^([a-z]+:)?\/\//i,r=n=>i.test(n);return{resolve:(n,o,u=!1)=>{r(n)||(n.startsWith("/")||(n="/"+n),n=t+n);let l=n.indexOf("?")>-1?"&":"?";return u&&(n+=l+"lowLat=1",l="&"),o&&(n+=l+"_rnd="+Math.floor(999999999*Math.random())),n}}}function ky(s,e,t){let i=(...r)=>{t.apply(null,r),s.removeEventListener(e,i)};s.addEventListener(e,i)}function Qr(s,e,t,i){let r=window.XMLHttpRequest,a,n,o,u=!1,l=0,d,c,h=!1,p="arraybuffer",f=7e3,m=2e3,g=()=>{if(u)return;Eu(d);let M=qd(d),k;if(M<m){k=m-M,setTimeout(g,k);return}m*=2,m>f&&(m=f),n&&n.abort(),n=new r,E()},S=M=>(a=M,C),v=M=>(c=M,C),y=()=>(p="json",C),I=()=>{if(!u){if(--l>=0){g(),i&&i();return}u=!0,c&&c(),t&&t()}},T=M=>(h=M,C),E=()=>{d=Be(),n=new r,n.open("get",s);let M=0,k,Q=0,U=()=>(Eu(d),Math.max(d,Math.max(k||0,Q||0)));if(a&&n.addEventListener("progress",A=>{let F=Be();a.updateChunk&&A.loaded>M&&(a.updateChunk(U(),A.loaded-M),M=A.loaded,k=F)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>I())),n.addEventListener("load",()=>{if(u)return;Eu(n);let A=n.status;if(A>=200&&A<300){let{response:F,responseType:R}=n,x=F==null?void 0:F.byteLength;if(typeof x=="number"&&a){let $=x-M;$&&a.updateChunk&&a.updateChunk(U(),$)}R==="json"&&(!F||!(0,Ry.default)(F).length)?I():(c&&c(),e(F))}else I()}),n.addEventListener("error",()=>{I()}),h){let A=()=>{Eu(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(Q=Be(),n.removeEventListener("readystatechange",A))};n.addEventListener("readystatechange",A)}return n.responseType=p,n.send(),C},C={withBitrateReporting:S,withParallel:T,withJSONResponse:y,withRetryCount:M=>(l=M,C),withRetryInterval:(M,k)=>(Py(M)&&(m=M),Py(k)&&(f=k),C),withTimeout:M=>(o=M,C),withFinally:v,send:E,abort:()=>{n&&(n.abort(),n=void 0),u=!0,c&&c()}};return C}var La=class{constructor(e){this.intervals=[];this.currentRate=0;this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,i){return{start:e,end:t,bytes:i}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;let e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-500;if(t-e>2e3){let i=0,r=0;for(;this.intervals.length>0;){let a=this.intervals[0];if(a.end<=t)i+=a.end-a.start,r+=a.bytes,this.intervals.splice(0,1);else{if(a.start>=t)break;{let n=t-a.start,o=a.end-a.start;i+=n;let u=a.bytes*n/o;r+=u,a.start=t,a.bytes-=u}}}if(r>0&&i>0){let a=r*8/(i/1e3);return this._updateRate(a),this.logger(`rate updated, new=${Math.round(a/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(r)}/${Math.round(i)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,i){return this.intervals.push(this._createInterval(e,t,i)),this._joinIntervals(),this.intervals.length>100&&(this.logger(`too many intervals (${this.intervals.length}); will merge`,{type:"warn"}),this._doMergeIntervals(this.intervals[1],this.intervals[0]),this.intervals.splice(0,1)),this._flushIntervals()}getBitRate(){return this.currentRate}};var My=N(nr(),1);var Ba=class{constructor(e,t,i,r,a){this.pendingQueue=[];this.activeRequests={};this.completeRequests={};this.averageSegmentDuration=2e3;this.lastPrefetchStart=0;this.throttleTimeout=null;this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=i,this.MAX_PARALLEL_REQUESTS=r,this.logger=a}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){let t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){let i=Be(),r=u=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=u,e._errorCB?e._errorCB(u):(this.limitCompleteCount(),this.completeRequests[t]=e)},a=u=>{e._complete=1,e._responseData=u,e._downloadTime=Be()-i,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(u,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=Qr(t,a,()=>r("error"),o),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(n),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=Be()}_getParallelRequestCount(){return Math.min(this.MAX_PARALLEL_REQUESTS,this.averageSegmentDuration<3e3?3:2)}_getPrefetchDelay(){return Math.max(100,Math.min(5e3,this.averageSegmentDuration/3))}_canSendPending(){let e=this._getParallelRequestCount(),t=Be();if(Object.keys(this.activeRequests).length>=e)return!1;let i=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),i>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),i),!1):!0}_sendPending(){for(;this._canSendPending();){let e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){(0,My.default)(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,i,r){let a={};return a.send=()=>{let n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=i,n._retryCB=r,n._finallyCB=a._finallyCB,n._error||n._complete?(this._removeFromActive(e),setTimeout(()=>{n._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(n._responseData,n._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),i(n._errorMsg)),a._finallyCB&&a._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{let o=this.pendingQueue.indexOf(e);o!==-1&&this.pendingQueue.splice(o,1),this.logger(`Request not prefetched, starting new request, url=${e}${o===-1?"":"; removed pending"}`),this._sendRequest(a,e)}},a._cb=t,a._errorCB=i,a._retryCB=r,a.abort=function(){a.request&&a.request.abort()},a.withFinally=n=>(a._finallyCB=n,a),a}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}};import{Subject as S$}from"@vkontakte/videoplayer-shared/es2018";var Au=1e4,Hd=3;var v$=6e4,y$=10,T$=1,I$=500,Da=class{constructor(e){this.paused=!1;this.autoQuality=!0;this.autoQualityLimits=void 0;this.buffering=!0;this.destroyed=!1;this.videoPlayStarted=!1;this.lowLatency=!1;this.bitrate=0;this.manifest=[];this.sourceBuffer=0;this.bufferStates=[];this.sourceJitter=-1;this.waitingForFirstBufferAfterSrcChange=!1;this.params=e,this.soundProhibitedEvent$=new S$,this.chunkRateEstimator=new La(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=jd(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setAutoQualityLimits(e){this.autoQualityLimits=e}switchByName(e){let t;for(let i=0;i<this.manifest.length;++i)if(t=this.manifest[i],t.name===e){this._switchToQuality(t);return}}catchUp(){if(this.rep&&this.rep.stop(),this.currentManifestEntry){let e=this.params.playbackState.getState();this.paused=e==="paused",this._initPlayerWith(this.currentManifestEntry),this._notifyBuffering(!0)}}stop(){this.params.videoElement.pause(),this.rep&&(this.rep.stop(),this.rep=null)}pause(){this.paused=!0,this.params.videoElement.pause(),this.videoPlayStarted=!1,this._notifyBuffering(!1)}play(){this.paused=!1;let e=this.lowLatency&&this._getBufferSizeSec()>this.sourceJitter+5;this.rep&&!e?(this.bufferStates=[],this.videoPlayStarted=!1,this.shouldPlay()?this._playVideoElement():this._notifyBuffering(!0)):this.catchUp()}startPlay(e,t){this.autoQuality=t,this._initPlayerWith(e)}destroy(){this.destroyed=!0,this.rep&&(this.rep.stop(),this.rep=null),this.manifestRequest&&this.manifestRequest.abort(),this.manifestRefetchTimer&&(clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=void 0)}reinit(e){this.manifestUrl=e,this.urlResolver=jd(e),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){let e=this.params.videoElement,t=0,i=e.buffered.length;return i!==0&&(t=e.buffered.end(i-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){let{videoElement:e,logger:t}=this.params;e.addEventListener("error",()=>{var r,a;!!e.error&&!this.destroyed&&(t(`Video element error: ${(r=e.error)==null?void 0:r.code}, details: ${(a=e.error)==null?void 0:a.message}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{let i=this._getBufferSizeSec();!this.paused&&i<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(i+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){let{logger:e,videoElement:t}=this.params,i=t.buffered.length,r;i!==0&&!this.waitingForFirstBufferAfterSrcChange&&(r=t.buffered.start(i-1),t.currentTime<r&&(e("Fixup stall"),t.currentTime=r))}_selectQuality(e){let{videoElement:t}=this.params,i,r,a,n=t&&1.62*(j.display.pixelRatio||1)*t.offsetHeight||520;for(let o=0;o<this.manifest.length;++o){a=this.manifest[o];let{max:u,min:l}=this.autoQualityLimits||{};!my({limits:this.autoQualityLimits,highestAvailableHeight:this.manifest[0].video.height,lowestAvailableHeight:(0,Ly.default)(this.manifest,-1).video.height})&&(u&&a.video.height>u||l&&a.video.height<l)||(a.bitrate<e&&n>Math.min(a.video.height,a.video.width)?(!r||a.bitrate>r.bitrate)&&(r=a):(!i||i.bitrate>a.bitrate)&&(i=a))}return r||i}shouldPlay(){if(this.paused)return!1;let t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||wu(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){let{logger:i,videoElement:r,playerCallback:a}=this.params;this.mediaSource=new window.MediaSource,i("setting video src"),r.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,r.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});let n=()=>{ky(r,"progress",()=>{r.buffered.length?(r.currentTime=r.buffered.start(0),this.waitingForFirstBufferAfterSrcChange=!1,a({name:"playing"})):n()})};this.waitingForFirstBufferAfterSrcChange=!0,n()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new Ba(Hd,Au,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:i,playerCallback:r}=this.params,a=!1,n=null,o=null,u=null,l=null,d=!1,c=()=>{let I=a&&(!d||d===this.rep);return I||t("Not running!"),I},h=(I,T,E)=>{u&&u.abort(),u=Qr(this.urlResolver.resolve(I,!1),T,E,()=>this._retryCallback()).withTimeout(Au).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Hd).withFinally(()=>{u=null}).send()},p=(I,T,E)=>{$a(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(I,!1),T,E,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},f=I=>{let T=i.playbackRate;i.playbackRate!==I&&(t(`Playback rate switch: ${T}=>${I}`),i.playbackRate=I)},m=I=>{this.lowLatency=I,t(`lowLatency changed to ${I}`),g()},g=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)f(1);else{let I=this._getBufferSizeSec();if(this.bufferStates.length<5){f(1);return}let E=Be()-1e4,O=0;for(let w=0;w<this.bufferStates.length;w++){let P=this.bufferStates[w];I=Math.min(I,P.buf),P.ts<E&&O++}this.bufferStates.splice(0,O),t(`update playback rate; minBuffer=${I} drop=${O} jitter=${this.sourceJitter}`);let L=I-T$;this.sourceJitter>=0?L-=this.sourceJitter/2:this.sourceJitter-=1,L>3?f(1.15):L>1?f(1.1):L>.3?f(1.05):f(1)}},S=I=>{let T,E=()=>T&&T.start?T.start.length:0,O=A=>T.start[A]/1e3,L=A=>T.dur[A]/1e3,w=A=>T.fragIndex+A,P=(A,F)=>({chunkIdx:w(A),startTS:O(A),dur:L(A),discontinuity:F}),C=()=>{let A=0;if(T&&T.dur){let F=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,R=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,x=F;this.sourceJitter>1&&(x+=this.sourceJitter-1);let $=T.dur.length-1;for(;$>=0&&(x-=T.dur[$],!(x<=0));--$);A=Math.min($,T.dur.length-1-R),A=Math.max(A,0)}return P(A,!0)},M=A=>{let F=E();if(!(F<=0)){if(wu(A)){for(let R=0;R<F;R++)if(O(R)>A)return P(R)}return C()}},k=A=>{let F=E(),R=A?A.chunkIdx+1:0,x=R-T.fragIndex;if(!(F<=0)){if(!A||x<0||x-F>y$)return t(`Resync: offset=${x} bChunks=${F} chunk=`+JSON.stringify(A)),C();if(!(x>=F))return P(R-T.fragIndex,!1)}},Q=(A,F,R)=>{l&&l.abort(),l=Qr(this.urlResolver.resolve(A,!0,this.lowLatency),F,R,()=>this._retryCallback()).withTimeout(Au).withRetryCount(Hd).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(A,F)=>{Q(I,R=>{if(!c())return;T=R;let x=!!T.lowLatency;x!==this.lowLatency&&m(x);let $=0;for(let oe=0;oe<T.dur.length;++oe)$+=T.dur[oe];$>0&&($a(this.filesFetcher),this.filesFetcher.optimizeForSegDuration($/T.dur.length)),r({name:"index",zeroTime:T.zeroTime,shiftDuration:T.shiftDuration}),this.sourceJitter=T.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,T.jitter/1e3)):1,A(M(F))},()=>this._handleNetworkError())},nextChunk:k}},v=()=>{a=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),$a(this.filesFetcher),this.filesFetcher.abortAll()};return d={start:I=>{let{videoElement:T,logger:E}=this.params,O=S(e.jidxUrl),L,w,P,C,M=0,k,Q,U,A=()=>{k&&(clearTimeout(k),k=void 0);let K=Math.max(I$,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),ye=M+K,Te=Be(),Ie=Math.min(1e4,ye-Te);M=Te;let Ve=()=>{l||c()&&O.seek(()=>{c()&&(M=Be(),F(),A())})};Ie>0?k=window.setTimeout(()=>{this.paused?A():Ve()},Ie):Ve()},F=()=>{let K;for(;K=O.nextChunk(C);)C=K,Ce(K);let ye=O.nextChunk(P);if(ye){if(P&&ye.discontinuity){E("Detected discontinuity; restarting playback"),this.paused?A():(v(),this._initPlayerWith(e));return}oe(ye)}else A()},R=(K,ye)=>{if(!c()||!this.sourceBuffer)return;let Te,Ie,Ve,Tt=At=>{window.setTimeout(()=>{c()&&R(K,ye)},At)};if(this.sourceBuffer.updating)E("Source buffer is updating; delaying appendBuffer"),Tt(100);else{let At=Be(),qt=T.currentTime;!this.paused&&T.buffered.length>1&&Q===qt&&At-U>500&&(E("Stall suspected; trying to fix"),this._fixupStall()),Q!==qt&&(Q=qt,U=At);let Xt=this._getBufferSizeSec();if(Xt>30)E(`Buffered ${Xt} seconds; delaying appendBuffer`),Tt(2e3);else try{this.sourceBuffer.appendBuffer(K),this.videoPlayStarted?(this.bufferStates.push({ts:At,buf:Xt}),g(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),ye&&ye()}catch(Ai){if(Ai.name==="QuotaExceededError")E("QuotaExceededError; delaying appendBuffer"),Ve=this.sourceBuffer.buffered.length,Ve!==0&&(Te=this.sourceBuffer.buffered.start(0),Ie=qt,Ie-Te>4&&this.sourceBuffer.remove(Te,Ie-3)),Tt(1e3);else throw Ai}}},x=()=>{w&&L&&(E([`Appending chunk, sz=${w.byteLength}:`,JSON.stringify(P)]),R(w,function(){w=null,F()}))},$=K=>e.fragUrlTemplate.replace("%%id%%",K.chunkIdx),oe=K=>{c()&&p($(K),(ye,Te)=>{if(c()){if(Te/=1e3,w=ye,P=K,n=K.startTS,Te){let Ie=Math.min(10,K.dur/Te);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*Ie:Ie}x()}},()=>this._handleNetworkError())},Ce=K=>{c()&&($a(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve($(K),!1)))},se=K=>{c()&&(e.cachedHeader=K,R(K,()=>{L=!0,x()}))};a=!0,O.seek(K=>{if(c()){if(M=Be(),!K){A();return}C=K,!g$(I)||K.startTS>I?oe(K):(P=K,F())}},I),e.cachedHeader?se(e.cachedHeader):h(e.headerUrl,se,()=>this._handleNetworkError())},stop:v,getTimestampSec:()=>n},d}_switchToQuality(e){let{logger:t,playerCallback:i}=this.params,r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),wu(r)&&(r+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,$a(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return wu(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,i=c=>{if(!this.autoQuality)return;let h,p,f;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&c<this.bitrate&&(p=this._getBufferSizeSec(),f=c/this.bitrate,p>10&&f>.8||p>15&&f>.5||p>20&&f>.3)){e(`Not switching: buffer=${Math.floor(p)}; bitrate=${this.bitrate}; newRate=${Math.floor(c)}`);return}h=this._selectQuality(c),h?this._switchToQuality(h):e(`Could not find quality by bitrate ${c}`)},a={updateChunk:(h,p)=>{let f=Be();if(this.chunkRateEstimator.addInterval(h,f,p)){let g=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:p,duration:f-h,speed:g}),!0}},get:()=>{let h=this.chunkRateEstimator.getBitRate();return h?h*.85:0}},n=-1/0,o,u=!0,l=()=>{let c=a.get();if(c&&o&&this.autoQuality){if(u&&c>o&&qd(n)<3e4)return;i(c)}u=this.autoQuality};return{updateChunk:(c,h)=>{let p=a.updateChunk(c,h);return p&&l(),p},notifySwitch:c=>{let h=Be();c<o&&(n=h),o=c}}}_fetchManifest(e,t,i){this.manifestRequest=Qr(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(Au).withRetryCount(this.params.config.manifestRetryMaxCount).withRetryInterval(this.params.config.manifestRetryInterval,this.params.config.manifestRetryMaxInterval).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(){let{videoElement:e}=this.params;at(e,()=>{this.soundProhibitedEvent$.next()}).then(t=>{t||(this.params.liveOffset.pause(),this.params.videoState.setState("paused"))})}_handleManifestUpdate(e){let{logger:t,playerCallback:i,videoElement:r}=this.params,a=n=>{let o=[];return n!=null&&n.length?(n.forEach((u,l)=>{var d,c;u.video&&r.canPlayType(u.codecs).replace(/no/,"")&&((c=(d=window.MediaSource)==null?void 0:d.isTypeSupported)!=null&&c.call(d,u.codecs))&&(u.index=l,o.push(u))}),o.sort(function(u,l){return u.video&&l.video?l.video.height-u.video.height:l.bitrate-u.bitrate}),o):(i({name:"error",type:"empty_manifest"}),[])};this.manifest=a(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),i({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},v$))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var Dy=N(Ji(),1);import{debounce as x$,filter as By,fromEvent as E$,interval as w$,isHigher as A$,isInvariantQuality as P$,isLower as R$,merge as k$,Subject as $y,Subscription as M$}from"@vkontakte/videoplayer-shared/es2018";var zd=class{constructor(){this.onDroopedVideoFramesLimit$=new $y;this.subscription=new M$;this.playing=!1;this.tracks=[];this.forceChecker$=new $y;this.isForceCheckCounter=0;this.prevTotalVideoFrames=0;this.prevDroppedVideoFrames=0;this.limitCounts={};this.handleChangeVideoQuality=()=>{let e=this.tracks.find(({size:t})=>(t==null?void 0:t.height)===this.video.videoHeight&&(t==null?void 0:t.width)===this.video.videoWidth);e&&!P$(e.quality)&&this.onChangeQuality(e.quality)};this.checkDroppedFrames=()=>{var n;let{totalVideoFrames:e,droppedVideoFrames:t}=this.video.getVideoPlaybackQuality(),i=e-this.prevTotalVideoFrames,r=t-this.prevDroppedVideoFrames,a=1-(i-r)/i;!isNaN(a)&&a>0&&this.log({message:`[dropped]. current dropped percent: ${a}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(a)&&a>=this.droppedFramesChecker.percentLimit&&A$(this.currentQuality,this.droppedFramesChecker.minQualityBanLimit)&&(this.limitCounts[this.currentQuality]=((n=this.limitCounts[this.currentQuality])!=null?n:0)+1,this.maxQualityLimit=this.getMaxQualityLimit(this.currentQuality),this.currentTimer&&window.clearTimeout(this.currentTimer),this.currentTimer=window.setTimeout(()=>this.maxQualityLimit=this.getMaxQualityLimit(),this.droppedFramesChecker.qualityUpWaitingTime),this.onDroopedVideoFramesLimitTrigger()),this.savePrevFrameCounts(e,t)}}connect(e){this.log=e.logger.createComponentLog("DroppedFramesManager"),this.video=e.video,this.isAuto=e.isAuto,this.tracks=e.tracks,this.droppedFramesChecker=e.droppedFramesChecker,this.subscription.add(e.playing$.subscribe(()=>this.playing=!0)),this.subscription.add(e.pause$.subscribe(()=>this.playing=!1)),this.isEnabled&&this.subscribe()}destroy(){this.currentTimer&&window.clearTimeout(this.currentTimer),this.subscription.unsubscribe()}get droppedVideoMaxQualityLimit(){return this.maxQualityLimit}subscribe(){this.subscription.add(E$(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=w$(this.droppedFramesChecker.checkTime).pipe(By(()=>this.playing),By(()=>{let r=!!this.isForceCheckCounter;return r&&(this.isForceCheckCounter-=1),!r})),t=this.forceChecker$.pipe(x$(this.droppedFramesChecker.checkTime)),i=k$(e,t);this.subscription.add(i.subscribe(this.checkDroppedFrames))}onChangeQuality(e){this.currentQuality=e;let{totalVideoFrames:t,droppedVideoFrames:i}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,i),this.isForceCheckCounter=this.droppedFramesChecker.tickCountAfterQualityChange,this.forceChecker$.next()}onDroopedVideoFramesLimitTrigger(){this.isAuto.getState()&&(this.log({message:`[onDroopedVideoFramesLimit]. maxQualityLimit: ${this.maxQualityLimit}`}),this.onDroopedVideoFramesLimit$.next())}getMaxQualityLimit(e){var i,r;let t=(r=(i=(0,Dy.default)(this.limitCounts).filter(([,a])=>a>=this.droppedFramesChecker.countLimit).sort(([a],[n])=>R$(a,n)?-1:1))==null?void 0:i[0])==null?void 0:r[0];return e!=null?e:t}get isEnabled(){return this.droppedFramesChecker.enabled&&this.isDroppedFramesCheckerSupport}get isDroppedFramesCheckerSupport(){return!!this.video&&typeof this.video.getVideoPlaybackQuality=="function"}savePrevFrameCounts(e,t){this.prevTotalVideoFrames=e,this.prevDroppedVideoFrames=t}},Gr=zd;import{map as L$,Observable as B$}from"@vkontakte/videoplayer-shared/es2018";import{fromEvent as $$}from"@vkontakte/videoplayer-shared/es2018";var Ca=()=>{var s;return!!((s=window.documentPictureInPicture)!=null&&s.window)||!!document.pictureInPictureElement};var D$=(s,e)=>new B$(t=>{if(!window.IntersectionObserver)return;let i={root:null},r=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||Ca()))},{...i,...e});r.observe(s);let a=$$(document,"visibilitychange").pipe(L$(n=>!document.hidden||Ca())).subscribe(n=>t.next(n));return()=>{r.unobserve(s),a.unsubscribe()}}),Et=D$;var q$=["paused","playing","ready"],j$=["paused","playing","ready"],Va=class{constructor(e){this.subscription=new N$;this.videoState=new G("stopped");this.representations$=new Gd([]);this.droppedFramesManager=new Gr;this.maxSeekBackTime$=new Gd(1/0);this.zeroTime$=new Gd(void 0);this.liveOffset=new or;this._dashCb=e=>{var t,i,r,a;switch(e.name){case"buffering":{let n=e.isBuffering;this.params.output.isBuffering$.next(n);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,category:Oy.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{let n=e.manifest,o=[];for(let u of n){let l=(t=u.name)!=null?t:u.index.toString(10),d=(i=Bi(u.name))!=null?i:U$(u.video),c=u.bitrate/1e3,h={...u.video};if(!d)continue;let p={id:l,quality:d,bitrate:c,size:h};o.push({track:p,representation:u})}this.representations$.next(o),this.params.output.availableVideoTracks$.next(o.map(({track:u})=>u)),((r=this.videoState.getTransition())==null?void 0:r.to)==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let n=e.quality,o=(a=this.representations$.getValue().find(({representation:u})=>u===n))==null?void 0:a.track;this.params.output.hostname$.next(new URL(n.headerUrl,this.params.source.url).hostname),Qd(o)&&this.params.output.currentVideoTrack$.next(o);break}case"bandwidth":{let{size:n,duration:o}=e;this.params.dependencies.throughputEstimator.addRawSpeed(n,o);break}case"index":{this.maxSeekBackTime$.next(e.shiftDuration||0),this.zeroTime$.next(e.zeroTime);break}}};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; seekState: ${JSON.stringify(a)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"));return}if(t)return;let n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if((0,Wd.default)(j$,e)&&(n||o)){this.prepare();return}if((r==null?void 0:r.to)!=="paused"&&a.state==="requested"&&(0,Wd.default)(q$,e)){this.seek(a.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(Se(this.params.source.url));return;case"manifest_ready":this.videoState.startTransitionTo("ready"),this.prepare();break;case"ready":if(i==="paused")this.videoState.setState("paused");else if(i==="playing"){this.videoState.startTransitionTo("playing");let u=r==null?void 0:r.from;u&&u==="ready"&&this.dash.catchUp(),this.dash.play()}return;case"playing":i==="paused"&&(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.dash.pause());return;case"paused":if(i==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.dash.play(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let u=this.liveOffset.getTotalOffset();u>=this.maxSeekBackTime$.getValue()&&(u=0,this.liveOffset.resetTo(u)),this.liveOffset.resume(),this.params.output.position$.next(-u/1e3),this.dash.reinit(Se(this.params.source.url,u))}return;default:return Cy(e)}};this.textTracksManager=new xt(e.source.url),this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=r=>{e.output.error$.next({id:"DashLiveProvider",category:Oy.WTF,message:"DashLiveProvider internal logic error",thrown:r})};this.subscription.add(Fy(this.videoState.stateChangeStarted$.pipe(Pu(r=>({transition:r,type:"start"}))),this.videoState.stateChangeEnded$.pipe(Pu(r=>({transition:r,type:"end"})))).subscribe(({transition:r,type:a})=>{this.log({message:`[videoState change] ${a}: ${JSON.stringify(r)}`})})),this.video=tt(e.container,e.tuning),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.subscription.add(this.dash.soundProhibitedEvent$.subscribe(this.params.output.soundProhibitedEvent$)),this.params.output.duration$.next(1/0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(Fe(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);let i=st(this.video);this.subscription.add(()=>i.destroy()),this.subscription.add(this.representations$.pipe(Pu(r=>r.map(({track:a})=>a)),_y(r=>!!r.length),F$()).subscribe(r=>this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:r}))),this.subscription.add(i.canplay$.subscribe(()=>{var r;((r=this.videoState.getTransition())==null?void 0:r.to)==="ready"&&this.videoState.setState("ready")},t)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused")},t)).add(i.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.videoState.setState("playing")},t)).add(i.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(O$(),Pu(r=>-r/1e3)).subscribe(this.params.output.duration$)).add(C$({zeroTime:this.zeroTime$.pipe(_y(Qd)),position:i.timeUpdate$}).subscribe(({zeroTime:r,position:a})=>this.params.output.liveTime$.next(r+a*1e3),t)).add(zt(this.video,this.params.desiredState.isLooped,t)).add(rt(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(It(this.video,this.params.desiredState.playbackRate,i.playbackRateState$,t)).add(i.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(i.loadedMetadata$.subscribe(this.params.output.loadedMetadataEvent$)).add(i.playing$.subscribe(this.params.output.firstFrameEvent$)).add(i.canplay$.subscribe(this.params.output.canplay$)).add(i.inPiP$.subscribe(this.params.output.inPiP$)).add(i.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(Et(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:r,min:a}})=>{this.dash.setAutoQualityLimits({max:r&&Ny(r),min:a&&Ny(a)}),this.params.output.autoVideoTrackLimits$.next({max:r,min:a})})).add(this.videoState.stateChangeEnded$.subscribe(r=>{var a;switch(r.to){case"stopped":this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState("stopped");break;case"manifest_ready":case"ready":((a=this.params.desiredState.playbackState.getTransition())==null?void 0:a.to)==="ready"&&this.params.desiredState.playbackState.setState("ready");break;case"paused":this.params.desiredState.playbackState.setState("paused");break;case"playing":this.params.desiredState.playbackState.setState("playing");break;default:return Cy(r.to)}},t)).add(Fy(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,_$(["init"])).pipe(V$(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),it(this.video)}createLiveDashPlayer(){let e=new Da({videoElement:this.video,videoState:this.videoState,playbackState:this.params.desiredState.playbackState,liveOffset:this.liveOffset,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode,manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){var l,d,c,h,p,f;let e=this.representations$.getValue(),t=(d=(l=this.params.desiredState.videoTrack.getTransition())==null?void 0:l.to)!=null?d:this.params.desiredState.videoTrack.getState(),i=(h=(c=this.params.desiredState.autoVideoTrackSwitching.getTransition())==null?void 0:c.to)!=null?h:this.params.desiredState.autoVideoTrackSwitching.getState(),r=!i&&Qd(t)?t:Wt(e.map(({track:m})=>m),{container:this.video.getBoundingClientRect(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),a=r==null?void 0:r.id,n=this.params.desiredState.videoTrack.getTransition(),o=(p=this.params.desiredState.videoTrack.getState())==null?void 0:p.id,u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(r&&(n||a!==o)&&this.setVideoTrack(r),u&&this.setAutoQuality(i),n||u||a!==o){let m=(f=e.find(({track:g})=>g.id===a))==null?void 0:f.representation;Vy(m,"Representations missing"),this.dash.startPlay(m,i)}}setVideoTrack(e){var i;let t=(i=this.representations$.getValue().find(({track:r})=>r.id===e.id))==null?void 0:i.representation;Vy(t,`No such representation ${e.id}`),this.dash.switchByName(t.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),r=t==="paused"&&i==="paused",a=-e,n=a<=this.maxSeekBackTime$.getValue()?a:0;this.params.output.position$.next(e/1e3),this.dash.reinit(Se(this.params.source.url,n)),r&&this.dash.pause(),this.liveOffset.resetTo(n,r)}};var Uy=Va;var ex=N(gt(),1);var $e=(s,e)=>{let t=0;for(let i=0;i<s.length;i++){let r=s.start(i)*1e3,a=s.end(i)*1e3;r<=e&&e<=a&&(t=a)}return Math.max(t-e,0)};import{assertNever as wC,assertNonNullable as AC,debounce as PC,ErrorCategory as XI,filter as Dp,filterChanged as el,fromEvent as RC,isNonNullable as JI,map as Cp,merge as tl,observableFrom as Vp,once as ZI,Subscription as kC}from"@vkontakte/videoplayer-shared/es2018";var Ru=class{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,i){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:i})}removeEventListener(e,t){if(!(e in this.listeners))return;let i=this.listeners[e];for(let r=0,a=i.length;r<a;r++)if(i[r].callback===t){i.splice(r,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;let i=this.listeners[e.type].slice();for(let r=0,a=i.length;r<a;r++){let n=i[r];try{n.callback.call(this,e)}catch(o){Promise.resolve().then(()=>{throw o})}n.options&&n.options.once&&this.removeEventListener(e.type,n.callback)}return!e.defaultPrevented}},Wr=class extends Ru{constructor(){super(),this.listeners||Ru.call(this),Object.defineProperty(this,"aborted",{value:!1,writable:!0,configurable:!0}),Object.defineProperty(this,"onabort",{value:null,writable:!0,configurable:!0}),Object.defineProperty(this,"reason",{value:void 0,writable:!0,configurable:!0})}toString(){return"[object AbortSignal]"}dispatchEvent(e){e.type==="abort"&&(this.aborted=!0,typeof this.onabort=="function"&&this.onabort.call(this,e)),super.dispatchEvent(e)}},Oa=class{constructor(){Object.defineProperty(this,"signal",{value:new Wr,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch(r){typeof document!="undefined"?document.createEvent?(t=document.createEvent("Event"),t.initEvent("abort",!1,!1)):(t=document.createEventObject(),t.type="abort"):t={type:"abort",bubbles:!1,cancelable:!1}}let i=e;if(i===void 0)if(typeof document=="undefined")i=new Error("This operation was aborted"),i.name="AbortError";else try{i=new DOMException("signal is aborted without reason")}catch(r){i=new Error("This operation was aborted"),i.name="AbortError"}this.signal.reason=i,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol!="undefined"&&Symbol.toStringTag&&(Oa.prototype[Symbol.toStringTag]="AbortController",Wr.prototype[Symbol.toStringTag]="AbortSignal");function ku(s){return s.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof s.Request=="function"&&!s.Request.prototype.hasOwnProperty("signal")||!s.AbortController}function Yd(s){typeof s=="function"&&(s={fetch:s});let{fetch:e,Request:t=e.Request,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r=!1}=s;if(!ku({fetch:e,Request:t,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r}))return{fetch:e,Request:a};let a=t;(a&&!a.prototype.hasOwnProperty("signal")||r)&&(a=function(l,d){let c;d&&d.signal&&(c=d.signal,delete d.signal);let h=new t(l,d);return c&&Object.defineProperty(h,"signal",{writable:!1,enumerable:!1,configurable:!0,value:c}),h},a.prototype=t.prototype);let n=e;return{fetch:(u,l)=>{let d=a&&a.prototype.isPrototypeOf(u)?u.signal:l?l.signal:void 0;if(d){let c;try{c=new DOMException("Aborted","AbortError")}catch(p){c=new Error("Aborted"),c.name="AbortError"}if(d.aborted)return Promise.reject(c);let h=new Promise((p,f)=>{d.addEventListener("abort",()=>f(c),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([h,n(u,l)])}return n(u,l)},Request:a}}var H$=()=>"fetch"in window,_a=H$()&&ku({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),qy=_a?Yd({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,wt=_a?qy.fetch:window.fetch,Dj=_a?qy.Request:window.Request,ae=_a?Oa:window.AbortController,Cj=_a?Wr:window.AbortSignal;var Rp=N(Fa(),1);var RT=N(PT(),1);import{ErrorCategory as Ua}from"@vkontakte/videoplayer-shared/es2018";var Mu=s=>{if(!s)return{id:"EmptyResponse",category:Ua.PARSER,message:"Empty response"};if(s.length<=2&&s.match(/^\d+$/))return{id:`UVError#${s}`,category:Ua.NETWORK,message:`UV Error ${s}`};let e=(0,RT.default)(s).substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:Ua.NETWORK,message:"Received unexpected HTML, possibly a ISP block"};if(e.startsWith("<?xml"))return new DOMParser().parseFromString(s,"text/xml").querySelector("parsererror")?{id:"InvalidXML",category:Ua.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:Ua.PARSER,message:"Response is valid XML, but parser failed"}};var Ne=(s,e,t=0)=>{for(let i=0;i<s.length;i++)if(s.start(i)*1e3-t<=e&&s.end(i)*1e3+t>e)return!0;return!1};import{abortable as wp,assertNonNullable as ss,combine as as,ErrorCategory as Ft,filter as Qu,filterChanged as Tn,flattenObject as In,fromEvent as Ti,getTraceSubscriptionMethod as oC,interval as Ap,isNonNullable as xn,isNullable as zI,map as ns,merge as pr,now as Pp,Subject as Gu,Subscription as QI,tap as uC,throttle as lC,ValueSubject as he}from"@vkontakte/videoplayer-shared/es2018";var $u=N(gt(),1),ts=N(Ot(),1),Du=N(Fa(),1);var kD=(s,e={})=>{let i=e.timeout||1,r=performance.now();return window.setTimeout(()=>{s({get didTimeout(){return e.timeout?!1:performance.now()-r-1>i},timeRemaining(){return Math.max(0,1+(performance.now()-r))}})},1)},MD=s=>window.clearTimeout(s),kT=s=>typeof s=="function"&&(s==null?void 0:s.toString().endsWith("{ [native code] }")),MT=!kT(window.requestIdleCallback)||!kT(window.cancelIdleCallback),Yr=MT?kD:window.requestIdleCallback,Yt=MT?MD:window.cancelIdleCallback;var CI=N(eu(),1);import{assertNever as LD,ErrorCategory as LT,Subject as BT}from"@vkontakte/videoplayer-shared/es2018";var BD=18,$T=!1;try{$T=j.browser.isSafari&&!!j.browser.safariVersion&&j.browser.safariVersion<=BD}catch(s){console.error(s)}var tp=class{constructor(e){this.bufferFull$=new BT;this.error$=new BT;this.queue=[];this.currentTask=null;this.destroyed=!1;this.abortRequested=!1;this.completeTask=()=>{var e;try{if(this.currentTask){let t=(e=this.currentTask.signal)==null?void 0:e.aborted;this.currentTask.callback(!t),this.currentTask=null}this.queue.length&&this.pull()}catch(t){this.error$.next({id:"BufferTaskQueueUnknown",category:LT.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(i=>{let r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(r=>{let a={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(a),this.pull()})}async abort(e){return new Promise(t=>{let i,r=a=>{this.abortRequested=!1,t(a)};$T&&e?i={operation:"safariAbort",init:e,callback:r}:i={operation:"abort",callback:r};for(let{callback:a}of this.queue)a(!1);this.abortRequested=!0,i&&(this.queue=[i]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){var r;if((this.buffer.updating||this.currentTask||this.destroyed)&&!this.abortRequested)return;let e=this.queue.shift();if(!e)return;if((r=e.signal)!=null&&r.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(a){a instanceof DOMException&&a.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):a instanceof DOMException&&a.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:LT.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:a}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){let{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:LD(t)}}},DT=tp;var Kr=s=>{let e=0;for(let t=0;t<s.length;t++)e+=s.end(t)-s.start(t);return e*1e3};import{abortable as Ci,assertNonNullable as nt,ErrorCategory as Si,fromEvent as vp,getExponentialDelay as yp,isNonNullable as es,isNullable as Ue,now as Bu,once as Y0,Subject as K0,Subscription as X0,ValueSubject as dr}from"@vkontakte/videoplayer-shared/es2018";var X=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let i=this.readUint32();this.type=this.readString(4),this.size32=i<=e.buffer.byteLength-e.byteOffset?i:NaN;let r=this.size32?this.size32-8:void 0,a=e.byteOffset+this.cursor;this.size64=0,this.usertype=0,this.content=new DataView(e.buffer,a,r)}get id(){return this.type}get size(){return this.size32}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t="ascii"){let r=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,r}readUint8(){let e=this.source.getUint8(this.cursor);return this.cursor+=1,e}readUint16(){let e=this.source.getUint16(this.cursor);return this.cursor+=2,e}readUint32(){let e=this.source.getUint32(this.cursor);return this.cursor+=4,e}readUint64(){let e=this.source.getBigInt64(this.cursor);return this.cursor+=8,e}};var Xr=class extends X{};var qa=class extends X{constructor(t,i){super(t,i);this.ondemandPrefix="ondemandlivejson";this.ondemandDataReceivedKey="t-in";this.ondemandDataPreparedKey="t-out";let r=this.content.byteOffset,a=r+this.content.byteLength,n=new TextDecoder("ascii").decode(this.content.buffer.slice(r,a)).split(this.ondemandPrefix)[1],o=JSON.parse(n);this.serverDataReceivedTimestamp=o[this.ondemandDataReceivedKey],this.serverDataPreparedTime=o[this.ondemandDataPreparedKey]}};var ja=class extends X{constructor(e,t){super(e,t),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let i=this.size-this.cursor;for(;i;){let r=this.readString(4);this.compatibleBrands.push(r),i-=4}}};var Ha=class extends X{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ue=class extends X{constructor(e,t){super(e,t);let i=this.readUint32();this.version=i>>>24,this.flags=i&16777215}};var za=class extends ue{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.timescale=this.readUint32(),this.duration=this.readUint32(),this.rate=this.readUint32(),this.volume=this.readUint16()}};var Qa=class extends X{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ga=class extends X{constructor(e,t){super(e,t),this.data=this.content}};var lr=class extends ue{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e,t){super(e,t),this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let i=0;i<this.referenceCount;i++){let r=this.readUint32(),a=r>>>31,n=r<<1>>>1,o=this.readUint32();r=this.readUint32();let u=r>>>28,l=r<<3>>>3;this.segments.push({referenceType:a,referencedSize:n,subsegmentDuration:o,SAPType:u,SAPDeltaTime:l})}}};var Wa=class extends X{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ya=class extends X{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ka=class extends ue{constructor(e,t){switch(super(e,t),this.readUint8()){case 0:this.stereoMode=0;break;case 1:this.stereoMode=1;break;case 2:this.stereoMode=2;break;case 3:this.stereoMode=3;break;case 4:this.stereoMode=4;break}this.cursor+=1}};var Xa=class extends ue{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var Ja=class extends ue{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var Za=class extends X{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var en=class extends ue{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.trackId=this.readUint32(),this.cursor+=4,this.duration=this.readUint32(),this.cursor+=8,this.layer=this.readUint16(),this.alternateGroup=this.readUint16(),this.cursor+=2,this.cursor+=2,this.matrix=[[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()]],this.width=this.readUint32(),this.height=this.readUint32()}};var tn=class extends X{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var rn=class extends X{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var sn=class extends ue{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var an=class extends X{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var nn=class extends ue{constructor(e,t){super(e,t),this.trackId=this.readUint32(),this.flags&1&&(this.baseDataOffset=this.readUint64()),this.flags&2&&(this.sampleDescriptionIndex=this.readUint32()),this.flags&8&&(this.defaultSampleDuration=this.readUint32()),this.flags&16&&(this.defaultSampleSize=this.readUint32()),this.flags&32&&(this.defaultSampleFlags=this.readUint32())}};var on=class extends ue{constructor(t,i){super(t,i);this.baseMediaDecodeTime32=0;this.baseMediaDecodeTime64=BigInt(0);this.version===1?this.baseMediaDecodeTime64=this.readUint64():this.baseMediaDecodeTime32=this.readUint32()}get baseMediaDecodeTime(){return this.version===1?this.baseMediaDecodeTime64:this.baseMediaDecodeTime32}};var un=class extends ue{constructor(t,i){super(t,i);this.sampleDuration=[];this.sampleSize=[];this.sampleFlags=[];this.sampleCompositionTimeOffset=[];this.optionalFields=0;this.sampleCount=this.readUint32(),this.flags&1&&(this.dataOffset=this.readUint32()),this.flags&4&&(this.firstSampleFlags=this.readUint32());for(let r=0;r<this.sampleCount;r++)this.flags&256&&this.sampleDuration.push(this.readUint32()),this.flags&512&&this.sampleSize.push(this.readUint32()),this.flags&1024&&this.sampleFlags.push(this.readUint32()),this.flags&2048&&this.sampleCompositionTimeOffset.push(this.readUint32())}};var ln=class extends X{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var cn=class extends ue{constructor(e,t){super(e,t),this.entryCount=this.readUint32(),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+8,this.content.byteLength-8))}};var dn=class extends X{constructor(e,t){super(e,t),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+78,this.content.byteLength-78))}};var DD={ftyp:ja,moov:Ha,mvhd:za,moof:Qa,mdat:Ga,sidx:lr,trak:Wa,mdia:Za,mfhd:sn,tkhd:en,traf:an,tfhd:nn,tfdt:on,trun:un,minf:tn,sv3d:Ya,st3d:Ka,prhd:Xa,proj:rn,equi:Ja,uuid:qa,stbl:ln,stsd:cn,avc1:dn,unknown:Xr},bi=class s{constructor(e={}){this.options={offset:0,...e}}parse(e){let t=[],i=this.options.offset;for(;i<e.byteLength;)try{let a=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+i+4,4)),n=this.createBox(a,new DataView(e.buffer,e.byteOffset+i));if(!n.size)break;t.push(n),i+=n.size}catch(r){break}return t}createBox(e,t){let i=DD[e];return i?new i(t,new s):new Xr(t,new s)}};var Di=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{var i,r,a;(a=(i=this.index)[r=t.type])!=null||(i[r]=[]),this.index[t.type].push(t),t.children.length>0&&this.indexBoxLevel(t.children)})}find(e){return this.index[e]&&this.index[e][0]?this.index[e][0]:null}findAll(e){return this.index[e]||[]}};var VD=new TextDecoder("ascii"),OD=s=>VD.decode(new DataView(s.buffer,s.byteOffset+4,4))==="ftyp",_D=s=>{let e=new lr(s,new bi),t=e.earliestPresentationTime/e.timescale*1e3,i=s.byteOffset+s.byteLength+e.firstOffset;return e.segments.map(a=>{if(a.referenceType!==0)throw new Error("Unsupported multilevel sidx");let n=a.subsegmentDuration/e.timescale*1e3,o={status:"none",time:{from:t,to:t+n},byte:{from:i,to:i+a.referencedSize-1}};return t+=n,i+=a.referencedSize,o})},FD=(s,e)=>{let i=new bi().parse(s),r=new Di(i),a=r.findAll("moof"),n=e?r.findAll("uuid"):r.findAll("mdat");if(!(n.length&&a.length))return null;let o=a[0],u=n[n.length-1],l=o.source.byteOffset,c=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(s.buffer,l,c)},ND=s=>{let t=new bi().parse(s),i=new Di(t),r={},a=i.findAll("uuid");return a.length?a[a.length-1]:r},UD=s=>{var r;let t=new bi().parse(s);return(r=new Di(t).find("sidx"))==null?void 0:r.timescale},qD=(s,e)=>{let i=new bi().parse(s),a=new Di(i).findAll("traf"),n=a[a.length-1].children.find(c=>c.type==="tfhd"),o=a[a.length-1].children.find(c=>c.type==="tfdt"),u=a[a.length-1].children.find(c=>c.type==="trun"),l=0;return u.sampleDuration.length?l=u.sampleDuration.reduce((c,h)=>c+h,0):l=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+l)/e*1e3},jD=s=>{let e={is3dVideo:!1,stereoMode:0,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}},i=new bi().parse(s),r=new Di(i);if(r.find("sv3d")){e.is3dVideo=!0;let n=r.find("st3d");n&&(e.stereoMode=n.stereoMode);let o=r.find("prhd");o&&(e.projectionData.pose.yaw=o.poseYawDegrees,e.projectionData.pose.pitch=o.posePitchDegrees,e.projectionData.pose.roll=o.poseRollDegrees);let u=r.find("equi");u&&(e.projectionData.bounds.top=u.projectionBoundsTop,e.projectionData.bounds.right=u.projectionBoundsRight,e.projectionData.bounds.bottom=u.projectionBoundsBottom,e.projectionData.bounds.left=u.projectionBoundsLeft)}return e},CT={validateData:OD,parseInit:jD,getIndexRange:()=>{},parseSegments:_D,parseFeedableSegmentChunk:FD,getChunkEndTime:qD,getServerLatencyTimestamps:ND,getTimescaleFromIndex:UD};var hn=N(gt(),1);import{assertNonNullable as rp,isNonNullable as FT,isNullable as zD}from"@vkontakte/videoplayer-shared/es2018";import{assertNever as HD}from"@vkontakte/videoplayer-shared/es2018";var VT={440786851:{type:"master"},17030:{type:"uint"},17143:{type:"uint"},17138:{type:"uint"},17139:{type:"uint"},17026:{type:"string"},17031:{type:"uint"},17029:{type:"uint"},236:{type:"binary"},408125543:{type:"master"},290298740:{type:"master"},19899:{type:"master"},21419:{type:"binary"},21420:{type:"uint"},357149030:{type:"master"},2807729:{type:"uint"},17545:{type:"float"},374648427:{type:"master"},174:{type:"master"},224:{type:"master"},30320:{type:"master"},30321:{type:"uint"},30322:{type:"master"},272869232:{type:"master"},524531317:{type:"master"},231:{type:"uint"},22612:{type:"master"},22743:{type:"uint"},167:{type:"uint"},171:{type:"uint"},163:{type:"binary"},160:{type:"master"},175:{type:"binary"},423732329:{type:"master"},307544935:{type:"master"},475249515:{type:"master"},187:{type:"master"},179:{type:"uint"},183:{type:"master"},247:{type:"uint"},241:{type:"uint"},240:{type:"uint"},178:{type:"uint"},21368:{type:"uint"},234:{type:"uint"},219:{type:"master"},150:{type:"uint"}},OT=s=>{let e=s.getUint8(0),t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);let i=pn(s,t),r=i in VT,a=r?VT[i].type:"binary",n=s.getUint8(t),o=0;n&128?o=1:n&64?o=2:n&32?o=3:n&16?o=4:n&8?o=5:n&4?o=6:n&2?o=7:n&1&&(o=8);let u=new DataView(s.buffer,s.byteOffset+t+1,o-1),l=n&255>>o,d=pn(u),c=l*2**((o-1)*8)+d,h=t+o,p;return h+c>s.byteLength?p=new DataView(s.buffer,s.byteOffset+h):p=new DataView(s.buffer,s.byteOffset+h,c),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:a,tagHeaderSize:h,tagSize:h+c,value:p,valueSize:c}},pn=(s,e=s.byteLength)=>{switch(e){case 1:return s.getUint8(0);case 2:return s.getUint16(0);case 3:return s.getUint8(0)*2**16+s.getUint16(1);case 4:return s.getUint32(0);case 5:return s.getUint8(0)*2**32+s.getUint32(1);case 6:return s.getUint16(0)*2**32+s.getUint32(2);case 7:{let t=s.getUint8(0)*281474976710656+s.getUint16(1)*4294967296+s.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},_t=(s,e)=>{switch(e){case"int":return s.getInt8(0);case"uint":return pn(s);case"float":return s.byteLength===4?s.getFloat32(0):s.getFloat64(0);case"string":return new TextDecoder("ascii").decode(s);case"utf8":return new TextDecoder("utf-8").decode(s);case"date":return new Date(Date.UTC(2001,0)+s.getInt8(0)).getTime();case"master":return s;case"binary":return s;default:HD(e)}},cr=(s,e)=>{let t=0;for(;t<s.byteLength;){let i=new DataView(s.buffer,s.byteOffset+t),r=OT(i);if(!e(r))return;r.type==="master"&&cr(r.value,e),t=r.value.byteOffset-s.byteOffset+r.valueSize}},_T=s=>{if(s.getUint32(0)!==440786851)return!1;let e,t,i,r=OT(s);return cr(r.value,({tag:a,type:n,value:o})=>(a===17143?e=_t(o,n):a===17026?t=_t(o,n):a===17029&&(i=_t(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)};var NT=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],QD=[231,22612,22743,167,171,163,160,175],GD=s=>{let e,t,i,r,a=!1,n=!1,o=!1,u,l,d=!1,c=0;return cr(s,({tag:h,type:p,value:f,valueSize:m})=>{if(h===21419){let g=_t(f,p);l=pn(g)}else h!==21420&&(l=void 0);return h===408125543?(e=f.byteOffset,t=f.byteOffset+m):h===357149030?a=!0:h===290298740?n=!0:h===2807729?i=_t(f,p):h===17545?r=_t(f,p):h===21420&&l===475249515?u=_t(f,p):h===374648427?cr(f,({tag:g,type:S,value:v})=>g===30321?(d=_t(v,S)===1,!1):!0):a&&n&&(0,hn.default)(NT,h)&&(o=!0),!o}),rp(e,"Failed to parse webm Segment start"),rp(t,"Failed to parse webm Segment end"),rp(r,"Failed to parse webm Segment duration"),i=i!=null?i:1e6,{segmentStart:Math.round(e/1e9*i*1e3),segmentEnd:Math.round(t/1e9*i*1e3),timeScale:i,segmentDuration:Math.round(r/1e9*i*1e3),cuesSeekPosition:u,is3dVideo:d,stereoMode:c,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},WD=s=>{if(zD(s.cuesSeekPosition))return;let e=s.segmentStart+s.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},YD=(s,e)=>{let t=!1,i=!1,r=o=>FT(o.time)&&FT(o.position),a=[],n;return cr(s,({tag:o,type:u,value:l})=>{switch(o){case 475249515:t=!0;break;case 187:n&&r(n)&&a.push(n),n={};break;case 179:n&&(n.time=_t(l,u));break;case 183:break;case 241:n&&(n.position=_t(l,u));break;default:t&&(0,hn.default)(NT,o)&&(i=!0)}return!(t&&i)}),n&&r(n)&&a.push(n),a.map((o,u)=>{let{time:l,position:d}=o,c=a[u+1];return{status:"none",time:{from:l,to:c?c.time:e.segmentDuration},byte:{from:e.segmentStart+d,to:c?e.segmentStart+c.position-1:e.segmentEnd-1}}})},KD=s=>{let e=0,t=!1;try{cr(s,i=>i.tag===524531317?i.tagSize<=s.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):(0,hn.default)(QD,i.tag)?(e+i.tagSize<=s.byteLength&&(e+=i.tagSize,t||(t=(0,hn.default)([163,160,175],i.tag))),!0):!1)}catch(i){}return e>0&&e<=s.byteLength&&t?new DataView(s.buffer,s.byteOffset,e):null},UT={validateData:_T,parseInit:GD,getIndexRange:WD,parseSegments:YD,parseFeedableSegmentChunk:KD};var fn=s=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(s);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return UT;case"mp4":return CT}}throw new ReferenceError(`Unsupported mime type ${s}`)};var bp=N(lp(),1),MI=N(Ji(),1),LI=N(cp(),1),BI=N(Ot(),1),gp=N(nr(),1);var II=N(gt(),1),Zr=s=>{let e=s.split("."),[t,...i]=e;if(!t)return!1;switch(t){case"av01":{let[r,a,n]=i;return!!(n&&parseInt(n,10)>8)}case"vp09":{let[r,a,n]=i;return!!(r&&parseInt(r,10)>=2&&n&&parseInt(n,10)>8)}case"avc1":{let r=i[0];if(!r||r.length!==6)return!1;let[a,n]=r.toUpperCase(),o=a+n;return(0,II.default)(["6E","7A","F4"],o)}}return!1};import{isNonNullable as G0,isNullable as RI}from"@vkontakte/videoplayer-shared/es2018";var Lu=s=>{if(s.includes("/")){let e=s.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(s)};var xI=s=>{var e;try{let t=z0(),i=s.match(t),{groups:r}=i!=null?i:{};if(r){let a={};if(r.extensions){let u=r.extensions.toLowerCase().match(/(?:[0-9a-wy-z](?:-[a-z0-9]{2,8})+)/g);Array.from(u||[]).forEach(l=>{a[l[0]]=l.slice(2)})}let n=(e=r.variants)==null?void 0:e.split(/-/).filter(u=>u!==""),o={extlang:r.extlang,langtag:r.langtag,language:r.language,privateuse:r.privateuse||r.privateuse2,region:r.region,script:r.script,extensions:a,variants:n};return Object.keys(o).forEach(u=>{let l=o[u];(typeof l=="undefined"||l==="")&&delete o[u]}),o}return null}catch(t){return null}};function z0(){let s="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",d=`^(?:(?<langtag>${`
117
+ `}),v};var Fe=s=>new URL(s).hostname;import{assertNever as Cy,assertNonNullable as Vy,combine as C$,debounce as V$,ErrorCategory as Oy,filter as _y,filterChanged as O$,isNonNullable as Qd,map as Pu,merge as Fy,observableFrom as _$,once as F$,Subscription as N$,ValueSubject as Gd,videoQualityToHeight as Ny,videoSizeToQuality as U$}from"@vkontakte/videoplayer-shared/es2018";var Ly=N(Ot(),1);var Ay=N(gt(),1),wy=s=>{if(s instanceof DOMException&&(0,Ay.default)(["Failed to load because no supported source was found.","The element has no supported sources."],s.message))throw s;return!(s instanceof DOMException&&(s.code===20||s.name==="AbortError"))},at=async(s,e)=>{let t=s.muted;try{await s.play()}catch(i){if(!wy(i))return!1;if(e&&e(),t)return console.warn(i),!1;s.muted=!0;try{await s.play()}catch(r){return wy(r)&&(s.muted=!1,console.warn(r)),!1}}return!0};import{isNonNullable as wu,isNullable as g$,assertNonNullable as $a}from"@vkontakte/videoplayer-shared/es2018";var ky=N(nr(),1);import{isNonNullable as Py,assertNonNullable as Eu,now as m$}from"@vkontakte/videoplayer-shared/es2018";function Be(){return m$()}function qd(s){return Be()-s}function jd(s){let e=s.split("/"),t=e.slice(0,e.length-1).join("/"),i=/^([a-z]+:)?\/\//i,r=n=>i.test(n);return{resolve:(n,o,u=!1)=>{r(n)||(n.startsWith("/")||(n="/"+n),n=t+n);let l=n.indexOf("?")>-1?"&":"?";return u&&(n+=l+"lowLat=1",l="&"),o&&(n+=l+"_rnd="+Math.floor(999999999*Math.random())),n}}}function Ry(s,e,t){let i=(...r)=>{t.apply(null,r),s.removeEventListener(e,i)};s.addEventListener(e,i)}function Qr(s,e,t,i){let r=window.XMLHttpRequest,a,n,o,u=!1,l=0,d,c,h=!1,p="arraybuffer",f=7e3,m=2e3,g=()=>{if(u)return;Eu(d);let M=qd(d),R;if(M<m){R=m-M,setTimeout(g,R);return}m*=2,m>f&&(m=f),n&&n.abort(),n=new r,E()},S=M=>(a=M,C),v=M=>(c=M,C),y=()=>(p="json",C),I=()=>{if(!u){if(--l>=0){g(),i&&i();return}u=!0,c&&c(),t&&t()}},T=M=>(h=M,C),E=()=>{d=Be(),n=new r,n.open("get",s);let M=0,R,Q=0,U=()=>(Eu(d),Math.max(d,Math.max(R||0,Q||0)));if(a&&n.addEventListener("progress",A=>{let F=Be();a.updateChunk&&A.loaded>M&&(a.updateChunk(U(),A.loaded-M),M=A.loaded,R=F)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>I())),n.addEventListener("load",()=>{if(u)return;Eu(n);let A=n.status;if(A>=200&&A<300){let{response:F,responseType:k}=n,x=F==null?void 0:F.byteLength;if(typeof x=="number"&&a){let $=x-M;$&&a.updateChunk&&a.updateChunk(U(),$)}k==="json"&&(!F||!(0,ky.default)(F).length)?I():(c&&c(),e(F))}else I()}),n.addEventListener("error",()=>{I()}),h){let A=()=>{Eu(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(Q=Be(),n.removeEventListener("readystatechange",A))};n.addEventListener("readystatechange",A)}return n.responseType=p,n.send(),C},C={withBitrateReporting:S,withParallel:T,withJSONResponse:y,withRetryCount:M=>(l=M,C),withRetryInterval:(M,R)=>(Py(M)&&(m=M),Py(R)&&(f=R),C),withTimeout:M=>(o=M,C),withFinally:v,send:E,abort:()=>{n&&(n.abort(),n=void 0),u=!0,c&&c()}};return C}var La=class{constructor(e){this.intervals=[];this.currentRate=0;this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,i){return{start:e,end:t,bytes:i}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;let e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-500;if(t-e>2e3){let i=0,r=0;for(;this.intervals.length>0;){let a=this.intervals[0];if(a.end<=t)i+=a.end-a.start,r+=a.bytes,this.intervals.splice(0,1);else{if(a.start>=t)break;{let n=t-a.start,o=a.end-a.start;i+=n;let u=a.bytes*n/o;r+=u,a.start=t,a.bytes-=u}}}if(r>0&&i>0){let a=r*8/(i/1e3);return this._updateRate(a),this.logger(`rate updated, new=${Math.round(a/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(r)}/${Math.round(i)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,i){return this.intervals.push(this._createInterval(e,t,i)),this._joinIntervals(),this.intervals.length>100&&(this.logger(`too many intervals (${this.intervals.length}); will merge`,{type:"warn"}),this._doMergeIntervals(this.intervals[1],this.intervals[0]),this.intervals.splice(0,1)),this._flushIntervals()}getBitRate(){return this.currentRate}};var My=N(nr(),1);var Ba=class{constructor(e,t,i,r,a){this.pendingQueue=[];this.activeRequests={};this.completeRequests={};this.averageSegmentDuration=2e3;this.lastPrefetchStart=0;this.throttleTimeout=null;this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=i,this.MAX_PARALLEL_REQUESTS=r,this.logger=a}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){let t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){let i=Be(),r=u=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=u,e._errorCB?e._errorCB(u):(this.limitCompleteCount(),this.completeRequests[t]=e)},a=u=>{e._complete=1,e._responseData=u,e._downloadTime=Be()-i,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(u,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=Qr(t,a,()=>r("error"),o),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(n),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=Be()}_getParallelRequestCount(){return Math.min(this.MAX_PARALLEL_REQUESTS,this.averageSegmentDuration<3e3?3:2)}_getPrefetchDelay(){return Math.max(100,Math.min(5e3,this.averageSegmentDuration/3))}_canSendPending(){let e=this._getParallelRequestCount(),t=Be();if(Object.keys(this.activeRequests).length>=e)return!1;let i=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),i>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),i),!1):!0}_sendPending(){for(;this._canSendPending();){let e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){(0,My.default)(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,i,r){let a={};return a.send=()=>{let n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=i,n._retryCB=r,n._finallyCB=a._finallyCB,n._error||n._complete?(this._removeFromActive(e),setTimeout(()=>{n._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(n._responseData,n._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),i(n._errorMsg)),a._finallyCB&&a._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{let o=this.pendingQueue.indexOf(e);o!==-1&&this.pendingQueue.splice(o,1),this.logger(`Request not prefetched, starting new request, url=${e}${o===-1?"":"; removed pending"}`),this._sendRequest(a,e)}},a._cb=t,a._errorCB=i,a._retryCB=r,a.abort=function(){a.request&&a.request.abort()},a.withFinally=n=>(a._finallyCB=n,a),a}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}};import{Subject as S$}from"@vkontakte/videoplayer-shared/es2018";var Au=1e4,Hd=3;var v$=6e4,y$=10,T$=1,I$=500,Da=class{constructor(e){this.paused=!1;this.autoQuality=!0;this.autoQualityLimits=void 0;this.buffering=!0;this.destroyed=!1;this.videoPlayStarted=!1;this.lowLatency=!1;this.bitrate=0;this.manifest=[];this.sourceBuffer=0;this.bufferStates=[];this.sourceJitter=-1;this.waitingForFirstBufferAfterSrcChange=!1;this.params=e,this.soundProhibitedEvent$=new S$,this.chunkRateEstimator=new La(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=jd(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setAutoQualityLimits(e){this.autoQualityLimits=e}switchByName(e){let t;for(let i=0;i<this.manifest.length;++i)if(t=this.manifest[i],t.name===e){this._switchToQuality(t);return}}catchUp(){if(this.rep&&this.rep.stop(),this.currentManifestEntry){let e=this.params.playbackState.getState();this.paused=e==="paused",this._initPlayerWith(this.currentManifestEntry),this._notifyBuffering(!0)}}stop(){this.params.videoElement.pause(),this.rep&&(this.rep.stop(),this.rep=null)}pause(){this.paused=!0,this.params.videoElement.pause(),this.videoPlayStarted=!1,this._notifyBuffering(!1)}play(){this.paused=!1;let e=this.lowLatency&&this._getBufferSizeSec()>this.sourceJitter+5;this.rep&&!e?(this.bufferStates=[],this.videoPlayStarted=!1,this.shouldPlay()?this._playVideoElement():this._notifyBuffering(!0)):this.catchUp()}startPlay(e,t){this.autoQuality=t,this._initPlayerWith(e)}destroy(){this.destroyed=!0,this.rep&&(this.rep.stop(),this.rep=null),this.manifestRequest&&this.manifestRequest.abort(),this.manifestRefetchTimer&&(clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=void 0)}reinit(e){this.manifestUrl=e,this.urlResolver=jd(e),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){let e=this.params.videoElement,t=0,i=e.buffered.length;return i!==0&&(t=e.buffered.end(i-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){let{videoElement:e,logger:t}=this.params;e.addEventListener("error",()=>{var r,a;!!e.error&&!this.destroyed&&(t(`Video element error: ${(r=e.error)==null?void 0:r.code}, details: ${(a=e.error)==null?void 0:a.message}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{let i=this._getBufferSizeSec();!this.paused&&i<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(i+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){let{logger:e,videoElement:t}=this.params,i=t.buffered.length,r;i!==0&&!this.waitingForFirstBufferAfterSrcChange&&(r=t.buffered.start(i-1),t.currentTime<r&&(e("Fixup stall"),t.currentTime=r))}_selectQuality(e){let{videoElement:t}=this.params,i,r,a,n=t&&1.62*(j.display.pixelRatio||1)*t.offsetHeight||520;for(let o=0;o<this.manifest.length;++o){a=this.manifest[o];let{max:u,min:l}=this.autoQualityLimits||{};!my({limits:this.autoQualityLimits,highestAvailableHeight:this.manifest[0].video.height,lowestAvailableHeight:(0,Ly.default)(this.manifest,-1).video.height})&&(u&&a.video.height>u||l&&a.video.height<l)||(a.bitrate<e&&n>Math.min(a.video.height,a.video.width)?(!r||a.bitrate>r.bitrate)&&(r=a):(!i||i.bitrate>a.bitrate)&&(i=a))}return r||i}shouldPlay(){if(this.paused)return!1;let t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||wu(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){let{logger:i,videoElement:r,playerCallback:a}=this.params;this.mediaSource=new window.MediaSource,i("setting video src"),r.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,r.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});let n=()=>{Ry(r,"progress",()=>{r.buffered.length?(r.currentTime=r.buffered.start(0),this.waitingForFirstBufferAfterSrcChange=!1,a({name:"playing"})):n()})};this.waitingForFirstBufferAfterSrcChange=!0,n()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new Ba(Hd,Au,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:i,playerCallback:r}=this.params,a=!1,n=null,o=null,u=null,l=null,d=!1,c=()=>{let I=a&&(!d||d===this.rep);return I||t("Not running!"),I},h=(I,T,E)=>{u&&u.abort(),u=Qr(this.urlResolver.resolve(I,!1),T,E,()=>this._retryCallback()).withTimeout(Au).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Hd).withFinally(()=>{u=null}).send()},p=(I,T,E)=>{$a(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(I,!1),T,E,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},f=I=>{let T=i.playbackRate;i.playbackRate!==I&&(t(`Playback rate switch: ${T}=>${I}`),i.playbackRate=I)},m=I=>{this.lowLatency=I,t(`lowLatency changed to ${I}`),g()},g=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)f(1);else{let I=this._getBufferSizeSec();if(this.bufferStates.length<5){f(1);return}let E=Be()-1e4,O=0;for(let w=0;w<this.bufferStates.length;w++){let P=this.bufferStates[w];I=Math.min(I,P.buf),P.ts<E&&O++}this.bufferStates.splice(0,O),t(`update playback rate; minBuffer=${I} drop=${O} jitter=${this.sourceJitter}`);let L=I-T$;this.sourceJitter>=0?L-=this.sourceJitter/2:this.sourceJitter-=1,L>3?f(1.15):L>1?f(1.1):L>.3?f(1.05):f(1)}},S=I=>{let T,E=()=>T&&T.start?T.start.length:0,O=A=>T.start[A]/1e3,L=A=>T.dur[A]/1e3,w=A=>T.fragIndex+A,P=(A,F)=>({chunkIdx:w(A),startTS:O(A),dur:L(A),discontinuity:F}),C=()=>{let A=0;if(T&&T.dur){let F=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,k=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,x=F;this.sourceJitter>1&&(x+=this.sourceJitter-1);let $=T.dur.length-1;for(;$>=0&&(x-=T.dur[$],!(x<=0));--$);A=Math.min($,T.dur.length-1-k),A=Math.max(A,0)}return P(A,!0)},M=A=>{let F=E();if(!(F<=0)){if(wu(A)){for(let k=0;k<F;k++)if(O(k)>A)return P(k)}return C()}},R=A=>{let F=E(),k=A?A.chunkIdx+1:0,x=k-T.fragIndex;if(!(F<=0)){if(!A||x<0||x-F>y$)return t(`Resync: offset=${x} bChunks=${F} chunk=`+JSON.stringify(A)),C();if(!(x>=F))return P(k-T.fragIndex,!1)}},Q=(A,F,k)=>{l&&l.abort(),l=Qr(this.urlResolver.resolve(A,!0,this.lowLatency),F,k,()=>this._retryCallback()).withTimeout(Au).withRetryCount(Hd).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(A,F)=>{Q(I,k=>{if(!c())return;T=k;let x=!!T.lowLatency;x!==this.lowLatency&&m(x);let $=0;for(let oe=0;oe<T.dur.length;++oe)$+=T.dur[oe];$>0&&($a(this.filesFetcher),this.filesFetcher.optimizeForSegDuration($/T.dur.length)),r({name:"index",zeroTime:T.zeroTime,shiftDuration:T.shiftDuration}),this.sourceJitter=T.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,T.jitter/1e3)):1,A(M(F))},()=>this._handleNetworkError())},nextChunk:R}},v=()=>{a=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),$a(this.filesFetcher),this.filesFetcher.abortAll()};return d={start:I=>{let{videoElement:T,logger:E}=this.params,O=S(e.jidxUrl),L,w,P,C,M=0,R,Q,U,A=()=>{R&&(clearTimeout(R),R=void 0);let K=Math.max(I$,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),ye=M+K,Te=Be(),Ie=Math.min(1e4,ye-Te);M=Te;let Ve=()=>{l||c()&&O.seek(()=>{c()&&(M=Be(),F(),A())})};Ie>0?R=window.setTimeout(()=>{this.paused?A():Ve()},Ie):Ve()},F=()=>{let K;for(;K=O.nextChunk(C);)C=K,Ce(K);let ye=O.nextChunk(P);if(ye){if(P&&ye.discontinuity){E("Detected discontinuity; restarting playback"),this.paused?A():(v(),this._initPlayerWith(e));return}oe(ye)}else A()},k=(K,ye)=>{if(!c()||!this.sourceBuffer)return;let Te,Ie,Ve,Tt=At=>{window.setTimeout(()=>{c()&&k(K,ye)},At)};if(this.sourceBuffer.updating)E("Source buffer is updating; delaying appendBuffer"),Tt(100);else{let At=Be(),qt=T.currentTime;!this.paused&&T.buffered.length>1&&Q===qt&&At-U>500&&(E("Stall suspected; trying to fix"),this._fixupStall()),Q!==qt&&(Q=qt,U=At);let Xt=this._getBufferSizeSec();if(Xt>30)E(`Buffered ${Xt} seconds; delaying appendBuffer`),Tt(2e3);else try{this.sourceBuffer.appendBuffer(K),this.videoPlayStarted?(this.bufferStates.push({ts:At,buf:Xt}),g(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),ye&&ye()}catch(Ai){if(Ai.name==="QuotaExceededError")E("QuotaExceededError; delaying appendBuffer"),Ve=this.sourceBuffer.buffered.length,Ve!==0&&(Te=this.sourceBuffer.buffered.start(0),Ie=qt,Ie-Te>4&&this.sourceBuffer.remove(Te,Ie-3)),Tt(1e3);else throw Ai}}},x=()=>{w&&L&&(E([`Appending chunk, sz=${w.byteLength}:`,JSON.stringify(P)]),k(w,function(){w=null,F()}))},$=K=>e.fragUrlTemplate.replace("%%id%%",K.chunkIdx),oe=K=>{c()&&p($(K),(ye,Te)=>{if(c()){if(Te/=1e3,w=ye,P=K,n=K.startTS,Te){let Ie=Math.min(10,K.dur/Te);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*Ie:Ie}x()}},()=>this._handleNetworkError())},Ce=K=>{c()&&($a(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve($(K),!1)))},se=K=>{c()&&(e.cachedHeader=K,k(K,()=>{L=!0,x()}))};a=!0,O.seek(K=>{if(c()){if(M=Be(),!K){A();return}C=K,!g$(I)||K.startTS>I?oe(K):(P=K,F())}},I),e.cachedHeader?se(e.cachedHeader):h(e.headerUrl,se,()=>this._handleNetworkError())},stop:v,getTimestampSec:()=>n},d}_switchToQuality(e){let{logger:t,playerCallback:i}=this.params,r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),wu(r)&&(r+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,$a(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return wu(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,i=c=>{if(!this.autoQuality)return;let h,p,f;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&c<this.bitrate&&(p=this._getBufferSizeSec(),f=c/this.bitrate,p>10&&f>.8||p>15&&f>.5||p>20&&f>.3)){e(`Not switching: buffer=${Math.floor(p)}; bitrate=${this.bitrate}; newRate=${Math.floor(c)}`);return}h=this._selectQuality(c),h?this._switchToQuality(h):e(`Could not find quality by bitrate ${c}`)},a={updateChunk:(h,p)=>{let f=Be();if(this.chunkRateEstimator.addInterval(h,f,p)){let g=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:p,duration:f-h,speed:g}),!0}},get:()=>{let h=this.chunkRateEstimator.getBitRate();return h?h*.85:0}},n=-1/0,o,u=!0,l=()=>{let c=a.get();if(c&&o&&this.autoQuality){if(u&&c>o&&qd(n)<3e4)return;i(c)}u=this.autoQuality};return{updateChunk:(c,h)=>{let p=a.updateChunk(c,h);return p&&l(),p},notifySwitch:c=>{let h=Be();c<o&&(n=h),o=c}}}_fetchManifest(e,t,i){this.manifestRequest=Qr(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(Au).withRetryCount(this.params.config.manifestRetryMaxCount).withRetryInterval(this.params.config.manifestRetryInterval,this.params.config.manifestRetryMaxInterval).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(){let{videoElement:e}=this.params;at(e,()=>{this.soundProhibitedEvent$.next()}).then(t=>{t||(this.params.liveOffset.pause(),this.params.videoState.setState("paused"))})}_handleManifestUpdate(e){let{logger:t,playerCallback:i,videoElement:r}=this.params,a=n=>{let o=[];return n!=null&&n.length?(n.forEach((u,l)=>{var d,c;u.video&&r.canPlayType(u.codecs).replace(/no/,"")&&((c=(d=window.MediaSource)==null?void 0:d.isTypeSupported)!=null&&c.call(d,u.codecs))&&(u.index=l,o.push(u))}),o.sort(function(u,l){return u.video&&l.video?l.video.height-u.video.height:l.bitrate-u.bitrate}),o):(i({name:"error",type:"empty_manifest"}),[])};this.manifest=a(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),i({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},v$))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var Dy=N(Ji(),1);import{debounce as x$,filter as By,fromEvent as E$,interval as w$,isHigher as A$,isInvariantQuality as P$,isLower as k$,merge as R$,Subject as $y,Subscription as M$}from"@vkontakte/videoplayer-shared/es2018";var zd=class{constructor(){this.onDroopedVideoFramesLimit$=new $y;this.subscription=new M$;this.playing=!1;this.tracks=[];this.forceChecker$=new $y;this.isForceCheckCounter=0;this.prevTotalVideoFrames=0;this.prevDroppedVideoFrames=0;this.limitCounts={};this.handleChangeVideoQuality=()=>{let e=this.tracks.find(({size:t})=>(t==null?void 0:t.height)===this.video.videoHeight&&(t==null?void 0:t.width)===this.video.videoWidth);e&&!P$(e.quality)&&this.onChangeQuality(e.quality)};this.checkDroppedFrames=()=>{var n;let{totalVideoFrames:e,droppedVideoFrames:t}=this.video.getVideoPlaybackQuality(),i=e-this.prevTotalVideoFrames,r=t-this.prevDroppedVideoFrames,a=1-(i-r)/i;!isNaN(a)&&a>0&&this.log({message:`[dropped]. current dropped percent: ${a}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(a)&&a>=this.droppedFramesChecker.percentLimit&&A$(this.currentQuality,this.droppedFramesChecker.minQualityBanLimit)&&(this.limitCounts[this.currentQuality]=((n=this.limitCounts[this.currentQuality])!=null?n:0)+1,this.maxQualityLimit=this.getMaxQualityLimit(this.currentQuality),this.currentTimer&&window.clearTimeout(this.currentTimer),this.currentTimer=window.setTimeout(()=>this.maxQualityLimit=this.getMaxQualityLimit(),this.droppedFramesChecker.qualityUpWaitingTime),this.onDroopedVideoFramesLimitTrigger()),this.savePrevFrameCounts(e,t)}}connect(e){this.log=e.logger.createComponentLog("DroppedFramesManager"),this.video=e.video,this.isAuto=e.isAuto,this.tracks=e.tracks,this.droppedFramesChecker=e.droppedFramesChecker,this.subscription.add(e.playing$.subscribe(()=>this.playing=!0)),this.subscription.add(e.pause$.subscribe(()=>this.playing=!1)),this.isEnabled&&this.subscribe()}destroy(){this.currentTimer&&window.clearTimeout(this.currentTimer),this.subscription.unsubscribe()}get droppedVideoMaxQualityLimit(){return this.maxQualityLimit}subscribe(){this.subscription.add(E$(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=w$(this.droppedFramesChecker.checkTime).pipe(By(()=>this.playing),By(()=>{let r=!!this.isForceCheckCounter;return r&&(this.isForceCheckCounter-=1),!r})),t=this.forceChecker$.pipe(x$(this.droppedFramesChecker.checkTime)),i=R$(e,t);this.subscription.add(i.subscribe(this.checkDroppedFrames))}onChangeQuality(e){this.currentQuality=e;let{totalVideoFrames:t,droppedVideoFrames:i}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,i),this.isForceCheckCounter=this.droppedFramesChecker.tickCountAfterQualityChange,this.forceChecker$.next()}onDroopedVideoFramesLimitTrigger(){this.isAuto.getState()&&(this.log({message:`[onDroopedVideoFramesLimit]. maxQualityLimit: ${this.maxQualityLimit}`}),this.onDroopedVideoFramesLimit$.next())}getMaxQualityLimit(e){var i,r;let t=(r=(i=(0,Dy.default)(this.limitCounts).filter(([,a])=>a>=this.droppedFramesChecker.countLimit).sort(([a],[n])=>k$(a,n)?-1:1))==null?void 0:i[0])==null?void 0:r[0];return e!=null?e:t}get isEnabled(){return this.droppedFramesChecker.enabled&&this.isDroppedFramesCheckerSupport}get isDroppedFramesCheckerSupport(){return!!this.video&&typeof this.video.getVideoPlaybackQuality=="function"}savePrevFrameCounts(e,t){this.prevTotalVideoFrames=e,this.prevDroppedVideoFrames=t}},Gr=zd;import{map as L$,Observable as B$}from"@vkontakte/videoplayer-shared/es2018";import{fromEvent as $$}from"@vkontakte/videoplayer-shared/es2018";var Ca=()=>{var s;return!!((s=window.documentPictureInPicture)!=null&&s.window)||!!document.pictureInPictureElement};var D$=(s,e)=>new B$(t=>{if(!window.IntersectionObserver)return;let i={root:null},r=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||Ca()))},{...i,...e});r.observe(s);let a=$$(document,"visibilitychange").pipe(L$(n=>!document.hidden||Ca())).subscribe(n=>t.next(n));return()=>{r.unobserve(s),a.unsubscribe()}}),Et=D$;var q$=["paused","playing","ready"],j$=["paused","playing","ready"],Va=class{constructor(e){this.subscription=new N$;this.videoState=new G("stopped");this.representations$=new Gd([]);this.droppedFramesManager=new Gr;this.maxSeekBackTime$=new Gd(1/0);this.zeroTime$=new Gd(void 0);this.liveOffset=new or;this._dashCb=e=>{var t,i,r,a;switch(e.name){case"buffering":{let n=e.isBuffering;this.params.output.isBuffering$.next(n);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,category:Oy.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{let n=e.manifest,o=[];for(let u of n){let l=(t=u.name)!=null?t:u.index.toString(10),d=(i=Bi(u.name))!=null?i:U$(u.video),c=u.bitrate/1e3,h={...u.video};if(!d)continue;let p={id:l,quality:d,bitrate:c,size:h};o.push({track:p,representation:u})}this.representations$.next(o),this.params.output.availableVideoTracks$.next(o.map(({track:u})=>u)),((r=this.videoState.getTransition())==null?void 0:r.to)==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let n=e.quality,o=(a=this.representations$.getValue().find(({representation:u})=>u===n))==null?void 0:a.track;this.params.output.hostname$.next(new URL(n.headerUrl,this.params.source.url).hostname),Qd(o)&&this.params.output.currentVideoTrack$.next(o);break}case"bandwidth":{let{size:n,duration:o}=e;this.params.dependencies.throughputEstimator.addRawSpeed(n,o);break}case"index":{this.maxSeekBackTime$.next(e.shiftDuration||0),this.zeroTime$.next(e.zeroTime);break}}};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; seekState: ${JSON.stringify(a)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"));return}if(t)return;let n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if((0,Wd.default)(j$,e)&&(n||o)){this.prepare();return}if((r==null?void 0:r.to)!=="paused"&&a.state==="requested"&&(0,Wd.default)(q$,e)){this.seek(a.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(Se(this.params.source.url));return;case"manifest_ready":this.videoState.startTransitionTo("ready"),this.prepare();break;case"ready":if(i==="paused")this.videoState.setState("paused");else if(i==="playing"){this.videoState.startTransitionTo("playing");let u=r==null?void 0:r.from;u&&u==="ready"&&this.dash.catchUp(),this.dash.play()}return;case"playing":i==="paused"&&(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.dash.pause());return;case"paused":if(i==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.dash.play(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let u=this.liveOffset.getTotalOffset();u>=this.maxSeekBackTime$.getValue()&&(u=0,this.liveOffset.resetTo(u)),this.liveOffset.resume(),this.params.output.position$.next(-u/1e3),this.dash.reinit(Se(this.params.source.url,u))}return;default:return Cy(e)}};this.textTracksManager=new xt(e.source.url),this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=r=>{e.output.error$.next({id:"DashLiveProvider",category:Oy.WTF,message:"DashLiveProvider internal logic error",thrown:r})};this.subscription.add(Fy(this.videoState.stateChangeStarted$.pipe(Pu(r=>({transition:r,type:"start"}))),this.videoState.stateChangeEnded$.pipe(Pu(r=>({transition:r,type:"end"})))).subscribe(({transition:r,type:a})=>{this.log({message:`[videoState change] ${a}: ${JSON.stringify(r)}`})})),this.video=tt(e.container,e.tuning),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.subscription.add(this.dash.soundProhibitedEvent$.subscribe(this.params.output.soundProhibitedEvent$)),this.params.output.duration$.next(1/0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(Fe(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);let i=st(this.video);this.subscription.add(()=>i.destroy()),this.subscription.add(this.representations$.pipe(Pu(r=>r.map(({track:a})=>a)),_y(r=>!!r.length),F$()).subscribe(r=>this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:r}))),this.subscription.add(i.canplay$.subscribe(()=>{var r;((r=this.videoState.getTransition())==null?void 0:r.to)==="ready"&&this.videoState.setState("ready")},t)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused")},t)).add(i.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.videoState.setState("playing")},t)).add(i.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(O$(),Pu(r=>-r/1e3)).subscribe(this.params.output.duration$)).add(C$({zeroTime:this.zeroTime$.pipe(_y(Qd)),position:i.timeUpdate$}).subscribe(({zeroTime:r,position:a})=>this.params.output.liveTime$.next(r+a*1e3),t)).add(zt(this.video,this.params.desiredState.isLooped,t)).add(rt(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(It(this.video,this.params.desiredState.playbackRate,i.playbackRateState$,t)).add(i.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(i.loadedMetadata$.subscribe(this.params.output.loadedMetadataEvent$)).add(i.playing$.subscribe(this.params.output.firstFrameEvent$)).add(i.canplay$.subscribe(this.params.output.canplay$)).add(i.inPiP$.subscribe(this.params.output.inPiP$)).add(i.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(Et(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:r,min:a}})=>{this.dash.setAutoQualityLimits({max:r&&Ny(r),min:a&&Ny(a)}),this.params.output.autoVideoTrackLimits$.next({max:r,min:a})})).add(this.videoState.stateChangeEnded$.subscribe(r=>{var a;switch(r.to){case"stopped":this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState("stopped");break;case"manifest_ready":case"ready":((a=this.params.desiredState.playbackState.getTransition())==null?void 0:a.to)==="ready"&&this.params.desiredState.playbackState.setState("ready");break;case"paused":this.params.desiredState.playbackState.setState("paused");break;case"playing":this.params.desiredState.playbackState.setState("playing");break;default:return Cy(r.to)}},t)).add(Fy(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,_$(["init"])).pipe(V$(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),it(this.video)}createLiveDashPlayer(){let e=new Da({videoElement:this.video,videoState:this.videoState,playbackState:this.params.desiredState.playbackState,liveOffset:this.liveOffset,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode,manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){var l,d,c,h,p,f;let e=this.representations$.getValue(),t=(d=(l=this.params.desiredState.videoTrack.getTransition())==null?void 0:l.to)!=null?d:this.params.desiredState.videoTrack.getState(),i=(h=(c=this.params.desiredState.autoVideoTrackSwitching.getTransition())==null?void 0:c.to)!=null?h:this.params.desiredState.autoVideoTrackSwitching.getState(),r=!i&&Qd(t)?t:Wt(e.map(({track:m})=>m),{container:this.video.getBoundingClientRect(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),a=r==null?void 0:r.id,n=this.params.desiredState.videoTrack.getTransition(),o=(p=this.params.desiredState.videoTrack.getState())==null?void 0:p.id,u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(r&&(n||a!==o)&&this.setVideoTrack(r),u&&this.setAutoQuality(i),n||u||a!==o){let m=(f=e.find(({track:g})=>g.id===a))==null?void 0:f.representation;Vy(m,"Representations missing"),this.dash.startPlay(m,i)}}setVideoTrack(e){var i;let t=(i=this.representations$.getValue().find(({track:r})=>r.id===e.id))==null?void 0:i.representation;Vy(t,`No such representation ${e.id}`),this.dash.switchByName(t.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),r=t==="paused"&&i==="paused",a=-e,n=a<=this.maxSeekBackTime$.getValue()?a:0;this.params.output.position$.next(e/1e3),this.dash.reinit(Se(this.params.source.url,n)),r&&this.dash.pause(),this.liveOffset.resetTo(n,r)}};var Uy=Va;var ex=N(gt(),1);var $e=(s,e)=>{let t=0;for(let i=0;i<s.length;i++){let r=s.start(i)*1e3,a=s.end(i)*1e3;r<=e&&e<=a&&(t=a)}return Math.max(t-e,0)};import{assertNever as wC,assertNonNullable as AC,debounce as PC,ErrorCategory as XI,filter as Dp,filterChanged as el,fromEvent as kC,isNonNullable as JI,isNullable as RC,map as Cp,merge as tl,observableFrom as Vp,once as ZI,Subscription as MC}from"@vkontakte/videoplayer-shared/es2018";var ku=class{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,i){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:i})}removeEventListener(e,t){if(!(e in this.listeners))return;let i=this.listeners[e];for(let r=0,a=i.length;r<a;r++)if(i[r].callback===t){i.splice(r,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;let i=this.listeners[e.type].slice();for(let r=0,a=i.length;r<a;r++){let n=i[r];try{n.callback.call(this,e)}catch(o){Promise.resolve().then(()=>{throw o})}n.options&&n.options.once&&this.removeEventListener(e.type,n.callback)}return!e.defaultPrevented}},Wr=class extends ku{constructor(){super(),this.listeners||ku.call(this),Object.defineProperty(this,"aborted",{value:!1,writable:!0,configurable:!0}),Object.defineProperty(this,"onabort",{value:null,writable:!0,configurable:!0}),Object.defineProperty(this,"reason",{value:void 0,writable:!0,configurable:!0})}toString(){return"[object AbortSignal]"}dispatchEvent(e){e.type==="abort"&&(this.aborted=!0,typeof this.onabort=="function"&&this.onabort.call(this,e)),super.dispatchEvent(e)}},Oa=class{constructor(){Object.defineProperty(this,"signal",{value:new Wr,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch(r){typeof document!="undefined"?document.createEvent?(t=document.createEvent("Event"),t.initEvent("abort",!1,!1)):(t=document.createEventObject(),t.type="abort"):t={type:"abort",bubbles:!1,cancelable:!1}}let i=e;if(i===void 0)if(typeof document=="undefined")i=new Error("This operation was aborted"),i.name="AbortError";else try{i=new DOMException("signal is aborted without reason")}catch(r){i=new Error("This operation was aborted"),i.name="AbortError"}this.signal.reason=i,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol!="undefined"&&Symbol.toStringTag&&(Oa.prototype[Symbol.toStringTag]="AbortController",Wr.prototype[Symbol.toStringTag]="AbortSignal");function Ru(s){return s.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof s.Request=="function"&&!s.Request.prototype.hasOwnProperty("signal")||!s.AbortController}function Yd(s){typeof s=="function"&&(s={fetch:s});let{fetch:e,Request:t=e.Request,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r=!1}=s;if(!Ru({fetch:e,Request:t,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r}))return{fetch:e,Request:a};let a=t;(a&&!a.prototype.hasOwnProperty("signal")||r)&&(a=function(l,d){let c;d&&d.signal&&(c=d.signal,delete d.signal);let h=new t(l,d);return c&&Object.defineProperty(h,"signal",{writable:!1,enumerable:!1,configurable:!0,value:c}),h},a.prototype=t.prototype);let n=e;return{fetch:(u,l)=>{let d=a&&a.prototype.isPrototypeOf(u)?u.signal:l?l.signal:void 0;if(d){let c;try{c=new DOMException("Aborted","AbortError")}catch(p){c=new Error("Aborted"),c.name="AbortError"}if(d.aborted)return Promise.reject(c);let h=new Promise((p,f)=>{d.addEventListener("abort",()=>f(c),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([h,n(u,l)])}return n(u,l)},Request:a}}var H$=()=>"fetch"in window,_a=H$()&&Ru({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),qy=_a?Yd({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,wt=_a?qy.fetch:window.fetch,Vj=_a?qy.Request:window.Request,ae=_a?Oa:window.AbortController,Oj=_a?Wr:window.AbortSignal;var kp=N(Fa(),1);var kT=N(PT(),1);import{ErrorCategory as Ua}from"@vkontakte/videoplayer-shared/es2018";var Mu=s=>{if(!s)return{id:"EmptyResponse",category:Ua.PARSER,message:"Empty response"};if(s.length<=2&&s.match(/^\d+$/))return{id:`UVError#${s}`,category:Ua.NETWORK,message:`UV Error ${s}`};let e=(0,kT.default)(s).substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:Ua.NETWORK,message:"Received unexpected HTML, possibly a ISP block"};if(e.startsWith("<?xml"))return new DOMParser().parseFromString(s,"text/xml").querySelector("parsererror")?{id:"InvalidXML",category:Ua.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:Ua.PARSER,message:"Response is valid XML, but parser failed"}};var Ne=(s,e,t=0)=>{for(let i=0;i<s.length;i++)if(s.start(i)*1e3-t<=e&&s.end(i)*1e3+t>e)return!0;return!1};import{abortable as wp,assertNonNullable as ss,combine as as,ErrorCategory as Ft,filter as Qu,filterChanged as Tn,flattenObject as In,fromEvent as Ti,getTraceSubscriptionMethod as oC,interval as Ap,isNonNullable as xn,isNullable as zI,map as ns,merge as pr,now as Pp,Subject as Gu,Subscription as QI,tap as uC,throttle as lC,ValueSubject as he}from"@vkontakte/videoplayer-shared/es2018";var $u=N(gt(),1),ts=N(Ot(),1),Du=N(Fa(),1);var RD=(s,e={})=>{let i=e.timeout||1,r=performance.now();return window.setTimeout(()=>{s({get didTimeout(){return e.timeout?!1:performance.now()-r-1>i},timeRemaining(){return Math.max(0,1+(performance.now()-r))}})},1)},MD=s=>window.clearTimeout(s),RT=s=>typeof s=="function"&&(s==null?void 0:s.toString().endsWith("{ [native code] }")),MT=!RT(window.requestIdleCallback)||!RT(window.cancelIdleCallback),Yr=MT?RD:window.requestIdleCallback,Yt=MT?MD:window.cancelIdleCallback;var CI=N(eu(),1);import{assertNever as LD,ErrorCategory as LT,Subject as BT}from"@vkontakte/videoplayer-shared/es2018";var BD=18,$T=!1;try{$T=j.browser.isSafari&&!!j.browser.safariVersion&&j.browser.safariVersion<=BD}catch(s){console.error(s)}var tp=class{constructor(e){this.bufferFull$=new BT;this.error$=new BT;this.queue=[];this.currentTask=null;this.destroyed=!1;this.abortRequested=!1;this.completeTask=()=>{var e;try{if(this.currentTask){let t=(e=this.currentTask.signal)==null?void 0:e.aborted;this.currentTask.callback(!t),this.currentTask=null}this.queue.length&&this.pull()}catch(t){this.error$.next({id:"BufferTaskQueueUnknown",category:LT.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(i=>{let r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(r=>{let a={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(a),this.pull()})}async abort(e){return new Promise(t=>{let i,r=a=>{this.abortRequested=!1,t(a)};$T&&e?i={operation:"safariAbort",init:e,callback:r}:i={operation:"abort",callback:r};for(let{callback:a}of this.queue)a(!1);this.abortRequested=!0,i&&(this.queue=[i]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){var r;if((this.buffer.updating||this.currentTask||this.destroyed)&&!this.abortRequested)return;let e=this.queue.shift();if(!e)return;if((r=e.signal)!=null&&r.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(a){a instanceof DOMException&&a.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):a instanceof DOMException&&a.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:LT.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:a}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){let{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:LD(t)}}},DT=tp;var Kr=s=>{let e=0;for(let t=0;t<s.length;t++)e+=s.end(t)-s.start(t);return e*1e3};import{abortable as Ci,assertNonNullable as nt,ErrorCategory as Si,fromEvent as vp,getExponentialDelay as yp,isNonNullable as es,isNullable as Ue,now as Bu,once as Y0,Subject as K0,Subscription as X0,ValueSubject as dr}from"@vkontakte/videoplayer-shared/es2018";var X=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let i=this.readUint32();this.type=this.readString(4),this.size32=i<=e.buffer.byteLength-e.byteOffset?i:NaN;let r=this.size32?this.size32-8:void 0,a=e.byteOffset+this.cursor;this.size64=0,this.usertype=0,this.content=new DataView(e.buffer,a,r)}get id(){return this.type}get size(){return this.size32}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t="ascii"){let r=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,r}readUint8(){let e=this.source.getUint8(this.cursor);return this.cursor+=1,e}readUint16(){let e=this.source.getUint16(this.cursor);return this.cursor+=2,e}readUint32(){let e=this.source.getUint32(this.cursor);return this.cursor+=4,e}readUint64(){let e=this.source.getBigInt64(this.cursor);return this.cursor+=8,e}};var Xr=class extends X{};var qa=class extends X{constructor(t,i){super(t,i);this.ondemandPrefix="ondemandlivejson";this.ondemandDataReceivedKey="t-in";this.ondemandDataPreparedKey="t-out";let r=this.content.byteOffset,a=r+this.content.byteLength,n=new TextDecoder("ascii").decode(this.content.buffer.slice(r,a)).split(this.ondemandPrefix)[1],o=JSON.parse(n);this.serverDataReceivedTimestamp=o[this.ondemandDataReceivedKey],this.serverDataPreparedTime=o[this.ondemandDataPreparedKey]}};var ja=class extends X{constructor(e,t){super(e,t),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let i=this.size-this.cursor;for(;i;){let r=this.readString(4);this.compatibleBrands.push(r),i-=4}}};var Ha=class extends X{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ue=class extends X{constructor(e,t){super(e,t);let i=this.readUint32();this.version=i>>>24,this.flags=i&16777215}};var za=class extends ue{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.timescale=this.readUint32(),this.duration=this.readUint32(),this.rate=this.readUint32(),this.volume=this.readUint16()}};var Qa=class extends X{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ga=class extends X{constructor(e,t){super(e,t),this.data=this.content}};var lr=class extends ue{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e,t){super(e,t),this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let i=0;i<this.referenceCount;i++){let r=this.readUint32(),a=r>>>31,n=r<<1>>>1,o=this.readUint32();r=this.readUint32();let u=r>>>28,l=r<<3>>>3;this.segments.push({referenceType:a,referencedSize:n,subsegmentDuration:o,SAPType:u,SAPDeltaTime:l})}}};var Wa=class extends X{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ya=class extends X{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ka=class extends ue{constructor(e,t){switch(super(e,t),this.readUint8()){case 0:this.stereoMode=0;break;case 1:this.stereoMode=1;break;case 2:this.stereoMode=2;break;case 3:this.stereoMode=3;break;case 4:this.stereoMode=4;break}this.cursor+=1}};var Xa=class extends ue{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var Ja=class extends ue{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var Za=class extends X{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var en=class extends ue{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.trackId=this.readUint32(),this.cursor+=4,this.duration=this.readUint32(),this.cursor+=8,this.layer=this.readUint16(),this.alternateGroup=this.readUint16(),this.cursor+=2,this.cursor+=2,this.matrix=[[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()]],this.width=this.readUint32(),this.height=this.readUint32()}};var tn=class extends X{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var rn=class extends X{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var sn=class extends ue{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var an=class extends X{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var nn=class extends ue{constructor(e,t){super(e,t),this.trackId=this.readUint32(),this.flags&1&&(this.baseDataOffset=this.readUint64()),this.flags&2&&(this.sampleDescriptionIndex=this.readUint32()),this.flags&8&&(this.defaultSampleDuration=this.readUint32()),this.flags&16&&(this.defaultSampleSize=this.readUint32()),this.flags&32&&(this.defaultSampleFlags=this.readUint32())}};var on=class extends ue{constructor(t,i){super(t,i);this.baseMediaDecodeTime32=0;this.baseMediaDecodeTime64=BigInt(0);this.version===1?this.baseMediaDecodeTime64=this.readUint64():this.baseMediaDecodeTime32=this.readUint32()}get baseMediaDecodeTime(){return this.version===1?this.baseMediaDecodeTime64:this.baseMediaDecodeTime32}};var un=class extends ue{constructor(t,i){super(t,i);this.sampleDuration=[];this.sampleSize=[];this.sampleFlags=[];this.sampleCompositionTimeOffset=[];this.optionalFields=0;this.sampleCount=this.readUint32(),this.flags&1&&(this.dataOffset=this.readUint32()),this.flags&4&&(this.firstSampleFlags=this.readUint32());for(let r=0;r<this.sampleCount;r++)this.flags&256&&this.sampleDuration.push(this.readUint32()),this.flags&512&&this.sampleSize.push(this.readUint32()),this.flags&1024&&this.sampleFlags.push(this.readUint32()),this.flags&2048&&this.sampleCompositionTimeOffset.push(this.readUint32())}};var ln=class extends X{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var cn=class extends ue{constructor(e,t){super(e,t),this.entryCount=this.readUint32(),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+8,this.content.byteLength-8))}};var dn=class extends X{constructor(e,t){super(e,t),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+78,this.content.byteLength-78))}};var DD={ftyp:ja,moov:Ha,mvhd:za,moof:Qa,mdat:Ga,sidx:lr,trak:Wa,mdia:Za,mfhd:sn,tkhd:en,traf:an,tfhd:nn,tfdt:on,trun:un,minf:tn,sv3d:Ya,st3d:Ka,prhd:Xa,proj:rn,equi:Ja,uuid:qa,stbl:ln,stsd:cn,avc1:dn,unknown:Xr},bi=class s{constructor(e={}){this.options={offset:0,...e}}parse(e){let t=[],i=this.options.offset;for(;i<e.byteLength;)try{let a=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+i+4,4)),n=this.createBox(a,new DataView(e.buffer,e.byteOffset+i));if(!n.size)break;t.push(n),i+=n.size}catch(r){break}return t}createBox(e,t){let i=DD[e];return i?new i(t,new s):new Xr(t,new s)}};var Di=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{var i,r,a;(a=(i=this.index)[r=t.type])!=null||(i[r]=[]),this.index[t.type].push(t),t.children.length>0&&this.indexBoxLevel(t.children)})}find(e){return this.index[e]&&this.index[e][0]?this.index[e][0]:null}findAll(e){return this.index[e]||[]}};var VD=new TextDecoder("ascii"),OD=s=>VD.decode(new DataView(s.buffer,s.byteOffset+4,4))==="ftyp",_D=s=>{let e=new lr(s,new bi),t=e.earliestPresentationTime/e.timescale*1e3,i=s.byteOffset+s.byteLength+e.firstOffset;return e.segments.map(a=>{if(a.referenceType!==0)throw new Error("Unsupported multilevel sidx");let n=a.subsegmentDuration/e.timescale*1e3,o={status:"none",time:{from:t,to:t+n},byte:{from:i,to:i+a.referencedSize-1}};return t+=n,i+=a.referencedSize,o})},FD=(s,e)=>{let i=new bi().parse(s),r=new Di(i),a=r.findAll("moof"),n=e?r.findAll("uuid"):r.findAll("mdat");if(!(n.length&&a.length))return null;let o=a[0],u=n[n.length-1],l=o.source.byteOffset,c=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(s.buffer,l,c)},ND=s=>{let t=new bi().parse(s),i=new Di(t),r={},a=i.findAll("uuid");return a.length?a[a.length-1]:r},UD=s=>{var r;let t=new bi().parse(s);return(r=new Di(t).find("sidx"))==null?void 0:r.timescale},qD=(s,e)=>{let i=new bi().parse(s),a=new Di(i).findAll("traf"),n=a[a.length-1].children.find(c=>c.type==="tfhd"),o=a[a.length-1].children.find(c=>c.type==="tfdt"),u=a[a.length-1].children.find(c=>c.type==="trun"),l=0;return u.sampleDuration.length?l=u.sampleDuration.reduce((c,h)=>c+h,0):l=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+l)/e*1e3},jD=s=>{let e={is3dVideo:!1,stereoMode:0,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}},i=new bi().parse(s),r=new Di(i);if(r.find("sv3d")){e.is3dVideo=!0;let n=r.find("st3d");n&&(e.stereoMode=n.stereoMode);let o=r.find("prhd");o&&(e.projectionData.pose.yaw=o.poseYawDegrees,e.projectionData.pose.pitch=o.posePitchDegrees,e.projectionData.pose.roll=o.poseRollDegrees);let u=r.find("equi");u&&(e.projectionData.bounds.top=u.projectionBoundsTop,e.projectionData.bounds.right=u.projectionBoundsRight,e.projectionData.bounds.bottom=u.projectionBoundsBottom,e.projectionData.bounds.left=u.projectionBoundsLeft)}return e},CT={validateData:OD,parseInit:jD,getIndexRange:()=>{},parseSegments:_D,parseFeedableSegmentChunk:FD,getChunkEndTime:qD,getServerLatencyTimestamps:ND,getTimescaleFromIndex:UD};var hn=N(gt(),1);import{assertNonNullable as rp,isNonNullable as FT,isNullable as zD}from"@vkontakte/videoplayer-shared/es2018";import{assertNever as HD}from"@vkontakte/videoplayer-shared/es2018";var VT={440786851:{type:"master"},17030:{type:"uint"},17143:{type:"uint"},17138:{type:"uint"},17139:{type:"uint"},17026:{type:"string"},17031:{type:"uint"},17029:{type:"uint"},236:{type:"binary"},408125543:{type:"master"},290298740:{type:"master"},19899:{type:"master"},21419:{type:"binary"},21420:{type:"uint"},357149030:{type:"master"},2807729:{type:"uint"},17545:{type:"float"},374648427:{type:"master"},174:{type:"master"},224:{type:"master"},30320:{type:"master"},30321:{type:"uint"},30322:{type:"master"},272869232:{type:"master"},524531317:{type:"master"},231:{type:"uint"},22612:{type:"master"},22743:{type:"uint"},167:{type:"uint"},171:{type:"uint"},163:{type:"binary"},160:{type:"master"},175:{type:"binary"},423732329:{type:"master"},307544935:{type:"master"},475249515:{type:"master"},187:{type:"master"},179:{type:"uint"},183:{type:"master"},247:{type:"uint"},241:{type:"uint"},240:{type:"uint"},178:{type:"uint"},21368:{type:"uint"},234:{type:"uint"},219:{type:"master"},150:{type:"uint"}},OT=s=>{let e=s.getUint8(0),t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);let i=pn(s,t),r=i in VT,a=r?VT[i].type:"binary",n=s.getUint8(t),o=0;n&128?o=1:n&64?o=2:n&32?o=3:n&16?o=4:n&8?o=5:n&4?o=6:n&2?o=7:n&1&&(o=8);let u=new DataView(s.buffer,s.byteOffset+t+1,o-1),l=n&255>>o,d=pn(u),c=l*2**((o-1)*8)+d,h=t+o,p;return h+c>s.byteLength?p=new DataView(s.buffer,s.byteOffset+h):p=new DataView(s.buffer,s.byteOffset+h,c),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:a,tagHeaderSize:h,tagSize:h+c,value:p,valueSize:c}},pn=(s,e=s.byteLength)=>{switch(e){case 1:return s.getUint8(0);case 2:return s.getUint16(0);case 3:return s.getUint8(0)*2**16+s.getUint16(1);case 4:return s.getUint32(0);case 5:return s.getUint8(0)*2**32+s.getUint32(1);case 6:return s.getUint16(0)*2**32+s.getUint32(2);case 7:{let t=s.getUint8(0)*281474976710656+s.getUint16(1)*4294967296+s.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},_t=(s,e)=>{switch(e){case"int":return s.getInt8(0);case"uint":return pn(s);case"float":return s.byteLength===4?s.getFloat32(0):s.getFloat64(0);case"string":return new TextDecoder("ascii").decode(s);case"utf8":return new TextDecoder("utf-8").decode(s);case"date":return new Date(Date.UTC(2001,0)+s.getInt8(0)).getTime();case"master":return s;case"binary":return s;default:HD(e)}},cr=(s,e)=>{let t=0;for(;t<s.byteLength;){let i=new DataView(s.buffer,s.byteOffset+t),r=OT(i);if(!e(r))return;r.type==="master"&&cr(r.value,e),t=r.value.byteOffset-s.byteOffset+r.valueSize}},_T=s=>{if(s.getUint32(0)!==440786851)return!1;let e,t,i,r=OT(s);return cr(r.value,({tag:a,type:n,value:o})=>(a===17143?e=_t(o,n):a===17026?t=_t(o,n):a===17029&&(i=_t(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)};var NT=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],QD=[231,22612,22743,167,171,163,160,175],GD=s=>{let e,t,i,r,a=!1,n=!1,o=!1,u,l,d=!1,c=0;return cr(s,({tag:h,type:p,value:f,valueSize:m})=>{if(h===21419){let g=_t(f,p);l=pn(g)}else h!==21420&&(l=void 0);return h===408125543?(e=f.byteOffset,t=f.byteOffset+m):h===357149030?a=!0:h===290298740?n=!0:h===2807729?i=_t(f,p):h===17545?r=_t(f,p):h===21420&&l===475249515?u=_t(f,p):h===374648427?cr(f,({tag:g,type:S,value:v})=>g===30321?(d=_t(v,S)===1,!1):!0):a&&n&&(0,hn.default)(NT,h)&&(o=!0),!o}),rp(e,"Failed to parse webm Segment start"),rp(t,"Failed to parse webm Segment end"),rp(r,"Failed to parse webm Segment duration"),i=i!=null?i:1e6,{segmentStart:Math.round(e/1e9*i*1e3),segmentEnd:Math.round(t/1e9*i*1e3),timeScale:i,segmentDuration:Math.round(r/1e9*i*1e3),cuesSeekPosition:u,is3dVideo:d,stereoMode:c,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},WD=s=>{if(zD(s.cuesSeekPosition))return;let e=s.segmentStart+s.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},YD=(s,e)=>{let t=!1,i=!1,r=o=>FT(o.time)&&FT(o.position),a=[],n;return cr(s,({tag:o,type:u,value:l})=>{switch(o){case 475249515:t=!0;break;case 187:n&&r(n)&&a.push(n),n={};break;case 179:n&&(n.time=_t(l,u));break;case 183:break;case 241:n&&(n.position=_t(l,u));break;default:t&&(0,hn.default)(NT,o)&&(i=!0)}return!(t&&i)}),n&&r(n)&&a.push(n),a.map((o,u)=>{let{time:l,position:d}=o,c=a[u+1];return{status:"none",time:{from:l,to:c?c.time:e.segmentDuration},byte:{from:e.segmentStart+d,to:c?e.segmentStart+c.position-1:e.segmentEnd-1}}})},KD=s=>{let e=0,t=!1;try{cr(s,i=>i.tag===524531317?i.tagSize<=s.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):(0,hn.default)(QD,i.tag)?(e+i.tagSize<=s.byteLength&&(e+=i.tagSize,t||(t=(0,hn.default)([163,160,175],i.tag))),!0):!1)}catch(i){}return e>0&&e<=s.byteLength&&t?new DataView(s.buffer,s.byteOffset,e):null},UT={validateData:_T,parseInit:GD,getIndexRange:WD,parseSegments:YD,parseFeedableSegmentChunk:KD};var fn=s=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(s);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return UT;case"mp4":return CT}}throw new ReferenceError(`Unsupported mime type ${s}`)};var bp=N(lp(),1),MI=N(Ji(),1),LI=N(cp(),1),BI=N(Ot(),1),gp=N(nr(),1);var II=N(gt(),1),Zr=s=>{let e=s.split("."),[t,...i]=e;if(!t)return!1;switch(t){case"av01":{let[r,a,n]=i;return!!(n&&parseInt(n,10)>8)}case"vp09":{let[r,a,n]=i;return!!(r&&parseInt(r,10)>=2&&n&&parseInt(n,10)>8)}case"avc1":{let r=i[0];if(!r||r.length!==6)return!1;let[a,n]=r.toUpperCase(),o=a+n;return(0,II.default)(["6E","7A","F4"],o)}}return!1};import{isNonNullable as G0,isNullable as kI}from"@vkontakte/videoplayer-shared/es2018";var Lu=s=>{if(s.includes("/")){let e=s.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(s)};var xI=s=>{var e;try{let t=z0(),i=s.match(t),{groups:r}=i!=null?i:{};if(r){let a={};if(r.extensions){let u=r.extensions.toLowerCase().match(/(?:[0-9a-wy-z](?:-[a-z0-9]{2,8})+)/g);Array.from(u||[]).forEach(l=>{a[l[0]]=l.slice(2)})}let n=(e=r.variants)==null?void 0:e.split(/-/).filter(u=>u!==""),o={extlang:r.extlang,langtag:r.langtag,language:r.language,privateuse:r.privateuse||r.privateuse2,region:r.region,script:r.script,extensions:a,variants:n};return Object.keys(o).forEach(u=>{let l=o[u];(typeof l=="undefined"||l==="")&&delete o[u]}),o}return null}catch(t){return null}};function z0(){let s="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",d=`^(?:(?<langtag>${`
118
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 pp=N(Ot(),1);import{videoSizeToQuality as Q0}from"@vkontakte/videoplayer-shared/es2018";var EI=({id:s,width:e,height:t,bitrate:i,fps:r,quality:a,streamId:n})=>{var u;let o=(u=a?Bi(a):void 0)!=null?u:Q0({width:e,height:t});return o&&{id:s,quality:o,bitrate:i,size:{width:e,height:t},fps:r,streamId:n}},wI=({id:s,bitrate:e})=>({id:s,bitrate:e}),AI=({language:s,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:s,label:e}),PI=({language:s,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:s,label:e}),hp=({id:s,language:e,label:t,codecs:i,isDefault:r})=>({id:s,language:e,label:t,codec:(0,pp.default)(i.split("."),0),isDefault:r}),fp=({id:s,language:e,label:t,hdr:i,codecs:r})=>({id:s,language:e,hdr:i,label:t,codec:(0,pp.default)(r.split("."),0)}),mp=s=>"url"in s,Je=s=>s.type==="template",mn=s=>s instanceof DOMException&&(s.name==="AbortError"||s.code===20);var kI=s=>{if(!(s!=null&&s.startsWith("P")))return;let e=(n,o)=>{let u=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(u)?0:u)*o},i=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(s),r=(i==null?void 0:i[1])==="-"?-1:1,a={days:e(i==null?void 0:i[5],r),hours:e(i==null?void 0:i[6],r),minutes:e(i==null?void 0:i[7],r),seconds:e(i==null?void 0:i[8],r)};return a.days*24*60*60*1e3+a.hours*60*60*1e3+a.minutes*60*1e3+a.seconds*1e3},gi=(s,e)=>{let t=s;t=(0,bp.default)(t,"$$","$");let i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[r,a]of(0,MI.default)(i)){let n=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=(0,bp.default)(t,n,(o,u)=>RI(a)?o:RI(u)?a:(0,LI.default)(a,parseInt(u,10),"0"))}return t},$I=(s,e)=>{var w,P,C,M,k,Q,U,A,F,R,x,$,oe,Ce,se,K,ye,Te,Ie,Ve,Tt,At,qt,Xt,Ai,bs,gs,Ss,vs,ys,Ts,Is,xs,Es,ws,As,Ps,Rs,ks,Ms,Ls,Bs,$s,Ds,Cs,Vs,Os,_s,Fs,Ns,Us,qs,js,Hs,zs,Qs,Gs,Ws,Ys,Ks,Xs;let i=new DOMParser().parseFromString(s,"application/xml"),r={video:[],audio:[],text:[]},a=i.children[0],n=Array.from(a.querySelectorAll("MPD > BaseURL").values()).map(ce=>{var _,je;return(je=(_=ce.textContent)==null?void 0:_.trim())!=null?je:""}),o=(w=(0,BI.default)(n,0))!=null?w:"",u=a.getAttribute("type")==="dynamic",l=a.getAttribute("availabilityStartTime"),d=a.getAttribute("publishTime"),c=a.getElementsByTagName("vk:Attrs")[0],h=c==null?void 0:c.getElementsByTagName("vk:XLatestSegmentPublishTime")[0].textContent,p=c==null?void 0:c.getElementsByTagName("vk:XStreamIsLive")[0].textContent,f=c==null?void 0:c.getElementsByTagName("vk:XStreamIsUnpublished")[0].textContent,m=c==null?void 0:c.getElementsByTagName("vk:XPlaybackDuration")[0].textContent,g;u&&(g={availabilityStartTime:l?new Date(l).getTime():0,publishTime:d?new Date(d).getTime():0,latestSegmentPublishTime:h?new Date(h).getTime():0,streamIsAlive:p==="yes",streamIsUnpublished:f==="yes"});let S,v=a.getAttribute("mediaPresentationDuration"),y=[...a.getElementsByTagName("Period")],I=y.reduce((ce,_)=>({...ce,[_.id]:_.children}),{}),T=y.reduce((ce,_)=>({...ce,[_.id]:_.getAttribute("duration")}),{});v?S=kI(v):(0,gp.default)(T).filter(ce=>ce).length&&!u?S=(0,gp.default)(T).reduce((ce,_)=>{var je;return ce+((je=kI(_))!=null?je:0)},0):m&&(S=parseInt(m,10));let E=0,O=(C=(P=a.getAttribute("profiles"))==null?void 0:P.split(","))!=null?C:[];for(let ce of y.map(_=>_.id))for(let _ of I[ce]){let je=(M=_.getAttribute("id"))!=null?M:"id"+(E++).toString(10),Pt=(k=_.getAttribute("mimeType"))!=null?k:"",ji=(Q=_.getAttribute("codecs"))!=null?Q:"",Hi=(U=_.getAttribute("contentType"))!=null?U:Pt==null?void 0:Pt.split("/")[0],Rl=(F=(A=_.getAttribute("profiles"))==null?void 0:A.split(","))!=null?F:[],Js=(x=xI((R=_.getAttribute("lang"))!=null?R:""))!=null?x:{},Jt=(Ce=(oe=($=_.querySelector("Label"))==null?void 0:$.textContent)==null?void 0:oe.trim())!=null?Ce:void 0,kl=_.querySelectorAll("Representation"),Ml=_.querySelector("SegmentTemplate"),Ll=(K=(se=_.querySelector("Role"))==null?void 0:se.getAttribute("value"))!=null?K:void 0,ut=Hi,H={id:je,language:Js.language,isDefault:Ll==="main",label:Jt,codecs:ji,hdr:ut==="video"&&Zr(ji),mime:Pt,representations:[]};for(let V of kl){let we=(ye=V.getAttribute("lang"))!=null?ye:void 0,Rt=(Ie=(Te=Jt!=null?Jt:_.getAttribute("label"))!=null?Te:V.getAttribute("label"))!=null?Ie:void 0,Zt=(At=(Tt=(Ve=V.querySelector("BaseURL"))==null?void 0:Ve.textContent)==null?void 0:Tt.trim())!=null?At:"",He=new URL(Zt||o,e).toString(),Ae=(qt=V.getAttribute("mimeType"))!=null?qt:Pt,ei=(Ai=(Xt=V.getAttribute("codecs"))!=null?Xt:ji)!=null?Ai:"",ti;if(Hi==="text"){let Pe=V.getAttribute("id")||"",ii=((bs=Js.privateuse)==null?void 0:bs.includes("x-auto"))||Pe.includes("_auto"),ze=V.querySelector("SegmentTemplate");if(ze){let kt={representationId:(gs=V.getAttribute("id"))!=null?gs:void 0,bandwidth:(Ss=V.getAttribute("bandwidth"))!=null?Ss:void 0},ri=parseInt((vs=V.getAttribute("bandwidth"))!=null?vs:"",10)/1e3,si=(Ts=parseInt((ys=ze.getAttribute("startNumber"))!=null?ys:"",10))!=null?Ts:1,lt=parseInt((Is=ze.getAttribute("timescale"))!=null?Is:"",10),zi=(xs=ze.querySelectorAll("SegmentTimeline S"))!=null?xs:[],ct=ze.getAttribute("media");if(!ct)continue;let ai=[],ni=0,oi="",dt=0,Mt=si,ee=0;for(let de of zi){let Qe=parseInt((Es=de.getAttribute("d"))!=null?Es:"",10),ne=parseInt((ws=de.getAttribute("r"))!=null?ws:"",10)||0,Re=parseInt((As=de.getAttribute("t"))!=null?As:"",10);ee=Number.isFinite(Re)?Re:ee;let Ge=Qe/lt*1e3,ke=ee/lt*1e3;for(let me=0;me<ne+1;me++){let Me=gi(ct,{...kt,segmentNumber:Mt.toString(10),segmentTime:(ee+me*Qe).toString(10)}),pt=(ke!=null?ke:0)+me*Ge,Bt=pt+Ge;Mt++,ai.push({time:{from:pt,to:Bt},url:Me})}ee+=(ne+1)*Qe,ni+=(ne+1)*Ge}dt=ee/lt*1e3,oi=gi(ct,{...kt,segmentNumber:Mt.toString(10),segmentTime:ee.toString(10)});let Lt={time:{from:dt,to:1/0},url:oi},xe={type:"template",baseUrl:He,segmentTemplateUrl:ct,initUrl:"",totalSegmentsDurationMs:ni,segments:ai,nextSegmentBeyondManifest:Lt,timescale:lt};ti={id:Pe,kind:"text",segmentReference:xe,profiles:[],duration:S,bitrate:ri,mime:"",codecs:"",width:0,height:0,isAuto:ii}}else ti={id:Pe,isAuto:ii,kind:"text",url:He}}else{let Pe=(Rs=(Ps=V.getAttribute("contentType"))!=null?Ps:Ae==null?void 0:Ae.split("/")[0])!=null?Rs:Hi,ii=(Ms=(ks=_.getAttribute("profiles"))==null?void 0:ks.split(","))!=null?Ms:[],ze=parseInt((Ls=V.getAttribute("width"))!=null?Ls:"",10),kt=parseInt((Bs=V.getAttribute("height"))!=null?Bs:"",10),ri=parseInt(($s=V.getAttribute("bandwidth"))!=null?$s:"",10)/1e3,si=(Ds=V.getAttribute("frameRate"))!=null?Ds:"",lt=(Cs=V.getAttribute("quality"))!=null?Cs:void 0,zi=si?Lu(si):void 0,ct=(Vs=V.getAttribute("id"))!=null?Vs:"id"+(E++).toString(10),ai=Pe==="video"?`${kt}p`:Pe==="audio"?`${ri}Kbps`:ei,ni=`${ct}@${ai}`,oi=[...O,...Rl,...ii],dt,Mt=V.querySelector("SegmentBase"),ee=(Os=V.querySelector("SegmentTemplate"))!=null?Os:Ml;if(Mt){let xe=(Fs=(_s=V.querySelector("SegmentBase Initialization"))==null?void 0:_s.getAttribute("range"))!=null?Fs:"",[de,Qe]=xe.split("-").map(Me=>parseInt(Me,10)),ne={from:de,to:Qe},Re=(Ns=V.querySelector("SegmentBase"))==null?void 0:Ns.getAttribute("indexRange"),[Ge,ke]=Re?Re.split("-").map(Me=>parseInt(Me,10)):[],me=Re?{from:Ge,to:ke}:void 0;dt={type:"byteRange",url:He,initRange:ne,indexRange:me}}else if(ee){let xe={representationId:(Us=V.getAttribute("id"))!=null?Us:void 0,bandwidth:(qs=V.getAttribute("bandwidth"))!=null?qs:void 0},de=parseInt((js=ee.getAttribute("timescale"))!=null?js:"",10),Qe=(Hs=ee.getAttribute("initialization"))!=null?Hs:"",ne=ee.getAttribute("media"),Re=(Qs=parseInt((zs=ee.getAttribute("startNumber"))!=null?zs:"",10))!=null?Qs:1,Ge=gi(Qe,xe);if(!ne)throw new ReferenceError("No media attribute in SegmentTemplate");let ke=(Gs=ee.querySelectorAll("SegmentTimeline S"))!=null?Gs:[],me=[],Me=0,pt="",Bt=0;if(ke.length){let ui=Re,pe=0;for(let ht of ke){let be=parseInt((Ws=ht.getAttribute("d"))!=null?Ws:"",10),We=parseInt((Ys=ht.getAttribute("r"))!=null?Ys:"",10)||0,li=parseInt((Ks=ht.getAttribute("t"))!=null?Ks:"",10);pe=Number.isFinite(li)?li:pe;let Qi=be/de*1e3,Gi=pe/de*1e3;for(let ci=0;ci<We+1;ci++){let $l=gi(ne,{...xe,segmentNumber:ui.toString(10),segmentTime:(pe+ci*be).toString(10)}),Zs=(Gi!=null?Gi:0)+ci*Qi,Dl=Zs+Qi;ui++,me.push({time:{from:Zs,to:Dl},url:$l})}pe+=(We+1)*be,Me+=(We+1)*Qi}Bt=pe/de*1e3,pt=gi(ne,{...xe,segmentNumber:ui.toString(10),segmentTime:pe.toString(10)})}else if(G0(S)){let pe=parseInt((Xs=ee.getAttribute("duration"))!=null?Xs:"",10)/de*1e3,ht=Math.ceil(S/pe),be=0;for(let We=1;We<ht;We++){let li=gi(ne,{...xe,segmentNumber:We.toString(10),segmentTime:be.toString(10)});me.push({time:{from:be,to:be+pe},url:li}),be+=pe}Bt=be,pt=gi(ne,{...xe,segmentNumber:ht.toString(10),segmentTime:be.toString(10)})}let Bl={time:{from:Bt,to:1/0},url:pt};dt={type:"template",baseUrl:He,segmentTemplateUrl:ne,initUrl:Ge,totalSegmentsDurationMs:Me,segments:me,nextSegmentBeyondManifest:Bl,timescale:de}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Pe||!Ae)continue;let Lt={video:"video",audio:"audio",text:"text"}[Pe];if(!Lt)continue;ut||(ut=Lt),ti={id:ni,kind:Lt,segmentReference:dt,profiles:oi,duration:S,bitrate:ri,mime:Ae,codecs:ei,width:ze,height:kt,fps:zi,quality:lt}}H.language||(H.language=we),H.label||(H.label=Rt),H.mime||(H.mime=Ae),H.codecs||(H.codecs=ei),H.hdr||(H.hdr=ut==="video"&&Zr(ei)),H.representations.push(ti)}if(ut){let V=r[ut].find(we=>we.id===H.id);if(V&&H.representations.every(we=>Je(we.segmentReference)))for(let we of V.representations){let Rt=H.representations.find(Ae=>Ae.id===we.id),Zt=Rt==null?void 0:Rt.segmentReference,He=we.segmentReference;He.segments.push(...Zt.segments),He.nextSegmentBeyondManifest=Zt.nextSegmentBeyondManifest}else r[ut].push(H)}}return{duration:S,streams:r,baseUrls:n,live:g}};import{isNonNullable as DI}from"@vkontakte/videoplayer-shared/es2018";var q=(s,e)=>DI(s)&&DI(e)&&s.readyState==="open"&&W0(s,e);function W0(s,e){for(let t=0;t<s.activeSourceBuffers.length;++t)if(s.activeSourceBuffers[t]===e)return!0;return!1}var bn=class{constructor(e,t,i,{fetcher:r,tuning:a,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new dr(0);this.currentLowLatencySegmentLength$=new dr(0);this.currentSegmentLength$=new dr(0);this.onLastSegment$=new dr(!1);this.fullyBuffered$=new dr(!1);this.playingRepresentation$=new dr(void 0);this.playingRepresentationInit$=new dr(void 0);this.error$=new K0;this.gaps=[];this.subscription=new X0;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new ae;this.switchAbortController=new ae;this.destroyAbortController=new ae;this.bufferLimit=1/0;this.failedDownloads=0;this.baseUrls=[];this.baseUrlsIndex=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.lastDataObtainedTimestampMs=0;this.loadByteRangeSegmentsTimeoutId=0;this.startWith=Ci(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);nt(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new DT(this.sourceBuffer),this.subscription.add(vp(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:Si.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o!=null||(o={id:"SegmentEjection",category:Si.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),this.error$.next(o)})),this.subscription.add(vp(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:Si.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o||!q(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,Kr(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=this.getForwardBufferDuration(o),d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,n*2,l<d).catch(c=>{this.handleAsyncError(c,"pruneBuffer")})})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);let i=this.initData.get(t.id),r=this.segments.get(t.id),a=this.parsedInitData.get(t.id);nt(i,"No init buffer for starting representation"),nt(r,"No segments for starting representation"),i instanceof ArrayBuffer&&(this.searchGaps(r,t),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(a))}.bind(this));this.switchTo=Ci(this.destroyAbortController.signal,async function*(e,t=!1){if(!q(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);nt(i,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if(Ue(a)||Ue(r)?yield this.loadInit(i,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),nt(r,"No segments for starting representation"),a=this.initData.get(e),!(!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer||!q(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(a,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer();else{let n=this.getCurrentPosition();es(n)&&!this.isLive&&(this.bufferLimit=1/0,await this.pruneBuffer(n,1/0,!0)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}this.maintain()}}.bind(this));this.switchToOld=Ci(this.destroyAbortController.signal,async function*(e,t=!1){if(!q(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);nt(i,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if(Ue(a)||Ue(r)?yield this.loadInit(i,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),nt(r,"No segments for starting representation"),a=this.initData.get(e),!(!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer||!q(this.mediaSource,this.sourceBuffer)))if(yield this.abort(),yield this.sourceBufferTaskQueue.append(a,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let n=this.getCurrentPosition();es(n)&&(this.isLive||(this.bufferLimit=1/0,await this.pruneBuffer(n,1/0,!0)),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}}.bind(this));this.seekLive=Ci(this.destroyAbortController.signal,async function*(e){var u,l;let t=(u=(0,Du.default)(e,d=>d.representations))!=null?u:[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let d of this.representations.keys()){let c=t.find(f=>f.id===d);c&&this.representations.set(d,c);let h=this.representations.get(d);if(!h||!Je(h.segmentReference))return;let p=this.getActualLiveStartingSegments(h.segmentReference);this.segments.set(h.id,p)}let i=(l=this.switchingToRepresentationId)!=null?l:this.downloadingRepresentationId,r=this.representations.get(i);nt(r);let a=this.segments.get(i);nt(a,"No segments for starting representation");let n=this.initData.get(i);if(nt(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer))return;let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(a,r),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));var d;this.fetcher=r,this.tuning=a,this.compatibilityMode=u,this.forwardBufferTarget=a.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!(l!=null&&l.live),this.baseUrls=(d=l==null?void 0:l.baseUrls)!=null?d:[],this.initData=new Map(i.map(c=>[c.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(c=>[c.id,c])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchToWithPreviousAbort(e,t=!1){!q(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new ae,Ci(this.switchAbortController.signal,async function*(i,r=!1){this.switchingToRepresentationId=i;let a=this.representations.get(i);nt(a,`No such representation ${i}`);let n=this.segments.get(i),o=this.initData.get(i);if(Ue(o)||Ue(n)?yield this.loadInit(a,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(i),nt(n,"No segments for starting representation"),o=this.initData.get(i),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer||!q(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(o,this.downloadAbortController.signal),r)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=i,yield this.dropBuffer();else{let u=this.getCurrentPosition();es(u)&&!this.isLive&&(this.bufferLimit=this.forwardBufferTarget,yield this.pruneBuffer(u,1/0,!0)),this.downloadingRepresentationId=i,this.switchingToRepresentationId=void 0}this.maintain()}}.bind(this))(e,t))}warmUpMediaSource(){!Ue(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}async abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);return this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new ae,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(Ue(e)||Ue(this.downloadingRepresentationId)||Ue(this.playingRepresentationId)||Ue(this.sourceBuffer)||!q(this.mediaSource,this.sourceBuffer)||es(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(nt(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;let r=i.find(d=>e>=d.time.from&&e<d.time.to);es(r)&&isFinite(r.time.from)&&isFinite(r.time.to)&&this.currentSegmentLength$.next((r==null?void 0:r.time.to)-r.time.from);let a=e,n=100;if(this.playingRepresentationId!==this.downloadingRepresentationId){let d=this.getForwardBufferDuration(e),c=r?r.time.to+n:-1/0;r&&r.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&d>=r.time.to-e+n&&(a=c)}if(isFinite(this.bufferLimit)&&Kr(this.sourceBuffer.buffered)>=this.bufferLimit){let d=this.getForwardBufferDuration(e),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,d<c).catch(h=>{this.handleAsyncError(h,"pruneBuffer")});return}let u=[];if(!this.activeSegments.size&&(u=this.selectForwardBufferSegments(i,t.segmentReference.type,a),u.length)){let d="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if((0,$u.default)(u,r))d="high";else{let c=(0,ts.default)(u,0);c&&c.time.from-r.time.to>=this.forwardBufferTarget/2&&(d="low")}this.loadSegments(u,t,d).catch(c=>{this.handleAsyncError(c,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&r&&r.status==="fed"&&!u.length&&this.getForwardBufferDuration(e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let l=(0,ts.default)(i,-1);!this.isLive&&l&&(this.fullyBuffered$.next(l.time.to-e-this.getForwardBufferDuration(e)<n),this.onLastSegment$.next(e-l.time.from>0))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let i=0,r=this.isLive?this.liveInitialAdditionalOffset:0;for(let a of e)Math.trunc(a.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:a.time.from+r}),i=a.time.to;es(t.duration)&&t.duration-i>0&&!this.isLive&&this.gaps.push({representation:t.id,from:i,to:t.duration})}getActualLiveStartingSegments(e){let t=e.segments,i=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,r=[],a=0,n=t.length-1;do r.unshift(t[n]),a+=t[n].time.to-t[n].time.from,n--;while(a<i&&n>=0);return this.liveInitialAdditionalOffset=a-i,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){let t=(0,Du.default)(e==null?void 0:e.streams[this.kind],r=>r.representations).find(r=>r.id===this.downloadingRepresentationId);if(!t)return;let i=this.segments.get(t.id);if(i!=null&&i.length)return{from:i[0].time.from,to:i[i.length-1].time.to}}updateLive(e){var i,r,a,n;let t=(i=(0,Du.default)(e==null?void 0:e.streams[this.kind],o=>o.representations))!=null?i:[];if(![...this.segments.values()].every(o=>!o.length))for(let o of t){if(!o||!Je(o.segmentReference))return;let u=o.segmentReference.segments.map(p=>({...p,status:"none",size:void 0})),l=100,d=(r=this.segments.get(o.id))!=null?r:[],c=(n=(a=(0,ts.default)(d,-1))==null?void 0:a.time.to)!=null?n:0,h=u==null?void 0:u.findIndex(p=>c>=p.time.from+l&&c<=p.time.to+l);if(h===-1){this.liveUpdateSegmentIndex=0;let p=this.getActualLiveStartingSegments(o.segmentReference);this.segments.set(o.id,p)}else{let p=u.slice(h+1);this.segments.set(o.id,[...d,...p])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;nt(e);let t=this.segments.get(e);if(t!=null&&t.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}updateLowLatencyLiveIfNeeded(e){var i;let t=0;for(let r of this.representations.values()){let a=r.segmentReference;if(!Je(a))return;let n=(i=this.segments.get(r.id))!=null?i:[],o=n.find(l=>Math.floor(l.time.from)===Math.floor(e.time.from));if(o&&!isFinite(o.time.to)&&(o.time.to=e.time.to,t=o.time.to-o.time.from),!!!n.find(l=>Math.floor(l.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let l=Math.round(e.time.to*a.timescale/1e3).toString(10),d=gi(a.segmentTemplateUrl,{segmentTime:l});n.push({status:"none",time:{from:e.time.to,to:1/0},url:d})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){var a,n,o;let t=(n=(a=this.switchingToRepresentationId)!=null?a:this.downloadingRepresentationId)!=null?n:this.playingRepresentationId;if(!t)return;let i=this.segments.get(t);if(!i)return;let r=i.find(u=>u.time.from<=e&&u.time.to>=e);return(o=r==null?void 0:r.time.from)!=null?o:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)==null||e.destroy(),this.gapDetectionIdleCallback&&Yt&&Yt(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&Yt&&Yt(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}this.sourceBuffer=null,this.downloadAbortController.abort(),this.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,i){return this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){let i=e.findIndex(r=>t>=r.time.from&&t<r.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=i),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,i){let r=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&&q(this.mediaSource,this.sourceBuffer)&&!(Ne(this.sourceBuffer.buffered,h)&&Ne(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}async loadSegments(e,t,i="auto"){Je(t.segmentReference)?await this.loadTemplateSegment(e[0],t,i):await this.loadByteRangeSegments(e,t,i)}async loadTemplateSegment(e,t,i="auto"){e.status="downloading";let r={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(r);let{range:a,url:n,signal:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await Ci(o,async function*(){let d=yp(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,d))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let d=await this.fetcher.fetch(n,{range:a,signal:o,onProgress:u,priority:i,isLowLatency:this.isActiveLowLatency()});if(this.lastDataObtainedTimestampMs=Bu(),!d)return;let c=new DataView(d),h=fn(t.mime);if(!isFinite(r.segment.time.to)){let m=t.segmentReference.timescale;r.segment.time.to=h.getChunkEndTime(c,m)}u&&r.feedingBytes&&l?await Promise.all(l):await this.sourceBufferTaskQueue.append(c,o);let{serverDataReceivedTimestamp:p,serverDataPreparedTime:f}=h.getServerLatencyTimestamps(c);p&&f&&this.currentLiveSegmentServerLatency$.next(f-p),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(d){this.abortActiveSegments([e]),mn(d)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}updateRepresentationsBaseUrlIfNeeded(){if(!this.tuning.dash.enableBaseUrlSupport||!this.baseUrls.length||this.failedDownloads<=this.tuning.dash.maxSegmentRetryCount)return;this.baseUrlsIndex=(this.baseUrlsIndex+1)%this.baseUrls.length;let e=this.baseUrls[this.baseUrlsIndex];for(let t of this.representations.values())Je(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}async loadByteRangeSegments(e,t,i="auto"){if(!e.length)return;for(let u of e)u.status="downloading",this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:r,url:a,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(await Ci(n,async function*(){let u=yp(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),vp(window,"online").pipe(Y0()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(a,{range:r,onProgress:o,signal:n,priority:i}),this.lastDataObtainedTimestampMs=Bu(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),mn(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(Je(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:(0,ts.default)(e,0).byte.from,to:(0,ts.default)(e,-1).byte.to},{signal:a}=this.downloadAbortController;return{url:i,range:r,signal:a,onProgress:async(o,u)=>{if(!a.aborted)try{this.lastDataObtainedTimestampMs=Bu(),await this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:a,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:Si.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!Je(t.segmentReference))throw new Error("Representation is not template type");let i=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&i.searchParams.set("low-latency","yes");let r=i.toString(),{signal:a}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,d)=>{if(!a.aborted)try{this.lastDataObtainedTimestampMs=Bu();let c=this.onSomeTemplateDataLoaded({dataView:l,loaded:d,signal:a,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(c)}catch(c){this.error$.next({id:"SegmentFeeding",category:Si.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}}:void 0;return{url:r,signal:a,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,$u.default)(e,t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:a}){if(!this.activeSegments.size||!q(this.mediaSource,this.sourceBuffer))return;let n=this.representations.get(t);if(n)for(let o of this.activeSegments){let{segment:u}=o;if(o.representationId===t){if(a.aborted){r();continue}if(o.loadedBytes=i,o.loadedBytes>o.feedingBytes){let l=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),d=fn(n.mime).parseFeedableSegmentChunk(l,this.isLive);d!=null&&d.byteLength&&(u.status="partially_fed",o.feedingBytes+=d.byteLength,await this.sourceBufferTaskQueue.append(d),o.fedBytes+=d.byteLength)}}}}async onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:a,onSegmentAppendFailed:n}){if(!this.activeSegments.size||!q(this.mediaSource,this.sourceBuffer))return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){let{segment:l}=u;if(u.representationId!==t)continue;if(a.aborted){await n();continue}let d=l.byte.from-i,c=l.byte.to-i,h=c-d+1,p=d<r,f=c<=r;if(!p)continue;let m=fn(o.mime);if(l.status==="downloading"&&f){l.status="downloaded";let g=new DataView(e.buffer,e.byteOffset+d,h);await this.sourceBufferTaskQueue.append(g,a)&&!a.aborted?this.onSegmentFullyAppended(u,t):await n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(l.status==="downloading"||l.status==="partially_fed")&&(u.loadedBytes=Math.min(h,r-d),u.loadedBytes>u.feedingBytes)){let g=new DataView(e.buffer,e.byteOffset+d+u.feedingBytes,u.loadedBytes-u.feedingBytes),S=u.loadedBytes===h?g:m.parseFeedableSegmentChunk(g);S!=null&&S.byteLength&&(l.status="partially_fed",u.feedingBytes+=S.byteLength,await this.sourceBufferTaskQueue.append(S,a)&&!a.aborted?(u.fedBytes+=S.byteLength,u.fedBytes===h&&this.onSegmentFullyAppended(u,t)):await n())}}}onSegmentFullyAppended(e,t){var i;if(!(Ue(this.sourceBuffer)||!q(this.mediaSource,this.sourceBuffer))){!this.isLive&&j.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(Ne(this.sourceBuffer.buffered,e.segment.time.from,100)&&Ne(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:Si.VIDEO_PIPELINE,message:"Browser stuck on empty result of adding segment to source buffer"})),this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",mp(e.segment)&&(e.segment.size=e.fedBytes);for(let r of this.representations.values())if(r.id!==t)for(let a of(i=this.segments.get(r.id))!=null?i:[])a.status==="fed"&&Math.round(a.time.from)===Math.round(e.segment.time.from)&&Math.round(a.time.to)===Math.round(e.segment.time.to)&&(a.status="none");this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}}abortSegment(e){e.status==="partially_fed"?e.status="partially_ejected":e.status!=="partially_ejected"&&(e.status="none");for(let t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[r,a]of this.initData.entries()){let n=a instanceof Promise;t||(t=n),a===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let i=this.representations.get(e);i&&(this.initLoadIdleCallback=Yr(()=>(0,CI.default)(this.loadInit(i,"low",!1),()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",i=!1){let r=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!i&&this.failedDownloads>0?Ci(this.destroyAbortController.signal,async function*(){let o=yp(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,fn(e.mime),r)).then(async o=>{if(!o)return;let{init:u,dataView:l,segments:d}=o,c=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,c);let h=d;this.isLive&&Je(e.segmentReference)&&(h=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,h),u&&this.parsedInitData.set(e.id,u)}).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:Si.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n}async dropBuffer(){for(let e of this.segments.values())for(let t of e)t.status="none";await this.pruneBuffer(0,1/0,!0)}async pruneBuffer(e,t,i=!1){if(!this.sourceBuffer||!q(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||Ue(e))return!1;let r=[],a=0,n=u=>{u.sort((d,c)=>d.from-c.from);let l=[u[0]];for(let d=1;d<u.length;d++){let{from:c,to:h}=u[d],p=l[l.length-1];p.to>=c?p.to=Math.max(p.to,h):l.push(u[d])}return l},o=u=>{var d;if(a>=t)return r;r.push({...u.time}),r=n(r);let l=mp(u)?(d=u.size)!=null?d:0:u.byte.to-u.byte.from;a+=l};for(let u of this.segments.values())for(let l of u){let d=l.time.to<=e-this.tuning.dash.bufferPruningSafeZone,c=l.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(d||c)&&l.status==="fed"&&o(l)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let l=this.sourceBuffer.buffered.start(u)*1e3,d=this.sourceBuffer.buffered.end(u)*1e3,c=0;for(let h of this.segments.values())for(let p of h)(0,$u.default)(["none","partially_ejected"],p.status)&&Math.round(p.time.from)<=Math.round(l)&&Math.round(p.time.to)>=Math.round(d)&&c++;if(c===this.segments.size){let h={time:{from:l,to:d},url:"",status:"none"};o(h)}}if(r.length&&i){let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let l of this.segments.values())for(let d of l)d.time.from>=e+u&&d.status==="fed"&&o(d)}return r.length?(await Promise.all(r.map(l=>this.sourceBufferTaskQueue.remove(l.from,l.to)))).reduce((l,d)=>l||d,!1):!1}async abortBuffer(){if(!this.sourceBuffer||!q(this.mediaSource,this.sourceBuffer))return!1;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;return this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!q(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}getForwardBufferDuration(e=this.getCurrentPosition()){return!this.sourceBuffer||!q(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||Ue(e)?0:$e(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!(!this.sourceBuffer||!q(this.mediaSource,this.sourceBuffer))){if(this.tuning.useRefactoredSearchGap)for(let i=0;i<this.sourceBuffer.buffered.length;i++)this.gaps=this.gaps.filter(r=>this.sourceBuffer&&(Math.round(r.from)<Math.round(this.sourceBuffer.buffered.start(i)*1e3)||Math.round(r.to)>Math.round(this.sourceBuffer.buffered.end(i)*1e3)));for(let i of t){let r={representation:e,from:i.time.from,to:i.time.to};for(let a=0;a<this.sourceBuffer.buffered.length;a++){let n=this.sourceBuffer.buffered.start(a)*1e3,o=this.sourceBuffer.buffered.end(a)*1e3;if(!(o<=i.time.from||n>=i.time.to)){if(n<=i.time.from&&o>=i.time.to){r=void 0;break}o>i.time.from&&o<i.time.to&&(r.from=o),n<i.time.to&&n>i.time.from&&(r.to=n)}}r&&r.to-r.from>1&&!this.gaps.some(a=>r&&a.from===r.from&&a.to===r.to)&&this.gaps.push(r)}}}detectGapsWhenIdle(e,t){if(!(this.gapDetectionIdleCallback||!this.sourceBuffer||!q(this.mediaSource,this.sourceBuffer))){if(!this.tuning.useRefactoredSearchGap)for(let i=0;i<this.sourceBuffer.buffered.length;i++)this.gaps=this.gaps.filter(r=>this.sourceBuffer&&(Math.round(r.from)<Math.round(this.sourceBuffer.buffered.start(i)*1e3)||Math.round(r.to)>Math.round(this.sourceBuffer.buffered.end(i)*1e3)));this.gapDetectionIdleCallback=Yr(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:Si.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if(Ue(this.sourceBuffer)||!q(this.mediaSource,this.sourceBuffer)||Ue(this.playingRepresentationId))return;let e=[];for(let i=0;i<this.sourceBuffer.buffered.length;i++){let r=Math.floor(this.sourceBuffer.buffered.start(i)*1e3),a=Math.ceil(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:r,to:a})}let t=100;for(let i of this.segments.values())for(let r of i){let{status:a}=r;if(a!=="fed"&&a!=="partially_ejected")continue;let n=Math.floor(r.time.from),o=Math.ceil(r.time.to),u=e.some(d=>d.from-t<=n&&d.to+t>=o),l=e.filter(d=>n>=d.from&&n<d.to-t||o>d.from+t&&o<=d.to);u||(l.length===1?r.status="partially_ejected":this.gaps.some(d=>d.from===r.time.from||d.to===r.time.to)?r.status="partially_ejected":r.status="none")}}handleAsyncError(e,t){this.error$.next({id:t,category:Si.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}};var Vi=s=>{let e=new URL(s);return e.searchParams.set("quic","1"),e.toString()};var Cu=s=>{var a;let e=s.get("X-Delivery-Type"),t=s.get("X-Reused"),i=e===null?"http1":e!=null?e:void 0,r=t===null?void 0:(a={1:!0,0:!1}[t])!=null?a:void 0;return{type:i,reused:r}};import{abortable as gn,assertNever as VI,fromEvent as OI,merge as J0,now as Sn,Subscription as Z0,Subject as _I,ValueSubject as Tp,flattenObject as is,ErrorCategory as vn}from"@vkontakte/videoplayer-shared/es2018";var Vu=s=>{let e=new URL(s);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var _u=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:a=!1}){this.lastConnectionType$=new Tp(void 0);this.lastConnectionReused$=new Tp(void 0);this.lastRequestFirstBytes$=new Tp(void 0);this.recoverableError$=new _I;this.error$=new _I;this.abortAllController=new ae;this.subscription=new Z0;this.fetchManifest=gn(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=Vi(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=Vu(i));let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(Ou);return r?(t.log("success",is({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(r.headers),r.text()):(t.error("error",is({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=gn(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:a="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1}={}){var C,M;let l=e,d=new Headers,c=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{d.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let k=new URL(l,location.href);k.searchParams.append("bytes",`${i.from}-${i.to}`),l=k.toString();break}default:VI(t)}this.requestQuic&&(l=Vi(l));let h=this.abortAllController.signal,p;if(n){let k=new ae;if(p=J0(OI(this.abortAllController.signal,"abort"),OI(n,"abort")).subscribe(()=>{try{k.abort()}catch(Q){Ou(Q)}}),this.subscription.add(p),this.abortAllController.signal.aborted||n.aborted)try{k.abort()}catch(Q){Ou(Q)}h=k.signal}let f=Sn();c.log("startRequest",is({url:l,priority:a,rangeMethod:t,range:i,isLowLatency:u,requestStartedAt:f}));let m=yield this.doFetch(l,{priority:a,headers:d,signal:h}),g=Sn();if(!m)return c.error("error",{message:"No response in request"}),c.end(),p==null||p.unsubscribe(),null;if((C=this.throughputEstimator)==null||C.addRawRtt(g-f),!m.ok||!m.body){p==null||p.unsubscribe();let k=`Fetch error ${m.status}: ${m.statusText}`;return c.error("error",{message:k}),c.end(),Promise.reject(new Error(`Fetch error ${m.status}: ${m.statusText}`))}if(this.onHeadersReceived(m.headers),!r&&!o){p==null||p.unsubscribe();let k=Sn(),Q={requestStartedAt:f,requestEndedAt:k,duration:k-f};return c.log("endRequest",is(Q)),c.end(),m.arrayBuffer()}let[S,v]=m.body.tee(),y=S.getReader();o&&((M=this.throughputEstimator)==null||M.trackStream(v,u));let I=0,T=new Uint8Array(0),E=!1,O=k=>{p==null||p.unsubscribe(),E=!0,Ou(k)},L=gn(h,async function*({done:k,value:Q}){if(I===0&&this.lastRequestFirstBytes$.next(Sn()-f),h.aborted){p==null||p.unsubscribe();return}if(!k&&Q){let U=new Uint8Array(T.length+Q.length);U.set(T),U.set(Q,T.length),T=U,I+=Q.byteLength,r==null||r(new DataView(T.buffer),I),yield y==null?void 0:y.read().then(L,O)}}.bind(this));yield y==null?void 0:y.read().then(L,O),p==null||p.unsubscribe();let w=Sn(),P={failed:E,requestStartedAt:f,requestEndedAt:w,duration:w-f};return E?(c.error("endRequest",is(P)),c.end(),null):(c.log("endRequest",is(P)),c.end(),T.buffer)}.bind(this));this.fetchByteRangeRepresentation=gn(this.abortAllController.signal,async function*(e,t,i){var S;if(e.type!=="byteRange")return null;let{from:r,to:a}=e.initRange,n=r,o=a,u=!1,l,d;e.indexRange&&(l=e.indexRange.from,d=e.indexRange.to,u=a+1===l,u&&(n=Math.min(l,r),o=Math.max(d,a))),n=Math.min(n,0);let c=yield this.fetch(e.url,{range:{from:n,to:o},priority:i,measureThroughput:!1});if(!c)return null;let h=new DataView(c,r-n,a-n+1);if(!t.validateData(h))throw new Error("Invalid media file");let p=t.parseInit(h),f=(S=e.indexRange)!=null?S:t.getIndexRange(p);if(!f)throw new ReferenceError("No way to load representation index");let m;if(u)m=new DataView(c,f.from-n,f.to-f.from+1);else{let v=yield this.fetch(e.url,{range:f,priority:i,measureThroughput:!1});if(!v)return null;m=new DataView(v)}let g=t.parseSegments(m,p,f);return{init:p,dataView:new DataView(c),segments:g}}.bind(this));this.fetchTemplateRepresentation=gn(this.abortAllController.signal,async function*(e,t){if(e.type!=="template")return null;let i=new URL(e.initUrl,e.baseUrl).toString(),r=yield this.fetch(i,{priority:t,measureThroughput:!1});return r?{init:null,segments:e.segments.map(n=>({...n,status:"none",size:void 0})),dataView:new DataView(r)}:null}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=r,this.tracer=i.createComponentTracer("Fetcher"),this.useEnableSubtitlesParam=a}onHeadersReceived(e){let{type:t,reused:i}=Cu(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,t,i="auto"){var a,n;let{type:r}=e;switch(r){case"byteRange":return(a=await this.fetchByteRangeRepresentation(e,t,i))!=null?a:null;case"template":return(n=await this.fetchTemplateRepresentation(e,i))!=null?n:null;default:VI(r)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}async doFetch(e,t){let i=await wt(e,t);if(i.ok)return i;let r=await i.text(),a=parseInt(r);if(!isNaN(a))switch(a){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:vn.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:vn.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:vn.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:vn.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${a})`,category:vn.FATAL})}}},Ou=s=>{if(!mn(s))throw s};var vi=(s,e,t)=>t*e+(1-t)*s,Ip=(s,e)=>s.reduce((t,i)=>t+i,0)/e,FI=(s,e,t,i)=>{let r=0,a=t,n=Ip(s,e),o=e<i?e:i;for(let u=0;u<o;u++)s[a]>n?r++:r--,a=(s.length+a-1)%s.length;return Math.abs(r)===o};import{isNullable as eC,ValueSubject as NI}from"@vkontakte/videoplayer-shared/es2018";var Oi=class{constructor(e){this.prevReported=void 0;this.pastMeasures=[];this.takenMeasures=0;this.measuresCursor=0;var i;this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new NI(e.initial),this.debounced$=new NI(e.initial);let t=(i=e.label)!=null?i:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new Ke(`raw_${t}`),this.smoothedSeries$=new Ke(`smoothed_${t}`),this.reportedSeries$=new Ke(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,i=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=(this.pastMeasures[o]-this.smoothed)**2,i++);this.takenMeasures=i,t/=i;let r=Math.sqrt(t),a=this.smoothed+this.params.deviationFactor*r,n=this.smoothed-this.params.deviationFactor*r;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>a||this.smoothed<n)&&(eC(this.prevReported)||Math.abs(this.smoothed-this.prevReported)/this.prevReported>=this.params.changeThreshold)&&(this.prevReported=this.smoothed,this.debounced$.next(this.smoothed),this.reportedSeries$.next(this.smoothed))}};var Fu=class extends Oi{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=vi(this.slow,e,this.params.emaAlphaSlow),this.fast=vi(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var Nu=class extends Oi{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=Ip(this.pastMeasures,this.takenMeasures);this.emaSmoothed=vi(this.emaSmoothed,e,this.params.emaAlpha);let i=FI(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}};var Uu=class extends Oi{constructor(t){super(t);this.furtherValues=[];this.currentTopExtremumValue=0;this.extremumInterval=t.extremumInterval}next(t){this.currentTopExtremumValue<=t?(this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.length===this.extremumInterval?(super.next(this.currentTopExtremumValue),this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.push(t)}updateSmoothedValue(t){this.smoothed=this.smoothed?vi(this.smoothed,t,this.params.emaAlpha):t}};var yi=class{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new Fu({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new Nu({initial:e,emaAlpha:i.emaAlpha,basisTrendChangeCount:i.basisTrendChangeCount,changeThreshold:i.changeThreshold,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"})}static getLiveBufferSmoothedValue(e,t){return new Uu({initial:e,label:"liveEdgeDelay",...t})}};var rs=(s,e)=>{s&&s.playbackRate!==e&&(s.playbackRate=e)};import{isNullable as tC,ValueSubject as iC}from"@vkontakte/videoplayer-shared/es2018";var yn=class s{constructor(e,t){this.currentRepresentation$=new iC(null);this.maxRepresentations=4;this.representationsCursor=0;this.representations=[];this.currentSegment=null;this.getCurrentPosition=t.getCurrentPosition,this.processStreams(e)}updateLive(e){this.processStreams(e==null?void 0:e.streams.text)}seekLive(e){this.processStreams(e)}maintain(e=this.getCurrentPosition()){var t;if(!tC(e))for(let i of this.representations)for(let r of i){let a=r.segmentReference,n=a.segments.length,o=a.segments[0].time.from,u=a.segments[n-1].time.to;if(e<o||e>u)continue;let l=a.segments.find(d=>d.time.from<=e&&d.time.to>=e);!l||((t=this.currentSegment)==null?void 0:t.time.from)===l.time.from&&this.currentSegment.time.to===l.time.to||(this.currentSegment=l,this.currentRepresentation$.next({...r,label:"Live Text",language:"ru",isAuto:!0,url:new URL(l.url,a.baseUrl).toString()}))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e!=null?e:[]){let i=s.filterRepresentations(t.representations);if(i){this.representations[this.representationsCursor]=i,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!(e!=null&&e.some(t=>s.filterRepresentations(t.representations)))}static filterRepresentations(e){return e==null?void 0:e.filter(t=>t.kind==="text"&&"segmentReference"in t&&Je(t.segmentReference))}};var ju=N(Ot(),1);import{assertNever as Hu}from"@vkontakte/videoplayer-shared/es2018";var UI=(s,{useManagedMediaSource:e,useOldMSEDetection:t})=>{let{containers:i,protocols:r,codecs:a,nativeHlsSupported:n}=j.video,o=(a.h264||a.h265)&&a.aac,u=r.mse&&(!t||!!window.MediaStreamTrack)||r.mms&&e;return s.filter(l=>{switch(l){case"DASH_SEP":return u&&i.mp4&&o;case"DASH_WEBM":return u&&i.webm&&a.vp9&&a.opus;case"DASH_WEBM_AV1":return u&&i.webm&&a.av1&&a.opus;case"DASH_STREAMS":return u&&(i.mp4&&o||i.webm&&(a.vp9||a.av1)&&(a.opus||a.aac));case"DASH_LIVE":return u&&i.mp4&&o;case"DASH_LIVE_CMAF":return u&&i.mp4&&o&&i.cmaf;case"DASH_ONDEMAND":return u&&i.mp4&&o;case"HLS":case"HLS_ONDEMAND":case"HLS_LIVE":case"HLS_LIVE_CMAF":return n;case"MPEG":return i.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return r.webrtc&&r.ws&&a.h264&&(i.mp4||i.webm);default:return Hu(l)}})},qu=s=>{let{webmDecodingInfo:e}=j.video,t="DASH_WEBM",i="DASH_WEBM_AV1";switch(s){case"vp9":return[t,i];case"av1":return[i,t];case"none":return[];case"smooth":return e?e[i].smooth?[i,t]:e[t].smooth?[t,i]:[i,t]:[t,i];case"power_efficient":return e?e[i].powerEfficient?[i,t]:e[t].powerEfficient?[t,i]:[i,t]:[t,i];default:Hu(s)}return[t,i]},qI=({webmCodec:s,androidPreferredFormat:e,preferMultiStream:t})=>{let i=[...t?["DASH_STREAMS"]:[],...qu(s),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],r=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(j.device.isAndroid)switch(e){case"mpeg":return["MPEG",...i,"HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...i,"MPEG"];case"dash":return[...i,"HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return[...r,"MPEG",...qu(s),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...qu(s),"MPEG",...r,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...qu(s),...r,"HLS","HLS_ONDEMAND"];default:Hu(e)}return j.video.nativeHlsSupported?[...i,"HLS","HLS_ONDEMAND","MPEG"]:[...i,"HLS","HLS_ONDEMAND","MPEG"]},jI=({androidPreferredFormat:s,preferCMAF:e,preferWebRTC:t})=>{let i=e?["DASH_LIVE_CMAF","DASH_LIVE"]:["DASH_LIVE","DASH_LIVE_CMAF"],r=e?["HLS_LIVE_CMAF","HLS_LIVE"]:["HLS_LIVE","HLS_LIVE_CMAF"],a=[...i,...r],n=[...r,...i],o,u=j.device.isMac&&j.browser.isSafari;if(j.device.isAndroid)switch(s){case"dash":case"dash_any_mpeg":case"dash_any_webm":case"dash_sep":{o=a;break}case"hls":case"mpeg":{o=n;break}default:Hu(s)}else j.video.nativeHlsSupported&&!u?o=n:u?o=e?["DASH_LIVE_CMAF","HLS_LIVE_CMAF","HLS_LIVE","DASH_LIVE"]:["HLS_LIVE","DASH_LIVE","DASH_LIVE_CMAF","HLS_LIVE_CMAF"]:o=a;return t?["WEB_RTC_LIVE",...o]:[...o,"WEB_RTC_LIVE"]},xp=s=>s?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],zu=s=>{if(s.size===0)return;if(s.size===1){let t=s.values().next();return(0,ju.default)(t.value.split("."),0)}for(let t of s){let i=(0,ju.default)(t.split("."),0);if(i==="opus"||i==="vp09"||i==="av01")return i}let e=s.values().next();return(0,ju.default)(e.value.split("."),0)};var cC=["timeupdate","progress","play","seeked","stalled","waiting"],dC=["timeupdate","progress","loadeddata","playing","seeked"];var Wu=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new QI;this.representationSubscription=new QI;this.state$=new G("none");this.currentVideoRepresentation$=new he(void 0);this.currentVideoRepresentationInit$=new he(void 0);this.currentAudioRepresentation$=new he(void 0);this.currentVideoSegmentLength$=new he(0);this.currentAudioSegmentLength$=new he(0);this.error$=new Gu;this.lastConnectionType$=new he(void 0);this.lastConnectionReused$=new he(void 0);this.lastRequestFirstBytes$=new he(void 0);this.currentLiveTextRepresentation$=new he(null);this.isLive$=new he(!1);this.isActiveLive$=new he(!1);this.isLowLatency$=new he(!1);this.liveDuration$=new he(0);this.liveSeekableDuration$=new he(0);this.liveAvailabilityStartTime$=new he(0);this.liveStreamStatus$=new he(void 0);this.bufferLength$=new he(0);this.liveLatency$=new he(void 0);this.liveLoadBufferLength$=new he(0);this.livePositionFromPlayer$=new he(0);this.currentStallDuration$=new he(0);this.videoLastDataObtainedTimestamp$=new he(0);this.fetcherRecoverableError$=new Gu;this.fetcherError$=new Gu;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new Gu;this.gapWatchdogActive=!1;this.destroyController=new ae;this.initManifest=wp(this.destroyController.signal,async function*(e,t,i){var r;this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=Se(t,i,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),(r=this.manifest)!=null&&r.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:Ft.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=wp(this.destroyController.signal,async function*(){var n,o;this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(u=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:Ft.NETWORK,message:"Failed to load manifest",thrown:u})});if(!e)return null;let t=null;try{t=$I(e!=null?e:"",this.manifestUrlString)}catch(u){let l=(n=Mu(e))!=null?n:{id:"ManifestParsing",category:Ft.PARSER,message:"Failed to parse MPD manifest",thrown:u};this.error$.next(l)}if(!t)return null;let i=(u,l,d)=>{var c,h,p,f;return!!((h=(c=this.element)==null?void 0:c.canPlayType)!=null&&h.call(c,l)&&((f=(p=vt())==null?void 0:p.isTypeSupported)!=null&&f.call(p,`${l}; codecs="${d}"`))||u==="text")};if(t.live){this.isLive$.next(!!t.live);let{availabilityStartTime:u,latestSegmentPublishTime:l,streamIsUnpublished:d,streamIsAlive:c}=t.live,h=((o=t.duration)!=null?o:0)/1e3;this.liveSeekableDuration$.next(-1*h),this.liveDuration$.next((l-u)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let p="active";c||(p=d?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(p)}let r={text:t.streams.text,video:[],audio:[]};for(let u of["video","audio"]){let d=t.streams[u].filter(({mime:p,codecs:f})=>i(u,p,f)),c=new Set(d.map(({codecs:p})=>p)),h=zu(c);if(h&&(r[u]=d.filter(({codecs:p})=>p.startsWith(h))),u==="video"){let p=this.tuning.preferHDR,f=r.video.some(g=>g.hdr),m=r.video.some(g=>!g.hdr);j.display.isHDR&&p&&f?r.video=r.video.filter(g=>g.hdr):m&&(r.video=r.video.filter(g=>!g.hdr))}}let a={...t,streams:r};return this.tracer.log("updateManifestEnd",In(a)),a}.bind(this));this.initRepresentations=wp(this.destroyController.signal,async function*(e,t,i){var h;this.tracer.log("initRepresentationsStart",In({initialVideo:e,initialAudio:t,sourceHls:i})),ss(this.manifest),ss(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let r=p=>{this.representationSubscription.add(Ti(p,"error").pipe(Qu(f=>{var m;return!!((m=this.element)!=null&&m.played.length)})).subscribe(f=>{this.error$.next({id:"VideoSource",category:Ft.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:f})}))};this.source=this.tuning.useManagedMediaSource?nu():new MediaSource;let a=document.createElement("source");if(r(a),a.src=URL.createObjectURL(this.source),this.element.appendChild(a),this.tuning.useManagedMediaSource&&Ur())if(i){let p=document.createElement("source");r(p),p.type="application/x-mpegurl",p.src=i.url,this.element.appendChild(p)}else this.element.disableRemotePlayback=!0;this.isActiveLive$.next(this.isLive$.getValue());let n={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),manifest:this.manifest},o=this.manifest.streams.video.reduce((p,f)=>[...p,...f.representations],[]);if(this.videoBufferManager=new bn("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],xn(t)){let p=this.manifest.streams.audio.reduce((f,m)=>[...f,...m.representations],[]);this.audioBufferManager=new bn("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}yn.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new yn(this.manifest.streams.text,n)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$));let u=()=>{var p;(p=this.stallWatchdogSubscription)==null||p.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add(pr(...dC.map(p=>Ti(this.element,p))).pipe(ns(p=>this.element?$e(this.element.buffered,this.element.currentTime*1e3):0),Tn(),uC(p=>{p>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add(pr(Ti(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe(Tn()).subscribe(f=>this.liveStreamEndTimestamp=Pp())),this.subscription.add(Ti(this.element,"pause").subscribe(()=>{this.livePauseWatchdogSubscription=Ap(1e3).subscribe(f=>{let m=Mi(this.manifestUrlString,2);this.manifestUrlString=Se(this.manifestUrlString,m+1e3,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add(Ti(this.element,"play").subscribe(f=>{var m;return(m=this.livePauseWatchdogSubscription)==null?void 0:m.unsubscribe()})),this.representationSubscription.add(as({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(ns(({isActiveLive:f,isLowLatency:m})=>f&&m),Tn()).subscribe(f=>{this.isManualDecreasePlaybackInLive()||rs(this.element,1)})),this.representationSubscription.add(as({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(Qu(({bufferLength:f,isActiveLive:m,isLowLatency:g})=>m&&g&&!!f)).subscribe(({bufferLength:f})=>this.liveBuffer.next(f))),this.representationSubscription.add(this.videoBufferManager.currentLowLatencySegmentLength$.subscribe(f=>{if(!this.isActiveLive$.getValue()&&!this.isLowLatency$.getValue()&&!f)return;let m=this.liveSeekableDuration$.getValue()-f/1e3;this.liveSeekableDuration$.next(Math.max(m,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+f/1e3)})),this.representationSubscription.add(as({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(Qu(({isLive:f})=>f),Tn((f,m)=>m.bufferLength<f.bufferLength),ns(({rtt:f,bufferLength:m,segmentServerLatency:g})=>{let S=Mi(this.manifestUrlString,2);return(f/2+m+g+S)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(as({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:f,isActiveLive:m,isLowLatency:g})=>{if(!g||!m)return;let S=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,v=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,y=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,I=f-S;if(this.isManualDecreasePlaybackInLive())return;let T=1;Math.abs(I)>v&&(T=1+Math.sign(I)*y),rs(this.element,T)})),this.representationSubscription.add(this.bufferLength$.subscribe(f=>{var g,S;let m=0;if(f){let v=((S=(g=this.element)==null?void 0:g.currentTime)!=null?S:0)*1e3;m=Math.min(...this.bufferManagers.map(I=>{var T,E;return(E=(T=I.getLiveSegmentsToLoadState(this.manifest))==null?void 0:T.to)!=null?E:v}))-v}this.liveLoadBufferLength$.getValue()!==m&&this.liveLoadBufferLength$.next(m)}));let p=0;this.representationSubscription.add(as({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(lC(1e3)).subscribe(async({liveLoadBufferLength:f,bufferLength:m})=>{if(!this.element||this.isUpdatingLive)return;let g=this.element.playbackRate,S=Mi(this.manifestUrlString,2),v=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,y=Math.min(v,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*g),I=this.tuning.dashCmafLive.normalizedActualBufferOffset*g,T=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*g,E=isFinite(f)?f:m,O=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),L=v<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(L);let w="none";if(O?w="active_low_latency":this.isLowLatency$.getValue()&&L?(this.bufferManagers.forEach(P=>P.proceedLowLatencyLive()),w="active_low_latency"):S!==0&&E<y?w="live_forward_buffering":E<y+T&&(w="live_with_target_offset"),isFinite(f)&&(p=f>p?f:p),w==="live_forward_buffering"||w==="live_with_target_offset"){let P=p-(y+I),C=this.normolizeLiveOffset(Math.trunc(S+P/g)),M=Math.abs(C-S),k=0;!f||M<=this.tuning.dashCmafLive.offsetCalculationError?k=S:C>0&&M>this.tuning.dashCmafLive.offsetCalculationError&&(k=C),this.manifestUrlString=Se(this.manifestUrlString,k,2)}(w==="live_with_target_offset"||w==="live_forward_buffering")&&(p=0,await this.updateLive())},f=>{this.error$.next({id:"updateLive",category:Ft.VIDEO_PIPELINE,thrown:f,message:"Failed to update live with subscription"})}))}let l=pr(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe(ns(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),d=pr(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe(ns(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue()))),c=as({allBuffersFull:l,someBufferEnded:d}).pipe(Tn(),ns(({allBuffersFull:p,someBufferEnded:f})=>p&&f),Qu(p=>p));if(this.representationSubscription.add(pr(this.forceEnded$,c).subscribe(()=>{var p;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(f=>!f.updating))try{(p=this.source)==null||p.endOfStream()}catch(f){this.error$.next({id:"EndOfStream",category:Ft.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:f})}})),this.representationSubscription.add(pr(...this.bufferManagers.map(p=>p.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.representationSubscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.representationSubscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.liveTextManager&&this.representationSubscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$)),this.source.readyState!=="open"){let p=this.tuning.dash.sourceOpenTimeout>=0;yield new Promise(f=>{var m;p&&(this.timeoutSourceOpenId=setTimeout(()=>{var g;if(((g=this.source)==null?void 0:g.readyState)==="open"){f();return}this.error$.next({id:"OpenOfStream",category:Ft.VIDEO_PIPELINE,message:"Failed to open MediaSource",thrown:new Error("Timeout reject when wait sourceopen event"),traceAsLog:!0})},this.tuning.dash.sourceOpenTimeout)),(m=this.source)==null||m.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),f()},{once:!0})})}if(!this.isLive$.getValue()){let p=[(h=this.manifest.duration)!=null?h:0,...(0,Rp.default)((0,Rp.default)([...this.manifest.streams.audio,...this.manifest.streams.video],f=>f.representations),f=>{let m=[];return f.duration&&m.push(f.duration),Je(f.segmentReference)&&f.segmentReference.totalSegmentsDurationMs&&m.push(f.segmentReference.totalSegmentsDurationMs),m})];this.source.duration=Math.max(...p)/1e3}this.audioBufferManager&&xn(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")}.bind(this));this.tick=()=>{var t,i,r,a;if(!this.element||!this.videoBufferManager||((t=this.source)==null?void 0:t.readyState)!=="open")return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),(i=this.audioBufferManager)==null||i.maintain(e),(r=this.liveTextManager)==null||r.maintain(e),(this.videoBufferManager.gaps.length||(a=this.audioBufferManager)!=null&&a.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=Ap(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),n=>{this.error$.next({id:"GapWatchdog",category:Ft.WTF,message:"Error handling gaps",thrown:n})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.fetcher=new _u({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.subscription.add(this.fetcher.recoverableError$.subscribe(this.fetcherRecoverableError$)),this.subscription.add(this.fetcher.error$.subscribe(this.fetcherError$)),this.liveBuffer=yi.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator}),this.initTracerSubscription()}async seekLive(e){var r,a,n;ss(this.element);let t=this.liveStreamStatus$.getValue()!=="active"?Pp()-this.liveStreamEndTimestamp:0,i=this.normolizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=Se(this.manifestUrlString,i,2),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await((r=this.videoBufferManager)==null?void 0:r.seekLive(this.manifest.streams.video)),await((a=this.audioBufferManager)==null?void 0:a.seekLive(this.manifest.streams.audio)),(n=this.liveTextManager)==null||n.seekLive(this.manifest.streams.text))}initBuffer(){ss(this.element),this.state$.setState("running"),this.subscription.add(pr(...cC.map(e=>Ti(this.element,e)),Ti(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:Ft.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(Ti(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(Ti(this.element,"waiting").subscribe(()=>{var t;this.element&&this.element.readyState===2&&!this.element.seeking&&Ne(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{var p,f,m,g,S,v,y,I,T,E,O;if(!this.element||((p=this.source)==null?void 0:p.readyState)!=="open")return;let i=this.currentStallDuration$.getValue();i+=50,this.currentStallDuration$.next(i);let r={timeInWaiting:i},a=Pp(),n=100,o=(m=(f=this.videoBufferManager)==null?void 0:f.lastDataObtainedTimestamp)!=null?m:0;this.videoLastDataObtainedTimestamp$.next(o);let u=(S=(g=this.audioBufferManager)==null?void 0:g.lastDataObtainedTimestamp)!=null?S:0,l=(y=(v=this.videoBufferManager)==null?void 0:v.getForwardBufferDuration())!=null?y:0,d=(T=(I=this.audioBufferManager)==null?void 0:I.getForwardBufferDuration())!=null?T:0,c=l<n&&a-o>this.tuning.dash.crashOnStallTWithoutDataTimeout,h=this.audioBufferManager&&d<n&&a-u>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((c||h)&&i>this.tuning.dash.crashOnStallTWithoutDataTimeout||i>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${i} ms`);if(this.isLive$.getValue()&&i%2e3===0){let L=this.normolizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(L).catch(w=>{this.error$.next({id:"stallIntervalCallback",category:Ft.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:w})}),r.liveLastOffset=L}else{let L=this.element.currentTime*1e3;(E=this.videoBufferManager)==null||E.maintain(L),(O=this.audioBufferManager)==null||O.maintain(L),r.position=L}this.tracer.log("stallIntervalCallback",In(r))};(t=this.stallWatchdogSubscription)==null||t.unsubscribe(),this.stallWatchdogSubscription=Ap(50).subscribe(e,i=>{this.error$.next({id:"StallWatchdogCallback",category:Ft.NETWORK,message:"Can't restore DASH after stall.",thrown:i})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,i=!1){let r={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return this.tuning.useNewSwitchTo?this.currentStallDuration$.getValue()>0?r==null?void 0:r.switchToWithPreviousAbort(t,i):r==null?void 0:r.switchTo(t,i):r==null?void 0:r.switchToOld(t,i)}async seek(e,t){var r,a,n,o,u;ss(this.element),ss(this.videoBufferManager);let i;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?i=e:i=Math.max((r=this.videoBufferManager.findSegmentStartTime(e))!=null?r:e,(n=(a=this.audioBufferManager)==null?void 0:a.findSegmentStartTime(e))!=null?n:e),this.warmUpMediaSourceIfNeeded(i),Ne(this.element.buffered,i)||await Promise.all([this.videoBufferManager.abort(),(o=this.audioBufferManager)==null?void 0:o.abort()]),!(zI(this.element)||zI(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),(u=this.audioBufferManager)==null||u.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",In({requestedPosition:e,forcePrecise:t,position:i})))}warmUpMediaSourceIfNeeded(e=(t=>(t=this.element)==null?void 0:t.currentTime)()){var i;xn(this.element)&&xn(this.source)&&xn(e)&&((i=this.source)==null?void 0:i.readyState)==="ended"&&this.element.duration*1e3-e>this.tuning.dash.seekBiasInTheEnd&&this.bufferManagers.forEach(r=>r.warmUpMediaSource())}get isStreamEnded(){var e;return((e=this.source)==null?void 0:e.readyState)==="ended"}stop(){var e,t,i;this.tracer.log("stop"),(e=this.element)==null||e.querySelectorAll("source").forEach(r=>{URL.revokeObjectURL(r.src),r.remove()}),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(t=this.videoBufferManager)==null||t.destroy(),this.videoBufferManager=null,(i=this.audioBufferManager)==null||i.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){var e;return(e=this.manifest)==null?void 0:e.streams}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){var e;this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),((e=this.source)==null?void 0:e.readyState)==="open"&&Array.from(this.source.sourceBuffers).every(t=>!t.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=oC(this.tracer.error.bind(this.tracer));this.subscription.add(this.error$.subscribe(e("error")))}isManualDecreasePlaybackInLive(){if(!this.element||!this.isLive$.getValue())return!1;let e=1-this.element.playbackRate;return Number(e.toFixed(2))>Number(this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup.toFixed(2))}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){var e,t;this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&((e=this.bufferManagers)==null||e.forEach(i=>i.updateLive(this.manifest)),(t=this.liveTextManager)==null||t.updateLive(this.manifest)),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getDebugBufferState();if(!e)return;let t=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),i={isJumpGapAfterSeekLive:this.isJumpGapAfterSeekLive,isActiveLowLatency:t,initialCurrentTime:this.element.currentTime};this.isJumpGapAfterSeekLive&&!t&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let r=this.element.currentTime*1e3,a=[],n=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let o of this.bufferManagers)for(let u of o.gaps)o.playingRepresentation$.getValue()===u.representation&&u.from-n<=r&&u.to+n>r&&(this.element.duration*1e3-u.to<this.tuning.endGapTolerance?a.push(1/0):a.push(u.to));if(a.length){let o=Math.max(...a)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,o===1/0?this.forceEnded$.next():(this.element.currentTime=o/1e3,i={...i,gapEnds:a,jumpTo:o,resultCurrentTime:this.element.currentTime},this.tracer.log("jumpGap",In(i)))}}};var Yu=class{constructor(e,t){this.fov=e,this.orientation=t}};var Ku=class{constructor(e,t){this.rotating=!1;this.fading=!1;this.lastTickTS=0;this.lastCameraTurnTS=0;this.fadeStartSpeed=null;this.fadeTime=0;this.camera=e,this.options=t,this.rotationSpeed={x:0,y:0,z:0},this.fadeCorrection=1/(this.options.speedFadeTime/1e3)**2}turnCamera(e=0,t=0,i=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+i)}pointCameraTo(e=0,t=0,i=0){t=this.limitCameraRotationY(t);let r=e-this.camera.orientation.x,a=t-this.camera.orientation.y,n=i-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=i,this.lastCameraTurn={x:r,y:a,z:n},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,i){this.rotationSpeed.x=e!=null?e:this.rotationSpeed.x,this.rotationSpeed.y=t!=null?t:this.rotationSpeed.y,this.rotationSpeed.z=i!=null?i:this.rotationSpeed.z}startRotation(){this.rotating=!0}stopRotation(e=!1){e?(this.setRotationSpeed(0,0,0),this.fadeStartSpeed=null):this.startFading(this.rotationSpeed.x,this.rotationSpeed.y,this.rotationSpeed.z),this.rotating=!1}onCameraRelease(){if(this.lastCameraTurn&&this.lastCameraTurnTS){let e=Date.now()-this.lastCameraTurnTS;if(e<this.options.speedFadeThreshold){let t=(1-e/this.options.speedFadeThreshold)*this.options.rotationSpeedCorrection;this.startFading(this.lastCameraTurn.x*t,this.lastCameraTurn.y*t,this.lastCameraTurn.z*t)}}}startFading(e,t,i){this.setRotationSpeed(e,t,i),this.fadeStartSpeed={...this.rotationSpeed},this.fading=!0}stopFading(){this.fadeStartSpeed=null,this.fading=!0,this.fadeTime=0}limitCameraRotationY(e){return Math.max(-this.options.maxYawAngle,Math.min(e,this.options.maxYawAngle))}tick(e){if(!this.lastTickTS){this.lastTickTS=e,this.lastCameraTurnTS=Date.now();return}let t=e-this.lastTickTS,i=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i);else if(this.fading&&this.fadeStartSpeed){let r=-this.fadeCorrection*(this.fadeTime/1e3)**2+1;this.setRotationSpeed(this.fadeStartSpeed.x*r,this.fadeStartSpeed.y*r,this.fadeStartSpeed.z*r),r>0?this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}};var WI=`attribute vec2 a_vertex;
124
+ `})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(d,"i")}var pp=N(Ot(),1);import{videoSizeToQuality as Q0}from"@vkontakte/videoplayer-shared/es2018";var EI=({id:s,width:e,height:t,bitrate:i,fps:r,quality:a,streamId:n})=>{var u;let o=(u=a?Bi(a):void 0)!=null?u:Q0({width:e,height:t});return o&&{id:s,quality:o,bitrate:i,size:{width:e,height:t},fps:r,streamId:n}},wI=({id:s,bitrate:e})=>({id:s,bitrate:e}),AI=({language:s,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:s,label:e}),PI=({language:s,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:s,label:e}),hp=({id:s,language:e,label:t,codecs:i,isDefault:r})=>({id:s,language:e,label:t,codec:(0,pp.default)(i.split("."),0),isDefault:r}),fp=({id:s,language:e,label:t,hdr:i,codecs:r})=>({id:s,language:e,hdr:i,label:t,codec:(0,pp.default)(r.split("."),0)}),mp=s=>"url"in s,Je=s=>s.type==="template",mn=s=>s instanceof DOMException&&(s.name==="AbortError"||s.code===20);var RI=s=>{if(!(s!=null&&s.startsWith("P")))return;let e=(n,o)=>{let u=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(u)?0:u)*o},i=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(s),r=(i==null?void 0:i[1])==="-"?-1:1,a={days:e(i==null?void 0:i[5],r),hours:e(i==null?void 0:i[6],r),minutes:e(i==null?void 0:i[7],r),seconds:e(i==null?void 0:i[8],r)};return a.days*24*60*60*1e3+a.hours*60*60*1e3+a.minutes*60*1e3+a.seconds*1e3},gi=(s,e)=>{let t=s;t=(0,bp.default)(t,"$$","$");let i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[r,a]of(0,MI.default)(i)){let n=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=(0,bp.default)(t,n,(o,u)=>kI(a)?o:kI(u)?a:(0,LI.default)(a,parseInt(u,10),"0"))}return t},$I=(s,e)=>{var w,P,C,M,R,Q,U,A,F,k,x,$,oe,Ce,se,K,ye,Te,Ie,Ve,Tt,At,qt,Xt,Ai,bs,gs,Ss,vs,ys,Ts,Is,xs,Es,ws,As,Ps,ks,Rs,Ms,Ls,Bs,$s,Ds,Cs,Vs,Os,_s,Fs,Ns,Us,qs,js,Hs,zs,Qs,Gs,Ws,Ys,Ks,Xs;let i=new DOMParser().parseFromString(s,"application/xml"),r={video:[],audio:[],text:[]},a=i.children[0],n=Array.from(a.querySelectorAll("MPD > BaseURL").values()).map(ce=>{var _,je;return(je=(_=ce.textContent)==null?void 0:_.trim())!=null?je:""}),o=(w=(0,BI.default)(n,0))!=null?w:"",u=a.getAttribute("type")==="dynamic",l=a.getAttribute("availabilityStartTime"),d=a.getAttribute("publishTime"),c=a.getElementsByTagName("vk:Attrs")[0],h=c==null?void 0:c.getElementsByTagName("vk:XLatestSegmentPublishTime")[0].textContent,p=c==null?void 0:c.getElementsByTagName("vk:XStreamIsLive")[0].textContent,f=c==null?void 0:c.getElementsByTagName("vk:XStreamIsUnpublished")[0].textContent,m=c==null?void 0:c.getElementsByTagName("vk:XPlaybackDuration")[0].textContent,g;u&&(g={availabilityStartTime:l?new Date(l).getTime():0,publishTime:d?new Date(d).getTime():0,latestSegmentPublishTime:h?new Date(h).getTime():0,streamIsAlive:p==="yes",streamIsUnpublished:f==="yes"});let S,v=a.getAttribute("mediaPresentationDuration"),y=[...a.getElementsByTagName("Period")],I=y.reduce((ce,_)=>({...ce,[_.id]:_.children}),{}),T=y.reduce((ce,_)=>({...ce,[_.id]:_.getAttribute("duration")}),{});v?S=RI(v):(0,gp.default)(T).filter(ce=>ce).length&&!u?S=(0,gp.default)(T).reduce((ce,_)=>{var je;return ce+((je=RI(_))!=null?je:0)},0):m&&(S=parseInt(m,10));let E=0,O=(C=(P=a.getAttribute("profiles"))==null?void 0:P.split(","))!=null?C:[];for(let ce of y.map(_=>_.id))for(let _ of I[ce]){let je=(M=_.getAttribute("id"))!=null?M:"id"+(E++).toString(10),Pt=(R=_.getAttribute("mimeType"))!=null?R:"",ji=(Q=_.getAttribute("codecs"))!=null?Q:"",Hi=(U=_.getAttribute("contentType"))!=null?U:Pt==null?void 0:Pt.split("/")[0],kl=(F=(A=_.getAttribute("profiles"))==null?void 0:A.split(","))!=null?F:[],Js=(x=xI((k=_.getAttribute("lang"))!=null?k:""))!=null?x:{},Jt=(Ce=(oe=($=_.querySelector("Label"))==null?void 0:$.textContent)==null?void 0:oe.trim())!=null?Ce:void 0,Rl=_.querySelectorAll("Representation"),Ml=_.querySelector("SegmentTemplate"),Ll=(K=(se=_.querySelector("Role"))==null?void 0:se.getAttribute("value"))!=null?K:void 0,ut=Hi,H={id:je,language:Js.language,isDefault:Ll==="main",label:Jt,codecs:ji,hdr:ut==="video"&&Zr(ji),mime:Pt,representations:[]};for(let V of Rl){let we=(ye=V.getAttribute("lang"))!=null?ye:void 0,kt=(Ie=(Te=Jt!=null?Jt:_.getAttribute("label"))!=null?Te:V.getAttribute("label"))!=null?Ie:void 0,Zt=(At=(Tt=(Ve=V.querySelector("BaseURL"))==null?void 0:Ve.textContent)==null?void 0:Tt.trim())!=null?At:"",He=new URL(Zt||o,e).toString(),Ae=(qt=V.getAttribute("mimeType"))!=null?qt:Pt,ei=(Ai=(Xt=V.getAttribute("codecs"))!=null?Xt:ji)!=null?Ai:"",ti;if(Hi==="text"){let Pe=V.getAttribute("id")||"",ii=((bs=Js.privateuse)==null?void 0:bs.includes("x-auto"))||Pe.includes("_auto"),ze=V.querySelector("SegmentTemplate");if(ze){let Rt={representationId:(gs=V.getAttribute("id"))!=null?gs:void 0,bandwidth:(Ss=V.getAttribute("bandwidth"))!=null?Ss:void 0},ri=parseInt((vs=V.getAttribute("bandwidth"))!=null?vs:"",10)/1e3,si=(Ts=parseInt((ys=ze.getAttribute("startNumber"))!=null?ys:"",10))!=null?Ts:1,lt=parseInt((Is=ze.getAttribute("timescale"))!=null?Is:"",10),zi=(xs=ze.querySelectorAll("SegmentTimeline S"))!=null?xs:[],ct=ze.getAttribute("media");if(!ct)continue;let ai=[],ni=0,oi="",dt=0,Mt=si,ee=0;for(let de of zi){let Qe=parseInt((Es=de.getAttribute("d"))!=null?Es:"",10),ne=parseInt((ws=de.getAttribute("r"))!=null?ws:"",10)||0,ke=parseInt((As=de.getAttribute("t"))!=null?As:"",10);ee=Number.isFinite(ke)?ke:ee;let Ge=Qe/lt*1e3,Re=ee/lt*1e3;for(let me=0;me<ne+1;me++){let Me=gi(ct,{...Rt,segmentNumber:Mt.toString(10),segmentTime:(ee+me*Qe).toString(10)}),pt=(Re!=null?Re:0)+me*Ge,Bt=pt+Ge;Mt++,ai.push({time:{from:pt,to:Bt},url:Me})}ee+=(ne+1)*Qe,ni+=(ne+1)*Ge}dt=ee/lt*1e3,oi=gi(ct,{...Rt,segmentNumber:Mt.toString(10),segmentTime:ee.toString(10)});let Lt={time:{from:dt,to:1/0},url:oi},xe={type:"template",baseUrl:He,segmentTemplateUrl:ct,initUrl:"",totalSegmentsDurationMs:ni,segments:ai,nextSegmentBeyondManifest:Lt,timescale:lt};ti={id:Pe,kind:"text",segmentReference:xe,profiles:[],duration:S,bitrate:ri,mime:"",codecs:"",width:0,height:0,isAuto:ii}}else ti={id:Pe,isAuto:ii,kind:"text",url:He}}else{let Pe=(ks=(Ps=V.getAttribute("contentType"))!=null?Ps:Ae==null?void 0:Ae.split("/")[0])!=null?ks:Hi,ii=(Ms=(Rs=_.getAttribute("profiles"))==null?void 0:Rs.split(","))!=null?Ms:[],ze=parseInt((Ls=V.getAttribute("width"))!=null?Ls:"",10),Rt=parseInt((Bs=V.getAttribute("height"))!=null?Bs:"",10),ri=parseInt(($s=V.getAttribute("bandwidth"))!=null?$s:"",10)/1e3,si=(Ds=V.getAttribute("frameRate"))!=null?Ds:"",lt=(Cs=V.getAttribute("quality"))!=null?Cs:void 0,zi=si?Lu(si):void 0,ct=(Vs=V.getAttribute("id"))!=null?Vs:"id"+(E++).toString(10),ai=Pe==="video"?`${Rt}p`:Pe==="audio"?`${ri}Kbps`:ei,ni=`${ct}@${ai}`,oi=[...O,...kl,...ii],dt,Mt=V.querySelector("SegmentBase"),ee=(Os=V.querySelector("SegmentTemplate"))!=null?Os:Ml;if(Mt){let xe=(Fs=(_s=V.querySelector("SegmentBase Initialization"))==null?void 0:_s.getAttribute("range"))!=null?Fs:"",[de,Qe]=xe.split("-").map(Me=>parseInt(Me,10)),ne={from:de,to:Qe},ke=(Ns=V.querySelector("SegmentBase"))==null?void 0:Ns.getAttribute("indexRange"),[Ge,Re]=ke?ke.split("-").map(Me=>parseInt(Me,10)):[],me=ke?{from:Ge,to:Re}:void 0;dt={type:"byteRange",url:He,initRange:ne,indexRange:me}}else if(ee){let xe={representationId:(Us=V.getAttribute("id"))!=null?Us:void 0,bandwidth:(qs=V.getAttribute("bandwidth"))!=null?qs:void 0},de=parseInt((js=ee.getAttribute("timescale"))!=null?js:"",10),Qe=(Hs=ee.getAttribute("initialization"))!=null?Hs:"",ne=ee.getAttribute("media"),ke=(Qs=parseInt((zs=ee.getAttribute("startNumber"))!=null?zs:"",10))!=null?Qs:1,Ge=gi(Qe,xe);if(!ne)throw new ReferenceError("No media attribute in SegmentTemplate");let Re=(Gs=ee.querySelectorAll("SegmentTimeline S"))!=null?Gs:[],me=[],Me=0,pt="",Bt=0;if(Re.length){let ui=ke,pe=0;for(let ht of Re){let be=parseInt((Ws=ht.getAttribute("d"))!=null?Ws:"",10),We=parseInt((Ys=ht.getAttribute("r"))!=null?Ys:"",10)||0,li=parseInt((Ks=ht.getAttribute("t"))!=null?Ks:"",10);pe=Number.isFinite(li)?li:pe;let Qi=be/de*1e3,Gi=pe/de*1e3;for(let ci=0;ci<We+1;ci++){let $l=gi(ne,{...xe,segmentNumber:ui.toString(10),segmentTime:(pe+ci*be).toString(10)}),Zs=(Gi!=null?Gi:0)+ci*Qi,Dl=Zs+Qi;ui++,me.push({time:{from:Zs,to:Dl},url:$l})}pe+=(We+1)*be,Me+=(We+1)*Qi}Bt=pe/de*1e3,pt=gi(ne,{...xe,segmentNumber:ui.toString(10),segmentTime:pe.toString(10)})}else if(G0(S)){let pe=parseInt((Xs=ee.getAttribute("duration"))!=null?Xs:"",10)/de*1e3,ht=Math.ceil(S/pe),be=0;for(let We=1;We<ht;We++){let li=gi(ne,{...xe,segmentNumber:We.toString(10),segmentTime:be.toString(10)});me.push({time:{from:be,to:be+pe},url:li}),be+=pe}Bt=be,pt=gi(ne,{...xe,segmentNumber:ht.toString(10),segmentTime:be.toString(10)})}let Bl={time:{from:Bt,to:1/0},url:pt};dt={type:"template",baseUrl:He,segmentTemplateUrl:ne,initUrl:Ge,totalSegmentsDurationMs:Me,segments:me,nextSegmentBeyondManifest:Bl,timescale:de}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Pe||!Ae)continue;let Lt={video:"video",audio:"audio",text:"text"}[Pe];if(!Lt)continue;ut||(ut=Lt),ti={id:ni,kind:Lt,segmentReference:dt,profiles:oi,duration:S,bitrate:ri,mime:Ae,codecs:ei,width:ze,height:Rt,fps:zi,quality:lt}}H.language||(H.language=we),H.label||(H.label=kt),H.mime||(H.mime=Ae),H.codecs||(H.codecs=ei),H.hdr||(H.hdr=ut==="video"&&Zr(ei)),H.representations.push(ti)}if(ut){let V=r[ut].find(we=>we.id===H.id);if(V&&H.representations.every(we=>Je(we.segmentReference)))for(let we of V.representations){let kt=H.representations.find(Ae=>Ae.id===we.id),Zt=kt==null?void 0:kt.segmentReference,He=we.segmentReference;He.segments.push(...Zt.segments),He.nextSegmentBeyondManifest=Zt.nextSegmentBeyondManifest}else r[ut].push(H)}}return{duration:S,streams:r,baseUrls:n,live:g}};import{isNonNullable as DI}from"@vkontakte/videoplayer-shared/es2018";var q=(s,e)=>DI(s)&&DI(e)&&s.readyState==="open"&&W0(s,e);function W0(s,e){for(let t=0;t<s.activeSourceBuffers.length;++t)if(s.activeSourceBuffers[t]===e)return!0;return!1}var bn=class{constructor(e,t,i,{fetcher:r,tuning:a,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new dr(0);this.currentLowLatencySegmentLength$=new dr(0);this.currentSegmentLength$=new dr(0);this.onLastSegment$=new dr(!1);this.fullyBuffered$=new dr(!1);this.playingRepresentation$=new dr(void 0);this.playingRepresentationInit$=new dr(void 0);this.error$=new K0;this.gaps=[];this.subscription=new X0;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new ae;this.switchAbortController=new ae;this.destroyAbortController=new ae;this.bufferLimit=1/0;this.failedDownloads=0;this.baseUrls=[];this.baseUrlsIndex=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.lastDataObtainedTimestampMs=0;this.loadByteRangeSegmentsTimeoutId=0;this.startWith=Ci(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);nt(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new DT(this.sourceBuffer),this.subscription.add(vp(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:Si.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o!=null||(o={id:"SegmentEjection",category:Si.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),this.error$.next(o)})),this.subscription.add(vp(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:Si.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o||!q(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,Kr(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=this.getForwardBufferDuration(o),d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,n*2,l<d).catch(c=>{this.handleAsyncError(c,"pruneBuffer")})})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);let i=this.initData.get(t.id),r=this.segments.get(t.id),a=this.parsedInitData.get(t.id);nt(i,"No init buffer for starting representation"),nt(r,"No segments for starting representation"),i instanceof ArrayBuffer&&(this.searchGaps(r,t),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(a))}.bind(this));this.switchTo=Ci(this.destroyAbortController.signal,async function*(e,t=!1){if(!q(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);nt(i,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if(Ue(a)||Ue(r)?yield this.loadInit(i,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),nt(r,"No segments for starting representation"),a=this.initData.get(e),!(!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer||!q(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(a,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer();else{let n=this.getCurrentPosition();es(n)&&!this.isLive&&(this.bufferLimit=1/0,await this.pruneBuffer(n,1/0,!0)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}this.maintain()}}.bind(this));this.switchToOld=Ci(this.destroyAbortController.signal,async function*(e,t=!1){if(!q(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);nt(i,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if(Ue(a)||Ue(r)?yield this.loadInit(i,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),nt(r,"No segments for starting representation"),a=this.initData.get(e),!(!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer||!q(this.mediaSource,this.sourceBuffer)))if(yield this.abort(),yield this.sourceBufferTaskQueue.append(a,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let n=this.getCurrentPosition();es(n)&&(this.isLive||(this.bufferLimit=1/0,await this.pruneBuffer(n,1/0,!0)),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}}.bind(this));this.seekLive=Ci(this.destroyAbortController.signal,async function*(e){var u,l;let t=(u=(0,Du.default)(e,d=>d.representations))!=null?u:[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let d of this.representations.keys()){let c=t.find(f=>f.id===d);c&&this.representations.set(d,c);let h=this.representations.get(d);if(!h||!Je(h.segmentReference))return;let p=this.getActualLiveStartingSegments(h.segmentReference);this.segments.set(h.id,p)}let i=(l=this.switchingToRepresentationId)!=null?l:this.downloadingRepresentationId,r=this.representations.get(i);nt(r);let a=this.segments.get(i);nt(a,"No segments for starting representation");let n=this.initData.get(i);if(nt(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer))return;let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(a,r),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));var d;this.fetcher=r,this.tuning=a,this.compatibilityMode=u,this.forwardBufferTarget=a.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!(l!=null&&l.live),this.baseUrls=(d=l==null?void 0:l.baseUrls)!=null?d:[],this.initData=new Map(i.map(c=>[c.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(c=>[c.id,c])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchToWithPreviousAbort(e,t=!1){!q(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new ae,Ci(this.switchAbortController.signal,async function*(i,r=!1){this.switchingToRepresentationId=i;let a=this.representations.get(i);nt(a,`No such representation ${i}`);let n=this.segments.get(i),o=this.initData.get(i);if(Ue(o)||Ue(n)?yield this.loadInit(a,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(i),nt(n,"No segments for starting representation"),o=this.initData.get(i),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer||!q(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(o,this.downloadAbortController.signal),r)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=i,yield this.dropBuffer();else{let u=this.getCurrentPosition();es(u)&&!this.isLive&&(this.bufferLimit=this.forwardBufferTarget,yield this.pruneBuffer(u,1/0,!0)),this.downloadingRepresentationId=i,this.switchingToRepresentationId=void 0}this.maintain()}}.bind(this))(e,t))}warmUpMediaSource(){!Ue(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}async abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);return this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new ae,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(Ue(e)||Ue(this.downloadingRepresentationId)||Ue(this.playingRepresentationId)||Ue(this.sourceBuffer)||!q(this.mediaSource,this.sourceBuffer)||es(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(nt(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;let r=i.find(d=>e>=d.time.from&&e<d.time.to);es(r)&&isFinite(r.time.from)&&isFinite(r.time.to)&&this.currentSegmentLength$.next((r==null?void 0:r.time.to)-r.time.from);let a=e,n=100;if(this.playingRepresentationId!==this.downloadingRepresentationId){let d=this.getForwardBufferDuration(e),c=r?r.time.to+n:-1/0;r&&r.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&d>=r.time.to-e+n&&(a=c)}if(isFinite(this.bufferLimit)&&Kr(this.sourceBuffer.buffered)>=this.bufferLimit){let d=this.getForwardBufferDuration(e),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,d<c).catch(h=>{this.handleAsyncError(h,"pruneBuffer")});return}let u=[];if(!this.activeSegments.size&&(u=this.selectForwardBufferSegments(i,t.segmentReference.type,a),u.length)){let d="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if((0,$u.default)(u,r))d="high";else{let c=(0,ts.default)(u,0);c&&c.time.from-r.time.to>=this.forwardBufferTarget/2&&(d="low")}this.loadSegments(u,t,d).catch(c=>{this.handleAsyncError(c,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&r&&r.status==="fed"&&!u.length&&this.getForwardBufferDuration(e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let l=(0,ts.default)(i,-1);!this.isLive&&l&&(this.fullyBuffered$.next(l.time.to-e-this.getForwardBufferDuration(e)<n),this.onLastSegment$.next(e-l.time.from>0))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let i=0,r=this.isLive?this.liveInitialAdditionalOffset:0;for(let a of e)Math.trunc(a.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:a.time.from+r}),i=a.time.to;es(t.duration)&&t.duration-i>0&&!this.isLive&&this.gaps.push({representation:t.id,from:i,to:t.duration})}getActualLiveStartingSegments(e){let t=e.segments,i=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,r=[],a=0,n=t.length-1;do r.unshift(t[n]),a+=t[n].time.to-t[n].time.from,n--;while(a<i&&n>=0);return this.liveInitialAdditionalOffset=a-i,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){let t=(0,Du.default)(e==null?void 0:e.streams[this.kind],r=>r.representations).find(r=>r.id===this.downloadingRepresentationId);if(!t)return;let i=this.segments.get(t.id);if(i!=null&&i.length)return{from:i[0].time.from,to:i[i.length-1].time.to}}updateLive(e){var i,r,a,n;let t=(i=(0,Du.default)(e==null?void 0:e.streams[this.kind],o=>o.representations))!=null?i:[];if(![...this.segments.values()].every(o=>!o.length))for(let o of t){if(!o||!Je(o.segmentReference))return;let u=o.segmentReference.segments.map(p=>({...p,status:"none",size:void 0})),l=100,d=(r=this.segments.get(o.id))!=null?r:[],c=(n=(a=(0,ts.default)(d,-1))==null?void 0:a.time.to)!=null?n:0,h=u==null?void 0:u.findIndex(p=>c>=p.time.from+l&&c<=p.time.to+l);if(h===-1){this.liveUpdateSegmentIndex=0;let p=this.getActualLiveStartingSegments(o.segmentReference);this.segments.set(o.id,p)}else{let p=u.slice(h+1);this.segments.set(o.id,[...d,...p])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;nt(e);let t=this.segments.get(e);if(t!=null&&t.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}updateLowLatencyLiveIfNeeded(e){var i;let t=0;for(let r of this.representations.values()){let a=r.segmentReference;if(!Je(a))return;let n=(i=this.segments.get(r.id))!=null?i:[],o=n.find(l=>Math.floor(l.time.from)===Math.floor(e.time.from));if(o&&!isFinite(o.time.to)&&(o.time.to=e.time.to,t=o.time.to-o.time.from),!!!n.find(l=>Math.floor(l.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let l=Math.round(e.time.to*a.timescale/1e3).toString(10),d=gi(a.segmentTemplateUrl,{segmentTime:l});n.push({status:"none",time:{from:e.time.to,to:1/0},url:d})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){var a,n,o;let t=(n=(a=this.switchingToRepresentationId)!=null?a:this.downloadingRepresentationId)!=null?n:this.playingRepresentationId;if(!t)return;let i=this.segments.get(t);if(!i)return;let r=i.find(u=>u.time.from<=e&&u.time.to>=e);return(o=r==null?void 0:r.time.from)!=null?o:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)==null||e.destroy(),this.gapDetectionIdleCallback&&Yt&&Yt(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&Yt&&Yt(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}this.sourceBuffer=null,this.downloadAbortController.abort(),this.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,i){return this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){let i=e.findIndex(r=>t>=r.time.from&&t<r.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=i),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,i){let r=this.getForwardBufferDuration(i),a=e.findIndex(({status:h,time:{from:p,to:f}},m)=>{let g=p<=i&&f>=i,S=p>i||g||m===0&&i===0,v=Math.min(this.forwardBufferTarget,this.bufferLimit),y=this.preloadOnly&&p<=i+v||r<v&&f-p>=v||f<=i+v;return(h==="none"||h==="partially_ejected"&&S&&y&&this.sourceBuffer&&q(this.mediaSource,this.sourceBuffer)&&!(Ne(this.sourceBuffer.buffered,p)&&Ne(this.sourceBuffer.buffered,f)))&&S&&y});if(a===-1)return[];if(t!=="byteRange")return e.slice(a,a+1);let n=e,o=0,u=0,l=[],d=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,c=this.preloadOnly?this.forwardBufferTarget:0;for(let h=a;h<n.length&&(o<=d||u<=c);h++){let p=n[h];if(o+=p.byte.to+1-p.byte.from,u+=p.time.to+1-p.time.from,p.status==="none"||p.status==="partially_ejected")l.push(p);else break}return l}async loadSegments(e,t,i="auto"){Je(t.segmentReference)?await this.loadTemplateSegment(e[0],t,i):await this.loadByteRangeSegments(e,t,i)}async loadTemplateSegment(e,t,i="auto"){e.status="downloading";let r={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(r);let{range:a,url:n,signal:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await Ci(o,async function*(){let d=yp(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,d))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let d=await this.fetcher.fetch(n,{range:a,signal:o,onProgress:u,priority:i,isLowLatency:this.isActiveLowLatency()});if(this.lastDataObtainedTimestampMs=Bu(),!d)return;let c=new DataView(d),h=fn(t.mime);if(!isFinite(r.segment.time.to)){let m=t.segmentReference.timescale;r.segment.time.to=h.getChunkEndTime(c,m)}u&&r.feedingBytes&&l?await Promise.all(l):await this.sourceBufferTaskQueue.append(c,o);let{serverDataReceivedTimestamp:p,serverDataPreparedTime:f}=h.getServerLatencyTimestamps(c);p&&f&&this.currentLiveSegmentServerLatency$.next(f-p),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(d){this.abortActiveSegments([e]),mn(d)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}updateRepresentationsBaseUrlIfNeeded(){if(!this.tuning.dash.enableBaseUrlSupport||!this.baseUrls.length||this.failedDownloads<=this.tuning.dash.maxSegmentRetryCount)return;this.baseUrlsIndex=(this.baseUrlsIndex+1)%this.baseUrls.length;let e=this.baseUrls[this.baseUrlsIndex];for(let t of this.representations.values())Je(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}async loadByteRangeSegments(e,t,i="auto"){if(!e.length)return;for(let u of e)u.status="downloading",this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:r,url:a,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(await Ci(n,async function*(){let u=yp(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),vp(window,"online").pipe(Y0()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(a,{range:r,onProgress:o,signal:n,priority:i}),this.lastDataObtainedTimestampMs=Bu(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),mn(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(Je(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:(0,ts.default)(e,0).byte.from,to:(0,ts.default)(e,-1).byte.to},{signal:a}=this.downloadAbortController;return{url:i,range:r,signal:a,onProgress:async(o,u)=>{if(!a.aborted)try{this.lastDataObtainedTimestampMs=Bu(),await this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:a,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:Si.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!Je(t.segmentReference))throw new Error("Representation is not template type");let i=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&i.searchParams.set("low-latency","yes");let r=i.toString(),{signal:a}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,d)=>{if(!a.aborted)try{this.lastDataObtainedTimestampMs=Bu();let c=this.onSomeTemplateDataLoaded({dataView:l,loaded:d,signal:a,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(c)}catch(c){this.error$.next({id:"SegmentFeeding",category:Si.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}}:void 0;return{url:r,signal:a,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,$u.default)(e,t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:a}){if(!this.activeSegments.size||!q(this.mediaSource,this.sourceBuffer))return;let n=this.representations.get(t);if(n)for(let o of this.activeSegments){let{segment:u}=o;if(o.representationId===t){if(a.aborted){r();continue}if(o.loadedBytes=i,o.loadedBytes>o.feedingBytes){let l=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),d=fn(n.mime).parseFeedableSegmentChunk(l,this.isLive);d!=null&&d.byteLength&&(u.status="partially_fed",o.feedingBytes+=d.byteLength,await this.sourceBufferTaskQueue.append(d),o.fedBytes+=d.byteLength)}}}}async onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:a,onSegmentAppendFailed:n}){if(!this.activeSegments.size||!q(this.mediaSource,this.sourceBuffer))return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){let{segment:l}=u;if(u.representationId!==t)continue;if(a.aborted){await n();continue}let d=l.byte.from-i,c=l.byte.to-i,h=c-d+1,p=d<r,f=c<=r;if(!p)continue;let m=fn(o.mime);if(l.status==="downloading"&&f){l.status="downloaded";let g=new DataView(e.buffer,e.byteOffset+d,h);await this.sourceBufferTaskQueue.append(g,a)&&!a.aborted?this.onSegmentFullyAppended(u,t):await n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(l.status==="downloading"||l.status==="partially_fed")&&(u.loadedBytes=Math.min(h,r-d),u.loadedBytes>u.feedingBytes)){let g=new DataView(e.buffer,e.byteOffset+d+u.feedingBytes,u.loadedBytes-u.feedingBytes),S=u.loadedBytes===h?g:m.parseFeedableSegmentChunk(g);S!=null&&S.byteLength&&(l.status="partially_fed",u.feedingBytes+=S.byteLength,await this.sourceBufferTaskQueue.append(S,a)&&!a.aborted?(u.fedBytes+=S.byteLength,u.fedBytes===h&&this.onSegmentFullyAppended(u,t)):await n())}}}onSegmentFullyAppended(e,t){var i;if(!(Ue(this.sourceBuffer)||!q(this.mediaSource,this.sourceBuffer))){!this.isLive&&j.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(Ne(this.sourceBuffer.buffered,e.segment.time.from,100)&&Ne(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:Si.VIDEO_PIPELINE,message:"Browser stuck on empty result of adding segment to source buffer"})),this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",mp(e.segment)&&(e.segment.size=e.fedBytes);for(let r of this.representations.values())if(r.id!==t)for(let a of(i=this.segments.get(r.id))!=null?i:[])a.status==="fed"&&Math.round(a.time.from)===Math.round(e.segment.time.from)&&Math.round(a.time.to)===Math.round(e.segment.time.to)&&(a.status="none");this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}}abortSegment(e){e.status==="partially_fed"?e.status="partially_ejected":e.status!=="partially_ejected"&&(e.status="none");for(let t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[r,a]of this.initData.entries()){let n=a instanceof Promise;t||(t=n),a===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let i=this.representations.get(e);i&&(this.initLoadIdleCallback=Yr(()=>(0,CI.default)(this.loadInit(i,"low",!1),()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",i=!1){let r=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!i&&this.failedDownloads>0?Ci(this.destroyAbortController.signal,async function*(){let o=yp(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,fn(e.mime),r)).then(async o=>{if(!o)return;let{init:u,dataView:l,segments:d}=o,c=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,c);let h=d;this.isLive&&Je(e.segmentReference)&&(h=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,h),u&&this.parsedInitData.set(e.id,u)}).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:Si.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n}async dropBuffer(){for(let e of this.segments.values())for(let t of e)t.status="none";await this.pruneBuffer(0,1/0,!0)}async pruneBuffer(e,t,i=!1){if(!this.sourceBuffer||!q(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||Ue(e))return!1;let r=[],a=0,n=u=>{u.sort((d,c)=>d.from-c.from);let l=[u[0]];for(let d=1;d<u.length;d++){let{from:c,to:h}=u[d],p=l[l.length-1];p.to>=c?p.to=Math.max(p.to,h):l.push(u[d])}return l},o=u=>{var d;if(a>=t)return r;r.push({...u.time}),r=n(r);let l=mp(u)?(d=u.size)!=null?d:0:u.byte.to-u.byte.from;a+=l};for(let u of this.segments.values())for(let l of u){let d=l.time.to<=e-this.tuning.dash.bufferPruningSafeZone,c=l.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(d||c)&&l.status==="fed"&&o(l)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let l=this.sourceBuffer.buffered.start(u)*1e3,d=this.sourceBuffer.buffered.end(u)*1e3,c=0;for(let h of this.segments.values())for(let p of h)(0,$u.default)(["none","partially_ejected"],p.status)&&Math.round(p.time.from)<=Math.round(l)&&Math.round(p.time.to)>=Math.round(d)&&c++;if(c===this.segments.size){let h={time:{from:l,to:d},url:"",status:"none"};o(h)}}if(r.length&&i){let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let l of this.segments.values())for(let d of l)d.time.from>=e+u&&d.status==="fed"&&o(d)}return r.length?(await Promise.all(r.map(l=>this.sourceBufferTaskQueue.remove(l.from,l.to)))).reduce((l,d)=>l||d,!1):!1}async abortBuffer(){if(!this.sourceBuffer||!q(this.mediaSource,this.sourceBuffer))return!1;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;return this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!q(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}getForwardBufferDuration(e=this.getCurrentPosition()){return!this.sourceBuffer||!q(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||Ue(e)?0:$e(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!(!this.sourceBuffer||!q(this.mediaSource,this.sourceBuffer))){if(this.tuning.useRefactoredSearchGap)for(let i=0;i<this.sourceBuffer.buffered.length;i++)this.gaps=this.gaps.filter(r=>this.sourceBuffer&&(Math.round(r.from)<Math.round(this.sourceBuffer.buffered.start(i)*1e3)||Math.round(r.to)>Math.round(this.sourceBuffer.buffered.end(i)*1e3)));for(let i of t){let r={representation:e,from:i.time.from,to:i.time.to};for(let a=0;a<this.sourceBuffer.buffered.length;a++){let n=this.sourceBuffer.buffered.start(a)*1e3,o=this.sourceBuffer.buffered.end(a)*1e3;if(!(o<=i.time.from||n>=i.time.to)){if(n<=i.time.from&&o>=i.time.to){r=void 0;break}o>i.time.from&&o<i.time.to&&(r.from=o),n<i.time.to&&n>i.time.from&&(r.to=n)}}r&&r.to-r.from>1&&!this.gaps.some(a=>r&&a.from===r.from&&a.to===r.to)&&this.gaps.push(r)}}}detectGapsWhenIdle(e,t){if(!(this.gapDetectionIdleCallback||!this.sourceBuffer||!q(this.mediaSource,this.sourceBuffer))){if(!this.tuning.useRefactoredSearchGap)for(let i=0;i<this.sourceBuffer.buffered.length;i++)this.gaps=this.gaps.filter(r=>this.sourceBuffer&&(Math.round(r.from)<Math.round(this.sourceBuffer.buffered.start(i)*1e3)||Math.round(r.to)>Math.round(this.sourceBuffer.buffered.end(i)*1e3)));this.gapDetectionIdleCallback=Yr(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:Si.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if(Ue(this.sourceBuffer)||!q(this.mediaSource,this.sourceBuffer)||Ue(this.playingRepresentationId))return;let e=[];for(let i=0;i<this.sourceBuffer.buffered.length;i++){let r=Math.floor(this.sourceBuffer.buffered.start(i)*1e3),a=Math.ceil(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:r,to:a})}let t=100;for(let i of this.segments.values())for(let r of i){let{status:a}=r;if(a!=="fed"&&a!=="partially_ejected")continue;let n=Math.floor(r.time.from),o=Math.ceil(r.time.to),u=e.some(d=>d.from-t<=n&&d.to+t>=o),l=e.filter(d=>n>=d.from&&n<d.to-t||o>d.from+t&&o<=d.to);u||(l.length===1?r.status="partially_ejected":this.gaps.some(d=>d.from===r.time.from||d.to===r.time.to)?r.status="partially_ejected":r.status="none")}}handleAsyncError(e,t){this.error$.next({id:t,category:Si.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}};var Vi=s=>{let e=new URL(s);return e.searchParams.set("quic","1"),e.toString()};var Cu=s=>{var a;let e=s.get("X-Delivery-Type"),t=s.get("X-Reused"),i=e===null?"http1":e!=null?e:void 0,r=t===null?void 0:(a={1:!0,0:!1}[t])!=null?a:void 0;return{type:i,reused:r}};import{abortable as gn,assertNever as VI,fromEvent as OI,merge as J0,now as Sn,Subscription as Z0,Subject as _I,ValueSubject as Tp,flattenObject as is,ErrorCategory as vn}from"@vkontakte/videoplayer-shared/es2018";var Vu=s=>{let e=new URL(s);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var _u=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:a=!1}){this.lastConnectionType$=new Tp(void 0);this.lastConnectionReused$=new Tp(void 0);this.lastRequestFirstBytes$=new Tp(void 0);this.recoverableError$=new _I;this.error$=new _I;this.abortAllController=new ae;this.subscription=new Z0;this.fetchManifest=gn(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=Vi(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=Vu(i));let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(Ou);return r?(t.log("success",is({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(r.headers),r.text()):(t.error("error",is({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=gn(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:a="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1}={}){var C,M;let l=e,d=new Headers,c=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{d.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let R=new URL(l,location.href);R.searchParams.append("bytes",`${i.from}-${i.to}`),l=R.toString();break}default:VI(t)}this.requestQuic&&(l=Vi(l));let h=this.abortAllController.signal,p;if(n){let R=new ae;if(p=J0(OI(this.abortAllController.signal,"abort"),OI(n,"abort")).subscribe(()=>{try{R.abort()}catch(Q){Ou(Q)}}),this.subscription.add(p),this.abortAllController.signal.aborted||n.aborted)try{R.abort()}catch(Q){Ou(Q)}h=R.signal}let f=Sn();c.log("startRequest",is({url:l,priority:a,rangeMethod:t,range:i,isLowLatency:u,requestStartedAt:f}));let m=yield this.doFetch(l,{priority:a,headers:d,signal:h}),g=Sn();if(!m)return c.error("error",{message:"No response in request"}),c.end(),p==null||p.unsubscribe(),null;if((C=this.throughputEstimator)==null||C.addRawRtt(g-f),!m.ok||!m.body){p==null||p.unsubscribe();let R=`Fetch error ${m.status}: ${m.statusText}`;return c.error("error",{message:R}),c.end(),Promise.reject(new Error(`Fetch error ${m.status}: ${m.statusText}`))}if(this.onHeadersReceived(m.headers),!r&&!o){p==null||p.unsubscribe();let R=Sn(),Q={requestStartedAt:f,requestEndedAt:R,duration:R-f};return c.log("endRequest",is(Q)),c.end(),m.arrayBuffer()}let[S,v]=m.body.tee(),y=S.getReader();o&&((M=this.throughputEstimator)==null||M.trackStream(v,u));let I=0,T=new Uint8Array(0),E=!1,O=R=>{p==null||p.unsubscribe(),E=!0,Ou(R)},L=gn(h,async function*({done:R,value:Q}){if(I===0&&this.lastRequestFirstBytes$.next(Sn()-f),h.aborted){p==null||p.unsubscribe();return}if(!R&&Q){let U=new Uint8Array(T.length+Q.length);U.set(T),U.set(Q,T.length),T=U,I+=Q.byteLength,r==null||r(new DataView(T.buffer),I),yield y==null?void 0:y.read().then(L,O)}}.bind(this));yield y==null?void 0:y.read().then(L,O),p==null||p.unsubscribe();let w=Sn(),P={failed:E,requestStartedAt:f,requestEndedAt:w,duration:w-f};return E?(c.error("endRequest",is(P)),c.end(),null):(c.log("endRequest",is(P)),c.end(),T.buffer)}.bind(this));this.fetchByteRangeRepresentation=gn(this.abortAllController.signal,async function*(e,t,i){var S;if(e.type!=="byteRange")return null;let{from:r,to:a}=e.initRange,n=r,o=a,u=!1,l,d;e.indexRange&&(l=e.indexRange.from,d=e.indexRange.to,u=a+1===l,u&&(n=Math.min(l,r),o=Math.max(d,a))),n=Math.min(n,0);let c=yield this.fetch(e.url,{range:{from:n,to:o},priority:i,measureThroughput:!1});if(!c)return null;let h=new DataView(c,r-n,a-n+1);if(!t.validateData(h))throw new Error("Invalid media file");let p=t.parseInit(h),f=(S=e.indexRange)!=null?S:t.getIndexRange(p);if(!f)throw new ReferenceError("No way to load representation index");let m;if(u)m=new DataView(c,f.from-n,f.to-f.from+1);else{let v=yield this.fetch(e.url,{range:f,priority:i,measureThroughput:!1});if(!v)return null;m=new DataView(v)}let g=t.parseSegments(m,p,f);return{init:p,dataView:new DataView(c),segments:g}}.bind(this));this.fetchTemplateRepresentation=gn(this.abortAllController.signal,async function*(e,t){if(e.type!=="template")return null;let i=new URL(e.initUrl,e.baseUrl).toString(),r=yield this.fetch(i,{priority:t,measureThroughput:!1});return r?{init:null,segments:e.segments.map(n=>({...n,status:"none",size:void 0})),dataView:new DataView(r)}:null}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=r,this.tracer=i.createComponentTracer("Fetcher"),this.useEnableSubtitlesParam=a}onHeadersReceived(e){let{type:t,reused:i}=Cu(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,t,i="auto"){var a,n;let{type:r}=e;switch(r){case"byteRange":return(a=await this.fetchByteRangeRepresentation(e,t,i))!=null?a:null;case"template":return(n=await this.fetchTemplateRepresentation(e,i))!=null?n:null;default:VI(r)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}async doFetch(e,t){let i=await wt(e,t);if(i.ok)return i;let r=await i.text(),a=parseInt(r);if(!isNaN(a))switch(a){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:vn.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:vn.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:vn.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:vn.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${a})`,category:vn.FATAL})}}},Ou=s=>{if(!mn(s))throw s};var vi=(s,e,t)=>t*e+(1-t)*s,Ip=(s,e)=>s.reduce((t,i)=>t+i,0)/e,FI=(s,e,t,i)=>{let r=0,a=t,n=Ip(s,e),o=e<i?e:i;for(let u=0;u<o;u++)s[a]>n?r++:r--,a=(s.length+a-1)%s.length;return Math.abs(r)===o};import{isNullable as eC,ValueSubject as NI}from"@vkontakte/videoplayer-shared/es2018";var Oi=class{constructor(e){this.prevReported=void 0;this.pastMeasures=[];this.takenMeasures=0;this.measuresCursor=0;var i;this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new NI(e.initial),this.debounced$=new NI(e.initial);let t=(i=e.label)!=null?i:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new Ke(`raw_${t}`),this.smoothedSeries$=new Ke(`smoothed_${t}`),this.reportedSeries$=new Ke(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,i=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=(this.pastMeasures[o]-this.smoothed)**2,i++);this.takenMeasures=i,t/=i;let r=Math.sqrt(t),a=this.smoothed+this.params.deviationFactor*r,n=this.smoothed-this.params.deviationFactor*r;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>a||this.smoothed<n)&&(eC(this.prevReported)||Math.abs(this.smoothed-this.prevReported)/this.prevReported>=this.params.changeThreshold)&&(this.prevReported=this.smoothed,this.debounced$.next(this.smoothed),this.reportedSeries$.next(this.smoothed))}};var Fu=class extends Oi{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=vi(this.slow,e,this.params.emaAlphaSlow),this.fast=vi(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var Nu=class extends Oi{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=Ip(this.pastMeasures,this.takenMeasures);this.emaSmoothed=vi(this.emaSmoothed,e,this.params.emaAlpha);let i=FI(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}};var Uu=class extends Oi{constructor(t){super(t);this.furtherValues=[];this.currentTopExtremumValue=0;this.extremumInterval=t.extremumInterval}next(t){this.currentTopExtremumValue<=t?(this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.length===this.extremumInterval?(super.next(this.currentTopExtremumValue),this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.push(t)}updateSmoothedValue(t){this.smoothed=this.smoothed?vi(this.smoothed,t,this.params.emaAlpha):t}};var yi=class{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new Fu({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new Nu({initial:e,emaAlpha:i.emaAlpha,basisTrendChangeCount:i.basisTrendChangeCount,changeThreshold:i.changeThreshold,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"})}static getLiveBufferSmoothedValue(e,t){return new Uu({initial:e,label:"liveEdgeDelay",...t})}};var rs=(s,e)=>{s&&s.playbackRate!==e&&(s.playbackRate=e)};import{isNullable as tC,ValueSubject as iC}from"@vkontakte/videoplayer-shared/es2018";var yn=class s{constructor(e,t){this.currentRepresentation$=new iC(null);this.maxRepresentations=4;this.representationsCursor=0;this.representations=[];this.currentSegment=null;this.getCurrentPosition=t.getCurrentPosition,this.processStreams(e)}updateLive(e){this.processStreams(e==null?void 0:e.streams.text)}seekLive(e){this.processStreams(e)}maintain(e=this.getCurrentPosition()){var t;if(!tC(e))for(let i of this.representations)for(let r of i){let a=r.segmentReference,n=a.segments.length,o=a.segments[0].time.from,u=a.segments[n-1].time.to;if(e<o||e>u)continue;let l=a.segments.find(d=>d.time.from<=e&&d.time.to>=e);!l||((t=this.currentSegment)==null?void 0:t.time.from)===l.time.from&&this.currentSegment.time.to===l.time.to||(this.currentSegment=l,this.currentRepresentation$.next({...r,label:"Live Text",language:"ru",isAuto:!0,url:new URL(l.url,a.baseUrl).toString()}))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e!=null?e:[]){let i=s.filterRepresentations(t.representations);if(i){this.representations[this.representationsCursor]=i,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!(e!=null&&e.some(t=>s.filterRepresentations(t.representations)))}static filterRepresentations(e){return e==null?void 0:e.filter(t=>t.kind==="text"&&"segmentReference"in t&&Je(t.segmentReference))}};var ju=N(Ot(),1);import{assertNever as Hu}from"@vkontakte/videoplayer-shared/es2018";var UI=(s,{useManagedMediaSource:e,useOldMSEDetection:t})=>{let{containers:i,protocols:r,codecs:a,nativeHlsSupported:n}=j.video,o=(a.h264||a.h265)&&a.aac,u=r.mse&&(!t||!!window.MediaStreamTrack)||r.mms&&e;return s.filter(l=>{switch(l){case"DASH_SEP":return u&&i.mp4&&o;case"DASH_WEBM":return u&&i.webm&&a.vp9&&a.opus;case"DASH_WEBM_AV1":return u&&i.webm&&a.av1&&a.opus;case"DASH_STREAMS":return u&&(i.mp4&&o||i.webm&&(a.vp9||a.av1)&&(a.opus||a.aac));case"DASH_LIVE":return u&&i.mp4&&o;case"DASH_LIVE_CMAF":return u&&i.mp4&&o&&i.cmaf;case"DASH_ONDEMAND":return u&&i.mp4&&o;case"HLS":case"HLS_ONDEMAND":case"HLS_LIVE":case"HLS_LIVE_CMAF":return n;case"MPEG":return i.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return r.webrtc&&r.ws&&a.h264&&(i.mp4||i.webm);default:return Hu(l)}})},qu=s=>{let{webmDecodingInfo:e}=j.video,t="DASH_WEBM",i="DASH_WEBM_AV1";switch(s){case"vp9":return[t,i];case"av1":return[i,t];case"none":return[];case"smooth":return e?e[i].smooth?[i,t]:e[t].smooth?[t,i]:[i,t]:[t,i];case"power_efficient":return e?e[i].powerEfficient?[i,t]:e[t].powerEfficient?[t,i]:[i,t]:[t,i];default:Hu(s)}return[t,i]},qI=({webmCodec:s,androidPreferredFormat:e,preferMultiStream:t})=>{let i=[...t?["DASH_STREAMS"]:[],...qu(s),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],r=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(j.device.isAndroid)switch(e){case"mpeg":return["MPEG",...i,"HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...i,"MPEG"];case"dash":return[...i,"HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return[...r,"MPEG",...qu(s),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...qu(s),"MPEG",...r,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...qu(s),...r,"HLS","HLS_ONDEMAND"];default:Hu(e)}return j.video.nativeHlsSupported?[...i,"HLS","HLS_ONDEMAND","MPEG"]:[...i,"HLS","HLS_ONDEMAND","MPEG"]},jI=({androidPreferredFormat:s,preferCMAF:e,preferWebRTC:t})=>{let i=e?["DASH_LIVE_CMAF","DASH_LIVE"]:["DASH_LIVE","DASH_LIVE_CMAF"],r=e?["HLS_LIVE_CMAF","HLS_LIVE"]:["HLS_LIVE","HLS_LIVE_CMAF"],a=[...i,...r],n=[...r,...i],o,u=j.device.isMac&&j.browser.isSafari;if(j.device.isAndroid)switch(s){case"dash":case"dash_any_mpeg":case"dash_any_webm":case"dash_sep":{o=a;break}case"hls":case"mpeg":{o=n;break}default:Hu(s)}else j.video.nativeHlsSupported&&!u?o=n:u?o=e?["DASH_LIVE_CMAF","HLS_LIVE_CMAF","HLS_LIVE","DASH_LIVE"]:["HLS_LIVE","DASH_LIVE","DASH_LIVE_CMAF","HLS_LIVE_CMAF"]:o=a;return t?["WEB_RTC_LIVE",...o]:[...o,"WEB_RTC_LIVE"]},xp=s=>s?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],zu=s=>{if(s.size===0)return;if(s.size===1){let t=s.values().next();return(0,ju.default)(t.value.split("."),0)}for(let t of s){let i=(0,ju.default)(t.split("."),0);if(i==="opus"||i==="vp09"||i==="av01")return i}let e=s.values().next();return(0,ju.default)(e.value.split("."),0)};var cC=["timeupdate","progress","play","seeked","stalled","waiting"],dC=["timeupdate","progress","loadeddata","playing","seeked"];var Wu=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new QI;this.representationSubscription=new QI;this.state$=new G("none");this.currentVideoRepresentation$=new he(void 0);this.currentVideoRepresentationInit$=new he(void 0);this.currentAudioRepresentation$=new he(void 0);this.currentVideoSegmentLength$=new he(0);this.currentAudioSegmentLength$=new he(0);this.error$=new Gu;this.lastConnectionType$=new he(void 0);this.lastConnectionReused$=new he(void 0);this.lastRequestFirstBytes$=new he(void 0);this.currentLiveTextRepresentation$=new he(null);this.isLive$=new he(!1);this.isActiveLive$=new he(!1);this.isLowLatency$=new he(!1);this.liveDuration$=new he(0);this.liveSeekableDuration$=new he(0);this.liveAvailabilityStartTime$=new he(0);this.liveStreamStatus$=new he(void 0);this.bufferLength$=new he(0);this.liveLatency$=new he(void 0);this.liveLoadBufferLength$=new he(0);this.livePositionFromPlayer$=new he(0);this.currentStallDuration$=new he(0);this.videoLastDataObtainedTimestamp$=new he(0);this.fetcherRecoverableError$=new Gu;this.fetcherError$=new Gu;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new Gu;this.gapWatchdogActive=!1;this.destroyController=new ae;this.initManifest=wp(this.destroyController.signal,async function*(e,t,i){var r;this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=Se(t,i,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),(r=this.manifest)!=null&&r.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:Ft.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=wp(this.destroyController.signal,async function*(){var n,o;this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(u=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:Ft.NETWORK,message:"Failed to load manifest",thrown:u})});if(!e)return null;let t=null;try{t=$I(e!=null?e:"",this.manifestUrlString)}catch(u){let l=(n=Mu(e))!=null?n:{id:"ManifestParsing",category:Ft.PARSER,message:"Failed to parse MPD manifest",thrown:u};this.error$.next(l)}if(!t)return null;let i=(u,l,d)=>{var c,h,p,f;return!!((h=(c=this.element)==null?void 0:c.canPlayType)!=null&&h.call(c,l)&&((f=(p=vt())==null?void 0:p.isTypeSupported)!=null&&f.call(p,`${l}; codecs="${d}"`))||u==="text")};if(t.live){this.isLive$.next(!!t.live);let{availabilityStartTime:u,latestSegmentPublishTime:l,streamIsUnpublished:d,streamIsAlive:c}=t.live,h=((o=t.duration)!=null?o:0)/1e3;this.liveSeekableDuration$.next(-1*h),this.liveDuration$.next((l-u)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let p="active";c||(p=d?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(p)}let r={text:t.streams.text,video:[],audio:[]};for(let u of["video","audio"]){let d=t.streams[u].filter(({mime:p,codecs:f})=>i(u,p,f)),c=new Set(d.map(({codecs:p})=>p)),h=zu(c);if(h&&(r[u]=d.filter(({codecs:p})=>p.startsWith(h))),u==="video"){let p=this.tuning.preferHDR,f=r.video.some(g=>g.hdr),m=r.video.some(g=>!g.hdr);j.display.isHDR&&p&&f?r.video=r.video.filter(g=>g.hdr):m&&(r.video=r.video.filter(g=>!g.hdr))}}let a={...t,streams:r};return this.tracer.log("updateManifestEnd",In(a)),a}.bind(this));this.initRepresentations=wp(this.destroyController.signal,async function*(e,t,i){var h;this.tracer.log("initRepresentationsStart",In({initialVideo:e,initialAudio:t,sourceHls:i})),ss(this.manifest),ss(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let r=p=>{this.representationSubscription.add(Ti(p,"error").pipe(Qu(f=>{var m;return!!((m=this.element)!=null&&m.played.length)})).subscribe(f=>{this.error$.next({id:"VideoSource",category:Ft.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:f})}))};this.source=this.tuning.useManagedMediaSource?nu():new MediaSource;let a=document.createElement("source");if(r(a),a.src=URL.createObjectURL(this.source),this.element.appendChild(a),this.tuning.useManagedMediaSource&&Ur())if(i){let p=document.createElement("source");r(p),p.type="application/x-mpegurl",p.src=i.url,this.element.appendChild(p)}else this.element.disableRemotePlayback=!0;this.isActiveLive$.next(this.isLive$.getValue());let n={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),manifest:this.manifest},o=this.manifest.streams.video.reduce((p,f)=>[...p,...f.representations],[]);if(this.videoBufferManager=new bn("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],xn(t)){let p=this.manifest.streams.audio.reduce((f,m)=>[...f,...m.representations],[]);this.audioBufferManager=new bn("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}yn.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new yn(this.manifest.streams.text,n)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$));let u=()=>{var p;(p=this.stallWatchdogSubscription)==null||p.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add(pr(...dC.map(p=>Ti(this.element,p))).pipe(ns(p=>this.element?$e(this.element.buffered,this.element.currentTime*1e3):0),Tn(),uC(p=>{p>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add(pr(Ti(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe(Tn()).subscribe(f=>this.liveStreamEndTimestamp=Pp())),this.subscription.add(Ti(this.element,"pause").subscribe(()=>{this.livePauseWatchdogSubscription=Ap(1e3).subscribe(f=>{let m=Mi(this.manifestUrlString,2);this.manifestUrlString=Se(this.manifestUrlString,m+1e3,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add(Ti(this.element,"play").subscribe(f=>{var m;return(m=this.livePauseWatchdogSubscription)==null?void 0:m.unsubscribe()})),this.representationSubscription.add(as({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(ns(({isActiveLive:f,isLowLatency:m})=>f&&m),Tn()).subscribe(f=>{this.isManualDecreasePlaybackInLive()||rs(this.element,1)})),this.representationSubscription.add(as({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(Qu(({bufferLength:f,isActiveLive:m,isLowLatency:g})=>m&&g&&!!f)).subscribe(({bufferLength:f})=>this.liveBuffer.next(f))),this.representationSubscription.add(this.videoBufferManager.currentLowLatencySegmentLength$.subscribe(f=>{if(!this.isActiveLive$.getValue()&&!this.isLowLatency$.getValue()&&!f)return;let m=this.liveSeekableDuration$.getValue()-f/1e3;this.liveSeekableDuration$.next(Math.max(m,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+f/1e3)})),this.representationSubscription.add(as({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(Qu(({isLive:f})=>f),Tn((f,m)=>m.bufferLength<f.bufferLength),ns(({rtt:f,bufferLength:m,segmentServerLatency:g})=>{let S=Mi(this.manifestUrlString,2);return(f/2+m+g+S)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(as({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:f,isActiveLive:m,isLowLatency:g})=>{if(!g||!m)return;let S=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,v=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,y=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,I=f-S;if(this.isManualDecreasePlaybackInLive())return;let T=1;Math.abs(I)>v&&(T=1+Math.sign(I)*y),rs(this.element,T)})),this.representationSubscription.add(this.bufferLength$.subscribe(f=>{var g,S;let m=0;if(f){let v=((S=(g=this.element)==null?void 0:g.currentTime)!=null?S:0)*1e3;m=Math.min(...this.bufferManagers.map(I=>{var T,E;return(E=(T=I.getLiveSegmentsToLoadState(this.manifest))==null?void 0:T.to)!=null?E:v}))-v}this.liveLoadBufferLength$.getValue()!==m&&this.liveLoadBufferLength$.next(m)}));let p=0;this.representationSubscription.add(as({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(lC(1e3)).subscribe(async({liveLoadBufferLength:f,bufferLength:m})=>{if(!this.element||this.isUpdatingLive)return;let g=this.element.playbackRate,S=Mi(this.manifestUrlString,2),v=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,y=Math.min(v,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*g),I=this.tuning.dashCmafLive.normalizedActualBufferOffset*g,T=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*g,E=isFinite(f)?f:m,O=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),L=v<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(L);let w="none";if(O?w="active_low_latency":this.isLowLatency$.getValue()&&L?(this.bufferManagers.forEach(P=>P.proceedLowLatencyLive()),w="active_low_latency"):S!==0&&E<y?w="live_forward_buffering":E<y+T&&(w="live_with_target_offset"),isFinite(f)&&(p=f>p?f:p),w==="live_forward_buffering"||w==="live_with_target_offset"){let P=p-(y+I),C=this.normolizeLiveOffset(Math.trunc(S+P/g)),M=Math.abs(C-S),R=0;!f||M<=this.tuning.dashCmafLive.offsetCalculationError?R=S:C>0&&M>this.tuning.dashCmafLive.offsetCalculationError&&(R=C),this.manifestUrlString=Se(this.manifestUrlString,R,2)}(w==="live_with_target_offset"||w==="live_forward_buffering")&&(p=0,await this.updateLive())},f=>{this.error$.next({id:"updateLive",category:Ft.VIDEO_PIPELINE,thrown:f,message:"Failed to update live with subscription"})}))}let l=pr(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe(ns(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),d=pr(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe(ns(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue()))),c=as({allBuffersFull:l,someBufferEnded:d}).pipe(Tn(),ns(({allBuffersFull:p,someBufferEnded:f})=>p&&f),Qu(p=>p));if(this.representationSubscription.add(pr(this.forceEnded$,c).subscribe(()=>{var p;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(f=>!f.updating))try{(p=this.source)==null||p.endOfStream()}catch(f){this.error$.next({id:"EndOfStream",category:Ft.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:f})}})),this.representationSubscription.add(pr(...this.bufferManagers.map(p=>p.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.representationSubscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.representationSubscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.liveTextManager&&this.representationSubscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$)),this.source.readyState!=="open"){let p=this.tuning.dash.sourceOpenTimeout>=0;yield new Promise(f=>{var m;p&&(this.timeoutSourceOpenId=setTimeout(()=>{var g;if(((g=this.source)==null?void 0:g.readyState)==="open"){f();return}this.error$.next({id:"OpenOfStream",category:Ft.VIDEO_PIPELINE,message:"Failed to open MediaSource",thrown:new Error("Timeout reject when wait sourceopen event"),traceAsLog:!0})},this.tuning.dash.sourceOpenTimeout)),(m=this.source)==null||m.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),f()},{once:!0})})}if(!this.isLive$.getValue()){let p=[(h=this.manifest.duration)!=null?h:0,...(0,kp.default)((0,kp.default)([...this.manifest.streams.audio,...this.manifest.streams.video],f=>f.representations),f=>{let m=[];return f.duration&&m.push(f.duration),Je(f.segmentReference)&&f.segmentReference.totalSegmentsDurationMs&&m.push(f.segmentReference.totalSegmentsDurationMs),m})];this.source.duration=Math.max(...p)/1e3}this.audioBufferManager&&xn(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")}.bind(this));this.tick=()=>{var t,i,r,a;if(!this.element||!this.videoBufferManager||((t=this.source)==null?void 0:t.readyState)!=="open")return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),(i=this.audioBufferManager)==null||i.maintain(e),(r=this.liveTextManager)==null||r.maintain(e),(this.videoBufferManager.gaps.length||(a=this.audioBufferManager)!=null&&a.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=Ap(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),n=>{this.error$.next({id:"GapWatchdog",category:Ft.WTF,message:"Error handling gaps",thrown:n})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.fetcher=new _u({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.subscription.add(this.fetcher.recoverableError$.subscribe(this.fetcherRecoverableError$)),this.subscription.add(this.fetcher.error$.subscribe(this.fetcherError$)),this.liveBuffer=yi.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator}),this.initTracerSubscription()}async seekLive(e){var r,a,n;ss(this.element);let t=this.liveStreamStatus$.getValue()!=="active"?Pp()-this.liveStreamEndTimestamp:0,i=this.normolizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=Se(this.manifestUrlString,i,2),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await((r=this.videoBufferManager)==null?void 0:r.seekLive(this.manifest.streams.video)),await((a=this.audioBufferManager)==null?void 0:a.seekLive(this.manifest.streams.audio)),(n=this.liveTextManager)==null||n.seekLive(this.manifest.streams.text))}initBuffer(){ss(this.element),this.state$.setState("running"),this.subscription.add(pr(...cC.map(e=>Ti(this.element,e)),Ti(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:Ft.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(Ti(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(Ti(this.element,"waiting").subscribe(()=>{var t;this.element&&this.element.readyState===2&&!this.element.seeking&&Ne(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{var p,f,m,g,S,v,y,I,T,E,O;if(!this.element||((p=this.source)==null?void 0:p.readyState)!=="open")return;let i=this.currentStallDuration$.getValue();i+=50,this.currentStallDuration$.next(i);let r={timeInWaiting:i},a=Pp(),n=100,o=(m=(f=this.videoBufferManager)==null?void 0:f.lastDataObtainedTimestamp)!=null?m:0;this.videoLastDataObtainedTimestamp$.next(o);let u=(S=(g=this.audioBufferManager)==null?void 0:g.lastDataObtainedTimestamp)!=null?S:0,l=(y=(v=this.videoBufferManager)==null?void 0:v.getForwardBufferDuration())!=null?y:0,d=(T=(I=this.audioBufferManager)==null?void 0:I.getForwardBufferDuration())!=null?T:0,c=l<n&&a-o>this.tuning.dash.crashOnStallTWithoutDataTimeout,h=this.audioBufferManager&&d<n&&a-u>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((c||h)&&i>this.tuning.dash.crashOnStallTWithoutDataTimeout||i>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${i} ms`);if(this.isLive$.getValue()&&i%2e3===0){let L=this.normolizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(L).catch(w=>{this.error$.next({id:"stallIntervalCallback",category:Ft.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:w})}),r.liveLastOffset=L}else{let L=this.element.currentTime*1e3;(E=this.videoBufferManager)==null||E.maintain(L),(O=this.audioBufferManager)==null||O.maintain(L),r.position=L}this.tracer.log("stallIntervalCallback",In(r))};(t=this.stallWatchdogSubscription)==null||t.unsubscribe(),this.stallWatchdogSubscription=Ap(50).subscribe(e,i=>{this.error$.next({id:"StallWatchdogCallback",category:Ft.NETWORK,message:"Can't restore DASH after stall.",thrown:i})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,i=!1){let r={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return this.tuning.useNewSwitchTo?this.currentStallDuration$.getValue()>0?r==null?void 0:r.switchToWithPreviousAbort(t,i):r==null?void 0:r.switchTo(t,i):r==null?void 0:r.switchToOld(t,i)}async seek(e,t){var r,a,n,o,u;ss(this.element),ss(this.videoBufferManager);let i;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?i=e:i=Math.max((r=this.videoBufferManager.findSegmentStartTime(e))!=null?r:e,(n=(a=this.audioBufferManager)==null?void 0:a.findSegmentStartTime(e))!=null?n:e),this.warmUpMediaSourceIfNeeded(i),Ne(this.element.buffered,i)||await Promise.all([this.videoBufferManager.abort(),(o=this.audioBufferManager)==null?void 0:o.abort()]),!(zI(this.element)||zI(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),(u=this.audioBufferManager)==null||u.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",In({requestedPosition:e,forcePrecise:t,position:i})))}warmUpMediaSourceIfNeeded(e=(t=>(t=this.element)==null?void 0:t.currentTime)()){var i;xn(this.element)&&xn(this.source)&&xn(e)&&((i=this.source)==null?void 0:i.readyState)==="ended"&&this.element.duration*1e3-e>this.tuning.dash.seekBiasInTheEnd&&this.bufferManagers.forEach(r=>r.warmUpMediaSource())}get isStreamEnded(){var e;return((e=this.source)==null?void 0:e.readyState)==="ended"}stop(){var e,t,i;this.tracer.log("stop"),(e=this.element)==null||e.querySelectorAll("source").forEach(r=>{URL.revokeObjectURL(r.src),r.remove()}),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(t=this.videoBufferManager)==null||t.destroy(),this.videoBufferManager=null,(i=this.audioBufferManager)==null||i.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){var e;return(e=this.manifest)==null?void 0:e.streams}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){var e;this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),((e=this.source)==null?void 0:e.readyState)==="open"&&Array.from(this.source.sourceBuffers).every(t=>!t.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=oC(this.tracer.error.bind(this.tracer));this.subscription.add(this.error$.subscribe(e("error")))}isManualDecreasePlaybackInLive(){if(!this.element||!this.isLive$.getValue())return!1;let e=1-this.element.playbackRate;return Number(e.toFixed(2))>Number(this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup.toFixed(2))}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){var e,t;this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&((e=this.bufferManagers)==null||e.forEach(i=>i.updateLive(this.manifest)),(t=this.liveTextManager)==null||t.updateLive(this.manifest)),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getDebugBufferState();if(!e)return;let t=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),i={isJumpGapAfterSeekLive:this.isJumpGapAfterSeekLive,isActiveLowLatency:t,initialCurrentTime:this.element.currentTime};this.isJumpGapAfterSeekLive&&!t&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let r=this.element.currentTime*1e3,a=[],n=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let o of this.bufferManagers)for(let u of o.gaps)o.playingRepresentation$.getValue()===u.representation&&u.from-n<=r&&u.to+n>r&&(this.element.duration*1e3-u.to<this.tuning.endGapTolerance?a.push(1/0):a.push(u.to));if(a.length){let o=Math.max(...a)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,o===1/0?this.forceEnded$.next():(this.element.currentTime=o/1e3,i={...i,gapEnds:a,jumpTo:o,resultCurrentTime:this.element.currentTime},this.tracer.log("jumpGap",In(i)))}}};var Yu=class{constructor(e,t){this.fov=e,this.orientation=t}};var Ku=class{constructor(e,t){this.rotating=!1;this.fading=!1;this.lastTickTS=0;this.lastCameraTurnTS=0;this.fadeStartSpeed=null;this.fadeTime=0;this.camera=e,this.options=t,this.rotationSpeed={x:0,y:0,z:0},this.fadeCorrection=1/(this.options.speedFadeTime/1e3)**2}turnCamera(e=0,t=0,i=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+i)}pointCameraTo(e=0,t=0,i=0){t=this.limitCameraRotationY(t);let r=e-this.camera.orientation.x,a=t-this.camera.orientation.y,n=i-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=i,this.lastCameraTurn={x:r,y:a,z:n},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,i){this.rotationSpeed.x=e!=null?e:this.rotationSpeed.x,this.rotationSpeed.y=t!=null?t:this.rotationSpeed.y,this.rotationSpeed.z=i!=null?i:this.rotationSpeed.z}startRotation(){this.rotating=!0}stopRotation(e=!1){e?(this.setRotationSpeed(0,0,0),this.fadeStartSpeed=null):this.startFading(this.rotationSpeed.x,this.rotationSpeed.y,this.rotationSpeed.z),this.rotating=!1}onCameraRelease(){if(this.lastCameraTurn&&this.lastCameraTurnTS){let e=Date.now()-this.lastCameraTurnTS;if(e<this.options.speedFadeThreshold){let t=(1-e/this.options.speedFadeThreshold)*this.options.rotationSpeedCorrection;this.startFading(this.lastCameraTurn.x*t,this.lastCameraTurn.y*t,this.lastCameraTurn.z*t)}}}startFading(e,t,i){this.setRotationSpeed(e,t,i),this.fadeStartSpeed={...this.rotationSpeed},this.fading=!0}stopFading(){this.fadeStartSpeed=null,this.fading=!0,this.fadeTime=0}limitCameraRotationY(e){return Math.max(-this.options.maxYawAngle,Math.min(e,this.options.maxYawAngle))}tick(e){if(!this.lastTickTS){this.lastTickTS=e,this.lastCameraTurnTS=Date.now();return}let t=e-this.lastTickTS,i=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i);else if(this.fading&&this.fadeStartSpeed){let r=-this.fadeCorrection*(this.fadeTime/1e3)**2+1;this.setRotationSpeed(this.fadeStartSpeed.x*r,this.fadeStartSpeed.y*r,this.fadeStartSpeed.z*r),r>0?this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}};var WI=`attribute vec2 a_vertex;
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 os=class{constructor(e,t,i){this.videoInitialized=!1;this.active=!1;this.container=e,this.sourceVideoElement=t,this.params=i,this.canvas=this.createCanvas();let r=this.canvas.getContext("webgl");if(!r)throw new Error("Could not initialize WebGL context");this.gl=r,this.container.appendChild(this.canvas),this.camera=new Yu(this.params.fov,this.params.orientation),this.cameraRotationManager=new Ku(this.camera,{rotationSpeed:this.params.rotationSpeed,maxYawAngle:this.params.maxYawAngle,rotationSpeedCorrection:this.params.rotationSpeedCorrection,degreeToPixelCorrection:this.params.degreeToPixelCorrection,speedFadeTime:this.params.speedFadeTime,speedFadeThreshold:this.params.speedFadeThreshold}),this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.textureMappingBuffer=this.createTextureMappingBuffer(),this.updateTextureMappingBuffer(),this.program=this.createProgram(),this.videoTexture=this.createTexture(),this.gl.useProgram(this.program),this.videoElementDataLoadedFn=this.onDataLoadedHandler.bind(this),this.renderFn=this.render.bind(this)}play(){this.active||(this.videoInitialized?this.doPlay():this.sourceVideoElement.readyState>=2?(this.videoInitialized=!0,this.doPlay()):this.sourceVideoElement.addEventListener("loadeddata",this.videoElementDataLoadedFn))}stop(){this.active=!1}startCameraManualRotation(e,t){this.cameraRotationManager.setRotationSpeed(e*this.params.rotationSpeed,t*this.params.rotationSpeed,0),this.cameraRotationManager.startRotation()}stopCameraManualRotation(e=!1){this.cameraRotationManager.stopRotation(e)}turnCamera(e,t){this.cameraRotationManager.turnCamera(e,t)}pointCameraTo(e,t){this.cameraRotationManager.pointCameraTo(e,t)}pixelToDegree(e){return{x:this.params.degreeToPixelCorrection*this.params.fov.x*-e.x/this.viewportWidth,y:this.params.degreeToPixelCorrection*this.params.fov.y*e.y/this.viewportHeight}}getCameraRotation(){return this.camera.orientation}holdCamera(){this.cameraRotationManager.stopRotation(!0)}releaseCamera(){this.cameraRotationManager.onCameraRelease()}destroy(){this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),this.stop(),this.canvas.remove()}setViewportSize(e,t){this.viewportWidth=e,this.viewportHeight=t,this.canvas.width=this.viewportWidth,this.canvas.height=this.viewportHeight,this.gl.viewport(0,0,this.canvas.width,this.canvas.height)}onDataLoadedHandler(){this.videoInitialized=!0,this.doPlay()}doPlay(){this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.active=!0,this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),requestAnimationFrame(this.renderFn)}render(e){this.cameraRotationManager.tick(e),this.updateTexture(),this.updateTextureMappingBuffer();let t=this.gl.getAttribLocation(this.program,"a_vertex"),i=this.gl.getAttribLocation(this.program,"a_texel"),r=this.gl.getUniformLocation(this.program,"u_texture"),a=this.gl.getUniformLocation(this.program,"u_focus");this.gl.enableVertexAttribArray(t),this.gl.enableVertexAttribArray(i),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.vertexBuffer),this.gl.vertexAttribPointer(t,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.vertexAttribPointer(i,2,this.gl.FLOAT,!1,0,0),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.uniform1i(r,0),this.gl.uniform2f(a,-this.camera.orientation.x,-this.camera.orientation.y),this.gl.drawArrays(this.gl.TRIANGLE_FAN,0,4),this.gl.bindTexture(this.gl.TEXTURE_2D,null),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),this.gl.disableVertexAttribArray(t),this.gl.disableVertexAttribArray(i),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){let i=this.gl.createShader(t);if(!i)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(i,e),this.gl.compileShader(i),!this.gl.getShaderParameter(i,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(i));return i}createProgram(){let e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");let t=this.createShader(WI,this.gl.VERTEX_SHADER),i=this.createShader(YI,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,i),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){let e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,i=1,r=this.frameHeight/(this.frameWidth/this.viewportWidth);return r>this.viewportHeight?t=this.viewportHeight/r:i=r/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-i,t,-i,t,i,-t,i]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){let e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,i=this.camera.fov.x/360/2,r=this.camera.fov.y/180/2,a=e-i,n=t-r,o=e+i,u=t-r,l=e+i,d=t+r,c=e-i,h=t+r;return[a,n,o,u,l,d,c,h]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){let e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}};import{isNullable as fC,now as En,once as mC,Subscription as bC,ValueSubject as kp,isNonNullable as gC,safeStorage as Mp,filterChanged as SC}from"@vkontakte/videoplayer-shared/es2018";var Xu="stalls_manager_metrics",Lp="stalls_manager_abr_params",KI="stalls_manager_default_tuning_abr_params",Bp=class{constructor(){this.isSeeked$=new kp(!1);this.isBuffering$=new kp(!1);this.maxQualityLimit=void 0;this.currentStallsCount=0;this.sumStallsDuration=0;this.lastStallDuration=0;this.providerStartWatchingTimestamp=0;this.lastUniqueVideoTrackSelectedTimestamp=0;this.predictedThroughputWithoutData=0;this.subscription=new bC;this.severeStallOccurred$=new kp(!1)}init(e){this.currentStallDuration$=e.currentStallDuration$,this.videoLastDataObtainedTimestamp$=e.videoLastDataObtainedTimestamp$,this.throughput$=e.throughput$,this.rtt$=e.rtt$,this.tuning=e.tuning,this.abrParams=e.abrParams,this.resetStoredAbrParamsIfNeeded(),this.subscribe(e)}get videoMaxQualityLimit(){return this.maxQualityLimit}get predictedThroughput(){return this.predictedThroughputWithoutData}get abrTuningParams(){let e=this.tuning.enabled?this.getStoredData(Lp):{};return{...this.abrParams,...e}}set lastVideoTrackSelected(e){var t;((t=this.lastUniqueVideoTrackSelected)==null?void 0:t.id)!==e.id&&(this.lastUniqueVideoTrackSelected=e,this.lastUniqueVideoTrackSelectedTimestamp=En(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe(),this.currentStallDuration$.getValue()!==0&&this.updateStallData();let e=(En()-this.providerStartWatchingTimestamp-this.sumStallsDuration)/1e3,t=this.sumStallsDuration;this.addStallInfoToHistory(e,t),this.updateStoredAbrParams()}resetStoredAbrParamsIfNeeded(){let{bitrateFactorAtEmptyBuffer:e,bitrateFactorAtFullBuffer:t,containerSizeFactor:i}={...this.getStoredData(KI)},{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:a,containerSizeFactor:n}={...this.abrParams};this.tuning.enabled&&e===r&&t===a&&i===n||(this.removeStoredData(Lp),this.setStoredData(KI,{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:a,containerSizeFactor:n}))}updateStoredAbrParams(){let e=[],t=this.getStoredData(Xu,"[]");if(!this.tuning.enabled||t.length<this.tuning.stallsMetricsHistoryLength)return;let i=t.reduce((a,n)=>a+n.tvt,0);if(this.tuning.useTotalStallsDurationPerTvt){let n=t.reduce((o,u)=>o+u.stallsDuration,0)/i;e.push(this.calculateOptimalAbrParams(n,i))}if(this.tuning.useAverageStallsDurationPerTvt){let a=t.reduce((n,o)=>n+o.stallsDurationPerTvt,0)/t.length;e.push(this.calculateOptimalAbrParams(a,i))}this.tuning.useEmaStallsDurationPerTvt&&e.push(this.calculateOptimalAbrParams(t[t.length-1].stallsDurationPerTvtSmoothed,i));let r={bitrateFactorAtEmptyBuffer:Math.max(...e.map(a=>a.bitrateFactorAtEmptyBuffer)),bitrateFactorAtFullBuffer:Math.max(...e.map(a=>a.bitrateFactorAtFullBuffer)),containerSizeFactor:Math.min(...e.map(a=>a.containerSizeFactor))};this.setStoredData(Xu,[]),this.setStoredData(Lp,r)}calculateOptimalAbrParams(e,t){let{targetStallsDurationPerTvt:i,deviationStallsDurationPerTvt:r,criticalStallsDurationPerTvt:a,abrAdjustingSpeed:n,significantTvt:o,stallsMetricsHistoryLength:u}=this.tuning,l=n*Math.min(t/(o*u),1),d=this.abrTuningParams;return e<i-r?d={bitrateFactorAtEmptyBuffer:Math.max(d.bitrateFactorAtEmptyBuffer-l,this.abrParams.minBitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.max(d.bitrateFactorAtFullBuffer-l,this.abrParams.minBitrateFactorAtFullBuffer),containerSizeFactor:Math.min(d.containerSizeFactor+l,this.abrParams.maxContainerSizeFactor)}:e>i+r&&(d={bitrateFactorAtEmptyBuffer:Math.min(d.bitrateFactorAtEmptyBuffer+l,this.abrParams.maxBitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.min(d.bitrateFactorAtFullBuffer+l,this.abrParams.maxBitrateFactorAtFullBuffer),containerSizeFactor:Math.max(d.containerSizeFactor-l,this.abrParams.minContainerSizeFactor)}),e>a&&(d={bitrateFactorAtEmptyBuffer:Math.max(d.bitrateFactorAtEmptyBuffer,this.abrParams.bitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.max(d.bitrateFactorAtFullBuffer,this.abrParams.bitrateFactorAtFullBuffer),containerSizeFactor:Math.min(d.containerSizeFactor,this.abrParams.containerSizeFactor)}),d}getStoredData(e,t="{}"){var i;return JSON.parse((i=Mp.get(e))!=null?i:t)}setStoredData(e,t){Mp.set(e,JSON.stringify(t))}removeStoredData(e){Mp.remove(e)}addStallInfoToHistory(e,t){if(e<this.tuning.minTvtToBeCounted||e>this.tuning.maxTvtToBeCounted||e*1e3<t)return;let i=this.getStoredData(Xu,"[]"),r=t/e,a=i.length?vi(i[i.length-1].stallsDurationPerTvtSmoothed,t/e,this.tuning.emaAlpha):r,n={tvt:e,stallsDuration:t,stallsDurationPerTvt:r,stallsDurationPerTvtSmoothed:a};i.push(n),i.length>this.tuning.stallsMetricsHistoryLength&&i.shift(),this.setStoredData(Xu,i)}updateStallData(){this.providerStartWatchingTimestamp&&!this.isSeeked$.getValue()&&(this.sumStallsDuration+=Math.min(this.lastStallDuration,this.tuning.maxPossibleStallDuration),this.currentStallsCount++)}subscribe(e){this.subscription.add(e.isSeeked$.subscribe(this.isSeeked$)),this.subscription.add(e.isBuffering$.subscribe(this.isBuffering$)),this.subscription.add(e.looped$.subscribe(t=>this.currentStallsCount=0)),this.subscription.add(e.playing$.pipe(mC()).subscribe(t=>this.providerStartWatchingTimestamp=En())),this.subscription.add(this.currentStallDuration$.pipe(SC()).subscribe(t=>{let{stallDurationNoDataBeforeQualityDecrease:i,stallCountBeforeQualityDecrease:r,resetQualityRestrictionTimeout:a,ignoreStallsOnSeek:n}=this.tuning;if(fC(this.lastUniqueVideoTrackSelected)||n&&this.isSeeked$.getValue())return;let o=this.rtt$.getValue(),u=this.throughput$.getValue(),l=this.videoLastDataObtainedTimestamp$.getValue(),d=En(),c=r&&this.currentStallsCount>=r,h=i&&d-this.lastUniqueVideoTrackSelectedTimestamp>=i+o&&d-l>=i+o&&t>=i;(c||h)&&(this.severeStallOccurred$.next(!0),window.clearTimeout(this.qualityRestrictionTimer),this.maxQualityLimit=this.lastUniqueVideoTrackSelected.quality,gC(this.lastUniqueVideoTrackSelected.bitrate)&&u>this.lastUniqueVideoTrackSelected.bitrate&&(this.predictedThroughputWithoutData=this.lastUniqueVideoTrackSelected.bitrate)),!t&&En()-this.providerStartWatchingTimestamp>this.lastStallDuration&&(this.updateStallData(),this.severeStallOccurred$.next(!1),window.clearTimeout(this.qualityRestrictionTimer),this.qualityRestrictionTimer=window.setTimeout(()=>{this.maxQualityLimit=void 0,this.predictedThroughputWithoutData=0},a)),this.lastStallDuration=t}))}},Ju=Bp;import{combine as vC,map as yC,observeElementSize as TC,Subscription as IC,ValueSubject as $p,noop as xC}from"@vkontakte/videoplayer-shared/es2018";var Zu=class{constructor(){this.subscription=new IC;this.pipSize$=new $p(void 0);this.videoSize$=new $p(void 0);this.elementSize$=new $p(void 0);this.pictureInPictureWindowRemoveEventListener=xC}connect({observableVideo:e,video:t}){let i=r=>{let a=r.target;this.pipSize$.next({width:a.width,height:a.height})};this.subscription.add(TC(t).subscribe(this.videoSize$)).add(e.enterPip$.subscribe(({pictureInPictureWindow:r})=>{this.pipSize$.next({width:r.width,height:r.height}),r.addEventListener("resize",i),this.pictureInPictureWindowRemoveEventListener=()=>{r.removeEventListener("resize",i)}})).add(e.leavePip$.subscribe(()=>{this.pictureInPictureWindowRemoveEventListener()})).add(vC({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(yC(({videoSize:r,inPip:a,pipSize:n})=>a?n:r)).subscribe(this.elementSize$))}getValue(){return this.elementSize$.getValue()}subscribe(e,t){return this.elementSize$.subscribe(e,t)}getObservable(){return this.elementSize$}destroy(){this.pictureInPictureWindowRemoveEventListener(),this.subscription.unsubscribe()}};var hr=class{constructor(e){this.subscription=new kC;this.videoState=new G("stopped");this.droppedFramesManager=new Gr;this.stallsManager=new Ju;this.elementSizeManager=new Zu;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new $i;this.audioTrackSwitchHistory=new $i;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(r.state==="requested"&&(i==null?void 0:i.to)!=="paused"&&e!=="stopped"&&t!=="stopped"&&this.seek(r.position,r.forcePrecise),t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),B(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"),B(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="ready"&&B(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"&&B(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&B(this.params.desiredState.playbackState,"paused");return;default:return wC(e)}}};this.init3DScene=e=>{var i,r,a;if(this.scene3D)return;this.scene3D=new os(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((i=e.projectionData)==null?void 0:i.pose.yaw)||0,y:((r=e.projectionData)==null?void 0:r.pose.pitch)||0,z:((a=e.projectionData)==null?void 0:a.pose.roll)||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSizeManager.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.textTracksManager=new xt(e.source.url),this.params=e,this.video=tt(e.container,e.tuning),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Fe(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.player=new Wu({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params,i=st(this.video);this.subscription.add(()=>i.destroy());let r=this.constructor.name,a=o=>{e.error$.next({id:r,category:XI.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(Dp(l=>!!l.length),ZI()).subscribe(l=>{this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:l})}));let n=this.params.desiredState.seekState.stateChangeEnded$.pipe(Cp(l=>l.to.state!=="none"),el());this.stallsManager.init({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$,videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,tuning:this.params.tuning.stallsManager,abrParams:this.params.tuning.autoTrackSelection,isBuffering$:i.isBuffering$,looped$:i.looped$,playing$:i.playing$}),a(i.ended$,e.endedEvent$),a(i.looped$,e.loopedEvent$),a(i.error$,e.error$),a(i.isBuffering$,e.isBuffering$),a(i.currentBuffer$,e.currentBuffer$),a(i.playing$,e.firstFrameEvent$),a(i.canplay$,e.canplay$),a(i.inPiP$,e.inPiP$),a(i.inFullscreen$,e.inFullscreen$),a(i.loadedMetadata$,e.loadedMetadataEvent$),a(this.player.error$,e.error$),a(this.player.fetcherRecoverableError$,e.fetcherRecoverableError$),a(this.player.fetcherError$,e.fetcherError$),a(this.player.lastConnectionType$,e.httpConnectionType$),a(this.player.lastConnectionReused$,e.httpConnectionReused$),a(this.player.isLive$,e.isLive$),a(this.player.lastRequestFirstBytes$.pipe(Dp(JI),ZI()),e.firstBytesEvent$),a(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),a(this.videoState.stateChangeEnded$.pipe(Cp(l=>l.to)),this.params.output.playbackState$),this.subscription.add(i.looped$.subscribe(()=>this.player.warmUpMediaSourceIfNeeded(),r)),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(zt(this.video,t.isLooped,r)),this.subscription.add(rt(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(It(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),a(Et(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),B(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),B(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(AC(d,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let h=[];for(let p of d.audio){h.push(hp(p));let f=[];for(let m of p.representations){let g=wI(m);f.push(g),this.audioTracksMap.set(g,{stream:p,representation:m})}this.audioStreamsMap.set(p,f)}this.params.output.availableAudioStreams$.next(h)}let c=[];for(let h of d.video){c.push(fp(h));let p=[];for(let f of h.representations){let m=EI({...f,streamId:h.id});m&&(p.push(m),this.videoTracksMap.set(m,{stream:h,representation:f}))}this.videoStreamsMap.set(h,p)}this.params.output.availableVideoStreams$.next(c);for(let h of d.text)for(let p of h.representations){let f=AI(h,p);this.textTracksMap.set(f,{stream:h,representation:p})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else l==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r)),this.subscription.add(tl(this.player.currentStallDuration$,this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,this.elementSizeManager.getObservable(),this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,RC(this.video,"progress")).pipe(Dp(()=>this.videoTracksMap.size>0)).subscribe(async()=>{let l=this.player.state$.getState(),d=this.player.state$.getTransition();if(!(0,ex.default)(["manifest_ready","running"],l)||d)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let c=this.selectVideoAudioRepresentations();if(!c)return;let[h,p]=c,f=[...this.videoTracksMap.keys()].find(g=>{var S;return((S=this.videoTracksMap.get(g))==null?void 0:S.representation.id)===h.id});JI(f)&&(this.stallsManager.lastVideoTrackSelected=f);let m=this.params.desiredState.autoVideoTrackLimits.getTransition();if(m&&this.params.output.autoVideoTrackLimits$.next(m.to),l==="manifest_ready")await this.player.initRepresentations(h.id,p==null?void 0:p.id,this.params.sourceHls);else if(await this.player.switchRepresentation("video",h.id),p){let g=!!t.audioStream.getTransition();await this.player.switchRepresentation("audio",p.id,g)}},r)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:l})=>{this.scene3D&&l&&this.scene3D.pointCameraTo(l.x,l.y)})),this.subscription.add(this.elementSizeManager.subscribe(l=>{this.scene3D&&l&&this.scene3D.setViewportSize(l.width,l.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(el()).subscribe(l=>{let d=[...this.videoTracksMap.entries()].find(([,{representation:f}])=>f.id===l);if(!d){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[c,{stream:h}]=d,p=this.params.desiredState.videoStream.getTransition();p&&p.to&&p.to.id===h.id&&this.params.desiredState.videoStream.setState(p.to),e.currentVideoTrack$.next(c),e.currentVideoStream$.next(fp(h))},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(el()).subscribe(l=>{let d=[...this.audioTracksMap.entries()].find(([,{representation:f}])=>f.id===l);if(!d){e.currentAudioStream$.next(void 0);return}let[c,{stream:h}]=d,p=this.params.desiredState.audioStream.getTransition();p&&p.to&&p.to.id===h.id&&this.params.desiredState.audioStream.setState(p.to),e.currentAudioStream$.next(hp(h))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(l=>{var d,c;if(l!=null&&l.is3dVideo&&((d=this.params.tuning.spherical)!=null&&d.enabled))try{this.init3DScene(l),e.is3DVideo$.next(!0)}catch(h){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${h}`})}else this.destroy3DScene(),(c=this.params.tuning.spherical)!=null&&c.enabled&&e.is3DVideo$.next(!1)},r)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,r)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,r)),this.textTracksManager.connect(this.video,t,e);let o=t.playbackState.stateChangeStarted$.pipe(Cp(({to:l})=>l==="ready"),el());this.subscription.add(tl(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,Vp(["init"])).subscribe(()=>{let l=t.autoVideoTrackSwitching.getState(),c=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:l?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(c)})),this.subscription.add(tl(o,this.player.state$.stateChangeEnded$,Vp(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let u=tl(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Vp(["init"])).pipe(PC(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){var P,C,M,k,Q,U,A,F,R,x,$,oe,Ce;if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?Ma:ka,t=this.params.tuning.useNewAutoSelectVideoTrack?xu:Iu,i=this.params.tuning.useNewAutoSelectVideoTrack?Wt:Tu,{desiredState:r,output:a}=this.params,n=r.autoVideoTrackSwitching.getState(),o=(P=r.videoTrack.getState())==null?void 0:P.id,l=[...this.videoTracksMap.keys()].find(({id:se})=>se===o),d=a.currentVideoTrack$.getValue(),c=((k=(M=r.videoStream.getState())!=null?M:l&&((C=this.videoTracksMap.get(l))==null?void 0:C.stream))!=null?k:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!c)return;let h=[...this.videoStreamsMap.keys()].find(({id:se})=>se===c.id),p=h&&this.videoStreamsMap.get(h);if(!p)return;let f=$e(this.video.buffered,this.video.currentTime*1e3),m;this.player.isActiveLive$.getValue()?m=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?m=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:m=n?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let g=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,S=Math.min(f/Math.min(m,g||1/0),1),v=(Q=r.audioStream.getState())!=null?Q:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,y=(U=[...this.audioStreamsMap.keys()].find(({id:se})=>se===(v==null?void 0:v.id)))!=null?U:this.audioStreamsMap.keys().next().value,I=0;if(y){if(l&&!n){let se=e(l,p,(A=this.audioStreamsMap.get(y))!=null?A:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);I=Math.max(I,(F=se==null?void 0:se.bitrate)!=null?F:-1/0)}if(d){let se=e(d,p,(R=this.audioStreamsMap.get(y))!=null?R:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);I=Math.max(I,(x=se==null?void 0:se.bitrate)!=null?x:-1/0)}}let T=i(p,{container:this.elementSizeManager.getValue(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.stallsManager.abrTuningParams,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:I,forwardBufferHealth:S,current:d,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,stallsVideoMaxQualityLimit:this.stallsManager.videoMaxQualityLimit,stallsPredictedThroughput:this.stallsManager.predictedThroughput,abrLogger:this.params.dependencies.abrLogger}),E=n?T!=null?T:l:l!=null?l:T,O=y&&t(E,p,($=this.audioStreamsMap.get(y))!=null?$:[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.stallsManager.abrTuningParams,forwardBufferHealth:S,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),L=(oe=this.videoTracksMap.get(E))==null?void 0:oe.representation,w=O&&((Ce=this.audioTracksMap.get(O))==null?void 0:Ce.representation);if(L&&w)return[L,w];if(L&&!w&&this.audioTracksMap.size===0)return[L,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){at(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),B(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:XI.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.stallsManager.destroy(),this.elementSizeManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),this.params.output.currentVideoStream$.next(void 0),it(this.video),this.tracer.end()}};var wn=class extends hr{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};import{combine as Op,merge as tx,filter as ix,filterChanged as MC,isNullable as _p,map as rx,ValueSubject as Fp,isNonNullable as LC}from"@vkontakte/videoplayer-shared/es2018";var An=class extends hr{constructor(e){super(e),this.textTracksManager.destroy()}subscribe(){super.subscribe();let e=-1,{output:t,observableVideo:i,desiredState:r,connect:a}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),a(i.timeUpdate$,t.liveBufferTime$),a(this.player.liveSeekableDuration$,t.duration$),a(this.player.liveLatency$,t.liveLatency$);let n=new Fp(1);a(i.playbackRateState$,n),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(r.isLowLatency.stateChangeEnded$.pipe(rx(o=>o.to)).subscribe(this.player.isLowLatency$)).add(Op({liveBufferTime:t.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(rx(({liveBufferTime:o,liveAvailabilityStartTime:u})=>o&&u?o+u:void 0)).subscribe(t.liveTime$)).add(this.player.liveStreamStatus$.pipe(ix(o=>LC(o))).subscribe(o=>t.isLiveEnded$.next(o!=="active"&&t.position$.getValue()===0))).add(Op({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:tx(i.playbackRateState$,new Fp(1))}).pipe(ix(({liveStreamStatus:o,liveDuration:u})=>o==="active"&&!!u)).subscribe(({liveDuration:o,playbackRate:u})=>{let l=t.liveBufferTime$.getValue(),d=t.position$.getValue(),{playbackCatchupSpeedup:c}=this.params.tuning.dashCmafLive.lowLatency;d||u<1-c||this.video.paused||_p(l)||(e=o-l)})).add(Op({time:t.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:tx(i.playbackRateState$,new Fp(1))}).pipe(MC((o,u)=>this.player.liveStreamStatus$.getValue()==="active"?o.liveDuration===u.liveDuration:o.time===u.time)).subscribe(({time:o,liveDuration:u,playbackRate:l})=>{let d=t.position$.getValue(),{playbackCatchupSpeedup:c}=this.params.tuning.dashCmafLive.lowLatency;if(!d&&!this.video.paused&&l>=1-c||_p(o)||_p(u))return;let h=-1*(u-o-e);t.position$.next(Math.min(h,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(o=>{if(o){let u=PI(o);this.params.output.availableTextTracks$.next([u])}}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=Math.trunc(t/1e3<=Math.abs(this.params.output.duration$.getValue())?t:0);this.player.seekLive(i).then(()=>{this.params.output.position$.next(e/1e3)})}};import{assertNever as xV,assertNonNullable as EV,debounce as wV,ErrorCategory as Cx,filter as oh,filterChanged as hl,fromEvent as AV,isNonNullable as Vx,map as uh,merge as fl,observableFrom as lh,once as Ox,Subscription as PV}from"@vkontakte/videoplayer-shared/es2018";var ah=N(Fa(),1);import{abortable as th,assertNonNullable as ps,combine as hs,ErrorCategory as Ut,filter as ll,filterChanged as ao,flattenObject as no,fromEvent as Kt,getTraceSubscriptionMethod as hV,interval as ih,isNonNullable as oo,isNullable as $x,map as fs,merge as vr,now as rh,Subject as cl,Subscription as sh,tap as fV,throttle as Dx,ValueSubject as fe}from"@vkontakte/videoplayer-shared/es2018";var al=N(gt(),1),cs=N(Ot(),1),nl=N(Fa(),1);var Rx=N(eu(),1);import{assertNever as BC,ErrorCategory as sx,Subject as ax}from"@vkontakte/videoplayer-shared/es2018";var $C=18,nx=!1;try{nx=j.browser.isSafari&&!!j.browser.safariVersion&&j.browser.safariVersion<=$C}catch(s){console.error(s)}var Np=class{constructor(e){this.bufferFull$=new ax;this.error$=new ax;this.queue=[];this.currentTask=null;this.destroyed=!1;this.abortRequested=!1;this.completeTask=()=>{var e;try{if(this.currentTask){let t=(e=this.currentTask.signal)==null?void 0:e.aborted;this.currentTask.callback(!t),this.currentTask=null}this.queue.length&&this.pull()}catch(t){this.error$.next({id:"BufferTaskQueueUnknown",category:sx.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(i=>{let r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(r=>{let a={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(a),this.pull()})}async abort(e){return new Promise(t=>{let i,r=a=>{this.abortRequested=!1,t(a)};nx&&e?i={operation:"safariAbort",init:e,callback:r}:i={operation:"abort",callback:r};for(let{callback:a}of this.queue)a(!1);this.abortRequested=!0,i&&(this.queue=[i]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){var r;if((this.buffer.updating||this.currentTask||this.destroyed)&&!this.abortRequested)return;let e=this.queue.shift();if(!e)return;if((r=e.signal)!=null&&r.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(a){a instanceof DOMException&&a.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):a instanceof DOMException&&a.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:sx.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:a}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){let{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:BC(t)}}},ox=Np;import{abortable as Fi,assertNonNullable as ot,ErrorCategory as gr,fromEvent as Xp,getExponentialDelay as Jp,isNonNullable as ls,isNullable as qe,now as sl,once as sV,Subject as aV,Subscription as nV,ValueSubject as Sr}from"@vkontakte/videoplayer-shared/es2018";var J=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let i=this.readUint32();this.type=this.readString(4),i>e.byteLength-e.byteOffset&&(this.size32=NaN);let r=this.size32?this.size32-8:void 0,a=e.byteOffset+this.cursor;this.size64=0,this.usertype=0,this.content=new DataView(e.buffer,a,r)}get id(){return this.type}get size(){return this.size32}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t="ascii"){let r=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,r}readUint8(){let e=this.source.getUint8(this.cursor);return this.cursor+=1,e}readUint16(){let e=this.source.getUint16(this.cursor);return this.cursor+=2,e}readUint32(){let e=this.source.getUint32(this.cursor);return this.cursor+=4,e}readUint64(){let e=this.source.getBigInt64(this.cursor);return this.cursor+=8,e}};var us=class extends J{};var Pn=class extends J{constructor(t,i){super(t,i);this.ondemandPrefix="ondemandlivejson";this.ondemandDataReceivedKey="t-in";this.ondemandDataPreparedKey="t-out";let r=this.content.byteOffset,a=r+this.content.byteLength,n=new TextDecoder("ascii").decode(this.content.buffer.slice(r,a)).split(this.ondemandPrefix)[1],o=JSON.parse(n);this.serverDataReceivedTimestamp=o[this.ondemandDataReceivedKey],this.serverDataPreparedTime=o[this.ondemandDataPreparedKey]}};var Rn=class extends J{constructor(e,t){super(e,t),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let i=this.size-this.cursor;for(;i;){let r=this.readString(4);this.compatibleBrands.push(r),i-=4}}};var kn=class extends J{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var le=class extends J{constructor(e,t){super(e,t);let i=this.readUint32();this.version=i>>>24,this.flags=i&16777215}};var Mn=class extends le{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.timescale=this.readUint32(),this.duration=this.readUint32(),this.rate=this.readUint32(),this.volume=this.readUint16()}};var Ln=class extends J{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Bn=class extends J{constructor(e,t){super(e,t),this.data=this.content}};var fr=class extends le{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e,t){super(e,t),this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let i=0;i<this.referenceCount;i++){let r=this.readUint32(),a=r>>>31,n=r<<1>>>1,o=this.readUint32();r=this.readUint32();let u=r>>>28,l=r<<3>>>3;this.segments.push({referenceType:a,referencedSize:n,subsegmentDuration:o,SAPType:u,SAPDeltaTime:l})}}};var $n=class extends J{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Dn=class extends J{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Cn=class extends le{constructor(e,t){switch(super(e,t),this.readUint8()){case 0:this.stereoMode=0;break;case 1:this.stereoMode=1;break;case 2:this.stereoMode=2;break;case 3:this.stereoMode=3;break;case 4:this.stereoMode=4;break}this.cursor+=1}};var Vn=class extends le{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var On=class extends le{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var _n=class extends J{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Fn=class extends le{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.trackId=this.readUint32(),this.cursor+=4,this.duration=this.readUint32(),this.cursor+=8,this.layer=this.readUint16(),this.alternateGroup=this.readUint16(),this.cursor+=2,this.cursor+=2,this.matrix=[[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()]],this.width=this.readUint32(),this.height=this.readUint32()}};var Nn=class extends J{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Un=class extends J{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var qn=class extends le{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var jn=class extends J{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Hn=class extends le{constructor(e,t){super(e,t),this.trackId=this.readUint32(),this.flags&1&&(this.baseDataOffset=this.readUint64()),this.flags&2&&(this.sampleDescriptionIndex=this.readUint32()),this.flags&8&&(this.defaultSampleDuration=this.readUint32()),this.flags&16&&(this.defaultSampleSize=this.readUint32()),this.flags&32&&(this.defaultSampleFlags=this.readUint32())}};var zn=class extends le{constructor(t,i){super(t,i);this.baseMediaDecodeTime32=0;this.baseMediaDecodeTime64=BigInt(0);this.version===1?this.baseMediaDecodeTime64=this.readUint64():this.baseMediaDecodeTime32=this.readUint32()}get baseMediaDecodeTime(){return this.version===1?this.baseMediaDecodeTime64:this.baseMediaDecodeTime32}};var Qn=class extends le{constructor(t,i){super(t,i);this.sampleDuration=[];this.sampleSize=[];this.sampleFlags=[];this.sampleCompositionTimeOffset=[];this.optionalFields=0;this.sampleCount=this.readUint32(),this.flags&1&&(this.dataOffset=this.readUint32()),this.flags&4&&(this.firstSampleFlags=this.readUint32());for(let r=0;r<this.sampleCount;r++)this.flags&256&&this.sampleDuration.push(this.readUint32()),this.flags&512&&this.sampleSize.push(this.readUint32()),this.flags&1024&&this.sampleFlags.push(this.readUint32()),this.flags&2048&&this.sampleCompositionTimeOffset.push(this.readUint32())}};var Gn=class extends J{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Wn=class extends le{constructor(e,t){super(e,t),this.entryCount=this.readUint32(),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+8,this.content.byteLength-8))}};var Yn=class extends J{constructor(e,t){super(e,t),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+78,this.content.byteLength-78))}};var CC={ftyp:Rn,moov:kn,mvhd:Mn,moof:Ln,mdat:Bn,sidx:fr,trak:$n,mdia:_n,mfhd:qn,tkhd:Fn,traf:jn,tfhd:Hn,tfdt:zn,trun:Qn,minf:Nn,sv3d:Dn,st3d:Cn,prhd:Vn,proj:Un,equi:On,uuid:Pn,stbl:Gn,stsd:Wn,avc1:Yn,unknown:us},Ii=class s{constructor(e={}){this.options={offset:0,...e}}parse(e){let t=[],i=this.options.offset;for(;i<e.byteLength;)try{let a=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+i+4,4)),n=this.createBox(a,new DataView(e.buffer,e.byteOffset+i,e.byteLength-i));if(!n.size)break;t.push(n),i+=n.size}catch(r){break}return t}createBox(e,t){let i=CC[e];return i?new i(t,new s):new us(t,new s)}};var _i=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{var i,r,a;(a=(i=this.index)[r=t.type])!=null||(i[r]=[]),this.index[t.type].push(t),t.children.length>0&&this.indexBoxLevel(t.children)})}find(e){return this.index[e]&&this.index[e][0]?this.index[e][0]:null}findAll(e){return this.index[e]||[]}};var OC=new TextDecoder("ascii"),_C=s=>OC.decode(new DataView(s.buffer,s.byteOffset+4,4))==="ftyp",FC=s=>{let e=new fr(s,new Ii),t=e.earliestPresentationTime/e.timescale*1e3,i=s.byteOffset+s.byteLength+e.firstOffset;return e.segments.map(a=>{if(a.referenceType!==0)throw new Error("Unsupported multilevel sidx");let n=a.subsegmentDuration/e.timescale*1e3,o={status:"none",time:{from:t,to:t+n},byte:{from:i,to:i+a.referencedSize-1}};return t+=n,i+=a.referencedSize,o})},NC=(s,e)=>{let i=new Ii().parse(s),r=new _i(i),a=r.findAll("moof"),n=e?r.findAll("uuid"):r.findAll("mdat");if(!(n.length&&a.length))return null;let o=a[0],u=n[n.length-1],l=o.source.byteOffset,c=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(s.buffer,l,c)},UC=s=>{let t=new Ii().parse(s),i=new _i(t),r={},a=i.findAll("uuid");return a.length?a[a.length-1]:r},qC=s=>{var r;let t=new Ii().parse(s);return(r=new _i(t).find("sidx"))==null?void 0:r.timescale},jC=(s,e)=>{let i=new Ii().parse(s),a=new _i(i).findAll("traf"),n=a[a.length-1].children.find(c=>c.type==="tfhd"),o=a[a.length-1].children.find(c=>c.type==="tfdt"),u=a[a.length-1].children.find(c=>c.type==="trun"),l=0;return u.sampleDuration.length?l=u.sampleDuration.reduce((c,h)=>c+h,0):l=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+l)/e*1e3},HC=s=>{let e={is3dVideo:!1,stereoMode:0,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}},i=new Ii().parse(s),r=new _i(i);if(r.find("sv3d")){e.is3dVideo=!0;let n=r.find("st3d");n&&(e.stereoMode=n.stereoMode);let o=r.find("prhd");o&&(e.projectionData.pose.yaw=o.poseYawDegrees,e.projectionData.pose.pitch=o.posePitchDegrees,e.projectionData.pose.roll=o.poseRollDegrees);let u=r.find("equi");u&&(e.projectionData.bounds.top=u.projectionBoundsTop,e.projectionData.bounds.right=u.projectionBoundsRight,e.projectionData.bounds.bottom=u.projectionBoundsBottom,e.projectionData.bounds.left=u.projectionBoundsLeft)}return e},ux={validateData:_C,parseInit:HC,getIndexRange:()=>{},parseSegments:FC,parseFeedableSegmentChunk:NC,getChunkEndTime:jC,getServerLatencyTimestamps:UC,getTimescaleFromIndex:qC};var Xn=N(gt(),1);import{assertNonNullable as qp,isNonNullable as px,isNullable as QC}from"@vkontakte/videoplayer-shared/es2018";import{assertNever as zC}from"@vkontakte/videoplayer-shared/es2018";var lx={440786851:{type:"master"},17030:{type:"uint"},17143:{type:"uint"},17138:{type:"uint"},17139:{type:"uint"},17026:{type:"string"},17031:{type:"uint"},17029:{type:"uint"},236:{type:"binary"},408125543:{type:"master"},290298740:{type:"master"},19899:{type:"master"},21419:{type:"binary"},21420:{type:"uint"},357149030:{type:"master"},2807729:{type:"uint"},17545:{type:"float"},374648427:{type:"master"},174:{type:"master"},224:{type:"master"},30320:{type:"master"},30321:{type:"uint"},30322:{type:"master"},272869232:{type:"master"},524531317:{type:"master"},231:{type:"uint"},22612:{type:"master"},22743:{type:"uint"},167:{type:"uint"},171:{type:"uint"},163:{type:"binary"},160:{type:"master"},175:{type:"binary"},423732329:{type:"master"},307544935:{type:"master"},475249515:{type:"master"},187:{type:"master"},179:{type:"uint"},183:{type:"master"},247:{type:"uint"},241:{type:"uint"},240:{type:"uint"},178:{type:"uint"},21368:{type:"uint"},234:{type:"uint"},219:{type:"master"},150:{type:"uint"}},cx=s=>{let e=s.getUint8(0),t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);let i=Kn(s,t),r=i in lx,a=r?lx[i].type:"binary",n=s.getUint8(t),o=0;n&128?o=1:n&64?o=2:n&32?o=3:n&16?o=4:n&8?o=5:n&4?o=6:n&2?o=7:n&1&&(o=8);let u=new DataView(s.buffer,s.byteOffset+t+1,o-1),l=n&255>>o,d=Kn(u),c=l*2**((o-1)*8)+d,h=t+o,p;return h+c>s.byteLength?p=new DataView(s.buffer,s.byteOffset+h):p=new DataView(s.buffer,s.byteOffset+h,c),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:a,tagHeaderSize:h,tagSize:h+c,value:p,valueSize:c}},Kn=(s,e=s.byteLength)=>{switch(e){case 1:return s.getUint8(0);case 2:return s.getUint16(0);case 3:return s.getUint8(0)*2**16+s.getUint16(1);case 4:return s.getUint32(0);case 5:return s.getUint8(0)*2**32+s.getUint32(1);case 6:return s.getUint16(0)*2**32+s.getUint32(2);case 7:{let t=s.getUint8(0)*281474976710656+s.getUint16(1)*4294967296+s.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},Nt=(s,e)=>{switch(e){case"int":return s.getInt8(0);case"uint":return Kn(s);case"float":return s.byteLength===4?s.getFloat32(0):s.getFloat64(0);case"string":return new TextDecoder("ascii").decode(s);case"utf8":return new TextDecoder("utf-8").decode(s);case"date":return new Date(Date.UTC(2001,0)+s.getInt8(0)).getTime();case"master":return s;case"binary":return s;default:zC(e)}},mr=(s,e)=>{let t=0;for(;t<s.byteLength;){let i=new DataView(s.buffer,s.byteOffset+t),r=cx(i);if(!e(r))return;r.type==="master"&&mr(r.value,e),t=r.value.byteOffset-s.byteOffset+r.valueSize}},dx=s=>{if(s.getUint32(0)!==440786851)return!1;let e,t,i,r=cx(s);return mr(r.value,({tag:a,type:n,value:o})=>(a===17143?e=Nt(o,n):a===17026?t=Nt(o,n):a===17029&&(i=Nt(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)};var hx=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],GC=[231,22612,22743,167,171,163,160,175],WC=s=>{let e,t,i,r,a=!1,n=!1,o=!1,u,l,d=!1,c=0;return mr(s,({tag:h,type:p,value:f,valueSize:m})=>{if(h===21419){let g=Nt(f,p);l=Kn(g)}else h!==21420&&(l=void 0);return h===408125543?(e=f.byteOffset,t=f.byteOffset+m):h===357149030?a=!0:h===290298740?n=!0:h===2807729?i=Nt(f,p):h===17545?r=Nt(f,p):h===21420&&l===475249515?u=Nt(f,p):h===374648427?mr(f,({tag:g,type:S,value:v})=>g===30321?(d=Nt(v,S)===1,!1):!0):a&&n&&(0,Xn.default)(hx,h)&&(o=!0),!o}),qp(e,"Failed to parse webm Segment start"),qp(t,"Failed to parse webm Segment end"),qp(r,"Failed to parse webm Segment duration"),i=i!=null?i:1e6,{segmentStart:Math.round(e/1e9*i*1e3),segmentEnd:Math.round(t/1e9*i*1e3),timeScale:i,segmentDuration:Math.round(r/1e9*i*1e3),cuesSeekPosition:u,is3dVideo:d,stereoMode:c,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},YC=s=>{if(QC(s.cuesSeekPosition))return;let e=s.segmentStart+s.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},KC=(s,e)=>{let t=!1,i=!1,r=o=>px(o.time)&&px(o.position),a=[],n;return mr(s,({tag:o,type:u,value:l})=>{switch(o){case 475249515:t=!0;break;case 187:n&&r(n)&&a.push(n),n={};break;case 179:n&&(n.time=Nt(l,u));break;case 183:break;case 241:n&&(n.position=Nt(l,u));break;default:t&&(0,Xn.default)(hx,o)&&(i=!0)}return!(t&&i)}),n&&r(n)&&a.push(n),a.map((o,u)=>{let{time:l,position:d}=o,c=a[u+1];return{status:"none",time:{from:l,to:c?c.time:e.segmentDuration},byte:{from:e.segmentStart+d,to:c?e.segmentStart+c.position-1:e.segmentEnd-1}}})},XC=s=>{let e=0,t=!1;try{mr(s,i=>i.tag===524531317?i.tagSize<=s.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):(0,Xn.default)(GC,i.tag)?(e+i.tagSize<=s.byteLength&&(e+=i.tagSize,t||(t=(0,Xn.default)([163,160,175],i.tag))),!0):!1)}catch(i){}return e>0&&e<=s.byteLength&&t?new DataView(s.buffer,s.byteOffset,e):null},fx={validateData:dx,parseInit:WC,getIndexRange:YC,parseSegments:KC,parseFeedableSegmentChunk:XC};var Jn=s=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(s);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return fx;case"mp4":return ux}}throw new ReferenceError(`Unsupported mime type ${s}`)};var Wp=N(lp(),1),Ex=N(Ji(),1),wx=N(cp(),1),Ax=N(Ot(),1),Yp=N(nr(),1);import{isNonNullable as tV,isNullable as Ix}from"@vkontakte/videoplayer-shared/es2018";var mx=s=>{var e;try{let t=JC(),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 JC(){let s="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",d=`^(?:(?<langtag>${`
178
+ `;var os=class{constructor(e,t,i){this.videoInitialized=!1;this.active=!1;this.container=e,this.sourceVideoElement=t,this.params=i,this.canvas=this.createCanvas();let r=this.canvas.getContext("webgl");if(!r)throw new Error("Could not initialize WebGL context");this.gl=r,this.container.appendChild(this.canvas),this.camera=new Yu(this.params.fov,this.params.orientation),this.cameraRotationManager=new Ku(this.camera,{rotationSpeed:this.params.rotationSpeed,maxYawAngle:this.params.maxYawAngle,rotationSpeedCorrection:this.params.rotationSpeedCorrection,degreeToPixelCorrection:this.params.degreeToPixelCorrection,speedFadeTime:this.params.speedFadeTime,speedFadeThreshold:this.params.speedFadeThreshold}),this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.textureMappingBuffer=this.createTextureMappingBuffer(),this.updateTextureMappingBuffer(),this.program=this.createProgram(),this.videoTexture=this.createTexture(),this.gl.useProgram(this.program),this.videoElementDataLoadedFn=this.onDataLoadedHandler.bind(this),this.renderFn=this.render.bind(this)}play(){this.active||(this.videoInitialized?this.doPlay():this.sourceVideoElement.readyState>=2?(this.videoInitialized=!0,this.doPlay()):this.sourceVideoElement.addEventListener("loadeddata",this.videoElementDataLoadedFn))}stop(){this.active=!1}startCameraManualRotation(e,t){this.cameraRotationManager.setRotationSpeed(e*this.params.rotationSpeed,t*this.params.rotationSpeed,0),this.cameraRotationManager.startRotation()}stopCameraManualRotation(e=!1){this.cameraRotationManager.stopRotation(e)}turnCamera(e,t){this.cameraRotationManager.turnCamera(e,t)}pointCameraTo(e,t){this.cameraRotationManager.pointCameraTo(e,t)}pixelToDegree(e){return{x:this.params.degreeToPixelCorrection*this.params.fov.x*-e.x/this.viewportWidth,y:this.params.degreeToPixelCorrection*this.params.fov.y*e.y/this.viewportHeight}}getCameraRotation(){return this.camera.orientation}holdCamera(){this.cameraRotationManager.stopRotation(!0)}releaseCamera(){this.cameraRotationManager.onCameraRelease()}destroy(){this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),this.stop(),this.canvas.remove()}setViewportSize(e,t){this.viewportWidth=e,this.viewportHeight=t,this.canvas.width=this.viewportWidth,this.canvas.height=this.viewportHeight,this.gl.viewport(0,0,this.canvas.width,this.canvas.height)}onDataLoadedHandler(){this.videoInitialized=!0,this.doPlay()}doPlay(){this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.active=!0,this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),requestAnimationFrame(this.renderFn)}render(e){this.cameraRotationManager.tick(e),this.updateTexture(),this.updateTextureMappingBuffer();let t=this.gl.getAttribLocation(this.program,"a_vertex"),i=this.gl.getAttribLocation(this.program,"a_texel"),r=this.gl.getUniformLocation(this.program,"u_texture"),a=this.gl.getUniformLocation(this.program,"u_focus");this.gl.enableVertexAttribArray(t),this.gl.enableVertexAttribArray(i),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.vertexBuffer),this.gl.vertexAttribPointer(t,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.vertexAttribPointer(i,2,this.gl.FLOAT,!1,0,0),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.uniform1i(r,0),this.gl.uniform2f(a,-this.camera.orientation.x,-this.camera.orientation.y),this.gl.drawArrays(this.gl.TRIANGLE_FAN,0,4),this.gl.bindTexture(this.gl.TEXTURE_2D,null),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),this.gl.disableVertexAttribArray(t),this.gl.disableVertexAttribArray(i),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){let i=this.gl.createShader(t);if(!i)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(i,e),this.gl.compileShader(i),!this.gl.getShaderParameter(i,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(i));return i}createProgram(){let e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");let t=this.createShader(WI,this.gl.VERTEX_SHADER),i=this.createShader(YI,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,i),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){let e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,i=1,r=this.frameHeight/(this.frameWidth/this.viewportWidth);return r>this.viewportHeight?t=this.viewportHeight/r:i=r/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-i,t,-i,t,i,-t,i]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){let e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,i=this.camera.fov.x/360/2,r=this.camera.fov.y/180/2,a=e-i,n=t-r,o=e+i,u=t-r,l=e+i,d=t+r,c=e-i,h=t+r;return[a,n,o,u,l,d,c,h]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){let e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}};import{isNullable as fC,now as En,once as mC,Subscription as bC,ValueSubject as Rp,isNonNullable as gC,safeStorage as Mp,filterChanged as SC}from"@vkontakte/videoplayer-shared/es2018";var Xu="stalls_manager_metrics",Lp="stalls_manager_abr_params",KI="stalls_manager_default_tuning_abr_params",Bp=class{constructor(){this.isSeeked$=new Rp(!1);this.isBuffering$=new Rp(!1);this.maxQualityLimit=void 0;this.currentStallsCount=0;this.sumStallsDuration=0;this.lastStallDuration=0;this.providerStartWatchingTimestamp=0;this.lastUniqueVideoTrackSelectedTimestamp=0;this.predictedThroughputWithoutData=0;this.subscription=new bC;this.severeStallOccurred$=new Rp(!1)}init(e){this.currentStallDuration$=e.currentStallDuration$,this.videoLastDataObtainedTimestamp$=e.videoLastDataObtainedTimestamp$,this.throughput$=e.throughput$,this.rtt$=e.rtt$,this.tuning=e.tuning,this.abrParams=e.abrParams,this.resetStoredAbrParamsIfNeeded(),this.subscribe(e)}get videoMaxQualityLimit(){return this.maxQualityLimit}get predictedThroughput(){return this.predictedThroughputWithoutData}get abrTuningParams(){let e=this.tuning.enabled?this.getStoredData(Lp):{};return{...this.abrParams,...e}}set lastVideoTrackSelected(e){var t;((t=this.lastUniqueVideoTrackSelected)==null?void 0:t.id)!==e.id&&(this.lastUniqueVideoTrackSelected=e,this.lastUniqueVideoTrackSelectedTimestamp=En(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe(),this.currentStallDuration$.getValue()!==0&&this.updateStallData();let e=(En()-this.providerStartWatchingTimestamp-this.sumStallsDuration)/1e3,t=this.sumStallsDuration;this.addStallInfoToHistory(e,t),this.updateStoredAbrParams()}resetStoredAbrParamsIfNeeded(){let{bitrateFactorAtEmptyBuffer:e,bitrateFactorAtFullBuffer:t,containerSizeFactor:i}={...this.getStoredData(KI)},{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:a,containerSizeFactor:n}={...this.abrParams};this.tuning.enabled&&e===r&&t===a&&i===n||(this.removeStoredData(Lp),this.setStoredData(KI,{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:a,containerSizeFactor:n}))}updateStoredAbrParams(){let e=[],t=this.getStoredData(Xu,"[]");if(!this.tuning.enabled||t.length<this.tuning.stallsMetricsHistoryLength)return;let i=t.reduce((a,n)=>a+n.tvt,0);if(this.tuning.useTotalStallsDurationPerTvt){let n=t.reduce((o,u)=>o+u.stallsDuration,0)/i;e.push(this.calculateOptimalAbrParams(n,i))}if(this.tuning.useAverageStallsDurationPerTvt){let a=t.reduce((n,o)=>n+o.stallsDurationPerTvt,0)/t.length;e.push(this.calculateOptimalAbrParams(a,i))}this.tuning.useEmaStallsDurationPerTvt&&e.push(this.calculateOptimalAbrParams(t[t.length-1].stallsDurationPerTvtSmoothed,i));let r={bitrateFactorAtEmptyBuffer:Math.max(...e.map(a=>a.bitrateFactorAtEmptyBuffer)),bitrateFactorAtFullBuffer:Math.max(...e.map(a=>a.bitrateFactorAtFullBuffer)),containerSizeFactor:Math.min(...e.map(a=>a.containerSizeFactor))};this.setStoredData(Xu,[]),this.setStoredData(Lp,r)}calculateOptimalAbrParams(e,t){let{targetStallsDurationPerTvt:i,deviationStallsDurationPerTvt:r,criticalStallsDurationPerTvt:a,abrAdjustingSpeed:n,significantTvt:o,stallsMetricsHistoryLength:u}=this.tuning,l=n*Math.min(t/(o*u),1),d=this.abrTuningParams;return e<i-r?d={bitrateFactorAtEmptyBuffer:Math.max(d.bitrateFactorAtEmptyBuffer-l,this.abrParams.minBitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.max(d.bitrateFactorAtFullBuffer-l,this.abrParams.minBitrateFactorAtFullBuffer),containerSizeFactor:Math.min(d.containerSizeFactor+l,this.abrParams.maxContainerSizeFactor)}:e>i+r&&(d={bitrateFactorAtEmptyBuffer:Math.min(d.bitrateFactorAtEmptyBuffer+l,this.abrParams.maxBitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.min(d.bitrateFactorAtFullBuffer+l,this.abrParams.maxBitrateFactorAtFullBuffer),containerSizeFactor:Math.max(d.containerSizeFactor-l,this.abrParams.minContainerSizeFactor)}),e>a&&(d={bitrateFactorAtEmptyBuffer:Math.max(d.bitrateFactorAtEmptyBuffer,this.abrParams.bitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.max(d.bitrateFactorAtFullBuffer,this.abrParams.bitrateFactorAtFullBuffer),containerSizeFactor:Math.min(d.containerSizeFactor,this.abrParams.containerSizeFactor)}),d}getStoredData(e,t="{}"){var i;return JSON.parse((i=Mp.get(e))!=null?i:t)}setStoredData(e,t){Mp.set(e,JSON.stringify(t))}removeStoredData(e){Mp.remove(e)}addStallInfoToHistory(e,t){if(e<this.tuning.minTvtToBeCounted||e>this.tuning.maxTvtToBeCounted||e*1e3<t)return;let i=this.getStoredData(Xu,"[]"),r=t/e,a=i.length?vi(i[i.length-1].stallsDurationPerTvtSmoothed,t/e,this.tuning.emaAlpha):r,n={tvt:e,stallsDuration:t,stallsDurationPerTvt:r,stallsDurationPerTvtSmoothed:a};i.push(n),i.length>this.tuning.stallsMetricsHistoryLength&&i.shift(),this.setStoredData(Xu,i)}updateStallData(){this.providerStartWatchingTimestamp&&!this.isSeeked$.getValue()&&(this.sumStallsDuration+=Math.min(this.lastStallDuration,this.tuning.maxPossibleStallDuration),this.currentStallsCount++)}subscribe(e){this.subscription.add(e.isSeeked$.subscribe(this.isSeeked$)),this.subscription.add(e.isBuffering$.subscribe(this.isBuffering$)),this.subscription.add(e.looped$.subscribe(t=>this.currentStallsCount=0)),this.subscription.add(e.playing$.pipe(mC()).subscribe(t=>this.providerStartWatchingTimestamp=En())),this.subscription.add(this.currentStallDuration$.pipe(SC()).subscribe(t=>{let{stallDurationNoDataBeforeQualityDecrease:i,stallCountBeforeQualityDecrease:r,resetQualityRestrictionTimeout:a,ignoreStallsOnSeek:n}=this.tuning;if(fC(this.lastUniqueVideoTrackSelected)||n&&this.isSeeked$.getValue())return;let o=this.rtt$.getValue(),u=this.throughput$.getValue(),l=this.videoLastDataObtainedTimestamp$.getValue(),d=En(),c=r&&this.currentStallsCount>=r,h=i&&d-this.lastUniqueVideoTrackSelectedTimestamp>=i+o&&d-l>=i+o&&t>=i;(c||h)&&(this.severeStallOccurred$.next(!0),window.clearTimeout(this.qualityRestrictionTimer),this.maxQualityLimit=this.lastUniqueVideoTrackSelected.quality,gC(this.lastUniqueVideoTrackSelected.bitrate)&&u>this.lastUniqueVideoTrackSelected.bitrate&&(this.predictedThroughputWithoutData=this.lastUniqueVideoTrackSelected.bitrate)),!t&&En()-this.providerStartWatchingTimestamp>this.lastStallDuration&&(this.updateStallData(),this.severeStallOccurred$.next(!1),window.clearTimeout(this.qualityRestrictionTimer),this.qualityRestrictionTimer=window.setTimeout(()=>{this.maxQualityLimit=void 0,this.predictedThroughputWithoutData=0},a)),this.lastStallDuration=t}))}},Ju=Bp;import{combine as vC,map as yC,observeElementSize as TC,Subscription as IC,ValueSubject as $p,noop as xC}from"@vkontakte/videoplayer-shared/es2018";var Zu=class{constructor(){this.subscription=new IC;this.pipSize$=new $p(void 0);this.videoSize$=new $p(void 0);this.elementSize$=new $p(void 0);this.pictureInPictureWindowRemoveEventListener=xC}connect({observableVideo:e,video:t}){let i=r=>{let a=r.target;this.pipSize$.next({width:a.width,height:a.height})};this.subscription.add(TC(t).subscribe(this.videoSize$)).add(e.enterPip$.subscribe(({pictureInPictureWindow:r})=>{this.pipSize$.next({width:r.width,height:r.height}),r.addEventListener("resize",i),this.pictureInPictureWindowRemoveEventListener=()=>{r.removeEventListener("resize",i)}})).add(e.leavePip$.subscribe(()=>{this.pictureInPictureWindowRemoveEventListener()})).add(vC({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(yC(({videoSize:r,inPip:a,pipSize:n})=>a?n:r)).subscribe(this.elementSize$))}getValue(){return this.elementSize$.getValue()}subscribe(e,t){return this.elementSize$.subscribe(e,t)}getObservable(){return this.elementSize$}destroy(){this.pictureInPictureWindowRemoveEventListener(),this.subscription.unsubscribe()}};var hr=class{constructor(e){this.subscription=new MC;this.videoState=new G("stopped");this.observableVideo=null;this.droppedFramesManager=new Gr;this.stallsManager=new Ju;this.elementSizeManager=new Zu;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new $i;this.audioTrackSwitchHistory=new $i;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(r.state==="requested"&&(i==null?void 0:i.to)!=="paused"&&e!=="stopped"&&t!=="stopped"&&this.seek(r.position,r.forcePrecise),t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),B(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"),B(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="ready"&&B(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"&&B(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&B(this.params.desiredState.playbackState,"paused");return;default:return wC(e)}}};this.init3DScene=e=>{var i,r,a;if(this.scene3D)return;this.scene3D=new os(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((i=e.projectionData)==null?void 0:i.pose.yaw)||0,y:((r=e.projectionData)==null?void 0:r.pose.pitch)||0,z:((a=e.projectionData)==null?void 0:a.pose.roll)||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSizeManager.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.textTracksManager=new xt(e.source.url),this.params=e,this.video=tt(e.container,e.tuning),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Fe(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.player=new Wu({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params;RC(this.observableVideo)&&(this.observableVideo=st(this.video),this.subscription.add(()=>{var n;return(n=this.observableVideo)==null?void 0:n.destroy()}));let i=this.constructor.name,r=n=>{e.error$.next({id:i,category:XI.WTF,message:`${i} internal logic error`,thrown:n})},a=(n,o)=>this.subscription.add(n.subscribe(o,r));return{output:e,desiredState:t,observableVideo:this.observableVideo,genericErrorListener:r,connect:a}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:a}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(Dp(l=>!!l.length),ZI()).subscribe(l=>{this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:l})}));let n=this.params.desiredState.seekState.stateChangeEnded$.pipe(Cp(l=>l.to.state!=="none"),el());this.stallsManager.init({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$,videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,tuning:this.params.tuning.stallsManager,abrParams:this.params.tuning.autoTrackSelection,isBuffering$:i.isBuffering$,looped$:i.looped$,playing$:i.playing$}),a(i.ended$,e.endedEvent$),a(i.looped$,e.loopedEvent$),a(i.error$,e.error$),a(i.isBuffering$,e.isBuffering$),a(i.currentBuffer$,e.currentBuffer$),a(i.playing$,e.firstFrameEvent$),a(i.canplay$,e.canplay$),a(i.inPiP$,e.inPiP$),a(i.inFullscreen$,e.inFullscreen$),a(i.loadedMetadata$,e.loadedMetadataEvent$),a(this.player.error$,e.error$),a(this.player.fetcherRecoverableError$,e.fetcherRecoverableError$),a(this.player.fetcherError$,e.fetcherError$),a(this.player.lastConnectionType$,e.httpConnectionType$),a(this.player.lastConnectionReused$,e.httpConnectionReused$),a(this.player.isLive$,e.isLive$),a(this.player.lastRequestFirstBytes$.pipe(Dp(JI),ZI()),e.firstBytesEvent$),a(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),a(this.videoState.stateChangeEnded$.pipe(Cp(l=>l.to)),this.params.output.playbackState$),this.subscription.add(i.looped$.subscribe(()=>this.player.warmUpMediaSourceIfNeeded(),r)),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(zt(this.video,t.isLooped,r)),this.subscription.add(rt(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(It(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),a(Et(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),B(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),B(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(AC(d,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let h=[];for(let p of d.audio){h.push(hp(p));let f=[];for(let m of p.representations){let g=wI(m);f.push(g),this.audioTracksMap.set(g,{stream:p,representation:m})}this.audioStreamsMap.set(p,f)}this.params.output.availableAudioStreams$.next(h)}let c=[];for(let h of d.video){c.push(fp(h));let p=[];for(let f of h.representations){let m=EI({...f,streamId:h.id});m&&(p.push(m),this.videoTracksMap.set(m,{stream:h,representation:f}))}this.videoStreamsMap.set(h,p)}this.params.output.availableVideoStreams$.next(c);for(let h of d.text)for(let p of h.representations){let f=AI(h,p);this.textTracksMap.set(f,{stream:h,representation:p})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else l==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r)),this.subscription.add(tl(this.player.currentStallDuration$,this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,this.elementSizeManager.getObservable(),this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,kC(this.video,"progress")).pipe(Dp(()=>this.videoTracksMap.size>0)).subscribe(async()=>{let l=this.player.state$.getState(),d=this.player.state$.getTransition();if(!(0,ex.default)(["manifest_ready","running"],l)||d)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let c=this.selectVideoAudioRepresentations();if(!c)return;let[h,p]=c,f=[...this.videoTracksMap.keys()].find(g=>{var S;return((S=this.videoTracksMap.get(g))==null?void 0:S.representation.id)===h.id});JI(f)&&(this.stallsManager.lastVideoTrackSelected=f);let m=this.params.desiredState.autoVideoTrackLimits.getTransition();if(m&&this.params.output.autoVideoTrackLimits$.next(m.to),l==="manifest_ready")await this.player.initRepresentations(h.id,p==null?void 0:p.id,this.params.sourceHls);else if(await this.player.switchRepresentation("video",h.id),p){let g=!!t.audioStream.getTransition();await this.player.switchRepresentation("audio",p.id,g)}},r)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:l})=>{this.scene3D&&l&&this.scene3D.pointCameraTo(l.x,l.y)})),this.subscription.add(this.elementSizeManager.subscribe(l=>{this.scene3D&&l&&this.scene3D.setViewportSize(l.width,l.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(el()).subscribe(l=>{let d=[...this.videoTracksMap.entries()].find(([,{representation:f}])=>f.id===l);if(!d){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[c,{stream:h}]=d,p=this.params.desiredState.videoStream.getTransition();p&&p.to&&p.to.id===h.id&&this.params.desiredState.videoStream.setState(p.to),e.currentVideoTrack$.next(c),e.currentVideoStream$.next(fp(h))},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(el()).subscribe(l=>{let d=[...this.audioTracksMap.entries()].find(([,{representation:f}])=>f.id===l);if(!d){e.currentAudioStream$.next(void 0);return}let[c,{stream:h}]=d,p=this.params.desiredState.audioStream.getTransition();p&&p.to&&p.to.id===h.id&&this.params.desiredState.audioStream.setState(p.to),e.currentAudioStream$.next(hp(h))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(l=>{var d,c;if(l!=null&&l.is3dVideo&&((d=this.params.tuning.spherical)!=null&&d.enabled))try{this.init3DScene(l),e.is3DVideo$.next(!0)}catch(h){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${h}`})}else this.destroy3DScene(),(c=this.params.tuning.spherical)!=null&&c.enabled&&e.is3DVideo$.next(!1)},r)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,r)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,r)),this.textTracksManager.connect(this.video,t,e);let o=t.playbackState.stateChangeStarted$.pipe(Cp(({to:l})=>l==="ready"),el());this.subscription.add(tl(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,Vp(["init"])).subscribe(()=>{let l=t.autoVideoTrackSwitching.getState(),c=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:l?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(c)})),this.subscription.add(tl(o,this.player.state$.stateChangeEnded$,Vp(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let u=tl(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Vp(["init"])).pipe(PC(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){var P,C,M,R,Q,U,A,F,k,x,$,oe,Ce;if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?Ma:Ra,t=this.params.tuning.useNewAutoSelectVideoTrack?xu:Iu,i=this.params.tuning.useNewAutoSelectVideoTrack?Wt:Tu,{desiredState:r,output:a}=this.params,n=r.autoVideoTrackSwitching.getState(),o=(P=r.videoTrack.getState())==null?void 0:P.id,l=[...this.videoTracksMap.keys()].find(({id:se})=>se===o),d=a.currentVideoTrack$.getValue(),c=((R=(M=r.videoStream.getState())!=null?M:l&&((C=this.videoTracksMap.get(l))==null?void 0:C.stream))!=null?R:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!c)return;let h=[...this.videoStreamsMap.keys()].find(({id:se})=>se===c.id),p=h&&this.videoStreamsMap.get(h);if(!p)return;let f=$e(this.video.buffered,this.video.currentTime*1e3),m;this.player.isActiveLive$.getValue()?m=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?m=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:m=n?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let g=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,S=Math.min(f/Math.min(m,g||1/0),1),v=(Q=r.audioStream.getState())!=null?Q:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,y=(U=[...this.audioStreamsMap.keys()].find(({id:se})=>se===(v==null?void 0:v.id)))!=null?U:this.audioStreamsMap.keys().next().value,I=0;if(y){if(l&&!n){let se=e(l,p,(A=this.audioStreamsMap.get(y))!=null?A:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);I=Math.max(I,(F=se==null?void 0:se.bitrate)!=null?F:-1/0)}if(d){let se=e(d,p,(k=this.audioStreamsMap.get(y))!=null?k:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);I=Math.max(I,(x=se==null?void 0:se.bitrate)!=null?x:-1/0)}}let T=i(p,{container:this.elementSizeManager.getValue(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.stallsManager.abrTuningParams,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:I,forwardBufferHealth:S,current:d,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,stallsVideoMaxQualityLimit:this.stallsManager.videoMaxQualityLimit,stallsPredictedThroughput:this.stallsManager.predictedThroughput,abrLogger:this.params.dependencies.abrLogger}),E=n?T!=null?T:l:l!=null?l:T,O=y&&t(E,p,($=this.audioStreamsMap.get(y))!=null?$:[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.stallsManager.abrTuningParams,forwardBufferHealth:S,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),L=(oe=this.videoTracksMap.get(E))==null?void 0:oe.representation,w=O&&((Ce=this.audioTracksMap.get(O))==null?void 0:Ce.representation);if(L&&w)return[L,w];if(L&&!w&&this.audioTracksMap.size===0)return[L,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){at(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),B(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:XI.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.stallsManager.destroy(),this.elementSizeManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),this.params.output.currentVideoStream$.next(void 0),it(this.video),this.tracer.end()}};var wn=class extends hr{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};import{combine as Op,merge as tx,filter as ix,filterChanged as LC,isNullable as _p,map as rx,ValueSubject as Fp,isNonNullable as BC}from"@vkontakte/videoplayer-shared/es2018";var An=class extends hr{constructor(e){super(e),this.textTracksManager.destroy()}subscribe(){super.subscribe();let e=-1,{output:t,observableVideo:i,desiredState:r,connect:a}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),a(i.timeUpdate$,t.liveBufferTime$),a(this.player.liveSeekableDuration$,t.duration$),a(this.player.liveLatency$,t.liveLatency$);let n=new Fp(1);a(i.playbackRateState$,n),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(r.isLowLatency.stateChangeEnded$.pipe(rx(o=>o.to)).subscribe(this.player.isLowLatency$)).add(Op({liveBufferTime:t.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(rx(({liveBufferTime:o,liveAvailabilityStartTime:u})=>o&&u?o+u:void 0)).subscribe(t.liveTime$)).add(this.player.liveStreamStatus$.pipe(ix(o=>BC(o))).subscribe(o=>t.isLiveEnded$.next(o!=="active"&&t.position$.getValue()===0))).add(Op({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:tx(i.playbackRateState$,new Fp(1))}).pipe(ix(({liveStreamStatus:o,liveDuration:u})=>o==="active"&&!!u)).subscribe(({liveDuration:o,playbackRate:u})=>{let l=t.liveBufferTime$.getValue(),d=t.position$.getValue(),{playbackCatchupSpeedup:c}=this.params.tuning.dashCmafLive.lowLatency;d||u<1-c||this.video.paused||_p(l)||(e=o-l)})).add(Op({time:t.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:tx(i.playbackRateState$,new Fp(1))}).pipe(LC((o,u)=>this.player.liveStreamStatus$.getValue()==="active"?o.liveDuration===u.liveDuration:o.time===u.time)).subscribe(({time:o,liveDuration:u,playbackRate:l})=>{let d=t.position$.getValue(),{playbackCatchupSpeedup:c}=this.params.tuning.dashCmafLive.lowLatency;if(!d&&!this.video.paused&&l>=1-c||_p(o)||_p(u))return;let h=-1*(u-o-e);t.position$.next(Math.min(h,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(o=>{if(o){let u=PI(o);this.params.output.availableTextTracks$.next([u])}}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=Math.trunc(t/1e3<=Math.abs(this.params.output.duration$.getValue())?t:0);this.player.seekLive(i).then(()=>{this.params.output.position$.next(e/1e3)})}};import{assertNever as EV,assertNonNullable as wV,debounce as AV,ErrorCategory as Cx,filter as oh,filterChanged as hl,fromEvent as PV,isNonNullable as Vx,isNullable as kV,map as uh,merge as fl,observableFrom as lh,once as Ox,Subscription as RV}from"@vkontakte/videoplayer-shared/es2018";var ah=N(Fa(),1);import{abortable as th,assertNonNullable as ps,combine as hs,ErrorCategory as Ut,filter as ll,filterChanged as ao,flattenObject as no,fromEvent as Kt,getTraceSubscriptionMethod as fV,interval as ih,isNonNullable as oo,isNullable as $x,map as fs,merge as vr,now as rh,Subject as cl,Subscription as sh,tap as mV,throttle as Dx,ValueSubject as fe}from"@vkontakte/videoplayer-shared/es2018";var al=N(gt(),1),cs=N(Ot(),1),nl=N(Fa(),1);var kx=N(eu(),1);import{assertNever as $C,ErrorCategory as sx,Subject as ax}from"@vkontakte/videoplayer-shared/es2018";var DC=18,nx=!1;try{nx=j.browser.isSafari&&!!j.browser.safariVersion&&j.browser.safariVersion<=DC}catch(s){console.error(s)}var Np=class{constructor(e){this.bufferFull$=new ax;this.error$=new ax;this.queue=[];this.currentTask=null;this.destroyed=!1;this.abortRequested=!1;this.completeTask=()=>{var e;try{if(this.currentTask){let t=(e=this.currentTask.signal)==null?void 0:e.aborted;this.currentTask.callback(!t),this.currentTask=null}this.queue.length&&this.pull()}catch(t){this.error$.next({id:"BufferTaskQueueUnknown",category:sx.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(i=>{let r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(r=>{let a={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(a),this.pull()})}async abort(e){return new Promise(t=>{let i,r=a=>{this.abortRequested=!1,t(a)};nx&&e?i={operation:"safariAbort",init:e,callback:r}:i={operation:"abort",callback:r};for(let{callback:a}of this.queue)a(!1);this.abortRequested=!0,i&&(this.queue=[i]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){var r;if((this.buffer.updating||this.currentTask||this.destroyed)&&!this.abortRequested)return;let e=this.queue.shift();if(!e)return;if((r=e.signal)!=null&&r.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(a){a instanceof DOMException&&a.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):a instanceof DOMException&&a.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:sx.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:a}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){let{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:$C(t)}}},ox=Np;import{abortable as Fi,assertNonNullable as ot,ErrorCategory as gr,fromEvent as Xp,getExponentialDelay as Jp,isNonNullable as ls,isNullable as qe,now as sl,once as aV,Subject as nV,Subscription as oV,ValueSubject as Sr}from"@vkontakte/videoplayer-shared/es2018";var J=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let i=this.readUint32();this.type=this.readString(4),i>e.byteLength-e.byteOffset&&(this.size32=NaN);let r=this.size32?this.size32-8:void 0,a=e.byteOffset+this.cursor;this.size64=0,this.usertype=0,this.content=new DataView(e.buffer,a,r)}get id(){return this.type}get size(){return this.size32}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t="ascii"){let r=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,r}readUint8(){let e=this.source.getUint8(this.cursor);return this.cursor+=1,e}readUint16(){let e=this.source.getUint16(this.cursor);return this.cursor+=2,e}readUint32(){let e=this.source.getUint32(this.cursor);return this.cursor+=4,e}readUint64(){let e=this.source.getBigInt64(this.cursor);return this.cursor+=8,e}};var us=class extends J{};var Pn=class extends J{constructor(t,i){super(t,i);this.ondemandPrefix="ondemandlivejson";this.ondemandDataReceivedKey="t-in";this.ondemandDataPreparedKey="t-out";let r=this.content.byteOffset,a=r+this.content.byteLength,n=new TextDecoder("ascii").decode(this.content.buffer.slice(r,a)).split(this.ondemandPrefix)[1],o=JSON.parse(n);this.serverDataReceivedTimestamp=o[this.ondemandDataReceivedKey],this.serverDataPreparedTime=o[this.ondemandDataPreparedKey]}};var kn=class extends J{constructor(e,t){super(e,t),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let i=this.size-this.cursor;for(;i;){let r=this.readString(4);this.compatibleBrands.push(r),i-=4}}};var Rn=class extends J{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var le=class extends J{constructor(e,t){super(e,t);let i=this.readUint32();this.version=i>>>24,this.flags=i&16777215}};var Mn=class extends le{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.timescale=this.readUint32(),this.duration=this.readUint32(),this.rate=this.readUint32(),this.volume=this.readUint16()}};var Ln=class extends J{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Bn=class extends J{constructor(e,t){super(e,t),this.data=this.content}};var fr=class extends le{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e,t){super(e,t),this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let i=0;i<this.referenceCount;i++){let r=this.readUint32(),a=r>>>31,n=r<<1>>>1,o=this.readUint32();r=this.readUint32();let u=r>>>28,l=r<<3>>>3;this.segments.push({referenceType:a,referencedSize:n,subsegmentDuration:o,SAPType:u,SAPDeltaTime:l})}}};var $n=class extends J{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Dn=class extends J{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Cn=class extends le{constructor(e,t){switch(super(e,t),this.readUint8()){case 0:this.stereoMode=0;break;case 1:this.stereoMode=1;break;case 2:this.stereoMode=2;break;case 3:this.stereoMode=3;break;case 4:this.stereoMode=4;break}this.cursor+=1}};var Vn=class extends le{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var On=class extends le{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var _n=class extends J{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Fn=class extends le{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.trackId=this.readUint32(),this.cursor+=4,this.duration=this.readUint32(),this.cursor+=8,this.layer=this.readUint16(),this.alternateGroup=this.readUint16(),this.cursor+=2,this.cursor+=2,this.matrix=[[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()]],this.width=this.readUint32(),this.height=this.readUint32()}};var Nn=class extends J{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Un=class extends J{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var qn=class extends le{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var jn=class extends J{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Hn=class extends le{constructor(e,t){super(e,t),this.trackId=this.readUint32(),this.flags&1&&(this.baseDataOffset=this.readUint64()),this.flags&2&&(this.sampleDescriptionIndex=this.readUint32()),this.flags&8&&(this.defaultSampleDuration=this.readUint32()),this.flags&16&&(this.defaultSampleSize=this.readUint32()),this.flags&32&&(this.defaultSampleFlags=this.readUint32())}};var zn=class extends le{constructor(t,i){super(t,i);this.baseMediaDecodeTime32=0;this.baseMediaDecodeTime64=BigInt(0);this.version===1?this.baseMediaDecodeTime64=this.readUint64():this.baseMediaDecodeTime32=this.readUint32()}get baseMediaDecodeTime(){return this.version===1?this.baseMediaDecodeTime64:this.baseMediaDecodeTime32}};var Qn=class extends le{constructor(t,i){super(t,i);this.sampleDuration=[];this.sampleSize=[];this.sampleFlags=[];this.sampleCompositionTimeOffset=[];this.optionalFields=0;this.sampleCount=this.readUint32(),this.flags&1&&(this.dataOffset=this.readUint32()),this.flags&4&&(this.firstSampleFlags=this.readUint32());for(let r=0;r<this.sampleCount;r++)this.flags&256&&this.sampleDuration.push(this.readUint32()),this.flags&512&&this.sampleSize.push(this.readUint32()),this.flags&1024&&this.sampleFlags.push(this.readUint32()),this.flags&2048&&this.sampleCompositionTimeOffset.push(this.readUint32())}};var Gn=class extends J{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Wn=class extends le{constructor(e,t){super(e,t),this.entryCount=this.readUint32(),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+8,this.content.byteLength-8))}};var Yn=class extends J{constructor(e,t){super(e,t),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+78,this.content.byteLength-78))}};var VC={ftyp:kn,moov:Rn,mvhd:Mn,moof:Ln,mdat:Bn,sidx:fr,trak:$n,mdia:_n,mfhd:qn,tkhd:Fn,traf:jn,tfhd:Hn,tfdt:zn,trun:Qn,minf:Nn,sv3d:Dn,st3d:Cn,prhd:Vn,proj:Un,equi:On,uuid:Pn,stbl:Gn,stsd:Wn,avc1:Yn,unknown:us},Ii=class s{constructor(e={}){this.options={offset:0,...e}}parse(e){let t=[],i=this.options.offset;for(;i<e.byteLength;)try{let a=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+i+4,4)),n=this.createBox(a,new DataView(e.buffer,e.byteOffset+i,e.byteLength-i));if(!n.size)break;t.push(n),i+=n.size}catch(r){break}return t}createBox(e,t){let i=VC[e];return i?new i(t,new s):new us(t,new s)}};var _i=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{var i,r,a;(a=(i=this.index)[r=t.type])!=null||(i[r]=[]),this.index[t.type].push(t),t.children.length>0&&this.indexBoxLevel(t.children)})}find(e){return this.index[e]&&this.index[e][0]?this.index[e][0]:null}findAll(e){return this.index[e]||[]}};var _C=new TextDecoder("ascii"),FC=s=>_C.decode(new DataView(s.buffer,s.byteOffset+4,4))==="ftyp",NC=s=>{let e=new fr(s,new Ii),t=e.earliestPresentationTime/e.timescale*1e3,i=s.byteOffset+s.byteLength+e.firstOffset;return e.segments.map(a=>{if(a.referenceType!==0)throw new Error("Unsupported multilevel sidx");let n=a.subsegmentDuration/e.timescale*1e3,o={status:"none",time:{from:t,to:t+n},byte:{from:i,to:i+a.referencedSize-1}};return t+=n,i+=a.referencedSize,o})},UC=(s,e)=>{let i=new Ii().parse(s),r=new _i(i),a=r.findAll("moof"),n=e?r.findAll("uuid"):r.findAll("mdat");if(!(n.length&&a.length))return null;let o=a[0],u=n[n.length-1],l=o.source.byteOffset,c=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(s.buffer,l,c)},qC=s=>{let t=new Ii().parse(s),i=new _i(t),r={},a=i.findAll("uuid");return a.length?a[a.length-1]:r},jC=s=>{var r;let t=new Ii().parse(s);return(r=new _i(t).find("sidx"))==null?void 0:r.timescale},HC=(s,e)=>{let i=new Ii().parse(s),a=new _i(i).findAll("traf"),n=a[a.length-1].children.find(c=>c.type==="tfhd"),o=a[a.length-1].children.find(c=>c.type==="tfdt"),u=a[a.length-1].children.find(c=>c.type==="trun"),l=0;return u.sampleDuration.length?l=u.sampleDuration.reduce((c,h)=>c+h,0):l=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+l)/e*1e3},zC=s=>{let e={is3dVideo:!1,stereoMode:0,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}},i=new Ii().parse(s),r=new _i(i);if(r.find("sv3d")){e.is3dVideo=!0;let n=r.find("st3d");n&&(e.stereoMode=n.stereoMode);let o=r.find("prhd");o&&(e.projectionData.pose.yaw=o.poseYawDegrees,e.projectionData.pose.pitch=o.posePitchDegrees,e.projectionData.pose.roll=o.poseRollDegrees);let u=r.find("equi");u&&(e.projectionData.bounds.top=u.projectionBoundsTop,e.projectionData.bounds.right=u.projectionBoundsRight,e.projectionData.bounds.bottom=u.projectionBoundsBottom,e.projectionData.bounds.left=u.projectionBoundsLeft)}return e},ux={validateData:FC,parseInit:zC,getIndexRange:()=>{},parseSegments:NC,parseFeedableSegmentChunk:UC,getChunkEndTime:HC,getServerLatencyTimestamps:qC,getTimescaleFromIndex:jC};var Xn=N(gt(),1);import{assertNonNullable as qp,isNonNullable as px,isNullable as GC}from"@vkontakte/videoplayer-shared/es2018";import{assertNever as QC}from"@vkontakte/videoplayer-shared/es2018";var lx={440786851:{type:"master"},17030:{type:"uint"},17143:{type:"uint"},17138:{type:"uint"},17139:{type:"uint"},17026:{type:"string"},17031:{type:"uint"},17029:{type:"uint"},236:{type:"binary"},408125543:{type:"master"},290298740:{type:"master"},19899:{type:"master"},21419:{type:"binary"},21420:{type:"uint"},357149030:{type:"master"},2807729:{type:"uint"},17545:{type:"float"},374648427:{type:"master"},174:{type:"master"},224:{type:"master"},30320:{type:"master"},30321:{type:"uint"},30322:{type:"master"},272869232:{type:"master"},524531317:{type:"master"},231:{type:"uint"},22612:{type:"master"},22743:{type:"uint"},167:{type:"uint"},171:{type:"uint"},163:{type:"binary"},160:{type:"master"},175:{type:"binary"},423732329:{type:"master"},307544935:{type:"master"},475249515:{type:"master"},187:{type:"master"},179:{type:"uint"},183:{type:"master"},247:{type:"uint"},241:{type:"uint"},240:{type:"uint"},178:{type:"uint"},21368:{type:"uint"},234:{type:"uint"},219:{type:"master"},150:{type:"uint"}},cx=s=>{let e=s.getUint8(0),t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);let i=Kn(s,t),r=i in lx,a=r?lx[i].type:"binary",n=s.getUint8(t),o=0;n&128?o=1:n&64?o=2:n&32?o=3:n&16?o=4:n&8?o=5:n&4?o=6:n&2?o=7:n&1&&(o=8);let u=new DataView(s.buffer,s.byteOffset+t+1,o-1),l=n&255>>o,d=Kn(u),c=l*2**((o-1)*8)+d,h=t+o,p;return h+c>s.byteLength?p=new DataView(s.buffer,s.byteOffset+h):p=new DataView(s.buffer,s.byteOffset+h,c),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:a,tagHeaderSize:h,tagSize:h+c,value:p,valueSize:c}},Kn=(s,e=s.byteLength)=>{switch(e){case 1:return s.getUint8(0);case 2:return s.getUint16(0);case 3:return s.getUint8(0)*2**16+s.getUint16(1);case 4:return s.getUint32(0);case 5:return s.getUint8(0)*2**32+s.getUint32(1);case 6:return s.getUint16(0)*2**32+s.getUint32(2);case 7:{let t=s.getUint8(0)*281474976710656+s.getUint16(1)*4294967296+s.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},Nt=(s,e)=>{switch(e){case"int":return s.getInt8(0);case"uint":return Kn(s);case"float":return s.byteLength===4?s.getFloat32(0):s.getFloat64(0);case"string":return new TextDecoder("ascii").decode(s);case"utf8":return new TextDecoder("utf-8").decode(s);case"date":return new Date(Date.UTC(2001,0)+s.getInt8(0)).getTime();case"master":return s;case"binary":return s;default:QC(e)}},mr=(s,e)=>{let t=0;for(;t<s.byteLength;){let i=new DataView(s.buffer,s.byteOffset+t),r=cx(i);if(!e(r))return;r.type==="master"&&mr(r.value,e),t=r.value.byteOffset-s.byteOffset+r.valueSize}},dx=s=>{if(s.getUint32(0)!==440786851)return!1;let e,t,i,r=cx(s);return mr(r.value,({tag:a,type:n,value:o})=>(a===17143?e=Nt(o,n):a===17026?t=Nt(o,n):a===17029&&(i=Nt(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)};var hx=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],WC=[231,22612,22743,167,171,163,160,175],YC=s=>{let e,t,i,r,a=!1,n=!1,o=!1,u,l,d=!1,c=0;return mr(s,({tag:h,type:p,value:f,valueSize:m})=>{if(h===21419){let g=Nt(f,p);l=Kn(g)}else h!==21420&&(l=void 0);return h===408125543?(e=f.byteOffset,t=f.byteOffset+m):h===357149030?a=!0:h===290298740?n=!0:h===2807729?i=Nt(f,p):h===17545?r=Nt(f,p):h===21420&&l===475249515?u=Nt(f,p):h===374648427?mr(f,({tag:g,type:S,value:v})=>g===30321?(d=Nt(v,S)===1,!1):!0):a&&n&&(0,Xn.default)(hx,h)&&(o=!0),!o}),qp(e,"Failed to parse webm Segment start"),qp(t,"Failed to parse webm Segment end"),qp(r,"Failed to parse webm Segment duration"),i=i!=null?i:1e6,{segmentStart:Math.round(e/1e9*i*1e3),segmentEnd:Math.round(t/1e9*i*1e3),timeScale:i,segmentDuration:Math.round(r/1e9*i*1e3),cuesSeekPosition:u,is3dVideo:d,stereoMode:c,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},KC=s=>{if(GC(s.cuesSeekPosition))return;let e=s.segmentStart+s.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},XC=(s,e)=>{let t=!1,i=!1,r=o=>px(o.time)&&px(o.position),a=[],n;return mr(s,({tag:o,type:u,value:l})=>{switch(o){case 475249515:t=!0;break;case 187:n&&r(n)&&a.push(n),n={};break;case 179:n&&(n.time=Nt(l,u));break;case 183:break;case 241:n&&(n.position=Nt(l,u));break;default:t&&(0,Xn.default)(hx,o)&&(i=!0)}return!(t&&i)}),n&&r(n)&&a.push(n),a.map((o,u)=>{let{time:l,position:d}=o,c=a[u+1];return{status:"none",time:{from:l,to:c?c.time:e.segmentDuration},byte:{from:e.segmentStart+d,to:c?e.segmentStart+c.position-1:e.segmentEnd-1}}})},JC=s=>{let e=0,t=!1;try{mr(s,i=>i.tag===524531317?i.tagSize<=s.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):(0,Xn.default)(WC,i.tag)?(e+i.tagSize<=s.byteLength&&(e+=i.tagSize,t||(t=(0,Xn.default)([163,160,175],i.tag))),!0):!1)}catch(i){}return e>0&&e<=s.byteLength&&t?new DataView(s.buffer,s.byteOffset,e):null},fx={validateData:dx,parseInit:YC,getIndexRange:KC,parseSegments:XC,parseFeedableSegmentChunk:JC};var Jn=s=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(s);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return fx;case"mp4":return ux}}throw new ReferenceError(`Unsupported mime type ${s}`)};var Wp=N(lp(),1),Ex=N(Ji(),1),wx=N(cp(),1),Ax=N(Ot(),1),Yp=N(nr(),1);import{isNonNullable as iV,isNullable as Ix}from"@vkontakte/videoplayer-shared/es2018";var mx=s=>{var e;try{let t=ZC(),i=s.match(t),{groups:r}=i!=null?i:{};if(r){let a={};if(r.extensions){let u=r.extensions.toLowerCase().match(/(?:[0-9a-wy-z](?:-[a-z0-9]{2,8})+)/g);Array.from(u||[]).forEach(l=>{a[l[0]]=l.slice(2)})}let n=(e=r.variants)==null?void 0:e.split(/-/).filter(u=>u!==""),o={extlang:r.extlang,langtag:r.langtag,language:r.language,privateuse:r.privateuse||r.privateuse2,region:r.region,script:r.script,extensions:a,variants:n};return Object.keys(o).forEach(u=>{let l=o[u];(typeof l=="undefined"||l==="")&&delete o[u]}),o}return null}catch(t){return null}};function ZC(){let s="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",d=`^(?:(?<langtag>${`
179
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 Hp=N(Ot(),1);import{videoSizeToQuality as ZC,throttleFn as eV}from"@vkontakte/videoplayer-shared/es2018";var bx=({id:s,width:e,height:t,bitrate:i,fps:r,quality:a,streamId:n})=>{var u;let o=(u=a?Bi(a):void 0)!=null?u:ZC({width:e,height:t});return o&&{id:s,quality:o,bitrate:i,size:{width:e,height:t},fps:r,streamId:n}},gx=({id:s,bitrate:e})=>({id:s,bitrate:e}),Sx=({language:s,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:s,label:e}),vx=({language:s,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:s,label:e}),zp=({id:s,language:e,label:t,codecs:i,isDefault:r})=>({id:s,language:e,label:t,codec:(0,Hp.default)(i.split("."),0),isDefault:r}),Qp=({id:s,language:e,label:t,hdr:i,codecs:r})=>({id:s,language:e,hdr:i,label:t,codec:(0,Hp.default)(r.split("."),0)}),Gp=s=>"url"in s,Ze=s=>s.type==="template",Zn=s=>s instanceof DOMException&&(s.name==="AbortError"||s.code===20);var yx=s=>{s.sort((t,i)=>t.from-i.from);let e=[s[0]];for(let t=1;t<s.length;t++){let{from:i,to:r}=s[t],a=e[e.length-1];a.to>=i?a.to=Math.max(a.to,r):e.push(s[t])}return e},br=(s,e)=>{for(let t of s)if(e(t))return t;return null},Tx=s=>{let e=!1,t=eV(()=>{e=!0},s);return()=>{try{return t(),e}finally{e=!1}}};var xx=s=>{if(!(s!=null&&s.startsWith("P")))return;let e=(n,o)=>{let u=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(u)?0:u)*o},i=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(s),r=(i==null?void 0:i[1])==="-"?-1:1,a={days:e(i==null?void 0:i[5],r),hours:e(i==null?void 0:i[6],r),minutes:e(i==null?void 0:i[7],r),seconds:e(i==null?void 0:i[8],r)};return a.days*24*60*60*1e3+a.hours*60*60*1e3+a.minutes*60*1e3+a.seconds*1e3},xi=(s,e)=>{let t=s;t=(0,Wp.default)(t,"$$","$");let i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[r,a]of(0,Ex.default)(i)){let n=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=(0,Wp.default)(t,n,(o,u)=>Ix(a)?o:Ix(u)?a:(0,wx.default)(a,parseInt(u,10),"0"))}return t},Px=(s,e)=>{var w,P,C,M,k,Q,U,A,F,R,x,$,oe,Ce,se,K,ye,Te,Ie,Ve,Tt,At,qt,Xt,Ai,bs,gs,Ss,vs,ys,Ts,Is,xs,Es,ws,As,Ps,Rs,ks,Ms,Ls,Bs,$s,Ds,Cs,Vs,Os,_s,Fs,Ns,Us,qs,js,Hs,zs,Qs,Gs,Ws,Ys,Ks,Xs;let i=new DOMParser().parseFromString(s,"application/xml"),r={video:[],audio:[],text:[]},a=i.children[0],n=Array.from(a.querySelectorAll("MPD > BaseURL").values()).map(ce=>{var _,je;return(je=(_=ce.textContent)==null?void 0:_.trim())!=null?je:""}),o=(w=(0,Ax.default)(n,0))!=null?w:"",u=a.getAttribute("type")==="dynamic",l=a.getAttribute("availabilityStartTime"),d=a.getAttribute("publishTime"),c=a.getElementsByTagName("vk:Attrs")[0],h=c==null?void 0:c.getElementsByTagName("vk:XLatestSegmentPublishTime")[0].textContent,p=c==null?void 0:c.getElementsByTagName("vk:XStreamIsLive")[0].textContent,f=c==null?void 0:c.getElementsByTagName("vk:XStreamIsUnpublished")[0].textContent,m=c==null?void 0:c.getElementsByTagName("vk:XPlaybackDuration")[0].textContent,g;u&&(g={availabilityStartTime:l?new Date(l).getTime():0,publishTime:d?new Date(d).getTime():0,latestSegmentPublishTime:h?new Date(h).getTime():0,streamIsAlive:p==="yes",streamIsUnpublished:f==="yes"});let S,v=a.getAttribute("mediaPresentationDuration"),y=[...a.getElementsByTagName("Period")],I=y.reduce((ce,_)=>({...ce,[_.id]:_.children}),{}),T=y.reduce((ce,_)=>({...ce,[_.id]:_.getAttribute("duration")}),{});v?S=xx(v):(0,Yp.default)(T).filter(ce=>ce).length&&!u?S=(0,Yp.default)(T).reduce((ce,_)=>{var je;return ce+((je=xx(_))!=null?je:0)},0):m&&(S=parseInt(m,10));let E=0,O=(C=(P=a.getAttribute("profiles"))==null?void 0:P.split(","))!=null?C:[];for(let ce of y.map(_=>_.id))for(let _ of I[ce]){let je=(M=_.getAttribute("id"))!=null?M:"id"+(E++).toString(10),Pt=(k=_.getAttribute("mimeType"))!=null?k:"",ji=(Q=_.getAttribute("codecs"))!=null?Q:"",Hi=(U=_.getAttribute("contentType"))!=null?U:Pt==null?void 0:Pt.split("/")[0],Rl=(F=(A=_.getAttribute("profiles"))==null?void 0:A.split(","))!=null?F:[],Js=(x=mx((R=_.getAttribute("lang"))!=null?R:""))!=null?x:{},Jt=(Ce=(oe=($=_.querySelector("Label"))==null?void 0:$.textContent)==null?void 0:oe.trim())!=null?Ce:void 0,kl=_.querySelectorAll("Representation"),Ml=_.querySelector("SegmentTemplate"),Ll=(K=(se=_.querySelector("Role"))==null?void 0:se.getAttribute("value"))!=null?K:void 0,ut=Hi,H={id:je,language:Js.language,isDefault:Ll==="main",label:Jt,codecs:ji,hdr:ut==="video"&&Zr(ji),mime:Pt,representations:[]};for(let V of kl){let we=(ye=V.getAttribute("lang"))!=null?ye:void 0,Rt=(Ie=(Te=Jt!=null?Jt:_.getAttribute("label"))!=null?Te:V.getAttribute("label"))!=null?Ie:void 0,Zt=(At=(Tt=(Ve=V.querySelector("BaseURL"))==null?void 0:Ve.textContent)==null?void 0:Tt.trim())!=null?At:"",He=new URL(Zt||o,e).toString(),Ae=(qt=V.getAttribute("mimeType"))!=null?qt:Pt,ei=(Ai=(Xt=V.getAttribute("codecs"))!=null?Xt:ji)!=null?Ai:"",ti;if(Hi==="text"){let Pe=V.getAttribute("id")||"",ii=((bs=Js.privateuse)==null?void 0:bs.includes("x-auto"))||Pe.includes("_auto"),ze=V.querySelector("SegmentTemplate");if(ze){let kt={representationId:(gs=V.getAttribute("id"))!=null?gs:void 0,bandwidth:(Ss=V.getAttribute("bandwidth"))!=null?Ss:void 0},ri=parseInt((vs=V.getAttribute("bandwidth"))!=null?vs:"",10)/1e3,si=(Ts=parseInt((ys=ze.getAttribute("startNumber"))!=null?ys:"",10))!=null?Ts:1,lt=parseInt((Is=ze.getAttribute("timescale"))!=null?Is:"",10),zi=(xs=ze.querySelectorAll("SegmentTimeline S"))!=null?xs:[],ct=ze.getAttribute("media");if(!ct)continue;let ai=[],ni=0,oi="",dt=0,Mt=si,ee=0;for(let de of zi){let Qe=parseInt((Es=de.getAttribute("d"))!=null?Es:"",10),ne=parseInt((ws=de.getAttribute("r"))!=null?ws:"",10)||0,Re=parseInt((As=de.getAttribute("t"))!=null?As:"",10);ee=Number.isFinite(Re)?Re:ee;let Ge=Qe/lt*1e3,ke=ee/lt*1e3;for(let me=0;me<ne+1;me++){let Me=xi(ct,{...kt,segmentNumber:Mt.toString(10),segmentTime:(ee+me*Qe).toString(10)}),pt=(ke!=null?ke:0)+me*Ge,Bt=pt+Ge;Mt++,ai.push({time:{from:pt,to:Bt},url:Me})}ee+=(ne+1)*Qe,ni+=(ne+1)*Ge}dt=ee/lt*1e3,oi=xi(ct,{...kt,segmentNumber:Mt.toString(10),segmentTime:ee.toString(10)});let Lt={time:{from:dt,to:1/0},url:oi},xe={type:"template",baseUrl:He,segmentTemplateUrl:ct,initUrl:"",totalSegmentsDurationMs:ni,segments:ai,nextSegmentBeyondManifest:Lt,timescale:lt};ti={id:Pe,kind:"text",segmentReference:xe,profiles:[],duration:S,bitrate:ri,mime:"",codecs:"",width:0,height:0,isAuto:ii}}else ti={id:Pe,isAuto:ii,kind:"text",url:He}}else{let Pe=(Rs=(Ps=V.getAttribute("contentType"))!=null?Ps:Ae==null?void 0:Ae.split("/")[0])!=null?Rs:Hi,ii=(Ms=(ks=_.getAttribute("profiles"))==null?void 0:ks.split(","))!=null?Ms:[],ze=parseInt((Ls=V.getAttribute("width"))!=null?Ls:"",10),kt=parseInt((Bs=V.getAttribute("height"))!=null?Bs:"",10),ri=parseInt(($s=V.getAttribute("bandwidth"))!=null?$s:"",10)/1e3,si=(Ds=V.getAttribute("frameRate"))!=null?Ds:"",lt=(Cs=V.getAttribute("quality"))!=null?Cs:void 0,zi=si?Lu(si):void 0,ct=(Vs=V.getAttribute("id"))!=null?Vs:"id"+(E++).toString(10),ai=Pe==="video"?`${kt}p`:Pe==="audio"?`${ri}Kbps`:ei,ni=`${ct}@${ai}`,oi=[...O,...Rl,...ii],dt,Mt=V.querySelector("SegmentBase"),ee=(Os=V.querySelector("SegmentTemplate"))!=null?Os:Ml;if(Mt){let xe=(Fs=(_s=V.querySelector("SegmentBase Initialization"))==null?void 0:_s.getAttribute("range"))!=null?Fs:"",[de,Qe]=xe.split("-").map(Me=>parseInt(Me,10)),ne={from:de,to:Qe},Re=(Ns=V.querySelector("SegmentBase"))==null?void 0:Ns.getAttribute("indexRange"),[Ge,ke]=Re?Re.split("-").map(Me=>parseInt(Me,10)):[],me=Re?{from:Ge,to:ke}:void 0;dt={type:"byteRange",url:He,initRange:ne,indexRange:me}}else if(ee){let xe={representationId:(Us=V.getAttribute("id"))!=null?Us:void 0,bandwidth:(qs=V.getAttribute("bandwidth"))!=null?qs:void 0},de=parseInt((js=ee.getAttribute("timescale"))!=null?js:"",10),Qe=(Hs=ee.getAttribute("initialization"))!=null?Hs:"",ne=ee.getAttribute("media"),Re=(Qs=parseInt((zs=ee.getAttribute("startNumber"))!=null?zs:"",10))!=null?Qs:1,Ge=xi(Qe,xe);if(!ne)throw new ReferenceError("No media attribute in SegmentTemplate");let ke=(Gs=ee.querySelectorAll("SegmentTimeline S"))!=null?Gs:[],me=[],Me=0,pt="",Bt=0;if(ke.length){let ui=Re,pe=0;for(let ht of ke){let be=parseInt((Ws=ht.getAttribute("d"))!=null?Ws:"",10),We=parseInt((Ys=ht.getAttribute("r"))!=null?Ys:"",10)||0,li=parseInt((Ks=ht.getAttribute("t"))!=null?Ks:"",10);pe=Number.isFinite(li)?li:pe;let Qi=be/de*1e3,Gi=pe/de*1e3;for(let ci=0;ci<We+1;ci++){let $l=xi(ne,{...xe,segmentNumber:ui.toString(10),segmentTime:(pe+ci*be).toString(10)}),Zs=(Gi!=null?Gi:0)+ci*Qi,Dl=Zs+Qi;ui++,me.push({time:{from:Zs,to:Dl},url:$l})}pe+=(We+1)*be,Me+=(We+1)*Qi}Bt=pe/de*1e3,pt=xi(ne,{...xe,segmentNumber:ui.toString(10),segmentTime:pe.toString(10)})}else if(tV(S)){let pe=parseInt((Xs=ee.getAttribute("duration"))!=null?Xs:"",10)/de*1e3,ht=Math.ceil(S/pe),be=0;for(let We=1;We<ht;We++){let li=xi(ne,{...xe,segmentNumber:We.toString(10),segmentTime:be.toString(10)});me.push({time:{from:be,to:be+pe},url:li}),be+=pe}Bt=be,pt=xi(ne,{...xe,segmentNumber:ht.toString(10),segmentTime:be.toString(10)})}let Bl={time:{from:Bt,to:1/0},url:pt};dt={type:"template",baseUrl:He,segmentTemplateUrl:ne,initUrl:Ge,totalSegmentsDurationMs:Me,segments:me,nextSegmentBeyondManifest:Bl,timescale:de}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Pe||!Ae)continue;let Lt={video:"video",audio:"audio",text:"text"}[Pe];if(!Lt)continue;ut||(ut=Lt),ti={id:ni,kind:Lt,segmentReference:dt,profiles:oi,duration:S,bitrate:ri,mime:Ae,codecs:ei,width:ze,height:kt,fps:zi,quality:lt}}H.language||(H.language=we),H.label||(H.label=Rt),H.mime||(H.mime=Ae),H.codecs||(H.codecs=ei),H.hdr||(H.hdr=ut==="video"&&Zr(ei)),H.representations.push(ti)}if(ut){let V=r[ut].find(we=>we.id===H.id);if(V&&H.representations.every(we=>Ze(we.segmentReference)))for(let we of V.representations){let Rt=H.representations.find(Ae=>Ae.id===we.id),Zt=Rt==null?void 0:Rt.segmentReference,He=we.segmentReference;He.segments.push(...Zt.segments),He.nextSegmentBeyondManifest=Zt.nextSegmentBeyondManifest}else r[ut].push(H)}}return{duration:S,streams:r,baseUrls:n,live:g}};import{fromEvent as iV,Subscription as rV}from"@vkontakte/videoplayer-shared/es2018";var il=s=>{let e=[];for(let t=0;t<s.length;t++){let i=Math.floor(s.start(t)*1e3),r=Math.ceil(s.end(t)*1e3);e.push(i,r)}return e};var rl=class{constructor(e,t){this.lastUpdateTs=0;this.lastCallTs=0;this.prevRanges=[];this.subscription=new rV;this.mediaSource=e,this.sourceBuffer=t,this.subscription.add(iV(this.sourceBuffer,"updateend").subscribe(()=>this.updateend()))}updateend(){if(!q(this.mediaSource,this.sourceBuffer))return;let{prevRanges:e}=this,t=il(this.sourceBuffer.buffered);this.prevRanges=t,this.isRangesRemoved(e,t)&&(this.lastUpdateTs=Date.now())}isRangesRemoved(e,t){if(e.length!==t.length)return!0;for(let i=0;i<e.length;i+=2){let r=e[i],a=e[i+1],n=t[i],o=t[i+1];if(n>r||o<a)return!0}return!1}wasUpdated(){let{lastCallTs:e,lastUpdateTs:t}=this;return this.lastCallTs=Date.now(),e<=t}destroy(){this.subscription.unsubscribe()}};var eo=class{constructor(e,t,i,{fetcher:r,tuning:a,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new Sr(0);this.currentLowLatencySegmentLength$=new Sr(0);this.currentSegmentLength$=new Sr(0);this.onLastSegment$=new Sr(!1);this.fullyBuffered$=new Sr(!1);this.playingRepresentation$=new Sr(void 0);this.playingRepresentationInit$=new Sr(void 0);this.error$=new aV;this.gaps=[];this.subscription=new nV;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new ae;this.switchAbortController=new ae;this.destroyAbortController=new ae;this.bufferLimit=1/0;this.failedDownloads=0;this.baseUrls=[];this.baseUrlsIndex=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.lastDataObtainedTimestampMs=0;this.loadByteRangeSegmentsTimeoutId=0;this.sourceBufferBufferedDiff=null;this.startWith=Fi(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);ot(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new ox(this.sourceBuffer),this.sourceBufferBufferedDiff=new rl(this.mediaSource,this.sourceBuffer),this.subscription.add(Xp(this.sourceBuffer,"updateend").subscribe(()=>{this.maintain()})),this.subscription.add(Xp(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:gr.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o||!q(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,Kr(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=$e(this.sourceBuffer.buffered,o),d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,n*2,l<d).catch(c=>{this.handleAsyncError(c,"pruneBuffer")})})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);let i=this.initData.get(t.id),r=this.segments.get(t.id),a=this.parsedInitData.get(t.id);ot(i,"No init buffer for starting representation"),ot(r,"No segments for starting representation"),i instanceof ArrayBuffer&&(this.searchGaps(r,t),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(a))}.bind(this));this.switchTo=Fi(this.destroyAbortController.signal,async function*(e,t=!1){if(!q(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);ot(i,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if(qe(a)||qe(r)?yield this.loadInit(i,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),ot(r,"No segments for starting representation"),a=this.initData.get(e),!(!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer||!q(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(a,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer();else{let n=this.getCurrentPosition();ls(n)&&!this.isLive&&(this.bufferLimit=1/0,await this.pruneBuffer(n,1/0,!0)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}this.maintain()}}.bind(this));this.switchToOld=Fi(this.destroyAbortController.signal,async function*(e,t=!1){if(!q(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);ot(i,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if(qe(a)||qe(r)?yield this.loadInit(i,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),ot(r,"No segments for starting representation"),a=this.initData.get(e),!(!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer||!q(this.mediaSource,this.sourceBuffer)))if(yield this.abort(),yield this.sourceBufferTaskQueue.append(a,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let n=this.getCurrentPosition();ls(n)&&(this.isLive||(this.bufferLimit=1/0,await this.pruneBuffer(n,1/0,!0)),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}}.bind(this));this.seekLive=Fi(this.destroyAbortController.signal,async function*(e){var u,l;let t=(u=(0,nl.default)(e,d=>d.representations))!=null?u:[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let d of this.representations.keys()){let c=t.find(f=>f.id===d);c&&this.representations.set(d,c);let h=this.representations.get(d);if(!h||!Ze(h.segmentReference))return;let p=this.getActualLiveStartingSegments(h.segmentReference);this.segments.set(h.id,p)}let i=(l=this.switchingToRepresentationId)!=null?l:this.downloadingRepresentationId,r=this.representations.get(i);ot(r);let a=this.segments.get(i);ot(a,"No segments for starting representation");let n=this.initData.get(i);if(ot(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer))return;let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(a,r),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));var d;this.fetcher=r,this.tuning=a,this.compatibilityMode=u,this.forwardBufferTarget=a.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!(l!=null&&l.live),this.baseUrls=(d=l==null?void 0:l.baseUrls)!=null?d:[],this.initData=new Map(i.map(c=>[c.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(c=>[c.id,c])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchToWithPreviousAbort(e,t=!1){!q(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new ae,Fi(this.switchAbortController.signal,async function*(i,r=!1){this.switchingToRepresentationId=i;let a=this.representations.get(i);ot(a,`No such representation ${i}`);let n=this.segments.get(i),o=this.initData.get(i);if(qe(o)||qe(n)?yield this.loadInit(a,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(i),ot(n,"No segments for starting representation"),o=this.initData.get(i),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer||!q(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(o,this.downloadAbortController.signal),r)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=i,yield this.dropBuffer();else{let u=this.getCurrentPosition();ls(u)&&!this.isLive&&(this.bufferLimit=this.forwardBufferTarget,yield this.pruneBuffer(u,1/0,!0)),this.downloadingRepresentationId=i,this.switchingToRepresentationId=void 0}this.maintain()}}.bind(this))(e,t))}warmUpMediaSource(){!qe(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}async abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);return this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new ae,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(qe(e)||qe(this.downloadingRepresentationId)||qe(this.playingRepresentationId)||qe(this.sourceBuffer)||!q(this.mediaSource,this.sourceBuffer)||ls(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(ot(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;let r=i.find(d=>e>=d.time.from&&e<d.time.to);ls(r)&&isFinite(r.time.from)&&isFinite(r.time.to)&&this.currentSegmentLength$.next((r==null?void 0:r.time.to)-r.time.from);let a=e,n=100;if(this.playingRepresentationId!==this.downloadingRepresentationId){let d=$e(this.sourceBuffer.buffered,e),c=r?r.time.to+n:-1/0;r&&r.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&d>=r.time.to-e+n&&(a=c)}if(isFinite(this.bufferLimit)&&Kr(this.sourceBuffer.buffered)>=this.bufferLimit){let d=$e(this.sourceBuffer.buffered,e),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,d<c).catch(h=>{this.handleAsyncError(h,"pruneBuffer")});return}let u=null;if(!this.activeSegments.size&&(u=this.selectForwardBufferSegments(i,t.segmentReference.type,a),u!=null&&u.length)){let d="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if((0,al.default)(u,r))d="high";else{let c=(0,cs.default)(u,0);c&&c.time.from-r.time.to>=this.forwardBufferTarget/2&&(d="low")}this.loadSegments(u,t,d).catch(c=>{this.handleAsyncError(c,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&r&&r.status==="fed"&&!(u!=null&&u.length)&&$e(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let l=(0,cs.default)(i,-1);!this.isLive&&l&&(this.fullyBuffered$.next(l.time.to-e-$e(this.sourceBuffer.buffered,e)<n),this.onLastSegment$.next(e-l.time.from>0))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let i=0,r=this.isLive?this.liveInitialAdditionalOffset:0;for(let a of e)Math.trunc(a.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:a.time.from+r,persistent:!0}),i=a.time.to;ls(t.duration)&&t.duration-i>0&&!this.isLive&&this.gaps.push({representation:t.id,from:i,to:t.duration,persistent:!0})}getActualLiveStartingSegments(e){let t=e.segments,i=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,r=[],a=0,n=t.length-1;do r.unshift(t[n]),a+=t[n].time.to-t[n].time.from,n--;while(a<i&&n>=0);return this.liveInitialAdditionalOffset=a-i,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){let t=(0,nl.default)(e==null?void 0:e.streams[this.kind],r=>r.representations).find(r=>r.id===this.downloadingRepresentationId);if(!t)return;let i=this.segments.get(t.id);if(i!=null&&i.length)return{from:i[0].time.from,to:i[i.length-1].time.to}}updateLive(e){var i,r,a,n;let t=(i=(0,nl.default)(e==null?void 0:e.streams[this.kind],o=>o.representations))!=null?i:[];if(![...this.segments.values()].every(o=>!o.length))for(let o of t){if(!o||!Ze(o.segmentReference))return;let u=o.segmentReference.segments.map(p=>({...p,status:"none",size:void 0})),l=100,d=(r=this.segments.get(o.id))!=null?r:[],c=(n=(a=(0,cs.default)(d,-1))==null?void 0:a.time.to)!=null?n:0,h=u==null?void 0:u.findIndex(p=>c>=p.time.from+l&&c<=p.time.to+l);if(h===-1){this.liveUpdateSegmentIndex=0;let p=this.getActualLiveStartingSegments(o.segmentReference);this.segments.set(o.id,p)}else{let p=u.slice(h+1);this.segments.set(o.id,[...d,...p])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;ot(e);let t=this.segments.get(e);if(t!=null&&t.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}updateLowLatencyLiveIfNeeded(e){let t=0;for(let i of this.representations.values()){let r=i.segmentReference;if(!Ze(r))return;let a=this.segments.get(i.id);if(!a)continue;let n=a.find(u=>Math.floor(u.time.from)===Math.floor(e.time.from));if(n&&!isFinite(n.time.to)&&(n.time.to=e.time.to,t=n.time.to-n.time.from),!!!a.find(u=>Math.floor(u.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let u=Math.round(e.time.to*r.timescale/1e3).toString(10),l=xi(r.segmentTemplateUrl,{segmentTime:u});a.push({status:"none",time:{from:e.time.to,to:1/0},url:l})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){var a,n,o;let t=(n=(a=this.switchingToRepresentationId)!=null?a:this.downloadingRepresentationId)!=null?n:this.playingRepresentationId;if(!t)return;let i=this.segments.get(t);if(!i)return;let r=i.find(u=>u.time.from<=e&&u.time.to>=e);return(o=r==null?void 0:r.time.from)!=null?o:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e,t;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)==null||e.destroy(),(t=this.sourceBufferBufferedDiff)==null||t.destroy(),this.gapDetectionIdleCallback&&Yt&&Yt(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&Yt&&Yt(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(i){if(!(i instanceof DOMException&&i.name==="NotFoundError"))throw i}this.sourceBuffer=null,this.downloadAbortController.abort(),this.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,i){return this.checkEjectedSegments(),this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){if(this.playingRepresentationId!==this.downloadingRepresentationId){let i=e.findIndex(r=>t>=r.time.from&&t<r.time.to);this.liveUpdateSegmentIndex=i}return this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):null}selectForwardBufferSegmentsRecord(e,t,i){let r=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&&q(this.mediaSource,this.sourceBuffer)&&!(Ne(this.sourceBuffer.buffered,h)&&Ne(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}async loadSegments(e,t,i="auto"){Ze(t.segmentReference)?await this.loadTemplateSegment(e[0],t,i):await this.loadByteRangeSegments(e,t,i)}async loadTemplateSegment(e,t,i="auto"){e.status="downloading";let r={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(r);let{range:a,url:n,signal:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await Fi(o,async function*(){let d=Jp(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,d))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let d=await this.fetcher.fetch(n,{range:a,signal:o,onProgress:u,priority:i,isLowLatency:this.isActiveLowLatency()});if(this.lastDataObtainedTimestampMs=sl(),!d)return;let c=new DataView(d),h=Jn(t.mime);if(!isFinite(r.segment.time.to)){let m=t.segmentReference.timescale;r.segment.time.to=h.getChunkEndTime(c,m)}u&&r.feedingBytes&&l?await Promise.all(l):await this.sourceBufferTaskQueue.append(c,o);let{serverDataReceivedTimestamp:p,serverDataPreparedTime:f}=h.getServerLatencyTimestamps(c);p&&f&&this.currentLiveSegmentServerLatency$.next(f-p),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(d){this.abortActiveSegments([e]),Zn(d)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}updateRepresentationsBaseUrlIfNeeded(){if(!this.tuning.dash.enableBaseUrlSupport||!this.baseUrls.length||this.failedDownloads<=this.tuning.dash.maxSegmentRetryCount)return;this.baseUrlsIndex=(this.baseUrlsIndex+1)%this.baseUrls.length;let e=this.baseUrls[this.baseUrlsIndex];for(let t of this.representations.values())Ze(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}async loadByteRangeSegments(e,t,i="auto"){if(!e.length)return;for(let u of e)u.status="downloading",this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:r,url:a,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(await Fi(n,async function*(){let u=Jp(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),Xp(window,"online").pipe(sV()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(a,{range:r,onProgress:o,signal:n,priority:i}),this.lastDataObtainedTimestampMs=sl(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),Zn(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(Ze(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:(0,cs.default)(e,0).byte.from,to:(0,cs.default)(e,-1).byte.to},{signal:a}=this.downloadAbortController;return{url:i,range:r,signal:a,onProgress:async(o,u)=>{if(!a.aborted)try{this.lastDataObtainedTimestampMs=sl(),await this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:a,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:gr.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!Ze(t.segmentReference))throw new Error("Representation is not template type");let i=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&i.searchParams.set("low-latency","yes");let r=i.toString(),{signal:a}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,d)=>{if(!a.aborted)try{this.lastDataObtainedTimestampMs=sl();let c=this.onSomeTemplateDataLoaded({dataView:l,loaded:d,signal:a,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(c)}catch(c){this.error$.next({id:"SegmentFeeding",category:gr.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}}:void 0;return{url:r,signal:a,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,al.default)(e,t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:a}){if(!this.activeSegments.size||!q(this.mediaSource,this.sourceBuffer))return;let n=this.representations.get(t);if(n)for(let o of this.activeSegments){let{segment:u}=o;if(o.representationId===t){if(a.aborted){r();continue}if(o.loadedBytes=i,o.loadedBytes>o.feedingBytes){let l=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),d=Jn(n.mime).parseFeedableSegmentChunk(l,this.isLive);d!=null&&d.byteLength&&(u.status="partially_fed",o.feedingBytes+=d.byteLength,await this.sourceBufferTaskQueue.append(d),o.fedBytes+=d.byteLength)}}}}async onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:a,onSegmentAppendFailed:n}){if(!this.activeSegments.size||!q(this.mediaSource,this.sourceBuffer))return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){if(u.representationId!==t)continue;if(a.aborted){await n();continue}let{segment:l}=u,d=l.byte.from-i,c=l.byte.to-i,h=c-d+1,p=d<r,f=c<=r;if(p){if(l.status==="downloading"&&f){l.status="downloaded";let m=new DataView(e.buffer,e.byteOffset+d,h);await this.sourceBufferTaskQueue.append(m,a)&&!a.aborted?this.onSegmentFullyAppended(u,t):await n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(l.status==="downloading"||l.status==="partially_fed")&&(u.loadedBytes=Math.min(h,r-d),u.loadedBytes>u.feedingBytes)){let m=new DataView(e.buffer,e.byteOffset+d+u.feedingBytes,u.loadedBytes-u.feedingBytes),g=u.loadedBytes===h?m:Jn(o.mime).parseFeedableSegmentChunk(m);g!=null&&g.byteLength&&(l.status="partially_fed",u.feedingBytes+=g.byteLength,await this.sourceBufferTaskQueue.append(g,a)&&!a.aborted?(u.fedBytes+=g.byteLength,u.fedBytes===h&&this.onSegmentFullyAppended(u,t)):await n())}}}}onSegmentFullyAppended(e,t){if(!(qe(this.sourceBuffer)||!q(this.mediaSource,this.sourceBuffer))){!this.isLive&&j.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(Ne(this.sourceBuffer.buffered,e.segment.time.from,100)&&Ne(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:gr.VIDEO_PIPELINE,message:"Browser stuck on empty result of adding segment to source buffer"})),this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",Gp(e.segment)&&(e.segment.size=e.fedBytes);for(let i of this.representations.values()){if(i.id===t)continue;let r=this.segments.get(i.id);if(r)for(let a of r)a.status==="fed"&&Math.round(a.time.from)===Math.round(e.segment.time.from)&&Math.round(a.time.to)===Math.round(e.segment.time.to)&&(a.status="none")}this.isActiveLowLatency()&&this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,e.segment)}}abortSegment(e){e.status==="partially_fed"?e.status="partially_ejected":e.status!=="partially_ejected"&&(e.status="none");for(let t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[r,a]of this.initData.entries()){let n=a instanceof Promise;t||(t=n),a===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let i=this.representations.get(e);i&&(this.initLoadIdleCallback=Yr(()=>(0,Rx.default)(this.loadInit(i,"low",!1),()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",i=!1){let r=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!i&&this.failedDownloads>0?Fi(this.destroyAbortController.signal,async function*(){let o=Jp(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,Jn(e.mime),r)).then(o=>{if(!o)return;let{init:u,dataView:l,segments:d}=o,c=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,c);let h=d;this.isLive&&Ze(e.segmentReference)&&(h=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,h),u&&this.parsedInitData.set(e.id,u)}).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:gr.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n}async dropBuffer(){for(let e of this.segments.values())for(let t of e)t.status="none";await this.pruneBuffer(0,1/0,!0)}async pruneBuffer(e,t,i=!1){if(!this.sourceBuffer||!q(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||qe(e))return!1;this.checkEjectedSegments();let r=[],a=0,n=o=>{var l;if(a>=t)return;r.push({...o.time});let u=Gp(o)?(l=o.size)!=null?l:0:o.byte.to-o.byte.from;a+=u};for(let o of this.segments.values())for(let u of o){let l=u.time.to<=e-this.tuning.dash.bufferPruningSafeZone,d=u.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(l||d)&&u.status==="fed"&&n(u)}for(let o=0;o<this.sourceBuffer.buffered.length;o++){let u=this.sourceBuffer.buffered.start(o)*1e3,l=this.sourceBuffer.buffered.end(o)*1e3,d=0;for(let c of this.segments.values())for(let h of c)(0,al.default)(["none","partially_ejected"],h.status)&&Math.round(h.time.from)<=Math.round(u)&&Math.round(h.time.to)>=Math.round(l)&&d++;if(d===this.segments.size){let c={time:{from:u,to:l},url:"",status:"none"};n(c)}}if(r.length&&i){let o=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let u of this.segments.values())for(let l of u)l.time.from>=e+o&&l.status==="fed"&&n(l)}return r.length?(r=yx(r),(await Promise.all(r.map(u=>this.sourceBufferTaskQueue.remove(u.from,u.to)))).reduce((u,l)=>u||l,!1)):!1}async abortBuffer(){if(!this.sourceBuffer||!q(this.mediaSource,this.sourceBuffer))return!1;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;return this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!q(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}getBufferedTo(){return!this.sourceBuffer||!q(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length?null:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}getForwardBufferDuration(e=this.getCurrentPosition()){return!this.sourceBuffer||!q(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||qe(e)?0:$e(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!this.sourceBuffer||!q(this.mediaSource,this.sourceBuffer))return;let{buffered:i}=this.sourceBuffer;this.tuning.useRefactoredSearchGap&&(this.gaps=this.gaps.filter(a=>{if(a.persistent)return!0;let n=Math.round(a.from),o=Math.round(a.to);for(let u=0;u<i.length;u++)if(n>=Math.round(i.start(u)*1e3)&&o<=Math.round(i.end(u)*1e3))return!1;return!0}));let r={representation:e,from:t.time.from,to:t.time.to,persistent:!1};for(let a=0;a<i.length;a++){let n=i.start(a)*1e3,o=i.end(a)*1e3;if(!(o<=t.time.from||n>=t.time.to)){if(n<=t.time.from&&o>=t.time.to){r=void 0;break}o>t.time.from&&o<t.time.to&&(r.from=o),n<t.time.to&&n>t.time.from&&(r.to=n)}}r&&r.to-r.from>1&&!this.gaps.some(a=>r&&a.from===r.from&&a.to===r.to)&&this.gaps.push(r)}detectGapsWhenIdle(e,t){if(!(this.gapDetectionIdleCallback||!this.sourceBuffer||!q(this.mediaSource,this.sourceBuffer))){if(!this.tuning.useRefactoredSearchGap)for(let i=0;i<this.sourceBuffer.buffered.length;i++)this.gaps=this.gaps.filter(r=>r.persistent||this.sourceBuffer&&(Math.round(r.from)<Math.round(this.sourceBuffer.buffered.start(i)*1e3)||Math.round(r.to)>Math.round(this.sourceBuffer.buffered.end(i)*1e3)));this.gapDetectionIdleCallback=Yr(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:gr.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if(qe(this.sourceBuffer)||!q(this.mediaSource,this.sourceBuffer)||qe(this.playingRepresentationId)||this.sourceBufferBufferedDiff&&!this.sourceBufferBufferedDiff.wasUpdated())return;let e=il(this.sourceBuffer.buffered),t=100;for(let i of this.segments.values())for(let r of i){let{status:a}=r;if(a!=="fed"&&a!=="partially_ejected")continue;let n=Math.floor(r.time.from),o=Math.ceil(r.time.to),u=!1,l=0;for(let d=0;d<e.length;d+=2){let c=e[d],h=e[d+1];u||(u=c-t<=n&&h+t>=o),(n>=c&&n<h-t||o>c+t&&o<=h)&&(l+=1)}u||(l===1?r.status="partially_ejected":this.gaps.some(d=>d.from===r.time.from||d.to===r.time.to)?r.status="partially_ejected":r.status="none")}}handleAsyncError(e,t){this.error$.next({id:t,category:gr.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}};import{abortable as to,assertNever as kx,fromEvent as Mx,merge as oV,now as io,Subject as Lx,ValueSubject as Zp,flattenObject as ds,ErrorCategory as ro,SubscriptionRemovable as uV}from"@vkontakte/videoplayer-shared/es2018";var ul=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:a=!1}){this.lastConnectionType$=new Zp(void 0);this.lastConnectionReused$=new Zp(void 0);this.lastRequestFirstBytes$=new Zp(void 0);this.recoverableError$=new Lx;this.error$=new Lx;this.abortAllController=new ae;this.subscription=new uV;this.fetchManifest=to(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=Vi(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=Vu(i));let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(ol);return r?(t.log("success",ds({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(r.headers),r.text()):(t.error("error",ds({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=to(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:a="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1}={}){var M,k,Q;let l=e,d=new Headers,c=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{d.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let U=new URL(l,location.href);U.searchParams.append("bytes",`${i.from}-${i.to}`),l=U.toString();break}default:kx(t)}this.requestQuic&&(l=Vi(l));let h=this.abortAllController.signal,p;if(n){let U=new ae;if(p=oV(Mx(this.abortAllController.signal,"abort"),Mx(n,"abort")).subscribe(()=>{try{U.abort()}catch(A){ol(A)}}),this.subscription.add(p),this.abortAllController.signal.aborted||n.aborted)try{U.abort()}catch(A){ol(A)}h=U.signal}let f=io();c.log("startRequest",ds({url:l,priority:a,rangeMethod:t,range:i,isLowLatency:u,requestStartedAt:f}));let m=yield this.doFetch(l,{priority:a,headers:d,signal:h}),g=io();if(!m)return c.error("error",{message:"No response in request"}),c.end(),this.unsubscribeAbortSubscription(p),null;if((M=this.throughputEstimator)==null||M.addRawRtt(g-f),!m.ok||!m.body){this.unsubscribeAbortSubscription(p);let U=`Fetch error ${m.status}: ${m.statusText}`;return c.error("error",{message:U}),c.end(),Promise.reject(new Error(`Fetch error ${m.status}: ${m.statusText}`))}if(this.onHeadersReceived(m.headers),!r&&!o){this.unsubscribeAbortSubscription(p);let U=io(),A={requestStartedAt:f,requestEndedAt:U,duration:U-f};return c.log("endRequest",ds(A)),c.end(),m.arrayBuffer()}let S=m.body;if(o){let U;[S,U]=m.body.tee(),(k=this.throughputEstimator)==null||k.trackStream(U,u)}let v=S.getReader(),y,I=parseInt((Q=m.headers.get("content-length"))!=null?Q:"",10);Number.isFinite(I)&&(y=I),!y&&i&&(y=i.to-i.from+1);let T=0,E=y?new Uint8Array(y):new Uint8Array(0),O=!1,L=U=>{this.unsubscribeAbortSubscription(p),O=!0,ol(U)},w=to(h,async function*({done:U,value:A}){if(T===0&&this.lastRequestFirstBytes$.next(io()-f),h.aborted){this.unsubscribeAbortSubscription(p);return}if(!U&&A){if(y)E.set(A,T),T+=A.byteLength;else{let F=new Uint8Array(E.length+A.length);F.set(E),F.set(A,E.length),E=F,T+=A.byteLength}r==null||r(new DataView(E.buffer),T),yield v==null?void 0:v.read().then(w,L)}}.bind(this));yield v==null?void 0:v.read().then(w,L),this.unsubscribeAbortSubscription(p);let P=io(),C={failed:O,requestStartedAt:f,requestEndedAt:P,duration:P-f};return O?(c.error("endRequest",ds(C)),c.end(),null):(c.log("endRequest",ds(C)),c.end(),E.buffer)}.bind(this));this.fetchByteRangeRepresentation=to(this.abortAllController.signal,async function*(e,t,i){var S;if(e.type!=="byteRange")return null;let{from:r,to:a}=e.initRange,n=r,o=a,u=!1,l,d;e.indexRange&&(l=e.indexRange.from,d=e.indexRange.to,u=a+1===l,u&&(n=Math.min(l,r),o=Math.max(d,a))),n=Math.min(n,0);let c=yield this.fetch(e.url,{range:{from:n,to:o},priority:i,measureThroughput:!1});if(!c)return null;let h=new DataView(c,r-n,a-n+1);if(!t.validateData(h))throw new Error("Invalid media file");let p=t.parseInit(h),f=(S=e.indexRange)!=null?S:t.getIndexRange(p);if(!f)throw new ReferenceError("No way to load representation index");let m;if(u)m=new DataView(c,f.from-n,f.to-f.from+1);else{let v=yield this.fetch(e.url,{range:f,priority:i,measureThroughput:!1});if(!v)return null;m=new DataView(v)}let g=t.parseSegments(m,p,f);return{init:p,dataView:new DataView(c),segments:g}}.bind(this));this.fetchTemplateRepresentation=to(this.abortAllController.signal,async function*(e,t){if(e.type!=="template")return null;let i=new URL(e.initUrl,e.baseUrl).toString(),r=yield this.fetch(i,{priority:t,measureThroughput:!1});return r?{init:null,segments:e.segments.map(n=>({...n,status:"none",size:void 0})),dataView:new DataView(r)}:null}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=r,this.tracer=i.createComponentTracer("Fetcher"),this.useEnableSubtitlesParam=a}onHeadersReceived(e){let{type:t,reused:i}=Cu(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,t,i="auto"){var a,n;let{type:r}=e;switch(r){case"byteRange":return(a=await this.fetchByteRangeRepresentation(e,t,i))!=null?a:null;case"template":return(n=await this.fetchTemplateRepresentation(e,i))!=null?n:null;default:kx(r)}}destroy(){this.abortAllController.abort(),this.tracer.end(),this.subscription.unsubscribe()}async doFetch(e,t){let i=await wt(e,t);if(i.ok)return i;let r=await i.text(),a=parseInt(r);if(!isNaN(a))switch(a){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:ro.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:ro.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:ro.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:ro.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${a})`,category:ro.FATAL})}}unsubscribeAbortSubscription(e){e&&(e.unsubscribe(),this.subscription.remove(e))}},ol=s=>{if(!Zn(s))throw s};import{isNullable as lV,ValueSubject as cV}from"@vkontakte/videoplayer-shared/es2018";var so=class s{constructor(e,t){this.currentRepresentation$=new cV(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(!lV(e))for(let i of this.representations)for(let r of i){let a=r.segmentReference,n=a.segments.length,o=a.segments[0].time.from,u=a.segments[n-1].time.to;if(e<o||e>u)continue;let l=a.segments.find(d=>d.time.from<=e&&d.time.to>=e);!l||((t=this.currentSegment)==null?void 0:t.time.from)===l.time.from&&this.currentSegment.time.to===l.time.to||(this.currentSegment=l,this.currentRepresentation$.next({...r,label:"Live Text",language:"ru",isAuto:!0,url:new URL(l.url,a.baseUrl).toString()}))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e!=null?e:[]){let i=s.filterRepresentations(t.representations);if(i){this.representations[this.representationsCursor]=i,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!(e!=null&&e.some(t=>s.filterRepresentations(t.representations)))}static filterRepresentations(e){return e==null?void 0:e.filter(t=>t.kind==="text"&&"segmentReference"in t&&Ze(t.segmentReference))}};var mV=["progress","play","seeked","stalled","waiting"],bV=["timeupdate","progress","loadeddata","playing","seeked"];var dl=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new sh;this.representationSubscription=new sh;this.state$=new G("none");this.currentVideoRepresentation$=new fe(void 0);this.currentVideoRepresentationInit$=new fe(void 0);this.currentAudioRepresentation$=new fe(void 0);this.currentVideoSegmentLength$=new fe(0);this.currentAudioSegmentLength$=new fe(0);this.error$=new cl;this.lastConnectionType$=new fe(void 0);this.lastConnectionReused$=new fe(void 0);this.lastRequestFirstBytes$=new fe(void 0);this.currentLiveTextRepresentation$=new fe(null);this.isLive$=new fe(!1);this.isActiveLive$=new fe(!1);this.isLowLatency$=new fe(!1);this.liveDuration$=new fe(0);this.liveSeekableDuration$=new fe(0);this.liveAvailabilityStartTime$=new fe(0);this.liveStreamStatus$=new fe(void 0);this.bufferLength$=new fe(0);this.liveLatency$=new fe(void 0);this.liveLoadBufferLength$=new fe(0);this.livePositionFromPlayer$=new fe(0);this.currentStallDuration$=new fe(0);this.videoLastDataObtainedTimestamp$=new fe(0);this.fetcherRecoverableError$=new cl;this.fetcherError$=new cl;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new cl;this.gapWatchdogActive=!1;this.destroyController=new ae;this.initManifest=th(this.destroyController.signal,async function*(e,t,i){var r;this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=Se(t,i,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),(r=this.manifest)!=null&&r.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:Ut.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=th(this.destroyController.signal,async function*(){var n,o;this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(u=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:Ut.NETWORK,message:"Failed to load manifest",thrown:u})});if(!e)return null;let t=null;try{t=Px(e!=null?e:"",this.manifestUrlString)}catch(u){let l=(n=Mu(e))!=null?n:{id:"ManifestParsing",category:Ut.PARSER,message:"Failed to parse MPD manifest",thrown:u};this.error$.next(l)}if(!t)return null;let i=(u,l,d)=>{var c,h,p,f;return!!((h=(c=this.element)==null?void 0:c.canPlayType)!=null&&h.call(c,l)&&((f=(p=vt())==null?void 0:p.isTypeSupported)!=null&&f.call(p,`${l}; codecs="${d}"`))||u==="text")};if(t.live){this.isLive$.next(!!t.live);let{availabilityStartTime:u,latestSegmentPublishTime:l,streamIsUnpublished:d,streamIsAlive:c}=t.live,h=((o=t.duration)!=null?o:0)/1e3;this.liveSeekableDuration$.next(-1*h),this.liveDuration$.next((l-u)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let p="active";c||(p=d?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(p)}let r={text:t.streams.text,video:[],audio:[]};for(let u of["video","audio"]){let d=t.streams[u].filter(({mime:p,codecs:f})=>i(u,p,f)),c=new Set(d.map(({codecs:p})=>p)),h=zu(c);if(h&&(r[u]=d.filter(({codecs:p})=>p.startsWith(h))),u==="video"){let p=this.tuning.preferHDR,f=r.video.some(g=>g.hdr),m=r.video.some(g=>!g.hdr);j.display.isHDR&&p&&f?r.video=r.video.filter(g=>g.hdr):m&&(r.video=r.video.filter(g=>!g.hdr))}}let a={...t,streams:r};return this.tracer.log("updateManifestEnd",no(a)),a}.bind(this));this.initRepresentations=th(this.destroyController.signal,async function*(e,t,i){var h;this.tracer.log("initRepresentationsStart",no({initialVideo:e,initialAudio:t,sourceHls:i})),ps(this.manifest),ps(this.element),this.representationSubscription.unsubscribe(),this.representationSubscription=new sh,this.state$.startTransitionTo("representations_ready");let r=p=>{this.representationSubscription.add(Kt(p,"error").pipe(ll(f=>{var m;return!!((m=this.element)!=null&&m.played.length)})).subscribe(f=>{this.error$.next({id:"VideoSource",category:Ut.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:f})}))};this.source=this.tuning.useManagedMediaSource?nu():new MediaSource;let a=document.createElement("source");if(r(a),a.src=URL.createObjectURL(this.source),this.element.appendChild(a),this.tuning.useManagedMediaSource&&Ur())if(i){let p=document.createElement("source");r(p),p.type="application/x-mpegurl",p.src=i.url,this.element.appendChild(p)}else this.element.disableRemotePlayback=!0;this.isActiveLive$.next(this.isLive$.getValue());let n={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),manifest:this.manifest},o=this.manifest.streams.video.reduce((p,f)=>[...p,...f.representations],[]);if(this.videoBufferManager=new eo("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],oo(t)){let p=this.manifest.streams.audio.reduce((f,m)=>[...f,...m.representations],[]);this.audioBufferManager=new eo("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}so.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new so(this.manifest.streams.text,n)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$));let u=()=>{var p;(p=this.stallWatchdogSubscription)==null||p.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add(vr(...bV.map(p=>Kt(this.element,p))).pipe(fs(p=>this.element?$e(this.element.buffered,this.element.currentTime*1e3):0),ao(),fV(p=>{p>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add(vr(Kt(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe(ao()).subscribe(f=>this.liveStreamEndTimestamp=rh())),this.subscription.add(Kt(this.element,"pause").subscribe(()=>{this.livePauseWatchdogSubscription=ih(1e3).subscribe(f=>{let m=Mi(this.manifestUrlString,2);this.manifestUrlString=Se(this.manifestUrlString,m+1e3,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add(Kt(this.element,"play").subscribe(f=>{var m;return(m=this.livePauseWatchdogSubscription)==null?void 0:m.unsubscribe()})),this.representationSubscription.add(hs({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(fs(({isActiveLive:f,isLowLatency:m})=>f&&m),ao()).subscribe(f=>{this.isManualDecreasePlaybackInLive()||rs(this.element,1)})),this.representationSubscription.add(hs({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(ll(({bufferLength:f,isActiveLive:m,isLowLatency:g})=>m&&g&&!!f)).subscribe(({bufferLength:f})=>this.liveBuffer.next(f))),this.representationSubscription.add(this.videoBufferManager.currentLowLatencySegmentLength$.subscribe(f=>{if(!this.isActiveLive$.getValue()&&!this.isLowLatency$.getValue()&&!f)return;let m=this.liveSeekableDuration$.getValue()-f/1e3;this.liveSeekableDuration$.next(Math.max(m,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+f/1e3)})),this.representationSubscription.add(hs({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(ll(({isLive:f})=>f),ao((f,m)=>m.bufferLength<f.bufferLength),fs(({rtt:f,bufferLength:m,segmentServerLatency:g})=>{let S=Mi(this.manifestUrlString,2);return(f/2+m+g+S)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(hs({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:f,isActiveLive:m,isLowLatency:g})=>{if(!g||!m)return;let S=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,v=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,y=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,I=f-S;if(this.isManualDecreasePlaybackInLive())return;let T=1;Math.abs(I)>v&&(T=1+Math.sign(I)*y),rs(this.element,T)})),this.representationSubscription.add(this.bufferLength$.subscribe(f=>{var g,S;let m=0;if(f){let v=((S=(g=this.element)==null?void 0:g.currentTime)!=null?S:0)*1e3;m=Math.min(...this.bufferManagers.map(I=>{var T,E;return(E=(T=I.getLiveSegmentsToLoadState(this.manifest))==null?void 0:T.to)!=null?E:v}))-v}this.liveLoadBufferLength$.getValue()!==m&&this.liveLoadBufferLength$.next(m)}));let p=0;this.representationSubscription.add(hs({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(Dx(1e3)).subscribe(async({liveLoadBufferLength:f,bufferLength:m})=>{if(!this.element||this.isUpdatingLive)return;let g=this.element.playbackRate,S=Mi(this.manifestUrlString,2),v=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,y=Math.min(v,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*g),I=this.tuning.dashCmafLive.normalizedActualBufferOffset*g,T=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*g,E=isFinite(f)?f:m,O=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),L=v<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(L);let w="none";if(O?w="active_low_latency":this.isLowLatency$.getValue()&&L?(this.bufferManagers.forEach(P=>P.proceedLowLatencyLive()),w="active_low_latency"):S!==0&&E<y?w="live_forward_buffering":E<y+T&&(w="live_with_target_offset"),isFinite(f)&&(p=f>p?f:p),w==="live_forward_buffering"||w==="live_with_target_offset"){let P=p-(y+I),C=this.normolizeLiveOffset(Math.trunc(S+P/g)),M=Math.abs(C-S),k=0;!f||M<=this.tuning.dashCmafLive.offsetCalculationError?k=S:C>0&&M>this.tuning.dashCmafLive.offsetCalculationError&&(k=C),this.manifestUrlString=Se(this.manifestUrlString,k,2)}(w==="live_with_target_offset"||w==="live_forward_buffering")&&(p=0,await this.updateLive())},f=>{this.error$.next({id:"updateLive",category:Ut.VIDEO_PIPELINE,thrown:f,message:"Failed to update live with subscription"})}))}let l=vr(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe(fs(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),d=vr(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe(fs(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue()))),c=hs({allBuffersFull:l,someBufferEnded:d}).pipe(ao(),fs(({allBuffersFull:p,someBufferEnded:f})=>p&&f),ll(p=>p));if(this.representationSubscription.add(vr(this.forceEnded$,c).subscribe(()=>{var p;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(f=>!f.updating))try{(p=this.source)==null||p.endOfStream()}catch(f){this.error$.next({id:"EndOfStream",category:Ut.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:f})}})),this.representationSubscription.add(vr(...this.bufferManagers.map(p=>p.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.representationSubscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.representationSubscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.liveTextManager&&this.representationSubscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$)),this.source.readyState!=="open"){let p=this.tuning.dash.sourceOpenTimeout>=0;yield new Promise(f=>{var m;p&&(this.timeoutSourceOpenId=setTimeout(()=>{var g;if(((g=this.source)==null?void 0:g.readyState)==="open"){f();return}this.error$.next({id:"OpenOfStream",category:Ut.VIDEO_PIPELINE,message:"Failed to open MediaSource",thrown:new Error("Timeout reject when wait sourceopen event"),traceAsLog:!0})},this.tuning.dash.sourceOpenTimeout)),(m=this.source)==null||m.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),f()},{once:!0})})}if(!this.isLive$.getValue()){let p=[(h=this.manifest.duration)!=null?h:0,...(0,ah.default)((0,ah.default)([...this.manifest.streams.audio,...this.manifest.streams.video],f=>f.representations),f=>{let m=[];return f.duration&&m.push(f.duration),Ze(f.segmentReference)&&f.segmentReference.totalSegmentsDurationMs&&m.push(f.segmentReference.totalSegmentsDurationMs),m})];this.source.duration=Math.max(...p)/1e3}this.audioBufferManager&&oo(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")}.bind(this));this.tick=()=>{var t,i,r,a;if(!this.element||!this.videoBufferManager||((t=this.source)==null?void 0:t.readyState)!=="open")return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),(i=this.audioBufferManager)==null||i.maintain(e),(r=this.liveTextManager)==null||r.maintain(e),(this.videoBufferManager.gaps.length||(a=this.audioBufferManager)!=null&&a.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=ih(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),n=>{this.error$.next({id:"GapWatchdog",category:Ut.WTF,message:"Error handling gaps",thrown:n})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.fetcher=new ul({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.subscription.add(this.fetcher.recoverableError$.subscribe(this.fetcherRecoverableError$)),this.subscription.add(this.fetcher.error$.subscribe(this.fetcherError$)),this.liveBuffer=yi.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator}),this.initTracerSubscription()}async seekLive(e){var r,a,n;ps(this.element);let t=this.liveStreamStatus$.getValue()!=="active"?rh()-this.liveStreamEndTimestamp:0,i=this.normolizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=Se(this.manifestUrlString,i,2),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await((r=this.videoBufferManager)==null?void 0:r.seekLive(this.manifest.streams.video)),await((a=this.audioBufferManager)==null?void 0:a.seekLive(this.manifest.streams.audio)),(n=this.liveTextManager)==null||n.seekLive(this.manifest.streams.text))}initBuffer(){ps(this.element),this.state$.setState("running");let e=Kt(this.element,"timeupdate");this.tuning.dash.timeupdateEventTickThrottle&&(e=e.pipe(Dx(this.tuning.dash.timeupdateEventTickThrottle))),this.subscription.add(vr(...mV.map(t=>Kt(this.element,t)),Kt(window,"online"),e).subscribe(()=>this.tick(),t=>{this.error$.next({id:"DashVKPlayer",category:Ut.WTF,message:"Internal logic error",thrown:t})})),this.subscription.add(Kt(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===HTMLMediaElement.HAVE_CURRENT_DATA&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(Kt(this.element,"waiting").subscribe(()=>{var i;this.element&&this.element.readyState===HTMLMediaElement.HAVE_CURRENT_DATA&&!this.element.seeking&&Ne(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let t=()=>{var f,m,g,S,v,y,I,T,E,O,L;if(!this.element||((f=this.source)==null?void 0:f.readyState)!=="open")return;let r=this.currentStallDuration$.getValue();r+=50,this.currentStallDuration$.next(r);let a={timeInWaiting:r},n=rh(),o=100,u=(g=(m=this.videoBufferManager)==null?void 0:m.lastDataObtainedTimestamp)!=null?g:0;this.videoLastDataObtainedTimestamp$.next(u);let l=(v=(S=this.audioBufferManager)==null?void 0:S.lastDataObtainedTimestamp)!=null?v:0,d=(I=(y=this.videoBufferManager)==null?void 0:y.getForwardBufferDuration())!=null?I:0,c=(E=(T=this.audioBufferManager)==null?void 0:T.getForwardBufferDuration())!=null?E:0,h=d<o&&n-u>this.tuning.dash.crashOnStallTWithoutDataTimeout,p=this.audioBufferManager&&c<o&&n-l>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((h||p)&&r>this.tuning.dash.crashOnStallTWithoutDataTimeout||r>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${r} ms`);if(this.isLive$.getValue()&&r%2e3===0){let w=this.normolizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(w).catch(P=>{this.error$.next({id:"stallIntervalCallback",category:Ut.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:P})}),a.liveLastOffset=w}else{let w=this.element.currentTime*1e3;(O=this.videoBufferManager)==null||O.maintain(w),(L=this.audioBufferManager)==null||L.maintain(w),a.position=w}this.tracer.log("stallIntervalCallback",no(a))};(i=this.stallWatchdogSubscription)==null||i.unsubscribe(),this.stallWatchdogSubscription=ih(50).subscribe(t,r=>{this.error$.next({id:"StallWatchdogCallback",category:Ut.NETWORK,message:"Can't restore DASH after stall.",thrown:r})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,i=!1){let r={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return this.tuning.useNewSwitchTo?this.currentStallDuration$.getValue()>0?r==null?void 0:r.switchToWithPreviousAbort(t,i):r==null?void 0:r.switchTo(t,i):r==null?void 0:r.switchToOld(t,i)}async seek(e,t){var r,a,n,o,u;ps(this.element),ps(this.videoBufferManager);let i;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?i=e:i=Math.max((r=this.videoBufferManager.findSegmentStartTime(e))!=null?r:e,(n=(a=this.audioBufferManager)==null?void 0:a.findSegmentStartTime(e))!=null?n:e),this.warmUpMediaSourceIfNeeded(i),Ne(this.element.buffered,i)||await Promise.all([this.videoBufferManager.abort(),(o=this.audioBufferManager)==null?void 0:o.abort()]),!($x(this.element)||$x(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),(u=this.audioBufferManager)==null||u.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",no({requestedPosition:e,forcePrecise:t,position:i})))}warmUpMediaSourceIfNeeded(e=(t=>(t=this.element)==null?void 0:t.currentTime)()){var i;oo(this.element)&&oo(this.source)&&oo(e)&&((i=this.source)==null?void 0:i.readyState)==="ended"&&this.element.duration*1e3-e>this.tuning.dash.seekBiasInTheEnd&&this.bufferManagers.forEach(r=>r.warmUpMediaSource())}get isStreamEnded(){var e;return((e=this.source)==null?void 0:e.readyState)==="ended"}stop(){var e,t,i;this.tracer.log("stop"),(e=this.element)==null||e.querySelectorAll("source").forEach(r=>{URL.revokeObjectURL(r.src),r.remove()}),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(t=this.videoBufferManager)==null||t.destroy(),this.videoBufferManager=null,(i=this.audioBufferManager)==null||i.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){var e;return(e=this.manifest)==null?void 0:e.streams}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){var e;this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),((e=this.source)==null?void 0:e.readyState)==="open"&&Array.from(this.source.sourceBuffers).every(t=>!t.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=hV(this.tracer.error.bind(this.tracer));this.subscription.add(this.error$.subscribe(e("error")))}isManualDecreasePlaybackInLive(){return!this.element||!this.isLive$.getValue()?!1:1-this.element.playbackRate>this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){var e,t;this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&((e=this.bufferManagers)==null||e.forEach(i=>i.updateLive(this.manifest)),(t=this.liveTextManager)==null||t.updateLive(this.manifest)),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getBufferedTo();if(e===null)return;let t=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),i=this.isJumpGapAfterSeekLive,r=this.element.currentTime;this.isJumpGapAfterSeekLive&&!t&&this.element.currentTime>e&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let a=this.element.currentTime*1e3,n=null,o=this.element.readyState===HTMLMediaElement.HAVE_METADATA?this.tuning.endGapTolerance:0;for(let u of this.bufferManagers)for(let l of u.gaps)(l.persistent||u.playingRepresentation$.getValue()===l.representation)&&l.from-o<=a&&l.to+o>a&&(this.element.duration*1e3-l.to<this.tuning.endGapTolerance?n=1/0:(n===null||l.to>n)&&(n=l.to));if(n!==null){let u=n+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,u===1/0?this.forceEnded$.next():(this.element.currentTime=u/1e3,this.tracer.log("jumpGap",no({isJumpGapAfterSeekLive:i,isActiveLowLatency:t,initialCurrentTime:r,jumpTo:u,resultCurrentTime:this.element.currentTime})))}}};import{combine as gV,map as SV,observeElementSize as vV,Subscription as yV,ValueSubject as nh,noop as TV}from"@vkontakte/videoplayer-shared/es2018";var pl=class{constructor(){this.subscription=new yV;this.pipSize$=new nh(void 0);this.videoSize$=new nh(void 0);this.elementSize$=new nh(void 0);this.pictureInPictureWindowRemoveEventListener=TV}connect({observableVideo:e,video:t}){let i=r=>{let a=r.target;this.pipSize$.next({width:a.width,height:a.height})};this.subscription.add(vV(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(gV({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(SV(({videoSize:r,inPip:a,pipSize:n})=>a?n:r)).subscribe(this.elementSize$))}getValue(){return this.elementSize$.getValue()}subscribe(e,t){return this.elementSize$.subscribe(e,t)}getObservable(){return this.elementSize$}destroy(){this.pictureInPictureWindowRemoveEventListener(),this.subscription.unsubscribe()}};var yr=class{constructor(e){this.subscription=new PV;this.videoState=new G("stopped");this.droppedFramesManager=new Gr;this.stallsManager=new Ju;this.elementSizeManager=new pl;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new $i;this.audioTrackSwitchHistory=new $i;this.selectedRepresentations={audio:null,video:null};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(r.state==="requested"&&(i==null?void 0:i.to)!=="paused"&&e!=="stopped"&&t!=="stopped"&&this.seek(r.position,r.forcePrecise),t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),B(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"),B(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="ready"&&B(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"&&B(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&B(this.params.desiredState.playbackState,"paused");return;default:return xV(e)}}};this.init3DScene=e=>{var i,r,a;if(this.scene3D)return;this.scene3D=new os(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((i=e.projectionData)==null?void 0:i.pose.yaw)||0,y:((r=e.projectionData)==null?void 0:r.pose.pitch)||0,z:((a=e.projectionData)==null?void 0:a.pose.roll)||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSizeManager.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.textTracksManager=new xt(e.source.url),this.params=e,this.video=tt(e.container,e.tuning),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Fe(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.player=new dl({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params,i=st(this.video);this.subscription.add(()=>i.destroy());let r=this.constructor.name,a=o=>{e.error$.next({id:r,category:Cx.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(oh(c=>!!c.length),Ox()).subscribe(c=>{this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:c})}));let n=this.params.desiredState.seekState.stateChangeEnded$.pipe(uh(c=>c.to.state!=="none"),hl());this.stallsManager.init({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$,videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,tuning:this.params.tuning.stallsManager,abrParams:this.params.tuning.autoTrackSelection,isBuffering$:i.isBuffering$,looped$:i.looped$,playing$:i.playing$}),a(i.ended$,e.endedEvent$),a(i.looped$,e.loopedEvent$),a(i.error$,e.error$),a(i.isBuffering$,e.isBuffering$),a(i.currentBuffer$,e.currentBuffer$),a(i.playing$,e.firstFrameEvent$),a(i.canplay$,e.canplay$),a(i.inPiP$,e.inPiP$),a(i.inFullscreen$,e.inFullscreen$),a(i.loadedMetadata$,e.loadedMetadataEvent$),a(this.player.error$,e.error$),a(this.player.fetcherRecoverableError$,e.fetcherRecoverableError$),a(this.player.fetcherError$,e.fetcherError$),a(this.player.lastConnectionType$,e.httpConnectionType$),a(this.player.lastConnectionReused$,e.httpConnectionReused$),a(this.player.isLive$,e.isLive$),a(this.player.lastRequestFirstBytes$.pipe(oh(Vx),Ox()),e.firstBytesEvent$),a(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),a(this.videoState.stateChangeEnded$.pipe(uh(c=>c.to)),this.params.output.playbackState$),this.subscription.add(i.looped$.subscribe(()=>this.player.warmUpMediaSourceIfNeeded(),r)),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(zt(this.video,t.isLooped,r)),this.subscription.add(rt(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(It(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),a(Et(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),B(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),B(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(EV(h,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let f=[];for(let m of h.audio){f.push(zp(m));let g=[];for(let S of m.representations){let v=gx(S);g.push(v),this.audioTracksMap.set(v,{stream:m,representation:S})}this.audioStreamsMap.set(m,g)}this.params.output.availableAudioStreams$.next(f)}let p=[];for(let f of h.video){p.push(Qp(f));let m=[];for(let g of f.representations){let S=bx({...g,streamId:f.id});S&&(m.push(S),this.videoTracksMap.set(S,{stream:f,representation:g}))}this.videoStreamsMap.set(f,m)}this.params.output.availableVideoStreams$.next(p);for(let f of h.text)for(let m of f.representations){let g=Sx(f,m);this.textTracksMap.set(g,{stream:f,representation:m})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else c==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r));let{vktvAbrThrottle:o}=this.params.tuning.dash,u=o&&Tx(o)||null;this.subscription.add(fl(this.player.currentStallDuration$,this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,this.elementSizeManager.getObservable(),this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,AV(this.video,"progress")).pipe(oh(()=>this.videoTracksMap.size>0)).subscribe(async()=>{let c=this.player.state$.getState(),h=this.player.state$.getTransition();if(c!=="manifest_ready"&&c!=="running"||h||c==="running"&&u&&!u())return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState()),this.selectVideoAudioRepresentations();let{video:p,audio:f}=this.selectedRepresentations;if(!p)return;let m=br(this.videoTracksMap.keys(),S=>{var v;return((v=this.videoTracksMap.get(S))==null?void 0:v.representation.id)===p.id});Vx(m)&&(this.stallsManager.lastVideoTrackSelected=m);let g=this.params.desiredState.autoVideoTrackLimits.getTransition();if(g&&this.params.output.autoVideoTrackLimits$.next(g.to),c==="manifest_ready")await this.player.initRepresentations(p.id,f==null?void 0:f.id,this.params.sourceHls);else if(await this.player.switchRepresentation("video",p.id),f){let S=!!t.audioStream.getTransition();await this.player.switchRepresentation("audio",f.id,S)}},r)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:c})=>{this.scene3D&&c&&this.scene3D.pointCameraTo(c.x,c.y)})),this.subscription.add(this.elementSizeManager.subscribe(c=>{this.scene3D&&c&&this.scene3D.setViewportSize(c.width,c.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(hl()).subscribe(c=>{let h=br(this.videoTracksMap.entries(),([,{representation:g}])=>g.id===c);if(!h){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[p,{stream:f}]=h,m=this.params.desiredState.videoStream.getTransition();m&&m.to&&m.to.id===f.id&&this.params.desiredState.videoStream.setState(m.to),e.currentVideoTrack$.next(p),e.currentVideoStream$.next(Qp(f))},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(hl()).subscribe(c=>{let h=br(this.audioTracksMap.entries(),([,{representation:g}])=>g.id===c);if(!h){e.currentAudioStream$.next(void 0);return}let[p,{stream:f}]=h,m=this.params.desiredState.audioStream.getTransition();m&&m.to&&m.to.id===f.id&&this.params.desiredState.audioStream.setState(m.to),e.currentAudioStream$.next(zp(f))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(c=>{var h,p;if(c!=null&&c.is3dVideo&&((h=this.params.tuning.spherical)!=null&&h.enabled))try{this.init3DScene(c),e.is3DVideo$.next(!0)}catch(f){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${f}`})}else this.destroy3DScene(),(p=this.params.tuning.spherical)!=null&&p.enabled&&e.is3DVideo$.next(!1)},r)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,r)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,r)),this.textTracksManager.connect(this.video,t,e);let l=t.playbackState.stateChangeStarted$.pipe(uh(({to:c})=>c==="ready"),hl());this.subscription.add(fl(l,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,lh(["init"])).subscribe(()=>{let c=t.autoVideoTrackSwitching.getState(),p=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:c?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(p)})),this.subscription.add(fl(l,this.player.state$.stateChangeEnded$,lh(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let d=fl(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,lh(["init"])).pipe(wV(0));this.subscription.add(d.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){var L,w,P,C,M,k,Q,U,A,F,R,x;if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?Ma:ka,t=this.params.tuning.useNewAutoSelectVideoTrack?xu:Iu,i=this.params.tuning.useNewAutoSelectVideoTrack?Wt:Tu,{desiredState:r,output:a}=this.params,n=r.autoVideoTrackSwitching.getState(),o=(L=r.videoTrack.getState())==null?void 0:L.id,u=br(this.videoTracksMap.keys(),$=>$.id===o),l=a.currentVideoTrack$.getValue(),d=((C=(P=r.videoStream.getState())!=null?P:u&&((w=this.videoTracksMap.get(u))==null?void 0:w.stream))!=null?C:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!d)return;let c=br(this.videoStreamsMap.keys(),$=>$.id===d.id),h=c&&this.videoStreamsMap.get(c);if(!h)return;let p=$e(this.video.buffered,this.video.currentTime*1e3),f;this.player.isActiveLive$.getValue()?f=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?f=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:f=n?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let m=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,g=Math.min(p/Math.min(f,m||1/0),1),S=(M=r.audioStream.getState())!=null?M:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,v=(S==null?void 0:S.id)&&br(this.audioStreamsMap.keys(),$=>$.id===S.id)||this.audioStreamsMap.keys().next().value,y=0;if(v){if(u&&!n){let $=e(u,h,(k=this.audioStreamsMap.get(v))!=null?k:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);y=Math.max(y,(Q=$==null?void 0:$.bitrate)!=null?Q:-1/0)}if(l){let $=e(l,h,(U=this.audioStreamsMap.get(v))!=null?U:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);y=Math.max(y,(A=$==null?void 0:$.bitrate)!=null?A:-1/0)}}let I=u;(n||!I)&&(I=i(h,{container:this.elementSizeManager.getValue(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.stallsManager.abrTuningParams,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:y,forwardBufferHealth:g,current:l,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,stallsVideoMaxQualityLimit:this.stallsManager.videoMaxQualityLimit,stallsPredictedThroughput:this.stallsManager.predictedThroughput,abrLogger:this.params.dependencies.abrLogger}));let T=v&&t(I,h,(F=this.audioStreamsMap.get(v))!=null?F:[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.stallsManager.abrTuningParams,forwardBufferHealth:g,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),E=(R=this.videoTracksMap.get(I))==null?void 0:R.representation,O=T&&((x=this.audioTracksMap.get(T))==null?void 0:x.representation);E&&O?(this.selectedRepresentations.video=E,this.selectedRepresentations.audio=O):E&&!O&&this.audioTracksMap.size===0&&(this.selectedRepresentations.video=E,this.selectedRepresentations.audio=null)}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){at(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),B(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Cx.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.stallsManager.destroy(),this.elementSizeManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),this.params.output.currentVideoStream$.next(void 0),it(this.video),this.tracer.end()}};var uo=class extends yr{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};import{combine as ch,merge as _x,filter as Fx,filterChanged as RV,isNullable as dh,map as Nx,ValueSubject as ph,isNonNullable as kV}from"@vkontakte/videoplayer-shared/es2018";var lo=class extends yr{constructor(e){super(e),this.textTracksManager.destroy()}subscribe(){super.subscribe();let e=-1,{output:t,observableVideo:i,desiredState:r,connect:a}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),a(i.timeUpdate$,t.liveBufferTime$),a(this.player.liveSeekableDuration$,t.duration$),a(this.player.liveLatency$,t.liveLatency$);let n=new ph(1);a(i.playbackRateState$,n),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(r.isLowLatency.stateChangeEnded$.pipe(Nx(o=>o.to)).subscribe(this.player.isLowLatency$)).add(ch({liveBufferTime:t.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(Nx(({liveBufferTime:o,liveAvailabilityStartTime:u})=>o&&u?o+u:void 0)).subscribe(t.liveTime$)).add(this.player.liveStreamStatus$.pipe(Fx(o=>kV(o))).subscribe(o=>t.isLiveEnded$.next(o!=="active"&&t.position$.getValue()===0))).add(ch({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:_x(i.playbackRateState$,new ph(1))}).pipe(Fx(({liveStreamStatus:o,liveDuration:u})=>o==="active"&&!!u)).subscribe(({liveDuration:o,playbackRate:u})=>{let l=t.liveBufferTime$.getValue(),d=t.position$.getValue(),{playbackCatchupSpeedup:c}=this.params.tuning.dashCmafLive.lowLatency;d||u<1-c||this.video.paused||dh(l)||(e=o-l)})).add(ch({time:t.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:_x(i.playbackRateState$,new ph(1))}).pipe(RV((o,u)=>this.player.liveStreamStatus$.getValue()==="active"?o.liveDuration===u.liveDuration:o.time===u.time)).subscribe(({time:o,liveDuration:u,playbackRate:l})=>{let d=t.position$.getValue(),{playbackCatchupSpeedup:c}=this.params.tuning.dashCmafLive.lowLatency;if(!d&&!this.video.paused&&l>=1-c||dh(o)||dh(u))return;let h=-1*(u-o-e);t.position$.next(Math.min(h,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(o=>{if(o){let u=vx(o);this.params.output.availableTextTracks$.next([u])}}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=Math.trunc(t/1e3<=Math.abs(this.params.output.duration$.getValue())?t:0);this.player.seekLive(i).then(()=>{this.params.output.position$.next(e/1e3)})}};var Ux="X-Playback-Duration",hh=async s=>{var r;let e=await wt(s),t=await e.text(),i=(r=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t))==null?void 0:r[1];return i?parseInt(i,10):e.headers.has(Ux)?parseInt(e.headers.get(Ux),10):void 0};import{assertNever as NV,combine as UV,debounce as qV,ErrorCategory as gl,filter as jV,filterChanged as HV,isNonNullable as Hx,isNullable as Sl,map as zx,merge as zV,observableFrom as QV,Subscription as GV,ValueSubject as bh,VideoQuality as WV}from"@vkontakte/videoplayer-shared/es2018";var mh=N(qc(),1);import{videoSizeToQuality as MV,getExponentialDelay as LV}from"@vkontakte/videoplayer-shared/es2018";var BV=s=>{let e=null;if(s.QUALITY&&(e=Bi(s.QUALITY)),!e&&s.RESOLUTION){let[t,i]=s.RESOLUTION.split("x").map(r=>parseInt(r,10));e=MV({width:t,height:i})}return e!=null?e:null},$V=(s,e)=>{var a,n;let t=s.split(`
186
- `),i=[],r=[];for(let o=0;o<t.length;o++){let u=t[o],l=u.match(/^#EXT-X-STREAM-INF:(.+)/),d=u.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!l&&!d)){if(l){let c=(0,mh.default)(l[1].split(",").map(v=>v.split("="))),h=(a=c.QUALITY)!=null?a:`stream-${c.BANDWIDTH}`,p=BV(c),f;c.BANDWIDTH&&(f=parseInt(c.BANDWIDTH,10)/1e3||void 0),!f&&c["AVERAGE-BANDWIDTH"]&&(f=parseInt(c["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let m=c["FRAME-RATE"]?parseFloat(c["FRAME-RATE"]):void 0,g;if(c.RESOLUTION){let[v,y]=c.RESOLUTION.split("x").map(I=>parseInt(I,10));v&&y&&(g={width:v,height:y})}let S=new URL(t[++o],e).toString();p&&i.push({id:h,quality:p,url:S,bandwidth:f,size:g,fps:m})}if(d){let c=(0,mh.default)(d[1].split(",").map(m=>{let g=m.indexOf("=");return[m.substring(0,g),m.substring(g+1)]}).map(([m,g])=>[m,g.replace(/^"|"$/g,"")])),h=(n=c.URI)==null?void 0:n.replace(/playlist$/,"subtitles.vtt"),p=c.LANGUAGE,f=c.NAME;h&&p&&r.push({type:"internal",id:p,label:f,language:p,url:h,isAuto:!1})}}}if(!i.length)throw new Error("Empty manifest");return{qualityManifests:i,textTracks:r}},DV=s=>new Promise(e=>{setTimeout(()=>{e()},s)}),fh=0,qx=async(s,e=s,t,i)=>{let a=await(await wt(s,i)).text();fh+=1;try{let{qualityManifests:n,textTracks:o}=$V(a,e);return{qualityManifests:n,textTracks:o}}catch(n){if(fh<=t.manifestRetryMaxCount)return await DV(LV(fh-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),qx(s,e,t)}return{qualityManifests:[],textTracks:[]}},ml=qx;import{isNonNullable as CV,Subscription as VV,throttle as OV,ValueSubject as jx,Subject as _V,ErrorCategory as FV}from"@vkontakte/videoplayer-shared/es2018";var bl=class{constructor(e,t,i,r,a){this.subscription=new VV;this.abortControllers={destroy:new ae,nextManifest:null};this.prepareUrl=void 0;this.currentTextTrackData=null;this.availableTextTracks$=new jx(null);this.getCurrentTime$=new jx(null);this.error$=new _V;this.params={fetchManifestData:i,sourceUrl:r,downloadThreshold:a},this.subscription.add(e.pipe(OV(1e3)).subscribe(n=>{this.processLiveTime(n)})),this.getCurrentTime$.next(()=>this.currentTextTrackData?this.currentTextTrackData.playlist.segmentStartTime/1e3+t.currentTime:0)}destroy(){this.subscription.unsubscribe(),this.abortControllers.destroy.abort()}async prepare(e){try{let t=new URL(e);t.searchParams.set("enable-subtitles","yes"),this.prepareUrl=t.toString();let{textTracks:i}=await this.fetchManifestData();await this.processTextTracks(i,this.params.sourceUrl)}catch(t){this.error("prepare",t)}}async processTextTracks(e,t){try{let i=await this.parseTextTracks(e,t);i&&(this.currentTextTrackData=i)}catch(i){this.error("processTextTracks",i)}}async parseTextTracks(e,t){for(let i of e){let r=new URL(i.url,t).toString(),n=await(await wt(r,{signal:this.abortControllers.destroy.signal})).text(),o=this.parsePlaylist(n,r);return{textTrack:i,playlist:o}}}parsePlaylist(e,t){let i={mediaSequence:0,programDateTime:"",segments:[],targetDuration:0,vkPlaybackDuration:0,segmentStartTime:0,vkStartTime:""},r=e.split(`
187
- `),a=0;for(let n=0;n<r.length;++n){let o=r[n];switch(!0){case o.startsWith("#EXTINF:"):{let u=r[++n],l=new URL(u,t).toString(),d=Number(this.extractPlaylistRowValue("#EXTINF:",o))*1e3;if(i.segments.push({time:{from:a,to:a+d},url:l}),a=a+d,!i.segmentStartTime){let c=new Date(i.vkStartTime).valueOf(),h=new Date(i.programDateTime).valueOf();i.segmentStartTime=h-c}break}case o.startsWith("#EXT-X-TARGETDURATION:"):i.targetDuration=Number(this.extractPlaylistRowValue("#EXT-X-TARGETDURATION:",o));break;case o.startsWith("#EXT-X-MEDIA-SEQUENCE:"):i.mediaSequence=Number(this.extractPlaylistRowValue("#EXT-X-MEDIA-SEQUENCE:",o));break;case o.startsWith("#EXT-X-VK-PLAYBACK-DURATION:"):i.vkPlaybackDuration=Number(this.extractPlaylistRowValue("#EXT-X-VK-PLAYBACK-DURATION:",o));break;case o.startsWith("#EXT-X-PROGRAM-DATE-TIME:"):{let u=this.extractPlaylistRowValue("#EXT-X-PROGRAM-DATE-TIME:",o);i.programDateTime=u;let l=new Date(u);l.setMilliseconds(0),a=l.valueOf();break}case o.startsWith("#EXT-X-VK-START-TIME:"):i.vkStartTime=this.extractPlaylistRowValue("#EXT-X-VK-START-TIME:",o);break}}return i}extractPlaylistRowValue(e,t){switch(e){case"#EXTINF:":return t.substring(e.length,t.length-1);default:return t.substring(e.length)}}processLiveTime(e){if(CV(e)&&this.currentTextTrackData){let{segments:t}=this.currentTextTrackData.playlist,{from:i}=t[0].time,{to:r}=t[t.length-1].time;if(e<i||e>r)return;r-e<this.params.downloadThreshold&&this.fetchNextManifestData();for(let n of t)if(n.time.from<=e&&n.time.to>=e){this.availableTextTracks$.next([{...this.currentTextTrackData.textTrack,url:n.url,isAuto:!0}]);break}}}async fetchNextManifestData(){try{if(this.abortControllers.nextManifest)return;this.abortControllers.nextManifest=new ae;let{textTracks:e}=await this.fetchManifestData(),t=await this.parseTextTracks(e,this.params.sourceUrl);this.currentTextTrackData&&t&&(this.currentTextTrackData.playlist.segments=t.playlist.segments)}catch(e){this.error("fetchNextManifestData",e)}finally{this.abortControllers.nextManifest=null}}async fetchManifestData(){var t;let e=(t=this.prepareUrl)!=null?t:this.params.sourceUrl;return await this.params.fetchManifestData(e,{signal:this.abortControllers.destroy.signal})}error(e,t){this.error$.next({id:"[LiveTextManager][HLS_LIVE_CMAF]",category:FV.WTF,thrown:t,message:e})}};var co=class{constructor(e){this.subscription=new GV;this.videoState=new G("stopped");this.textTracksManager=null;this.liveTextManager=null;this.manifests$=new bh([]);this.liveOffset=new or;this.manifestStartTime$=new bh(void 0);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),B(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"?B(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),B(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"&&B(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"&&(B(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return NV(t)}};var i;this.params=e,this.video=tt(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:WV.INVARIANT,url:this.params.source.url};let t=(r,a)=>ml(r,this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},a);this.params.tuning.useHlsLiveNewTextManager?this.liveTextManager=new bl(this.params.output.liveTime$,this.video,t,this.params.source.url,this.params.tuning.hlsLiveNewTextManagerDownloadThreshold):this.textTracksManager=new xt(e.source.url),t(this.generateLiveUrl()).then(({qualityManifests:r,textTracks:a})=>{var n;r.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:gl.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),(n=this.liveTextManager)==null||n.processTextTracks(a,this.params.source.url),this.manifests$.next([this.masterManifest,...r])}).catch(r=>{this.params.output.error$.next({id:"ExtractHlsQualities",category:gl.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:r})}),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Fe(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new bh((i=e.source.maxSeekBackTime)!=null?i:1/0),this.subscribe()}selectManifest(){var u,l,d,c;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),a=(c=(d=(u=r==null?void 0:r.to)==null?void 0:u.id)!=null?d:(l=t.getState())==null?void 0:l.id)!=null?c:"master",n=this.manifests$.getValue();if(!n.length)return;let o=i?"master":a;return i&&!r&&t.startTransitionTo(this.masterManifest),n.find(h=>h.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsLiveProvider",category:gl.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},r=st(this.video);this.subscription.add(()=>r.destroy());let a=(o,u)=>this.subscription.add(o.subscribe(u,i));a(r.ended$,e.endedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.loadedMetadata$,e.loadedMetadataEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(rt(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(It(this.video,t.playbackRate,r.playbackRateState$,i)),a(Et(this.video),e.elementVisible$),this.liveTextManager?(a(this.liveTextManager.getCurrentTime$,this.params.output.getCurrentTime$),a(this.liveTextManager.error$,this.params.output.error$)):this.textTracksManager&&this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),B(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),B(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(HV(),zx(o=>-o/1e3)).subscribe(this.params.output.duration$,i)),this.subscription.add(r.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&Hx(l.to)){let c=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let h=this.manifests$.getValue().find(p=>p.id===c);h&&(this.params.output.currentVideoTrack$.next(h),this.params.output.hostname$.next(Fe(h.url)))}d&&this.params.desiredState.autoVideoTrackSwitching.setState(d.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o&&o.state==="requested"&&this.seek(o.position)},i)),this.subscription.add(r.loadedData$.subscribe(()=>{var u,l,d;let o=(d=(l=(u=this.video)==null?void 0:u.getStartDate)==null?void 0:l.call(u))==null?void 0:d.getTime();this.manifestStartTime$.next(o||void 0)},i)),this.subscription.add(UV({startTime:this.manifestStartTime$.pipe(jV(Hx)),currentTime:r.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),i)),this.subscription.add(this.manifests$.pipe(zx(o=>o.map(({id:u,quality:l,size:d,bandwidth:c,fps:h})=>({id:u,quality:l,size:d,fps:h,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,i));let n=zV(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,QV(["init"])).pipe(qV(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){var e,t;this.subscription.unsubscribe(),(e=this.textTracksManager)==null||e.destroy(),(t=this.liveTextManager)==null||t.destroy(),this.params.output.element$.next(void 0),it(this.video)}prepare(){var o,u,l;let e=this.selectManifest();if(Sl(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:d,min:c}=(u=(o=t==null?void 0:t.to)!=null?o:i)!=null?u:{};for(let[h,p]of[[d,"mq"],[c,"lq"]]){let f=String(parseFloat(h||""));p&&h&&r.searchParams.set(p,f)}}let a=this.params.format==="HLS_LIVE_CMAF"?2:0,n=Se(r.toString(),this.liveOffset.getTotalOffset(),a);(l=this.liveTextManager)==null||l.prepare(n),this.video.setAttribute("src",n),this.video.load(),hh(n).then(d=>{var c;if(!Sl(d))this.maxSeekBackTime$.next(d);else{let h=(c=this.params.source.maxSeekBackTime)!=null?c:this.maxSeekBackTime$.getValue();(Sl(h)||!isFinite(h))&&wt(n).then(p=>p.text()).then(p=>{var m;let f=(m=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(p))==null?void 0:m[1];if(f){let g=new URL(f,n).toString();hh(g).then(S=>{Sl(S)||this.maxSeekBackTime$.next(S)})}}).catch(()=>{})}})}playIfAllowed(){at(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),B(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:gl.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3),this.params.output.seekedEvent$.next()}generateLiveUrl(){let e=Se(this.params.source.url);if(this.params.tuning.useHlsLiveNewTextManager){let t=new URL(e);t.searchParams.set("enable-subtitles","yes"),e=t.toString()}return e}};import{assertNever as YV,debounce as KV,ErrorCategory as gh,fromEvent as Sh,isNonNullable as XV,isNullable as JV,map as Qx,merge as Gx,observableFrom as Wx,Subscription as ZV,ValueSubject as eO,VideoQuality as tO}from"@vkontakte/videoplayer-shared/es2018";var po=class{constructor(e){this.subscription=new ZV;this.videoState=new G("stopped");this.manifests$=new eO([]);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"),B(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"?B(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),B(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"&&B(this.params.desiredState.playbackState,"playing");return;case"paused":i==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&B(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return YV(t)}};this.textTracksManager=new xt(e.source.url),this.params=e,this.video=tt(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:tO.INVARIANT,url:this.params.source.url},this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Fe(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),ml(Se(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:t,textTracks:i})=>{this.manifests$.next([this.masterManifest,...t]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(i)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:gh.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){var u,l,d,c;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),a=(c=(d=(u=r==null?void 0:r.to)==null?void 0:u.id)!=null?d:(l=t.getState())==null?void 0:l.id)!=null?c:"master",n=this.manifests$.getValue();if(!n.length)return;let o=i?"master":a;return i&&(!r||!r.from)&&t.startTransitionTo(this.masterManifest),n.find(h=>h.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsProvider",category:gh.WTF,message:"HlsProvider internal logic error",thrown:o})},r=st(this.video);this.subscription.add(()=>r.destroy());let a=(o,u)=>this.subscription.add(o.subscribe(u));if(a(r.timeUpdate$,e.position$),a(r.durationChange$,e.duration$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.loadedMetadata$,e.loadedMetadataEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.seeked$,e.seekedEvent$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),a(this.videoState.stateChangeEnded$.pipe(Qx(o=>o.to)),this.params.output.playbackState$),this.subscription.add(zt(this.video,t.isLooped,i)),this.subscription.add(rt(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(It(this.video,t.playbackRate,r.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),B(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),B(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&&XV(l.to)){let f=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let m=this.manifests$.getValue().find(g=>g.id===f);m&&(this.params.output.currentVideoTrack$.next(m),this.params.output.hostname$.next(Fe(m.url)))}let c=this.params.desiredState.playbackRate.getState(),h=(p=this.params.output.element$.getValue())==null?void 0:p.playbackRate;if(c!==h){let f=this.params.output.element$.getValue();f&&(this.params.desiredState.playbackRate.setState(c),f.playbackRate=c)}d&&this.params.desiredState.autoVideoTrackSwitching.setState(d.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o.state==="requested"&&this.seek(o.position)},i))),this.subscription.add(this.manifests$.pipe(Qx(o=>o.map(({id:u,quality:l,size:d,bandwidth:c,fps:h})=>({id:u,quality:l,size:d,fps:h,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,i)),!j.device.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(Gx(Sh(o,"addtrack"),Sh(o,"removetrack"),Sh(o,"change"),Wx(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},i))}let n=Gx(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,Wx(["init"])).pipe(KV(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),it(this.video)}prepare(){var a,n;let e=this.selectManifest();if(JV(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:o,min:u}=(n=(a=t==null?void 0:t.to)!=null?a:i)!=null?n:{};for(let[l,d]of[[o,"mq"],[u,"lq"]]){let c=String(parseFloat(l||""));d&&l&&r.searchParams.set(d,c)}}this.video.setAttribute("src",r.toString()),this.video.load()}playIfAllowed(){at(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),B(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:gh.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var Xx=N(Ji(),1),vh=N(nr(),1),Jx=N(Ot(),1);import{assertNever as iO,assertNonNullable as Yx,debounce as rO,ErrorCategory as Kx,isHigherOrEqual as sO,isLowerOrEqual as aO,isNonNullable as nO,merge as oO,observableFrom as uO,Subscription as lO,map as cO}from"@vkontakte/videoplayer-shared/es2018";var ho=class{constructor(e){this.subscription=new lO;this.videoState=new G("stopped");this.trackUrls={};this.textTracksManager=new xt;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),B(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"?B(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),B(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"&&B(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&B(this.params.desiredState.playbackState,"paused");return;default:return iO(e)}};this.params=e,this.video=tt(e.container,e.tuning),this.params.output.element$.next(this.video),(0,Xx.default)(this.params.source).reverse().forEach(([t,i],r)=>{let a=r.toString(10);this.trackUrls[a]={track:{quality:t,id:a},url:i}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next((0,vh.default)(this.trackUrls).map(({track:t})=>t)),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.subscribe()}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"MpegProvider",category:Kx.WTF,message:"MpegProvider internal logic error",thrown:o})},r=st(this.video);this.subscription.add(()=>r.destroy());let a=(o,u)=>this.subscription.add(o.subscribe(u,i));a(r.timeUpdate$,e.position$),a(r.durationChange$,e.duration$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.loadedMetadata$,e.loadedMetadataEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.seeked$,e.seekedEvent$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),a(this.videoState.stateChangeEnded$.pipe(cO(o=>o.to)),this.params.output.playbackState$),this.subscription.add(zt(this.video,t.isLooped,i)),this.subscription.add(rt(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(It(this.video,t.playbackRate,r.playbackRateState$,i)),a(Et(this.video),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),B(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),B(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&&nO(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=oO(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,uO(["init"])).pipe(rO(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),it(this.video)}prepare(){var i;let e=(i=this.params.desiredState.videoTrack.getState())==null?void 0:i.id;Yx(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];Yx(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=Vi(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(Fe(t))}playIfAllowed(){at(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),B(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Kx.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){var l,d;this.params.output.autoVideoTrackLimits$.next(e);let t=c=>{this.params.output.currentVideoTrack$.next(c),this.params.desiredState.videoTrack.startTransitionTo(c)},i=c=>{let h=Wt(n,{container:this.video.getBoundingClientRect(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,limits:c,abrLogger:this.params.dependencies.abrLogger});t(h)},r=(l=this.params.output.currentVideoTrack$.getValue())==null?void 0:l.quality,a=!!(e.max||e.min),n=(0,vh.default)(this.trackUrls).map(c=>c.track);if(!r||!a||qr(e,n[0].quality,(d=(0,Jx.default)(n,-1))==null?void 0:d.quality)){i();return}let o=e.max?aO(r,e.max):!0,u=e.min?sO(r,e.min):!0;o&&u||i(e)}};import{assertNever as eE,debounce as fO,merge as tE,observableFrom as mO,Subscription as bO,map as iE,ValueSubject as gO,ErrorCategory as Th,VideoQuality as SO}from"@vkontakte/videoplayer-shared/es2018";import{ErrorCategory as dO}from"@vkontakte/videoplayer-shared/es2018";var Zx=["stun:videostun.mycdn.me:80"],pO=1e3,hO=3,yh=()=>null,vl=class{constructor(e,t){this.ws=null;this.peerConnection=null;this.serverUrl="";this.streamKey="";this.stream=null;this.signalingType="JOIN";this.retryCount=0;this.externalStartCallback=yh;this.externalStopCallback=yh;this.externalErrorCallback=yh;this.options=this.normalizeOptions(t);let i=e.split("/");this.serverUrl=i.slice(0,i.length-1).join("/"),this.streamKey=i[i.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{let t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}async handleUpdateMessage(e){try{let t=await this.createOffer();this.peerConnection&&await this.peerConnection.setLocalDescription(t),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}}async handleLogin(){try{let e={iceServers:[{urls:Zx}]};this.peerConnection=new RTCPeerConnection(e),this.peerConnection.ontrack=this.onPeerConnectionStream.bind(this),this.peerConnection.onicecandidate=this.onPeerConnectionIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onPeerConnectionIceConnectionStateChange.bind(this);let t=await this.createOffer();await this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}}async handleAnswer(e){try{this.peerConnection&&await this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e}))}catch(t){this.handleRTCError(t)}}async handleCandidate(e){if(e)try{this.peerConnection&&await this.peerConnection.addIceCandidate(e)}catch(t){this.handleRTCError(t)}}handleUnpublished(){try{this.closeConnections(),this.externalStopCallback()}catch(e){this.handleRTCError(e)}}handleSystemError(e){this.options.errorChanel&&this.options.errorChanel.next({id:"webrtc-provider-error",category:dO.WTF,message:e.message})}async onPeerConnectionStream(e){let t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){let e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}async createOffer(){let e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");let t=await this.peerConnection.createOffer(e),i=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(i))throw new Error("No h264 codec support error");return t}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch(t){throw new Error("Can not parse socket message")}}closeConnections(){let e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),pO)}normalizeOptions(e={}){let t={stunServerList:Zx,maxRetryNumber:hO,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var fo=class{constructor(e){this.videoState=new G("stopped");this.maxSeekBackTime$=new gO(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"),B(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"),B(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"&&B(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&B(this.params.desiredState.playbackState,"paused");return;default:return eE(e)}};this.subscription=new bO,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=tt(e.container,e.tuning),this.liveStreamClient=new vl(this.params.source.url,{maxRetryNumber:this.params.tuning.webrtc.connectionRetryMaxNumber,errorChanel:this.params.output.error$}),this.liveStreamClient.onStart(this.onLiveStreamStart.bind(this)),this.liveStreamClient.onStop(this.onLiveStreamStop.bind(this)),this.liveStreamClient.onError(this.onLiveStreamError.bind(this)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),it(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,i=n=>{e.error$.next({id:"WebRTCLiveProvider",category:Th.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};this.subscription.add(tE(this.videoState.stateChangeStarted$.pipe(iE(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(iE(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})}));let r=st(this.video);this.subscription.add(()=>r.destroy());let a=(n,o)=>this.subscription.add(n.subscribe(o,i));a(r.timeUpdate$,e.liveTime$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(Et(this.video),this.params.output.elementVisible$),this.subscription.add(r.durationChange$.subscribe(n=>{e.duration$.next(n===1/0?0:n)})).add(r.canplay$.subscribe(()=>{var n;((n=this.videoState.getTransition())==null?void 0:n.to)==="ready"&&this.videoState.setState("ready")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused")},i)).add(r.playing$.subscribe(()=>{this.videoState.setState("playing")},i)).add(r.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(rt(this.video,t.volume,r.volumeState$,i)).add(r.volumeState$.subscribe(e.volume$,i)).add(this.videoState.stateChangeEnded$.subscribe(n=>{switch(n.to){case"stopped":e.position$.next(0),e.duration$.next(0),t.playbackState.setState("stopped");break;case"ready":break;case"paused":t.playbackState.setState("paused");break;case"playing":t.playbackState.setState("playing");break;default:return eE(n.to)}},i)).add(tE(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,mO(["init"])).pipe(fO(0)).subscribe(this.syncPlayback.bind(this),i)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),i))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(Fe(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.currentVideoTrack$.next({id:"webrtc",quality:SO.INVARIANT}),this.video.srcObject=e,B(this.params.desiredState.playbackState,"playing")}onLiveStreamStop(){this.videoState.startTransitionTo("stopped"),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.params.output.endedEvent$.next()}onLiveStreamError(e){this.onLiveStreamStop(),this.params.output.error$.next({id:"WebRTC stream runtime error",category:Th.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){at(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),B(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Th.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var mo=class{constructor(e){this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next()}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return!!this.current.done}};import{assertNever as go,assertNonNullable as Ni,ErrorCategory as yl,filter as uE,isNonNullable as lE,isNullable as wO,map as AO,merge as PO,once as RO,Subject as De,Subscription as cE,ValueSubject as W,flattenObject as Ih}from"@vkontakte/videoplayer-shared/es2018";import{Observable as vO,map as rE,Subscription as yO,Subject as TO}from"@vkontakte/videoplayer-shared/es2018";var sE=s=>new vO(e=>{let t=new yO,i=s.desiredPlaybackState$.stateChangeStarted$.pipe(rE(({from:l,to:d})=>`${l}-${d}`)),r=s.desiredPlaybackState$.stateChangeEnded$,a=s.providerChanged$.pipe(rE(({type:l})=>l!==void 0)),n=new TO,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 IO,Subscription as xO,combine as EO,filter as nE,once as oE}from"@vkontakte/videoplayer-shared/es2018";function aE(){return new(window.AudioContext||window.webkitAudioContext)}var bo=class bo{constructor(e,t,i,r){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=i;this.volumeMultiplier=r;this.destroyController=new ae;this.subscriptions=new xO;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe(nE(a=>!!a.type),oE()).subscribe(({type:a})=>this.subscribe(a)))}subscribe(e){j.browser.isSafari&&e!=="MPEG"||this.subscriptions.add(EO({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(nE(({playbackState:t,video:i,volume:{muted:r,volume:a}})=>t==="playing"&&!!i&&!r&&!!a),oE()).subscribe(({video:t})=>{this.initAudioContextOnce(t).then(i=>{i||this.destroy()}).catch(i=>{this.handleError(i),this.destroy()})}))}static isSupported(){return"AudioContext"in window&&"GainNode"in window&&"MediaElementAudioSourceNode"in window}async initAudioContextOnce(e){let{volumeMultiplier:t}=this,i=aE();this.audioContext=i;let r=i.createGain();if(this.gainNode=r,r.gain.value=t,r.connect(i.destination),i.state==="suspended"&&(await i.resume(),this.destroyController.signal.aborted))return!1;let a=i.createMediaElementSource(e);return this.mediaElementSource=a,a.connect(r),!0}cleanup(){this.mediaElementSource&&(this.mediaElementSource.disconnect(),this.mediaElementSource=null),this.gainNode&&(this.gainNode.disconnect(),this.gainNode=null),this.audioContext&&(this.audioContext.state!=="closed"&&this.audioContext.close(),this.audioContext=null)}destroy(){this.destroyController.abort(),this.subscriptions.unsubscribe(),this.cleanup()}handleError(e){var t;this.volumeMultiplierError$.next({id:bo.errorId,category:IO.VIDEO_PIPELINE,message:(t=e==null?void 0:e.message)!=null?t:`${bo.errorId} exception`,thrown:e})}};bo.errorId="VolumeMultiplierManager";var ms=bo;var kO={chunkDuration:5e3,maxParallelRequests:5},So=class{constructor(e){this.current$=new W({type:void 0});this.providerError$=new De;this.noAvailableProvidersError$=new De;this.volumeMultiplierError$=new De;this.providerOutput={position$:new W(0),duration$:new W(1/0),volume$:new W({muted:!1,volume:1}),availableVideoStreams$:new W([]),currentVideoStream$:new W(void 0),availableVideoTracks$:new W([]),currentVideoTrack$:new W(void 0),availableAudioStreams$:new W([]),currentAudioStream$:new W(void 0),availableAudioTracks$:new W([]),currentVideoSegmentLength$:new W(0),currentAudioSegmentLength$:new W(0),isAudioAvailable$:new W(!0),autoVideoTrackLimitingAvailable$:new W(!1),autoVideoTrackLimits$:new W(void 0),currentBuffer$:new W(void 0),isBuffering$:new W(!0),error$:new De,fetcherError$:new De,fetcherRecoverableError$:new De,warning$:new De,willSeekEvent$:new De,soundProhibitedEvent$:new De,seekedEvent$:new De,loopedEvent$:new De,endedEvent$:new De,firstBytesEvent$:new De,loadedMetadataEvent$:new De,firstFrameEvent$:new De,canplay$:new De,isLive$:new W(void 0),isLiveEnded$:new W(null),isLowLatency$:new W(!1),canChangePlaybackSpeed$:new W(!0),liveTime$:new W(void 0),liveBufferTime$:new W(void 0),liveLatency$:new W(void 0),severeStallOccurred$:new De,availableTextTracks$:new W([]),currentTextTrack$:new W(void 0),hostname$:new W(void 0),httpConnectionType$:new W(void 0),httpConnectionReused$:new W(void 0),inPiP$:new W(!1),inFullscreen$:new W(!1),element$:new W(void 0),elementVisible$:new W(!0),availableSources$:new W(void 0),is3DVideo$:new W(!1),playbackState$:new W(""),getCurrentTime$:new W(null)};this.subscription=new cE;this.volumeMultiplierManager=null;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer"),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name);let t=UI([...jI(this.params.tuning),...qI(this.params.tuning)],this.params.tuning).filter(l=>lE(e.sources[l])),{forceFormat:i,formatsToAvoid:r}=this.params.tuning,a=[];i?a=[i]:r.length?a=[...t.filter(l=>!(0,xh.default)(r,l)),...t.filter(l=>(0,xh.default)(r,l))]:a=t,this.log({message:`Selected formats: ${a.join(" > ")}`}),this.tracer.log("Selected formats",Ih(a)),this.screenFormatsIterator=new mo(a);let n=[...xp(!0),...xp(!1)];this.chromecastFormatsIterator=new mo(n.filter(l=>lE(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:o=1,tuning:{useVolumeMultiplier:u}}=this.params;u&&o!==1&&ms.isSupported()&&(this.volumeMultiplierManager=new ms(this.providerOutput,this.current$,this.volumeMultiplierError$,o))}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()}))}destroy(){var e;this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe(),(e=this.volumeMultiplierManager)==null||e.destroy(),this.volumeMultiplierManager=null,this.tracer.end()}initProvider(){let e=this.chooseDestination(),t=this.chooseFormat(e);if(wO(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:yl.WTF,message:"Failed to create provider",thrown:r})}i?this.current$.next({type:t,provider:i,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.tracer.log("reinitProvider"),this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.tracer.log("switchToNextProvider",{destination:e}),this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}destroyProvider(){let e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"}),this.tracer.log("destroyProvider"),e.destroy();let t=this.providerOutput.position$.getValue()*1e3,i=this.params.desiredState.seekState.getState(),r=i.state!=="none";if(this.params.desiredState.seekState.setState({state:"requested",position:r?i.position:t,forcePrecise:r?i.forcePrecise:!1}),e.scene3D){let n=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:n.x,y:n.y})}let a=this.providerOutput.isBuffering$;a.getValue()||a.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),this.tracer.log("createProvider",{destination:e,format:t}),e){case"SCREEN":return this.createScreenProvider(t);case"CHROMECAST":return this.createChromecastProvider(t);default:return go(e)}}createScreenProvider(e){let{sources:t,container:i,desiredState:r,panelSize:a}=this.params,n=this.providerOutput,o={container:i,source:null,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning,panelSize:a};switch(e){case"DASH_SEP":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_ONDEMAND":case"DASH_STREAMS":{let u=this.applyFailoverHost(t[e]),l=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return Ni(u),this.params.tuning.useNewDashProvider?new uo({...o,source:u,sourceHls:l}):new wn({...o,source:u,sourceHls:l})}case"DASH_LIVE_CMAF":{let u=this.applyFailoverHost(t[e]);return Ni(u),this.params.tuning.useNewDashProvider?new lo({...o,source:u}):new An({...o,source:u})}case"HLS":case"HLS_ONDEMAND":{let u=this.applyFailoverHost(t[e]);return Ni(u),new po({...o,source:u})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let u=this.applyFailoverHost(t[e]);return Ni(u),new co({...o,source:u,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let u=this.applyFailoverHost(t[e]);return Ni(u),new ho({...o,source:u})}case"DASH_LIVE":{let u=this.applyFailoverHost(t[e]);return Ni(u),new Uy({...o,source:u,config:{...kO,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let u=this.applyFailoverHost(t[e]);return Ni(u),new fo({container:i,source:u,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return go(e)}}createChromecastProvider(e){let{sources:t,container:i,desiredState:r,meta:a}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return Ni(o),new xa({connection:o,meta:a,container:i,source:t,format:e,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?"CHROMECAST":"SCREEN"}chooseFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case"CHROMECAST":return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return go(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return go(e)}}handleNoFormatsError(e){switch(e){case"SCREEN":this.noAvailableProvidersError$.next(this.params.tuning.forceFormat),this.current$.next({type:void 0});return;case"CHROMECAST":this.params.dependencies.chromecastInitializer.disconnect();return;default:return go(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;let t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;let i=r=>{let a=new URL(r);return a.host=t,a.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return{...e,url:i(e.url)}}return(0,pE.default)((0,dE.default)(e).map(([r,a])=>[r,i(a)]))}initProviderErrorHandling(){let e=new cE,t=!1,i=0;return e.add(PO(this.providerOutput.error$.pipe(uE(r=>!this.params.tuning.ignoreAudioRendererError||!r.message||!/AUDIO_RENDERER_ERROR/ig.test(r.message))),sE({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(AO(r=>({id:`ProviderHangup:${r}`,category:yl.WTF,message:`A ${r} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.providerOutput.fetcherError$.subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;let r=this.params.desiredState.playbackState.transitionEnded$.pipe(uE(({to:a})=>a==="playing"),RO()).subscribe(()=>t=!0);e.add(r)})),e.add(this.providerError$.subscribe(r=>{let a=this.current$.getValue().destination,n={error:r,currentDestination:a};if(a==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("SCREEN"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let o=r.category===yl.NETWORK,u=r.category===yl.FATAL,l=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),d=i<this.params.tuning.providerErrorLimit&&!u,c=l&&!u&&(o&&t||!d);n={...n,isNetworkError:o,isFatalError:u,haveFailoverHost:l,tryFailover:c,canReinitProvider:d},d?(i++,this.reinitProvider()):c?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):(i=0,this.switchToNextProvider(a!=null?a:"SCREEN"))}r.traceAsLog?this.tracer.log("providerInfo",Ih(n)):this.tracer.error("providerError",Ih(n))})),e}};import{fromEvent as Tl,once as MO,combine as LO,Subscription as hE,ValueSubject as Eh,map as BO,filter as $O,isNonNullable as Il,now as yt,safeStorage as wh}from"@vkontakte/videoplayer-shared/es2018";var DO=5e3,fE="one_video_throughput",mE="one_video_rtt",Ei=window.navigator.connection,bE=()=>{let s=Ei==null?void 0:Ei.downlink;if(Il(s)&&s!==10)return s*1e3},gE=()=>{let s=Ei==null?void 0:Ei.rtt;if(Il(s)&&s!==3e3)return s},SE=(s,e,t)=>{let i=t*8,r=i/s;return i/(r+e)},Ah=class s{constructor(e){this.subscription=new hE;this.concurrentDownloads=new Set;var r,a;this.tuningConfig=e;let t=s.load(fE)||(e.useBrowserEstimation?bE():void 0)||DO,i=(a=(r=s.load(mE))!=null?r:e.useBrowserEstimation?gE():void 0)!=null?a:0;if(this.throughput$=new Eh(t),this.rtt$=new Eh(i),this.rttAdjustedThroughput$=new Eh(SE(t,i,e.rttPenaltyRequestSize)),this.throughput=yi.getSmoothedValue(t,-1,e),this.rtt=yi.getSmoothedValue(i,1,e),e.useBrowserEstimation){let n=()=>{let u=bE();u&&this.throughput.next(u);let l=gE();Il(l)&&this.rtt.next(l)};Ei&&"onchange"in Ei&&this.subscription.add(Tl(Ei,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{wh.set(fE,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{wh.set(mE,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(LO({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(BO(({throughput:n,rtt:o})=>SE(n,o,e.rttPenaltyRequestSize)),$O(n=>{let o=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(n-o)/o>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,i=yt(),r=new hE;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add(Tl(e,"progress").pipe(MO()).subscribe(a=>{t=a.loaded,i=yt()}));break;case 1:case 0:r.add(Tl(e,"loadstart").subscribe(()=>{t=0,i=yt()}));break}r.add(Tl(e,"loadend").subscribe(a=>{if(e.status===200){let n=a.loaded,o=yt(),u=n-t,l=o-i;this.addRawSpeed(u,l,1)}this.concurrentDownloads.delete(e),r.unsubscribe()}))}trackStream(e,t=!1){let i=e.getReader();if(!i){e.cancel("Could not get reader");return}let r=0,a=yt(),n=0,o=yt(),u=d=>{this.concurrentDownloads.delete(e),i.releaseLock(),e.cancel(`Throughput Estimator error: ${d}`).catch(()=>{})},l=async({done:d,value:c})=>{if(d)!t&&this.addRawSpeed(r,yt()-a,1),this.concurrentDownloads.delete(e);else if(c){if(t){let h=yt();if(h-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||h-a>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let f=o-a;f&&this.addRawSpeed(n,f,1,t),n=c.byteLength,a=yt()}else n+=c.byteLength;o=yt()}else r+=c.byteLength,n+=c.byteLength,n>=this.tuningConfig.streamMinSampleSize&&yt()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,yt()-o,this.concurrentDownloads.size),n=0,o=yt());await(i==null?void 0:i.read().then(l,u))}};this.concurrentDownloads.add(e),i==null||i.read().then(l,u)}addRawSpeed(e,t,i=1,r=!1){if(s.sanityCheck(e,t,r)){let a=e*8/t;this.throughput.next(a*i)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,i=!1){let r=e*8/t;return!(!r||!isFinite(r)||r>1e6||r<30||i&&e<1e4||!i&&e<10*1024||!i&&t<=20)}static load(e){var i;let t=wh.get(e);if(Il(t))return(i=parseInt(t,10))!=null?i:void 0}},vE=Ah;import{fillWithDefault as CO,VideoQuality as xl}from"@vkontakte/videoplayer-shared/es2018";var yE={configName:["core"],throughputEstimator:{type:"EmaAndMa",emaAlphaSlow:.2,emaAlphaFast:.7,emaAlpha:.45,basisTrendChangeCount:10,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1*1024*1024,streamMinSampleSize:10*1024,streamMinSampleTime:300,deviationDepth:20,deviationFactor:.5,lowLatency:{continuesByteSequenceInterval:50,maxLastEvaluationTimeout:300}},autoTrackSelection:{maxBitrateFactorAtEmptyBuffer:4,bitrateFactorAtEmptyBuffer:2.8,minBitrateFactorAtEmptyBuffer:1.5,bitrateAudioFactorAtEmptyBuffer:10,maxBitrateFactorAtFullBuffer:3,bitrateFactorAtFullBuffer:2,minBitrateFactorAtFullBuffer:1,bitrateAudioFactorAtFullBuffer:7,minVideoAudioRatio:5,minAvailableThroughputAudioRatio:5,usePixelRatio:!0,pixelRatioMultiplier:void 0,pixelRatioLogBase:3,pixelRatioLogCoefficients:[1,0,1],limitByContainer:!0,maxContainerSizeFactor:2,containerSizeFactor:1.3,minContainerSizeFactor:1,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldownIncreaseQuality:15e3,trackCooldownDecreaseQuality:3e3,backgroundVideoQualityLimit:xl.Q_4320P,activeVideoAreaThreshold:.1,highQualityLimit:xl.Q_720P,trafficSavingLimit:xl.Q_480P},stallsManager:{enabled:!1,stallDurationNoDataBeforeQualityDecrease:500,stallDurationToBeCount:100,stallCountBeforeQualityDecrease:3,resetQualityRestrictionTimeout:1e4,ignoreStallsOnSeek:!0,stallsMetricsHistoryLength:5,maxPossibleStallDuration:3e4,minTvtToBeCounted:5,maxTvtToBeCounted:10800,significantTvt:600,targetStallsDurationPerTvt:1,deviationStallsDurationPerTvt:.5,criticalStallsDurationPerTvt:6,abrAdjustingSpeed:.1,emaAlpha:.6,useTotalStallsDurationPerTvt:!0,useAverageStallsDurationPerTvt:!0,useEmaStallsDurationPerTvt:!0},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:xl.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,seekBiasInTheEnd:2e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,crashOnStallTimeout:25e3,crashOnStallTWithoutDataTimeout:5e3,enableSubSegmentBufferFeeding:!0,bufferEmptinessTolerance:100,useFetchPriorityHints:!0,enableBaseUrlSupport:!0,maxSegmentRetryCount:5,sourceOpenTimeout:1e3,vktvAbrThrottle:0,timeupdateEventTickThrottle:300},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,maxLiveDuration:7200,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:250,playbackCatchupSpeedup:.05,isActiveOnDefault:!1,bufferEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:"07A4434E",useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"dash",preferCMAF:!1,preferWebRTC:!1,preferMultiStream:!1,preferHDR:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,seekNearDurationBias:1,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useHlsJs:!1,useNativeHLSTextTracks:!1,useManagedMediaSource:!0,useNewSwitchTo:!1,useNewDashProvider:!1,useNewAutoSelectVideoTrack:!1,useSafariEndlessRequestBugfix:!0,useRefactoredSearchGap:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,audioVideoSyncRate:20,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50},useVolumeMultiplier:!1,ignoreAudioRendererError:!1,useEnableSubtitlesParam:!1,useOldMSEDetection:!1,useHlsLiveNewTextManager:!1,exposeInternalsToGlobal:!1,hlsLiveNewTextManagerDownloadThreshold:4e3,disableYandexPiP:!1,asyncResolveClientChecker:!1,autostartOnlyIfVisible:!1},TE=s=>{var e;return{...CO(s,yE),configName:[...(e=s.configName)!=null?e:[],...yE.configName]}};import{assertNonNullable as El,combine as wi,ErrorCategory as wl,filter as z,filterChanged as te,fromEvent as Rh,isNonNullable as wE,isNullable as qO,Logger as jO,map as Z,mapTo as AE,merge as Ui,now as Al,once as Y,Subject as ie,Subscription as PE,tap as kh,ValueSubject as D,isHigher as HO,isInvariantQuality as RE,flattenObject as qi,throttle as Mh,getTraceSubscriptionMethod as kE,TracerFactory as zO,InternalsExposure as QO}from"@vkontakte/videoplayer-shared/es2018";import{merge as VO,map as OO,filter as IE,isNonNullable as _O}from"@vkontakte/videoplayer-shared/es2018";var Ph=({seekState:s,position$:e})=>VO(s.stateChangeEnded$.pipe(OO(({to:t})=>{var i;return t.state==="none"?void 0:((i=t.position)!=null?i:NaN)/1e3}),IE(_O)),e.pipe(IE(()=>s.getState().state==="none")));import{assertNonNullable as FO}from"@vkontakte/videoplayer-shared/es2018";var xE=s=>{let e=typeof s.container=="string"?document.getElementById(s.container):s.container;return FO(e,`Wrong container or containerId {${s.container}}`),e};import{filter as NO,once as UO}from"@vkontakte/videoplayer-shared/es2018";var EE=(s,e,t,i)=>{s!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&(t==null?void 0:t.getValue().length)===0?t.pipe(NO(r=>r.length>0),UO()).subscribe(r=>{r.find(i)&&e.startTransitionTo(s)}):(s===void 0||t!=null&&t.getValue().find(i))&&e.startTransitionTo(s)};var Pl=class{constructor(e={configName:[]},t=zO.createRootTracer(!1)){this.subscription=new PE;this.logger=new jO;this.abrLogger=this.logger.createComponentLog("ABR");this.internalsExposure=null;this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new D(!1);this.hasLiveOffsetByPausedTimer=0;this.playerInitRequest=0;this.playerInited=new D(!1);this.wasSetStartedQuality=!1;this.desiredState={playbackState:new G("stopped"),seekState:new G({state:"none"}),volume:new G({volume:1,muted:!1}),videoTrack:new G(void 0),videoStream:new G(void 0),audioStream:new G(void 0),autoVideoTrackSwitching:new G(!0),autoVideoTrackLimits:new G({}),isLooped:new G(!1),isLowLatency:new G(!1),playbackRate:new G(1),externalTextTracks:new G([]),internalTextTracks:new G([]),currentTextTrack:new G(void 0),textTrackCuesSettings:new G({}),cameraOrientation:new G({x:0,y:0})};this.info={playbackState$:new D(void 0),position$:new D(0),duration$:new D(1/0),muted$:new D(!1),volume$:new D(1),availableVideoStreams$:new D([]),currentVideoStream$:new D(void 0),availableQualities$:new D([]),availableQualitiesFps$:new D({}),currentQuality$:new D(void 0),isAutoQualityEnabled$:new D(!0),autoQualityLimitingAvailable$:new D(!1),autoQualityLimits$:new D({}),predefinedQualityLimitType$:new D("unknown"),availableAudioStreams$:new D([]),currentAudioStream$:new D(void 0),availableAudioTracks$:new D([]),isAudioAvailable$:new D(!0),currentPlaybackRate$:new D(1),currentBuffer$:new D({start:0,end:0}),isBuffering$:new D(!0),isStalled$:new D(!1),isEnded$:new D(!1),isLooped$:new D(!1),isLive$:new D(void 0),isLiveEnded$:new D(null),canChangePlaybackSpeed$:new D(void 0),atLiveEdge$:new D(void 0),atLiveDurationEdge$:new D(void 0),liveTime$:new D(void 0),liveBufferTime$:new D(void 0),liveLatency$:new D(void 0),currentFormat$:new D(void 0),availableTextTracks$:new D([]),currentTextTrack$:new D(void 0),throughputEstimation$:new D(void 0),rttEstimation$:new D(void 0),videoBitrate$:new D(void 0),hostname$:new D(void 0),httpConnectionType$:new D(void 0),httpConnectionReused$:new D(void 0),surface$:new D("none"),chromecastState$:new D("NOT_AVAILABLE"),chromecastDeviceName$:new D(void 0),intrinsicVideoSize$:new D(void 0),availableSources$:new D(void 0),is3DVideo$:new D(!1),currentVideoSegmentLength$:new D(0),currentAudioSegmentLength$:new D(0)};this.events={inited$:new ie,ready$:new ie,started$:new ie,playing$:new ie,paused$:new ie,stopped$:new ie,willReady$:new ie,willStart$:new ie,willResume$:new ie,willPause$:new ie,willStop$:new ie,willDestruct$:new ie,watchCoverageRecord$:new ie,watchCoverageLive$:new ie,managedError$:new ie,fatalError$:new ie,fetcherRecoverableError$:new ie,ended$:new ie,looped$:new ie,seeked$:new ie,willSeek$:new ie,autoplaySoundProhibited$:new ie,firstBytes$:new ie,loadedMetadata$:new ie,firstFrame$:new ie,canplay$:new ie,log$:new ie,fetcherError$:new ie,severeStallOccured$:new ie};this.experimental={element$:new D(void 0),tuningConfigName$:new D([]),enableDebugTelemetry$:new D(!1),dumpTelemetry:hy,getCurrentTime$:new D(null)};if(this.initLogs(),this.tuning=TE(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new Ao({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new vE(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new QO("CORE"),this.internalsExposure.expose({player:this})),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(i,r,a)=>{let n=Reflect.get(i,r,a);return typeof n!="function"?n:(...o)=>{try{return n.apply(i,o)}catch(u){let l=o.map(h=>JSON.stringify(h,(p,f)=>{let m=typeof f;return(0,ME.default)(["number","string","boolean"],m)?f:f===null?null:`<${m}>`})),d=`Player.${String(r)}`,c=`Exception calling ${d} (${l.join(", ")})`;throw this.events.fatalError$.next({id:d,category:wl.WTF,message:c,thrown:u}),u}}}})}initVideo(e){var a;this.config=e,(a=this.internalsExposure)==null||a.expose({config:e,logger:this.logger,tuning:this.tuning}),this.setMuted(this.tuning.isAudioDisabled);let t=()=>{var u,l,d;let{container:n,...o}=e;this.tracer.log("initVideo",qi(o)),this.domContainer=xE(e),this.chromecastInitializer.contentId=(u=e.meta)==null?void 0:u.videoId,this.providerContainer=new So({sources:e.sources,meta:(l=e.meta)!=null?l:{},failoverHosts:(d=e.failoverHosts)!=null?d:[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,tracer:this.tracer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning,volumeMultiplier:e.volumeMultiplier,panelSize:e.panelSize}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.initTracerSubscription(),this.providerContainer.init(),this.setLiveLowLatency(this.tuning.dashCmafLive.lowLatency.isActiveOnDefault),this.initDebugTelemetry(),this.initWakeLock(),this.playerInited.next(!0)},i=()=>{this.tuning.autostartOnlyIfVisible&&window.requestAnimationFrame?this.playerInitRequest=window.requestAnimationFrame(()=>t()):t()},r=()=>{this.tuning.asyncResolveClientChecker?j.isInited$.pipe(z(n=>!!n),Y()).subscribe(()=>{console.log("Core SDK async start"),i()}):i()};return this.isNotActiveTabCase()?(this.tracer.log("request play from hidden tab"),Rh(document,"visibilitychange").pipe(Y()).subscribe(r)):r(),this}destroy(){var e,t;this.tracer.log("destroy"),window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.playerInitRequest&&window.cancelAnimationFrame(this.playerInitRequest),this.events.willDestruct$.next(),this.stop(),(e=this.providerContainer)==null||e.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe(),this.tracer.end(),(t=this.internalsExposure)==null||t.destroy()}prepare(){return this.subscription.add(this.playerInited.pipe(z(e=>!!e),Y()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("prepare",{currentPlayBackState:e.getState()}),e.getState()==="stopped"&&e.startTransitionTo("ready")})),this}play(){return this.subscription.add(this.playerInited.pipe(z(e=>!!e),Y()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("play",{currentPlayBackState:e.getState()}),e.getState()!=="playing"&&e.startTransitionTo("playing")})),this}pause(){return this.subscription.add(this.playerInited.pipe(z(e=>!!e),Y()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("pause",{currentPlayBackState:e.getState()}),e.getState()!=="paused"&&e.startTransitionTo("paused")})),this}stop(){return this.subscription.add(this.playerInited.pipe(z(e=>!!e),Y()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("stop",{currentPlayBackState:e.getState()}),e.getState()!=="stopped"&&e.startTransitionTo("stopped")})),this}seekTime(e,t=!0){return this.subscription.add(this.playerInited.pipe(z(i=>!!i),Y()).subscribe(()=>{let i=this.info.duration$.getValue(),r=this.info.isLive$.getValue(),a=e;e>=i&&!r&&(a=i-this.tuning.seekNearDurationBias),this.tracer.log("seekTime",{duration:i,isLive:r,time:e,calculatedTime:a,forcePrecise:t}),Number.isFinite(a)&&(this.events.willSeek$.next({from:this.getExactTime(),to:a}),this.desiredState.seekState.setState({state:"requested",position:a*1e3,forcePrecise:t}))})),this}seekPercent(e){return this.subscription.add(this.playerInited.pipe(z(t=>!!t),Y()).subscribe(()=>{let t=this.info.duration$.getValue();this.tracer.log("seekPercent",{percent:e,duration:t}),isFinite(t)&&this.seekTime(Math.abs(t)*e,!1)})),this}setVolume(e,t){return this.subscription.add(this.playerInited.pipe(z(i=>!!i),Y()).subscribe(()=>{var o;let i=this.desiredState.volume,r=i.getTransition(),a=(o=r==null?void 0:r.to.muted)!=null?o:this.info.muted$.getValue(),n=t!=null?t:this.tuning.isAudioDisabled||a;this.tracer.log("setVolume",{volume:e,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:n}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setVolume(e):i.startTransitionTo({volume:e,muted:n})})),this}setMuted(e,t=!1){return this.subscription.add(this.playerInited.pipe(z(i=>!!i),Y()).subscribe(()=>{var o;let i=this.desiredState.volume,r=this.tuning.isAudioDisabled&&!t||e,a=i.getTransition(),n=(o=a==null?void 0:a.to.volume)!=null?o:this.info.volume$.getValue();this.tracer.log("setMuted",{isMuted:e,nextMuted:r,volume:n,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue()}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setMuted(r):i.startTransitionTo({volume:n,muted:r})})),this}setVideoStream(e){return this.subscription.add(this.playerInited.pipe(z(t=>!!t),Y()).subscribe(()=>{this.desiredState.videoStream.startTransitionTo(e)})),this}setAudioStream(e){return this.subscription.add(this.playerInited.pipe(z(t=>!!t),Y()).subscribe(()=>{this.desiredState.audioStream.startTransitionTo(e)})),this}setQuality(e){return this.subscription.add(this.playerInited.pipe(z(t=>!!t),Y()).subscribe(()=>{El(this.providerContainer);let t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();this.tracer.log("setQuality",{isDelayed:t.length===0,quality:e}),this.desiredState.videoTrack.getState()===void 0&&this.desiredState.videoTrack.getPrevState()===void 0&&t.length===0?this.wasSetStartedQuality?this.providerContainer.providerOutput.availableVideoTracks$.pipe(z(i=>i.length>0),Y()).subscribe(i=>{this.setVideoTrackIdByQuality(i,e)}):this.explicitInitialQuality=e:t.length>0&&this.setVideoTrackIdByQuality(t,e)})),this}setAutoQuality(e){return this.subscription.add(this.playerInited.pipe(z(t=>!!t),Y()).subscribe(()=>{this.tracer.log("setAutoQuality",{enable:e}),this.desiredState.autoVideoTrackSwitching.startTransitionTo(e)})),this}setAutoQualityLimits(e){return this.subscription.add(this.playerInited.pipe(z(t=>!!t),Y()).subscribe(()=>{this.tracer.log("setAutoQualityLimits",qi(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e)})),this}setPredefinedQualityLimits(e){return this.subscription.add(this.playerInited.pipe(z(t=>!!t),Y()).subscribe(()=>{if(this.info.predefinedQualityLimitType$.getValue()===e)return this;let{highQualityLimit:t,trafficSavingLimit:i}=this.tuning.autoTrackSelection,r;switch(e){case"high_quality":r={min:t,max:void 0};break;case"traffic_saving":r={max:i,min:void 0};break;default:r={max:void 0,min:void 0}}this.setAutoQualityLimits(r)})),this}setPlaybackRate(e){return this.subscription.add(this.playerInited.pipe(z(t=>!!t),Y()).subscribe(()=>{var i;El(this.providerContainer);let t=(i=this.providerContainer)==null?void 0:i.providerOutput.element$.getValue();this.tracer.log("setPlaybackRate",{playbackRate:e,isVideoElementAvailable:!!t}),t&&(this.desiredState.playbackRate.setState(e),t.playbackRate=e)})),this}setExternalTextTracks(e){return this.subscription.add(this.playerInited.pipe(z(t=>!!t),Y()).subscribe(()=>{e.length&&this.tracer.log("setExternalTextTracks",qi(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t})))})),this}selectTextTrack(e){return this.subscription.add(this.playerInited.pipe(z(t=>!!t),Y()).subscribe(()=>{var t;EE(e,this.desiredState.currentTextTrack,(t=this.providerContainer)==null?void 0:t.providerOutput.availableTextTracks$,i=>i.id===e),this.tracer.log("selectTextTrack",{textTrackId:e})})),this}setTextTrackCueSettings(e){return this.subscription.add(this.playerInited.pipe(z(t=>!!t),Y()).subscribe(()=>{this.tracer.log("setTextTrackCueSettings",{...e}),this.desiredState.textTrackCuesSettings.startTransitionTo(e)})),this}setLiveLowLatency(e){let t=this.info.isLive$.getValue(),i=this.desiredState.isLowLatency.getState();return!t||i===e?this:(this.tracer.log("live switch to low latency "+e),this.desiredState.isLowLatency.setState(e),this.seekTime(0))}setLooped(e){return this.subscription.add(this.playerInited.pipe(z(t=>!!t),Y()).subscribe(()=>{this.tracer.log("setLooped",{isLooped:e}),this.desiredState.isLooped.startTransitionTo(e)})),this}toggleChromecast(){this.tracer.log("toggleChromecast"),this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){return this.subscription.add(this.playerInited.pipe(z(i=>!!i),Y()).subscribe(()=>{let i=this.getScene3D();this.tracer.log("startCameraManualRotation",{isScene3DAvailable:!!i,mx:e,my:t}),i&&i.startCameraManualRotation(e,t)})),this}stopCameraManualRotation(e=!1){return this.subscription.add(this.playerInited.pipe(z(t=>!!t),Y()).subscribe(()=>{let t=this.getScene3D();this.tracer.log("stopCameraManualRotation",{isScene3DAvailable:!!t,immediate:e}),t&&t.stopCameraManualRotation(e)})),this}moveCameraFocusPX(e,t){return this.subscription.add(this.playerInited.pipe(z(i=>!!i),Y()).subscribe(()=>{let i=this.getScene3D();if(this.tracer.log("moveCameraFocusPX",{isScene3DAvailable:!!i,dxpx:e,dypx:t}),i){let r=i.getCameraRotation(),a=i.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:r.x+a.x,y:r.y+a.y})}})),this}holdCamera(){return this.subscription.add(this.playerInited.pipe(z(e=>e),Y()).subscribe(()=>{let e=this.getScene3D();e&&e.holdCamera()})),this}releaseCamera(){return this.subscription.add(this.playerInited.pipe(z(e=>!!e),Y()).subscribe(()=>{let e=this.getScene3D();e&&e.releaseCamera()})),this}getExactTime(){if(!this.providerContainer)return 0;let e=this.providerContainer.providerOutput.element$.getValue();if(qO(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),i=t.state==="none"?void 0:t.position;return wE(i)?i/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){var t,i;let e=(t=this.providerContainer)==null?void 0:t.current$.getValue();if((i=e==null?void 0:e.provider)!=null&&i.scene3D)return e.provider.scene3D}setIntrinsicVideoSize(...e){let t={width:e.reduce((i,{width:r})=>i||r||0,0),height:e.reduce((i,{height:r})=>i||r||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(Ui(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(Z(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(Z(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(Z(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(Z(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(Z(e=>e.to)).subscribe(e=>{this.info.autoQualityLimits$.next(e);let{highQualityLimit:t,trafficSavingLimit:i}=this.tuning.autoTrackSelection;this.info.predefinedQualityLimitType$.next(Nd(e,t,i))})),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(z(({from:e})=>e==="stopped"),Y()).subscribe(()=>{this.initedAt=Al(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case"ready":this.events.ready$.next();break;case"playing":this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case"paused":this.events.paused$.next();break;case"stopped":this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case"ready":this.events.willReady$.next();break;case"paused":this.events.willPause$.next();break;case"playing":this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case"stopped":this.events.willStop$.next();break;default:}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("willSeekEvent",qi(n)),n.state==="requested"?this.desiredState.seekState.setState({...n,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:wl.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe(Y()).subscribe(this.events.autoplaySoundProhibited$)).add(e.providerOutput.severeStallOccurred$.subscribe(this.events.severeStallOccured$)).add(e.providerOutput.seekedEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("seekedEvent",qi(n)),n.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe(Z(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(Z(n=>n.destination),te()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(wi({availableVideoTracks:e.providerOutput.availableVideoTracks$,currentVideoStream:e.providerOutput.currentVideoStream$}).pipe(Z(({availableVideoTracks:n,currentVideoStream:o})=>n.filter(u=>o?o.id===u.streamId:!0).map(({quality:u})=>u).sort((u,l)=>RE(u)?1:RE(l)?-1:HO(l,u)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(n=>{let o={};for(let u of n)u.fps&&(o[u.quality]=u.fps);this.info.availableQualitiesFps$.next(o)})).add(e.providerOutput.availableAudioStreams$.subscribe(this.info.availableAudioStreams$)).add(e.providerOutput.currentVideoStream$.subscribe(this.info.currentVideoStream$)).add(e.providerOutput.currentAudioStream$.subscribe(this.info.currentAudioStream$)).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.pipe(te()).subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.pipe(z(n=>wE(n))).subscribe(n=>{this.info.currentQuality$.next(n==null?void 0:n.quality),this.info.videoBitrate$.next(n==null?void 0:n.bitrate)})).add(e.providerOutput.currentVideoSegmentLength$.pipe(te((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe(te((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(te()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(te()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(te()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.autoVideoTrackLimits$.subscribe(n=>{this.desiredState.autoVideoTrackLimits.setState(n!=null?n:{})})).add(e.providerOutput.currentBuffer$.pipe(Z(n=>n?{start:n.from,end:n.to}:{start:0,end:0})).subscribe(this.info.currentBuffer$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.isLiveEnded$.pipe(kh(n=>n&&this.stop())).subscribe(this.info.isLiveEnded$)).add(e.providerOutput.canChangePlaybackSpeed$.subscribe(this.info.canChangePlaybackSpeed$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.liveBufferTime$.subscribe(this.info.liveBufferTime$)).add(e.providerOutput.liveLatency$.subscribe(this.info.liveLatency$)).add(wi({hasLiveOffsetByPaused:Ui(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(Z(n=>n.to),te(),Z(n=>n==="paused")),isLowLatency:e.providerOutput.isLowLatency$}).subscribe(({hasLiveOffsetByPaused:n,isLowLatency:o})=>{if(window.clearTimeout(this.hasLiveOffsetByPausedTimer),n){this.hasLiveOffsetByPausedTimer=window.setTimeout(()=>{this.hasLiveOffsetByPaused.next(!0)},this.getActiveLiveDelay(o));return}this.hasLiveOffsetByPaused.next(!1)})).add(wi({atLiveEdge:wi({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Ph({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(Z(({isLive:n,position:o,isLowLatency:u})=>{let l=this.getActiveLiveDelay(u);return n&&Math.abs(o)<l/1e3}),te(),kh(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(Z(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add(wi({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(Z(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),te(),kh(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(Z(n=>n.muted),te()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(Z(n=>n.volume),te()).subscribe(this.info.volume$)).add(Ph({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(Ui(e.providerOutput.endedEvent$.pipe(AE(!0)),e.providerOutput.seekedEvent$.pipe(AE(!1))).pipe(te()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.providerOutput.fetcherRecoverableError$.subscribe(this.events.fetcherRecoverableError$)).add(e.providerOutput.fetcherError$.subscribe(this.events.fatalError$)).add(e.volumeMultiplierError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe(Z(n=>({id:n?`No${n}`:"NoProviders",category:wl.VIDEO_PIPELINE,message:n?`${n} was forced but failed or not available`:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.getCurrentTime$.subscribe(this.experimental.getCurrentTime$)).add(e.providerOutput.firstBytesEvent$.pipe(Y(),Z(n=>n!=null?n:Al()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(Y(),Z(()=>Al()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(Y(),Z(()=>Al()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$)).add(e.providerOutput.availableSources$.subscribe(this.info.availableSources$));let t=new D(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let i=new D(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(z(({to:n})=>n==="playing"),Y()).subscribe(()=>i.next(!1)));let r=0,a=Ui(e.providerOutput.isBuffering$,t,i).pipe(Z(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||i.getValue();return n&&!o}),te());this.subscription.add(a.subscribe(n=>{n?r=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(r),this.info.isStalled$.next(!1))})),this.subscription.add(Ui(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{let n=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n==null?void 0:n.videoWidth,height:n==null?void 0:n.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{var u,l;let o=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:(u=n==null?void 0:n.size)==null?void 0:u.width,height:(l=n==null?void 0:n.size)==null?void 0:l.height},{width:o==null?void 0:o.videoWidth,height:o==null?void 0:o.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add(Ui(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,e.providerOutput.elementVisible$,this.chromecastInitializer.castState$).subscribe(()=>{let n=e.providerOutput.inPiP$.getValue(),o=e.providerOutput.inFullscreen$.getValue(),u=e.providerOutput.element$.getValue(),l=e.providerOutput.elementVisible$.getValue(),d=this.chromecastInitializer.castState$.getValue(),c;d==="CONNECTED"?c="second_screen":u?l?n?c="pip":o?c="fullscreen":c="inline":c="invisible":c="none",this.info.surface$.getValue()!==c&&this.info.surface$.next(c)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(Z(e=>e==null?void 0:e.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new PE;this.subscription.add(t),this.subscription.add(e.current$.pipe(te((i,r)=>i.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(z(i=>i.length>0),Y()).subscribe(i=>{this.setStartingVideoTrack(i)}))}))}setStartingVideoTrack(e){var r;let t;this.wasSetStartedQuality=!0;let i=(r=this.explicitInitialQuality)!=null?r:this.info.currentQuality$.getValue();i&&(t=e.find(({quality:a})=>a===i),t||this.setAutoQuality(!0)),t||(t=Wt(e,{container:this.domContainer.getBoundingClientRect(),panelSize:this.config.panelSize,estimatedThroughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),playbackRate:this.info.currentPlaybackRate$.getValue(),forwardBufferHealth:0,abrLogger:this.abrLogger})),this.desiredState.videoTrack.startTransitionTo(t),this.info.currentQuality$.next(t.quality),this.info.videoBitrate$.next(t.bitrate)}initLogs(){this.subscription.add(Ui(this.desiredState.videoTrack.stateChangeStarted$.pipe(Z(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(Z(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(Z(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(Z(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(Z(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(Z(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(Z(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(Z(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(Z(e=>({component:"desiredState",message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`}))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){var t;let e=(t=this.providerContainer)==null?void 0:t.providerOutput;El(this.providerContainer),El(e),py(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(i=>dy(i)),this.providerContainer.current$.subscribe(({type:i})=>Ra("provider",i)),e.duration$.subscribe(i=>Ra("duration",i)),e.availableVideoTracks$.pipe(z(i=>!!i.length),Y()).subscribe(i=>Ra("tracks",i)),this.events.fatalError$.subscribe(new Ke("fatalError")),this.events.managedError$.subscribe(new Ke("managedError")),e.position$.subscribe(new Ke("position")),e.currentVideoTrack$.pipe(Z(i=>i==null?void 0:i.quality)).subscribe(new Ke("quality")),this.info.currentBuffer$.subscribe(new Ke("buffer")),e.isBuffering$.subscribe(new Ke("isBuffering"))].forEach(i=>this.subscription.add(i)),Ra("codecs",j.video.supportedCodecs)}initTracerSubscription(){let e=kE(this.tracer.log.bind(this.tracer)),t=kE(this.tracer.error.bind(this.tracer));this.subscription.add(this.info.playbackState$.subscribe(e("playbackState"))).add(this.info.isLooped$.subscribe(e("isLooped"))).add(this.info.currentPlaybackRate$.pipe(te()).subscribe(e("currentPlaybackRate"))).add(this.info.isAutoQualityEnabled$.subscribe(e("isAutoQualityEnabled"))).add(this.info.autoQualityLimits$.subscribe(e("autoQualityLimits"))).add(this.info.currentFormat$.subscribe(e("currentFormat"))).add(this.info.availableQualities$.subscribe(e("availableQualities"))).add(this.info.availableQualitiesFps$.subscribe(e("availableQualitiesFps"))).add(this.info.availableAudioTracks$.subscribe(e("availableAudioTracks"))).add(this.info.isAudioAvailable$.subscribe(e("isAudioAvailable"))).add(wi({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe(z(({currentQuality:i,videoBitrate:r})=>!!i&&!!r),te((i,r)=>i.currentQuality===r.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe(z(i=>i>0),te()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe(z(i=>i>0),te()).subscribe(e("currentAudioSegmentLength"))).add(this.info.hostname$.subscribe(e("hostname"))).add(this.info.currentTextTrack$.subscribe(e("currentTextTrack"))).add(this.info.availableTextTracks$.subscribe(e("availableTextTracks"))).add(this.info.autoQualityLimitingAvailable$.subscribe(e("autoQualityLimitingAvailable"))).add(wi({currentBuffer:this.info.currentBuffer$.pipe(z(i=>i.end>0),te((i,r)=>i.end===r.end&&i.start===r.start)),position:this.info.position$.pipe(te())}).pipe(Mh(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe(te()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe(te()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe(te()).subscribe(e("canChangePlaybackSpeed"))).add(wi({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(z(({liveTime:i,liveBufferTime:r})=>!!i&&!!r),Mh(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(te(),z(i=>i===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(te(),z(i=>i===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe(te()).subscribe(e("muted"))).add(this.info.volume$.pipe(te()).subscribe(e("volume"))).add(this.info.isEnded$.pipe(te(),z(i=>i===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add(wi({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(z(({throughputEstimation:i,rtt:r})=>!!i&&!!r),Mh(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(te(),z(i=>i===!0)).subscribe(e("is3DVideo"))).add(this.info.surface$.subscribe(e("surface"))).add(this.events.ended$.subscribe(e("ended"))).add(this.events.looped$.subscribe(e("looped"))).add(this.events.managedError$.subscribe(t("managedError"))).add(this.events.fatalError$.subscribe(t("fatalError"))).add(this.events.firstBytes$.subscribe(e("firstBytes"))).add(this.events.firstFrame$.subscribe(e("firstFrame"))).add(this.events.canplay$.subscribe(e("canplay")))}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e,t=()=>{e==null||e.release(),e=void 0},i=async()=>{t(),e=await window.navigator.wakeLock.request("screen").catch(r=>{r instanceof DOMException&&r.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:wl.DOM,message:String(r)})})};this.subscription.add(Ui(Rh(document,"visibilitychange"),Rh(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let r=document.visibilityState==="visible",a=this.desiredState.playbackState.getState()==="playing",n=!!e&&!(e!=null&&e.released);r&&a?n||i():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let i=e.find(r=>r.quality===t);this.tracer.log("setVideoTrackIdByQuality",qi({quality:t,availableTracks:qi(e),track:qi(i),isAutoQuality:!i})),i?this.desiredState.videoTrack.startTransitionTo(i):this.setAutoQuality(!0)}getActiveLiveDelay(e=!1){return e?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay}isNotActiveTabCase(){return document.hidden&&this.tuning.autoplayOnlyInActiveTab&&!Ca()}};import{Subscription as bee,Observable as gee,Subject as See,ValueSubject as vee,VideoQuality as yee}from"@vkontakte/videoplayer-shared/es2018";var Tee=`@vkontakte/videoplayer-core@${Bh}`;export{vo as ChromecastState,Cl as HttpConnectionType,gee as Observable,et as PlaybackState,Pl as Player,yo as PredefinedQualityLimits,Tee as SDK_VERSION,See as Subject,bee as Subscription,Vl as Surface,Bh as VERSION,vee as ValueSubject,di as VideoFormat,yee as VideoQuality,j as clientChecker,Pa as isMobile};
185
+ `})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(d,"i")}var Hp=N(Ot(),1);import{videoSizeToQuality as eV,throttleFn as tV}from"@vkontakte/videoplayer-shared/es2018";var bx=({id:s,width:e,height:t,bitrate:i,fps:r,quality:a,streamId:n})=>{var u;let o=(u=a?Bi(a):void 0)!=null?u:eV({width:e,height:t});return o&&{id:s,quality:o,bitrate:i,size:{width:e,height:t},fps:r,streamId:n}},gx=({id:s,bitrate:e})=>({id:s,bitrate:e}),Sx=({language:s,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:s,label:e}),vx=({language:s,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:s,label:e}),zp=({id:s,language:e,label:t,codecs:i,isDefault:r})=>({id:s,language:e,label:t,codec:(0,Hp.default)(i.split("."),0),isDefault:r}),Qp=({id:s,language:e,label:t,hdr:i,codecs:r})=>({id:s,language:e,hdr:i,label:t,codec:(0,Hp.default)(r.split("."),0)}),Gp=s=>"url"in s,Ze=s=>s.type==="template",Zn=s=>s instanceof DOMException&&(s.name==="AbortError"||s.code===20);var yx=s=>{s.sort((t,i)=>t.from-i.from);let e=[s[0]];for(let t=1;t<s.length;t++){let{from:i,to:r}=s[t],a=e[e.length-1];a.to>=i?a.to=Math.max(a.to,r):e.push(s[t])}return e},br=(s,e)=>{for(let t of s)if(e(t))return t;return null},Tx=s=>{let e=!1,t=tV(()=>{e=!0},s);return()=>{try{return t(),e}finally{e=!1}}};var xx=s=>{if(!(s!=null&&s.startsWith("P")))return;let e=(n,o)=>{let u=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(u)?0:u)*o},i=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(s),r=(i==null?void 0:i[1])==="-"?-1:1,a={days:e(i==null?void 0:i[5],r),hours:e(i==null?void 0:i[6],r),minutes:e(i==null?void 0:i[7],r),seconds:e(i==null?void 0:i[8],r)};return a.days*24*60*60*1e3+a.hours*60*60*1e3+a.minutes*60*1e3+a.seconds*1e3},xi=(s,e)=>{let t=s;t=(0,Wp.default)(t,"$$","$");let i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[r,a]of(0,Ex.default)(i)){let n=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=(0,Wp.default)(t,n,(o,u)=>Ix(a)?o:Ix(u)?a:(0,wx.default)(a,parseInt(u,10),"0"))}return t},Px=(s,e)=>{var w,P,C,M,R,Q,U,A,F,k,x,$,oe,Ce,se,K,ye,Te,Ie,Ve,Tt,At,qt,Xt,Ai,bs,gs,Ss,vs,ys,Ts,Is,xs,Es,ws,As,Ps,ks,Rs,Ms,Ls,Bs,$s,Ds,Cs,Vs,Os,_s,Fs,Ns,Us,qs,js,Hs,zs,Qs,Gs,Ws,Ys,Ks,Xs;let i=new DOMParser().parseFromString(s,"application/xml"),r={video:[],audio:[],text:[]},a=i.children[0],n=Array.from(a.querySelectorAll("MPD > BaseURL").values()).map(ce=>{var _,je;return(je=(_=ce.textContent)==null?void 0:_.trim())!=null?je:""}),o=(w=(0,Ax.default)(n,0))!=null?w:"",u=a.getAttribute("type")==="dynamic",l=a.getAttribute("availabilityStartTime"),d=a.getAttribute("publishTime"),c=a.getElementsByTagName("vk:Attrs")[0],h=c==null?void 0:c.getElementsByTagName("vk:XLatestSegmentPublishTime")[0].textContent,p=c==null?void 0:c.getElementsByTagName("vk:XStreamIsLive")[0].textContent,f=c==null?void 0:c.getElementsByTagName("vk:XStreamIsUnpublished")[0].textContent,m=c==null?void 0:c.getElementsByTagName("vk:XPlaybackDuration")[0].textContent,g;u&&(g={availabilityStartTime:l?new Date(l).getTime():0,publishTime:d?new Date(d).getTime():0,latestSegmentPublishTime:h?new Date(h).getTime():0,streamIsAlive:p==="yes",streamIsUnpublished:f==="yes"});let S,v=a.getAttribute("mediaPresentationDuration"),y=[...a.getElementsByTagName("Period")],I=y.reduce((ce,_)=>({...ce,[_.id]:_.children}),{}),T=y.reduce((ce,_)=>({...ce,[_.id]:_.getAttribute("duration")}),{});v?S=xx(v):(0,Yp.default)(T).filter(ce=>ce).length&&!u?S=(0,Yp.default)(T).reduce((ce,_)=>{var je;return ce+((je=xx(_))!=null?je:0)},0):m&&(S=parseInt(m,10));let E=0,O=(C=(P=a.getAttribute("profiles"))==null?void 0:P.split(","))!=null?C:[];for(let ce of y.map(_=>_.id))for(let _ of I[ce]){let je=(M=_.getAttribute("id"))!=null?M:"id"+(E++).toString(10),Pt=(R=_.getAttribute("mimeType"))!=null?R:"",ji=(Q=_.getAttribute("codecs"))!=null?Q:"",Hi=(U=_.getAttribute("contentType"))!=null?U:Pt==null?void 0:Pt.split("/")[0],kl=(F=(A=_.getAttribute("profiles"))==null?void 0:A.split(","))!=null?F:[],Js=(x=mx((k=_.getAttribute("lang"))!=null?k:""))!=null?x:{},Jt=(Ce=(oe=($=_.querySelector("Label"))==null?void 0:$.textContent)==null?void 0:oe.trim())!=null?Ce:void 0,Rl=_.querySelectorAll("Representation"),Ml=_.querySelector("SegmentTemplate"),Ll=(K=(se=_.querySelector("Role"))==null?void 0:se.getAttribute("value"))!=null?K:void 0,ut=Hi,H={id:je,language:Js.language,isDefault:Ll==="main",label:Jt,codecs:ji,hdr:ut==="video"&&Zr(ji),mime:Pt,representations:[]};for(let V of Rl){let we=(ye=V.getAttribute("lang"))!=null?ye:void 0,kt=(Ie=(Te=Jt!=null?Jt:_.getAttribute("label"))!=null?Te:V.getAttribute("label"))!=null?Ie:void 0,Zt=(At=(Tt=(Ve=V.querySelector("BaseURL"))==null?void 0:Ve.textContent)==null?void 0:Tt.trim())!=null?At:"",He=new URL(Zt||o,e).toString(),Ae=(qt=V.getAttribute("mimeType"))!=null?qt:Pt,ei=(Ai=(Xt=V.getAttribute("codecs"))!=null?Xt:ji)!=null?Ai:"",ti;if(Hi==="text"){let Pe=V.getAttribute("id")||"",ii=((bs=Js.privateuse)==null?void 0:bs.includes("x-auto"))||Pe.includes("_auto"),ze=V.querySelector("SegmentTemplate");if(ze){let Rt={representationId:(gs=V.getAttribute("id"))!=null?gs:void 0,bandwidth:(Ss=V.getAttribute("bandwidth"))!=null?Ss:void 0},ri=parseInt((vs=V.getAttribute("bandwidth"))!=null?vs:"",10)/1e3,si=(Ts=parseInt((ys=ze.getAttribute("startNumber"))!=null?ys:"",10))!=null?Ts:1,lt=parseInt((Is=ze.getAttribute("timescale"))!=null?Is:"",10),zi=(xs=ze.querySelectorAll("SegmentTimeline S"))!=null?xs:[],ct=ze.getAttribute("media");if(!ct)continue;let ai=[],ni=0,oi="",dt=0,Mt=si,ee=0;for(let de of zi){let Qe=parseInt((Es=de.getAttribute("d"))!=null?Es:"",10),ne=parseInt((ws=de.getAttribute("r"))!=null?ws:"",10)||0,ke=parseInt((As=de.getAttribute("t"))!=null?As:"",10);ee=Number.isFinite(ke)?ke:ee;let Ge=Qe/lt*1e3,Re=ee/lt*1e3;for(let me=0;me<ne+1;me++){let Me=xi(ct,{...Rt,segmentNumber:Mt.toString(10),segmentTime:(ee+me*Qe).toString(10)}),pt=(Re!=null?Re:0)+me*Ge,Bt=pt+Ge;Mt++,ai.push({time:{from:pt,to:Bt},url:Me})}ee+=(ne+1)*Qe,ni+=(ne+1)*Ge}dt=ee/lt*1e3,oi=xi(ct,{...Rt,segmentNumber:Mt.toString(10),segmentTime:ee.toString(10)});let Lt={time:{from:dt,to:1/0},url:oi},xe={type:"template",baseUrl:He,segmentTemplateUrl:ct,initUrl:"",totalSegmentsDurationMs:ni,segments:ai,nextSegmentBeyondManifest:Lt,timescale:lt};ti={id:Pe,kind:"text",segmentReference:xe,profiles:[],duration:S,bitrate:ri,mime:"",codecs:"",width:0,height:0,isAuto:ii}}else ti={id:Pe,isAuto:ii,kind:"text",url:He}}else{let Pe=(ks=(Ps=V.getAttribute("contentType"))!=null?Ps:Ae==null?void 0:Ae.split("/")[0])!=null?ks:Hi,ii=(Ms=(Rs=_.getAttribute("profiles"))==null?void 0:Rs.split(","))!=null?Ms:[],ze=parseInt((Ls=V.getAttribute("width"))!=null?Ls:"",10),Rt=parseInt((Bs=V.getAttribute("height"))!=null?Bs:"",10),ri=parseInt(($s=V.getAttribute("bandwidth"))!=null?$s:"",10)/1e3,si=(Ds=V.getAttribute("frameRate"))!=null?Ds:"",lt=(Cs=V.getAttribute("quality"))!=null?Cs:void 0,zi=si?Lu(si):void 0,ct=(Vs=V.getAttribute("id"))!=null?Vs:"id"+(E++).toString(10),ai=Pe==="video"?`${Rt}p`:Pe==="audio"?`${ri}Kbps`:ei,ni=`${ct}@${ai}`,oi=[...O,...kl,...ii],dt,Mt=V.querySelector("SegmentBase"),ee=(Os=V.querySelector("SegmentTemplate"))!=null?Os:Ml;if(Mt){let xe=(Fs=(_s=V.querySelector("SegmentBase Initialization"))==null?void 0:_s.getAttribute("range"))!=null?Fs:"",[de,Qe]=xe.split("-").map(Me=>parseInt(Me,10)),ne={from:de,to:Qe},ke=(Ns=V.querySelector("SegmentBase"))==null?void 0:Ns.getAttribute("indexRange"),[Ge,Re]=ke?ke.split("-").map(Me=>parseInt(Me,10)):[],me=ke?{from:Ge,to:Re}:void 0;dt={type:"byteRange",url:He,initRange:ne,indexRange:me}}else if(ee){let xe={representationId:(Us=V.getAttribute("id"))!=null?Us:void 0,bandwidth:(qs=V.getAttribute("bandwidth"))!=null?qs:void 0},de=parseInt((js=ee.getAttribute("timescale"))!=null?js:"",10),Qe=(Hs=ee.getAttribute("initialization"))!=null?Hs:"",ne=ee.getAttribute("media"),ke=(Qs=parseInt((zs=ee.getAttribute("startNumber"))!=null?zs:"",10))!=null?Qs:1,Ge=xi(Qe,xe);if(!ne)throw new ReferenceError("No media attribute in SegmentTemplate");let Re=(Gs=ee.querySelectorAll("SegmentTimeline S"))!=null?Gs:[],me=[],Me=0,pt="",Bt=0;if(Re.length){let ui=ke,pe=0;for(let ht of Re){let be=parseInt((Ws=ht.getAttribute("d"))!=null?Ws:"",10),We=parseInt((Ys=ht.getAttribute("r"))!=null?Ys:"",10)||0,li=parseInt((Ks=ht.getAttribute("t"))!=null?Ks:"",10);pe=Number.isFinite(li)?li:pe;let Qi=be/de*1e3,Gi=pe/de*1e3;for(let ci=0;ci<We+1;ci++){let $l=xi(ne,{...xe,segmentNumber:ui.toString(10),segmentTime:(pe+ci*be).toString(10)}),Zs=(Gi!=null?Gi:0)+ci*Qi,Dl=Zs+Qi;ui++,me.push({time:{from:Zs,to:Dl},url:$l})}pe+=(We+1)*be,Me+=(We+1)*Qi}Bt=pe/de*1e3,pt=xi(ne,{...xe,segmentNumber:ui.toString(10),segmentTime:pe.toString(10)})}else if(iV(S)){let pe=parseInt((Xs=ee.getAttribute("duration"))!=null?Xs:"",10)/de*1e3,ht=Math.ceil(S/pe),be=0;for(let We=1;We<ht;We++){let li=xi(ne,{...xe,segmentNumber:We.toString(10),segmentTime:be.toString(10)});me.push({time:{from:be,to:be+pe},url:li}),be+=pe}Bt=be,pt=xi(ne,{...xe,segmentNumber:ht.toString(10),segmentTime:be.toString(10)})}let Bl={time:{from:Bt,to:1/0},url:pt};dt={type:"template",baseUrl:He,segmentTemplateUrl:ne,initUrl:Ge,totalSegmentsDurationMs:Me,segments:me,nextSegmentBeyondManifest:Bl,timescale:de}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Pe||!Ae)continue;let Lt={video:"video",audio:"audio",text:"text"}[Pe];if(!Lt)continue;ut||(ut=Lt),ti={id:ni,kind:Lt,segmentReference:dt,profiles:oi,duration:S,bitrate:ri,mime:Ae,codecs:ei,width:ze,height:Rt,fps:zi,quality:lt}}H.language||(H.language=we),H.label||(H.label=kt),H.mime||(H.mime=Ae),H.codecs||(H.codecs=ei),H.hdr||(H.hdr=ut==="video"&&Zr(ei)),H.representations.push(ti)}if(ut){let V=r[ut].find(we=>we.id===H.id);if(V&&H.representations.every(we=>Ze(we.segmentReference)))for(let we of V.representations){let kt=H.representations.find(Ae=>Ae.id===we.id),Zt=kt==null?void 0:kt.segmentReference,He=we.segmentReference;He.segments.push(...Zt.segments),He.nextSegmentBeyondManifest=Zt.nextSegmentBeyondManifest}else r[ut].push(H)}}return{duration:S,streams:r,baseUrls:n,live:g}};import{fromEvent as rV,Subscription as sV}from"@vkontakte/videoplayer-shared/es2018";var il=s=>{let e=[];for(let t=0;t<s.length;t++){let i=Math.floor(s.start(t)*1e3),r=Math.ceil(s.end(t)*1e3);e.push(i,r)}return e};var rl=class{constructor(e,t){this.lastUpdateTs=0;this.lastCallTs=0;this.prevRanges=[];this.subscription=new sV;this.mediaSource=e,this.sourceBuffer=t,this.subscription.add(rV(this.sourceBuffer,"updateend").subscribe(()=>this.updateend()))}updateend(){if(!q(this.mediaSource,this.sourceBuffer))return;let{prevRanges:e}=this,t=il(this.sourceBuffer.buffered);this.prevRanges=t,this.isRangesRemoved(e,t)&&(this.lastUpdateTs=Date.now())}isRangesRemoved(e,t){if(e.length!==t.length)return!0;for(let i=0;i<e.length;i+=2){let r=e[i],a=e[i+1],n=t[i],o=t[i+1];if(n>r||o<a)return!0}return!1}wasUpdated(){let{lastCallTs:e,lastUpdateTs:t}=this;return this.lastCallTs=Date.now(),e<=t}destroy(){this.subscription.unsubscribe()}};var eo=class{constructor(e,t,i,{fetcher:r,tuning:a,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new Sr(0);this.currentLowLatencySegmentLength$=new Sr(0);this.currentSegmentLength$=new Sr(0);this.onLastSegment$=new Sr(!1);this.fullyBuffered$=new Sr(!1);this.playingRepresentation$=new Sr(void 0);this.playingRepresentationInit$=new Sr(void 0);this.error$=new nV;this.gaps=[];this.subscription=new oV;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new ae;this.switchAbortController=new ae;this.destroyAbortController=new ae;this.bufferLimit=1/0;this.failedDownloads=0;this.baseUrls=[];this.baseUrlsIndex=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.lastDataObtainedTimestampMs=0;this.loadByteRangeSegmentsTimeoutId=0;this.sourceBufferBufferedDiff=null;this.startWith=Fi(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);ot(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new ox(this.sourceBuffer),this.sourceBufferBufferedDiff=new rl(this.mediaSource,this.sourceBuffer),this.subscription.add(Xp(this.sourceBuffer,"updateend").subscribe(()=>{this.maintain()})),this.subscription.add(Xp(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:gr.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o||!q(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,Kr(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=$e(this.sourceBuffer.buffered,o),d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,n*2,l<d).catch(c=>{this.handleAsyncError(c,"pruneBuffer")})})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);let i=this.initData.get(t.id),r=this.segments.get(t.id),a=this.parsedInitData.get(t.id);ot(i,"No init buffer for starting representation"),ot(r,"No segments for starting representation"),i instanceof ArrayBuffer&&(this.searchGaps(r,t),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(a))}.bind(this));this.switchTo=Fi(this.destroyAbortController.signal,async function*(e,t=!1){if(!q(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);ot(i,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if(qe(a)||qe(r)?yield this.loadInit(i,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),ot(r,"No segments for starting representation"),a=this.initData.get(e),!(!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer||!q(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(a,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer();else{let n=this.getCurrentPosition();ls(n)&&!this.isLive&&(this.bufferLimit=1/0,await this.pruneBuffer(n,1/0,!0)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}this.maintain()}}.bind(this));this.switchToOld=Fi(this.destroyAbortController.signal,async function*(e,t=!1){if(!q(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);ot(i,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if(qe(a)||qe(r)?yield this.loadInit(i,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),ot(r,"No segments for starting representation"),a=this.initData.get(e),!(!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer||!q(this.mediaSource,this.sourceBuffer)))if(yield this.abort(),yield this.sourceBufferTaskQueue.append(a,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let n=this.getCurrentPosition();ls(n)&&(this.isLive||(this.bufferLimit=1/0,await this.pruneBuffer(n,1/0,!0)),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}}.bind(this));this.seekLive=Fi(this.destroyAbortController.signal,async function*(e){var u,l;let t=(u=(0,nl.default)(e,d=>d.representations))!=null?u:[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let d of this.representations.keys()){let c=t.find(f=>f.id===d);c&&this.representations.set(d,c);let h=this.representations.get(d);if(!h||!Ze(h.segmentReference))return;let p=this.getActualLiveStartingSegments(h.segmentReference);this.segments.set(h.id,p)}let i=(l=this.switchingToRepresentationId)!=null?l:this.downloadingRepresentationId,r=this.representations.get(i);ot(r);let a=this.segments.get(i);ot(a,"No segments for starting representation");let n=this.initData.get(i);if(ot(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer))return;let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(a,r),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));var d;this.fetcher=r,this.tuning=a,this.compatibilityMode=u,this.forwardBufferTarget=a.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!(l!=null&&l.live),this.baseUrls=(d=l==null?void 0:l.baseUrls)!=null?d:[],this.initData=new Map(i.map(c=>[c.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(c=>[c.id,c])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchToWithPreviousAbort(e,t=!1){!q(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new ae,Fi(this.switchAbortController.signal,async function*(i,r=!1){this.switchingToRepresentationId=i;let a=this.representations.get(i);ot(a,`No such representation ${i}`);let n=this.segments.get(i),o=this.initData.get(i);if(qe(o)||qe(n)?yield this.loadInit(a,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(i),ot(n,"No segments for starting representation"),o=this.initData.get(i),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer||!q(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(o,this.downloadAbortController.signal),r)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=i,yield this.dropBuffer();else{let u=this.getCurrentPosition();ls(u)&&!this.isLive&&(this.bufferLimit=this.forwardBufferTarget,yield this.pruneBuffer(u,1/0,!0)),this.downloadingRepresentationId=i,this.switchingToRepresentationId=void 0}this.maintain()}}.bind(this))(e,t))}warmUpMediaSource(){!qe(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}async abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);return this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new ae,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(qe(e)||qe(this.downloadingRepresentationId)||qe(this.playingRepresentationId)||qe(this.sourceBuffer)||!q(this.mediaSource,this.sourceBuffer)||ls(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(ot(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;let r=i.find(d=>e>=d.time.from&&e<d.time.to);ls(r)&&isFinite(r.time.from)&&isFinite(r.time.to)&&this.currentSegmentLength$.next((r==null?void 0:r.time.to)-r.time.from);let a=e,n=100;if(this.playingRepresentationId!==this.downloadingRepresentationId){let d=$e(this.sourceBuffer.buffered,e),c=r?r.time.to+n:-1/0;r&&r.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&d>=r.time.to-e+n&&(a=c)}if(isFinite(this.bufferLimit)&&Kr(this.sourceBuffer.buffered)>=this.bufferLimit){let d=$e(this.sourceBuffer.buffered,e),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,d<c).catch(h=>{this.handleAsyncError(h,"pruneBuffer")});return}let u=null;if(!this.activeSegments.size&&(u=this.selectForwardBufferSegments(i,t.segmentReference.type,a),u!=null&&u.length)){let d="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if((0,al.default)(u,r))d="high";else{let c=(0,cs.default)(u,0);c&&c.time.from-r.time.to>=this.forwardBufferTarget/2&&(d="low")}this.loadSegments(u,t,d).catch(c=>{this.handleAsyncError(c,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&r&&r.status==="fed"&&!(u!=null&&u.length)&&$e(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let l=(0,cs.default)(i,-1);!this.isLive&&l&&(this.fullyBuffered$.next(l.time.to-e-$e(this.sourceBuffer.buffered,e)<n),this.onLastSegment$.next(e-l.time.from>0))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let i=0,r=this.isLive?this.liveInitialAdditionalOffset:0;for(let a of e)Math.trunc(a.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:a.time.from+r,persistent:!0}),i=a.time.to;ls(t.duration)&&t.duration-i>0&&!this.isLive&&this.gaps.push({representation:t.id,from:i,to:t.duration,persistent:!0})}getActualLiveStartingSegments(e){let t=e.segments,i=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,r=[],a=0,n=t.length-1;do r.unshift(t[n]),a+=t[n].time.to-t[n].time.from,n--;while(a<i&&n>=0);return this.liveInitialAdditionalOffset=a-i,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){let t=(0,nl.default)(e==null?void 0:e.streams[this.kind],r=>r.representations).find(r=>r.id===this.downloadingRepresentationId);if(!t)return;let i=this.segments.get(t.id);if(i!=null&&i.length)return{from:i[0].time.from,to:i[i.length-1].time.to}}updateLive(e){var i,r,a,n;let t=(i=(0,nl.default)(e==null?void 0:e.streams[this.kind],o=>o.representations))!=null?i:[];if(![...this.segments.values()].every(o=>!o.length))for(let o of t){if(!o||!Ze(o.segmentReference))return;let u=o.segmentReference.segments.map(p=>({...p,status:"none",size:void 0})),l=100,d=(r=this.segments.get(o.id))!=null?r:[],c=(n=(a=(0,cs.default)(d,-1))==null?void 0:a.time.to)!=null?n:0,h=u==null?void 0:u.findIndex(p=>c>=p.time.from+l&&c<=p.time.to+l);if(h===-1){this.liveUpdateSegmentIndex=0;let p=this.getActualLiveStartingSegments(o.segmentReference);this.segments.set(o.id,p)}else{let p=u.slice(h+1);this.segments.set(o.id,[...d,...p])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;ot(e);let t=this.segments.get(e);if(t!=null&&t.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}updateLowLatencyLiveIfNeeded(e){let t=0;for(let i of this.representations.values()){let r=i.segmentReference;if(!Ze(r))return;let a=this.segments.get(i.id);if(!a)continue;let n=a.find(u=>Math.floor(u.time.from)===Math.floor(e.time.from));if(n&&!isFinite(n.time.to)&&(n.time.to=e.time.to,t=n.time.to-n.time.from),!!!a.find(u=>Math.floor(u.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let u=Math.round(e.time.to*r.timescale/1e3).toString(10),l=xi(r.segmentTemplateUrl,{segmentTime:u});a.push({status:"none",time:{from:e.time.to,to:1/0},url:l})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){var a,n,o;let t=(n=(a=this.switchingToRepresentationId)!=null?a:this.downloadingRepresentationId)!=null?n:this.playingRepresentationId;if(!t)return;let i=this.segments.get(t);if(!i)return;let r=i.find(u=>u.time.from<=e&&u.time.to>=e);return(o=r==null?void 0:r.time.from)!=null?o:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e,t;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)==null||e.destroy(),(t=this.sourceBufferBufferedDiff)==null||t.destroy(),this.gapDetectionIdleCallback&&Yt&&Yt(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&Yt&&Yt(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(i){if(!(i instanceof DOMException&&i.name==="NotFoundError"))throw i}this.sourceBuffer=null,this.downloadAbortController.abort(),this.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,i){return this.checkEjectedSegments(),this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){if(this.playingRepresentationId!==this.downloadingRepresentationId){let i=e.findIndex(r=>t>=r.time.from&&t<r.time.to);this.liveUpdateSegmentIndex=i}return this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):null}selectForwardBufferSegmentsRecord(e,t,i){let r=this.getForwardBufferDuration(i),a=e.findIndex(({status:h,time:{from:p,to:f}},m)=>{let g=p<=i&&f>=i,S=p>i||g||m===0&&i===0,v=Math.min(this.forwardBufferTarget,this.bufferLimit),y=this.preloadOnly&&p<=i+v||r<v&&f-p>=v||f<=i+v;return(h==="none"||h==="partially_ejected"&&S&&y&&this.sourceBuffer&&q(this.mediaSource,this.sourceBuffer)&&!(Ne(this.sourceBuffer.buffered,p)&&Ne(this.sourceBuffer.buffered,f)))&&S&&y});if(a===-1)return null;if(t!=="byteRange")return e.slice(a,a+1);let n=e,o=0,u=0,l=[],d=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,c=this.preloadOnly?this.forwardBufferTarget:0;for(let h=a;h<n.length&&(o<=d||u<=c);h++){let p=n[h];if(o+=p.byte.to+1-p.byte.from,u+=p.time.to+1-p.time.from,p.status==="none"||p.status==="partially_ejected")l.push(p);else break}return l}async loadSegments(e,t,i="auto"){Ze(t.segmentReference)?await this.loadTemplateSegment(e[0],t,i):await this.loadByteRangeSegments(e,t,i)}async loadTemplateSegment(e,t,i="auto"){e.status="downloading";let r={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(r);let{range:a,url:n,signal:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await Fi(o,async function*(){let d=Jp(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,d))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let d=await this.fetcher.fetch(n,{range:a,signal:o,onProgress:u,priority:i,isLowLatency:this.isActiveLowLatency()});if(this.lastDataObtainedTimestampMs=sl(),!d)return;let c=new DataView(d),h=Jn(t.mime);if(!isFinite(r.segment.time.to)){let m=t.segmentReference.timescale;r.segment.time.to=h.getChunkEndTime(c,m)}u&&r.feedingBytes&&l?await Promise.all(l):await this.sourceBufferTaskQueue.append(c,o);let{serverDataReceivedTimestamp:p,serverDataPreparedTime:f}=h.getServerLatencyTimestamps(c);p&&f&&this.currentLiveSegmentServerLatency$.next(f-p),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(d){this.abortActiveSegments([e]),Zn(d)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}updateRepresentationsBaseUrlIfNeeded(){if(!this.tuning.dash.enableBaseUrlSupport||!this.baseUrls.length||this.failedDownloads<=this.tuning.dash.maxSegmentRetryCount)return;this.baseUrlsIndex=(this.baseUrlsIndex+1)%this.baseUrls.length;let e=this.baseUrls[this.baseUrlsIndex];for(let t of this.representations.values())Ze(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}async loadByteRangeSegments(e,t,i="auto"){if(!e.length)return;for(let u of e)u.status="downloading",this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:r,url:a,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(await Fi(n,async function*(){let u=Jp(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),Xp(window,"online").pipe(aV()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(a,{range:r,onProgress:o,signal:n,priority:i}),this.lastDataObtainedTimestampMs=sl(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),Zn(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(Ze(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:(0,cs.default)(e,0).byte.from,to:(0,cs.default)(e,-1).byte.to},{signal:a}=this.downloadAbortController;return{url:i,range:r,signal:a,onProgress:async(o,u)=>{if(!a.aborted)try{this.lastDataObtainedTimestampMs=sl(),await this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:a,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:gr.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!Ze(t.segmentReference))throw new Error("Representation is not template type");let i=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&i.searchParams.set("low-latency","yes");let r=i.toString(),{signal:a}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,d)=>{if(!a.aborted)try{this.lastDataObtainedTimestampMs=sl();let c=this.onSomeTemplateDataLoaded({dataView:l,loaded:d,signal:a,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(c)}catch(c){this.error$.next({id:"SegmentFeeding",category:gr.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}}:void 0;return{url:r,signal:a,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,al.default)(e,t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:a}){if(!this.activeSegments.size||!q(this.mediaSource,this.sourceBuffer))return;let n=this.representations.get(t);if(n)for(let o of this.activeSegments){let{segment:u}=o;if(o.representationId===t){if(a.aborted){r();continue}if(o.loadedBytes=i,o.loadedBytes>o.feedingBytes){let l=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),d=Jn(n.mime).parseFeedableSegmentChunk(l,this.isLive);d!=null&&d.byteLength&&(u.status="partially_fed",o.feedingBytes+=d.byteLength,await this.sourceBufferTaskQueue.append(d),o.fedBytes+=d.byteLength)}}}}async onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:a,onSegmentAppendFailed:n}){if(!this.activeSegments.size||!q(this.mediaSource,this.sourceBuffer))return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){if(u.representationId!==t)continue;if(a.aborted){await n();continue}let{segment:l}=u,d=l.byte.from-i,c=l.byte.to-i,h=c-d+1,p=d<r,f=c<=r;if(p){if(l.status==="downloading"&&f){l.status="downloaded";let m=new DataView(e.buffer,e.byteOffset+d,h);await this.sourceBufferTaskQueue.append(m,a)&&!a.aborted?this.onSegmentFullyAppended(u,t):await n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(l.status==="downloading"||l.status==="partially_fed")&&(u.loadedBytes=Math.min(h,r-d),u.loadedBytes>u.feedingBytes)){let m=new DataView(e.buffer,e.byteOffset+d+u.feedingBytes,u.loadedBytes-u.feedingBytes),g=u.loadedBytes===h?m:Jn(o.mime).parseFeedableSegmentChunk(m);g!=null&&g.byteLength&&(l.status="partially_fed",u.feedingBytes+=g.byteLength,await this.sourceBufferTaskQueue.append(g,a)&&!a.aborted?(u.fedBytes+=g.byteLength,u.fedBytes===h&&this.onSegmentFullyAppended(u,t)):await n())}}}}onSegmentFullyAppended(e,t){if(!(qe(this.sourceBuffer)||!q(this.mediaSource,this.sourceBuffer))){!this.isLive&&j.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(Ne(this.sourceBuffer.buffered,e.segment.time.from,100)&&Ne(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:gr.VIDEO_PIPELINE,message:"Browser stuck on empty result of adding segment to source buffer"})),this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",Gp(e.segment)&&(e.segment.size=e.fedBytes);for(let i of this.representations.values()){if(i.id===t)continue;let r=this.segments.get(i.id);if(r)for(let a of r)a.status==="fed"&&Math.round(a.time.from)===Math.round(e.segment.time.from)&&Math.round(a.time.to)===Math.round(e.segment.time.to)&&(a.status="none")}this.isActiveLowLatency()&&this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,e.segment)}}abortSegment(e){e.status==="partially_fed"?e.status="partially_ejected":e.status!=="partially_ejected"&&(e.status="none");for(let t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[r,a]of this.initData.entries()){let n=a instanceof Promise;t||(t=n),a===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let i=this.representations.get(e);i&&(this.initLoadIdleCallback=Yr(()=>(0,kx.default)(this.loadInit(i,"low",!1),()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",i=!1){let r=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!i&&this.failedDownloads>0?Fi(this.destroyAbortController.signal,async function*(){let o=Jp(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,Jn(e.mime),r)).then(o=>{if(!o)return;let{init:u,dataView:l,segments:d}=o,c=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,c);let h=d;this.isLive&&Ze(e.segmentReference)&&(h=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,h),u&&this.parsedInitData.set(e.id,u)}).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:gr.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n}async dropBuffer(){for(let e of this.segments.values())for(let t of e)t.status="none";await this.pruneBuffer(0,1/0,!0)}async pruneBuffer(e,t,i=!1){if(!this.sourceBuffer||!q(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||qe(e))return!1;this.checkEjectedSegments();let r=[],a=0,n=o=>{var l;if(a>=t)return;r.push({...o.time});let u=Gp(o)?(l=o.size)!=null?l:0:o.byte.to-o.byte.from;a+=u};for(let o of this.segments.values())for(let u of o){let l=u.time.to<=e-this.tuning.dash.bufferPruningSafeZone,d=u.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(l||d)&&u.status==="fed"&&n(u)}for(let o=0;o<this.sourceBuffer.buffered.length;o++){let u=this.sourceBuffer.buffered.start(o)*1e3,l=this.sourceBuffer.buffered.end(o)*1e3,d=0;for(let c of this.segments.values())for(let h of c)(0,al.default)(["none","partially_ejected"],h.status)&&Math.round(h.time.from)<=Math.round(u)&&Math.round(h.time.to)>=Math.round(l)&&d++;if(d===this.segments.size){let c={time:{from:u,to:l},url:"",status:"none"};n(c)}}if(r.length&&i){let o=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let u of this.segments.values())for(let l of u)l.time.from>=e+o&&l.status==="fed"&&n(l)}return r.length?(r=yx(r),(await Promise.all(r.map(u=>this.sourceBufferTaskQueue.remove(u.from,u.to)))).reduce((u,l)=>u||l,!1)):!1}async abortBuffer(){if(!this.sourceBuffer||!q(this.mediaSource,this.sourceBuffer))return!1;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;return this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!q(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}getBufferedTo(){return!this.sourceBuffer||!q(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length?null:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}getForwardBufferDuration(e=this.getCurrentPosition()){return!this.sourceBuffer||!q(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||qe(e)?0:$e(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!this.sourceBuffer||!q(this.mediaSource,this.sourceBuffer))return;let{buffered:i}=this.sourceBuffer;this.tuning.useRefactoredSearchGap&&(this.gaps=this.gaps.filter(a=>{if(a.persistent)return!0;let n=Math.round(a.from),o=Math.round(a.to);for(let u=0;u<i.length;u++)if(n>=Math.round(i.start(u)*1e3)&&o<=Math.round(i.end(u)*1e3))return!1;return!0}));let r={representation:e,from:t.time.from,to:t.time.to,persistent:!1};for(let a=0;a<i.length;a++){let n=i.start(a)*1e3,o=i.end(a)*1e3;if(!(o<=t.time.from||n>=t.time.to)){if(n<=t.time.from&&o>=t.time.to){r=void 0;break}o>t.time.from&&o<t.time.to&&(r.from=o),n<t.time.to&&n>t.time.from&&(r.to=n)}}r&&r.to-r.from>1&&!this.gaps.some(a=>r&&a.from===r.from&&a.to===r.to)&&this.gaps.push(r)}detectGapsWhenIdle(e,t){if(!(this.gapDetectionIdleCallback||!this.sourceBuffer||!q(this.mediaSource,this.sourceBuffer))){if(!this.tuning.useRefactoredSearchGap)for(let i=0;i<this.sourceBuffer.buffered.length;i++)this.gaps=this.gaps.filter(r=>r.persistent||this.sourceBuffer&&(Math.round(r.from)<Math.round(this.sourceBuffer.buffered.start(i)*1e3)||Math.round(r.to)>Math.round(this.sourceBuffer.buffered.end(i)*1e3)));this.gapDetectionIdleCallback=Yr(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:gr.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if(qe(this.sourceBuffer)||!q(this.mediaSource,this.sourceBuffer)||qe(this.playingRepresentationId)||this.sourceBufferBufferedDiff&&!this.sourceBufferBufferedDiff.wasUpdated())return;let e=il(this.sourceBuffer.buffered),t=100;for(let i of this.segments.values())for(let r of i){let{status:a}=r;if(a!=="fed"&&a!=="partially_ejected")continue;let n=Math.floor(r.time.from),o=Math.ceil(r.time.to),u=!1,l=0;for(let d=0;d<e.length;d+=2){let c=e[d],h=e[d+1];u||(u=c-t<=n&&h+t>=o),(n>=c&&n<h-t||o>c+t&&o<=h)&&(l+=1)}u||(l===1?r.status="partially_ejected":this.gaps.some(d=>d.from===r.time.from||d.to===r.time.to)?r.status="partially_ejected":r.status="none")}}handleAsyncError(e,t){this.error$.next({id:t,category:gr.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}};import{abortable as to,assertNever as Rx,fromEvent as Mx,merge as uV,now as io,Subject as Lx,ValueSubject as Zp,flattenObject as ds,ErrorCategory as ro,SubscriptionRemovable as lV}from"@vkontakte/videoplayer-shared/es2018";var ul=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:a=!1}){this.lastConnectionType$=new Zp(void 0);this.lastConnectionReused$=new Zp(void 0);this.lastRequestFirstBytes$=new Zp(void 0);this.recoverableError$=new Lx;this.error$=new Lx;this.abortAllController=new ae;this.subscription=new lV;this.fetchManifest=to(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=Vi(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=Vu(i));let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(ol);return r?(t.log("success",ds({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(r.headers),r.text()):(t.error("error",ds({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=to(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:a="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1}={}){var M,R,Q;let l=e,d=new Headers,c=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{d.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let U=new URL(l,location.href);U.searchParams.append("bytes",`${i.from}-${i.to}`),l=U.toString();break}default:Rx(t)}this.requestQuic&&(l=Vi(l));let h=this.abortAllController.signal,p;if(n){let U=new ae;if(p=uV(Mx(this.abortAllController.signal,"abort"),Mx(n,"abort")).subscribe(()=>{try{U.abort()}catch(A){ol(A)}}),this.subscription.add(p),this.abortAllController.signal.aborted||n.aborted)try{U.abort()}catch(A){ol(A)}h=U.signal}let f=io();c.log("startRequest",ds({url:l,priority:a,rangeMethod:t,range:i,isLowLatency:u,requestStartedAt:f}));let m=yield this.doFetch(l,{priority:a,headers:d,signal:h}),g=io();if(!m)return c.error("error",{message:"No response in request"}),c.end(),this.unsubscribeAbortSubscription(p),null;if((M=this.throughputEstimator)==null||M.addRawRtt(g-f),!m.ok||!m.body){this.unsubscribeAbortSubscription(p);let U=`Fetch error ${m.status}: ${m.statusText}`;return c.error("error",{message:U}),c.end(),Promise.reject(new Error(`Fetch error ${m.status}: ${m.statusText}`))}if(this.onHeadersReceived(m.headers),!r&&!o){this.unsubscribeAbortSubscription(p);let U=io(),A={requestStartedAt:f,requestEndedAt:U,duration:U-f};return c.log("endRequest",ds(A)),c.end(),m.arrayBuffer()}let S=m.body;if(o){let U;[S,U]=m.body.tee(),(R=this.throughputEstimator)==null||R.trackStream(U,u)}let v=S.getReader(),y,I=parseInt((Q=m.headers.get("content-length"))!=null?Q:"",10);Number.isFinite(I)&&(y=I),!y&&i&&(y=i.to-i.from+1);let T=0,E=y?new Uint8Array(y):new Uint8Array(0),O=!1,L=U=>{this.unsubscribeAbortSubscription(p),O=!0,ol(U)},w=to(h,async function*({done:U,value:A}){if(T===0&&this.lastRequestFirstBytes$.next(io()-f),h.aborted){this.unsubscribeAbortSubscription(p);return}if(!U&&A){if(y)E.set(A,T),T+=A.byteLength;else{let F=new Uint8Array(E.length+A.length);F.set(E),F.set(A,E.length),E=F,T+=A.byteLength}r==null||r(new DataView(E.buffer),T),yield v==null?void 0:v.read().then(w,L)}}.bind(this));yield v==null?void 0:v.read().then(w,L),this.unsubscribeAbortSubscription(p);let P=io(),C={failed:O,requestStartedAt:f,requestEndedAt:P,duration:P-f};return O?(c.error("endRequest",ds(C)),c.end(),null):(c.log("endRequest",ds(C)),c.end(),E.buffer)}.bind(this));this.fetchByteRangeRepresentation=to(this.abortAllController.signal,async function*(e,t,i){var S;if(e.type!=="byteRange")return null;let{from:r,to:a}=e.initRange,n=r,o=a,u=!1,l,d;e.indexRange&&(l=e.indexRange.from,d=e.indexRange.to,u=a+1===l,u&&(n=Math.min(l,r),o=Math.max(d,a))),n=Math.min(n,0);let c=yield this.fetch(e.url,{range:{from:n,to:o},priority:i,measureThroughput:!1});if(!c)return null;let h=new DataView(c,r-n,a-n+1);if(!t.validateData(h))throw new Error("Invalid media file");let p=t.parseInit(h),f=(S=e.indexRange)!=null?S:t.getIndexRange(p);if(!f)throw new ReferenceError("No way to load representation index");let m;if(u)m=new DataView(c,f.from-n,f.to-f.from+1);else{let v=yield this.fetch(e.url,{range:f,priority:i,measureThroughput:!1});if(!v)return null;m=new DataView(v)}let g=t.parseSegments(m,p,f);return{init:p,dataView:new DataView(c),segments:g}}.bind(this));this.fetchTemplateRepresentation=to(this.abortAllController.signal,async function*(e,t){if(e.type!=="template")return null;let i=new URL(e.initUrl,e.baseUrl).toString(),r=yield this.fetch(i,{priority:t,measureThroughput:!1});return r?{init:null,segments:e.segments.map(n=>({...n,status:"none",size:void 0})),dataView:new DataView(r)}:null}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=r,this.tracer=i.createComponentTracer("Fetcher"),this.useEnableSubtitlesParam=a}onHeadersReceived(e){let{type:t,reused:i}=Cu(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,t,i="auto"){var a,n;let{type:r}=e;switch(r){case"byteRange":return(a=await this.fetchByteRangeRepresentation(e,t,i))!=null?a:null;case"template":return(n=await this.fetchTemplateRepresentation(e,i))!=null?n:null;default:Rx(r)}}destroy(){this.abortAllController.abort(),this.tracer.end(),this.subscription.unsubscribe()}async doFetch(e,t){let i=await wt(e,t);if(i.ok)return i;let r=await i.text(),a=parseInt(r);if(!isNaN(a))switch(a){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:ro.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:ro.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:ro.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:ro.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${a})`,category:ro.FATAL})}}unsubscribeAbortSubscription(e){e&&(e.unsubscribe(),this.subscription.remove(e))}},ol=s=>{if(!Zn(s))throw s};import{isNullable as cV,ValueSubject as dV}from"@vkontakte/videoplayer-shared/es2018";var so=class s{constructor(e,t){this.currentRepresentation$=new dV(null);this.maxRepresentations=4;this.representationsCursor=0;this.representations=[];this.currentSegment=null;this.getCurrentPosition=t.getCurrentPosition,this.processStreams(e)}updateLive(e){this.processStreams(e==null?void 0:e.streams.text)}seekLive(e){this.processStreams(e)}maintain(e=this.getCurrentPosition()){var t;if(!cV(e))for(let i of this.representations)for(let r of i){let a=r.segmentReference,n=a.segments.length,o=a.segments[0].time.from,u=a.segments[n-1].time.to;if(e<o||e>u)continue;let l=a.segments.find(d=>d.time.from<=e&&d.time.to>=e);!l||((t=this.currentSegment)==null?void 0:t.time.from)===l.time.from&&this.currentSegment.time.to===l.time.to||(this.currentSegment=l,this.currentRepresentation$.next({...r,label:"Live Text",language:"ru",isAuto:!0,url:new URL(l.url,a.baseUrl).toString()}))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e!=null?e:[]){let i=s.filterRepresentations(t.representations);if(i){this.representations[this.representationsCursor]=i,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!(e!=null&&e.some(t=>s.filterRepresentations(t.representations)))}static filterRepresentations(e){return e==null?void 0:e.filter(t=>t.kind==="text"&&"segmentReference"in t&&Ze(t.segmentReference))}};var bV=["progress","play","seeked","stalled","waiting"],gV=["timeupdate","progress","loadeddata","playing","seeked"];var dl=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new sh;this.representationSubscription=new sh;this.state$=new G("none");this.currentVideoRepresentation$=new fe(void 0);this.currentVideoRepresentationInit$=new fe(void 0);this.currentAudioRepresentation$=new fe(void 0);this.currentVideoSegmentLength$=new fe(0);this.currentAudioSegmentLength$=new fe(0);this.error$=new cl;this.lastConnectionType$=new fe(void 0);this.lastConnectionReused$=new fe(void 0);this.lastRequestFirstBytes$=new fe(void 0);this.currentLiveTextRepresentation$=new fe(null);this.isLive$=new fe(!1);this.isActiveLive$=new fe(!1);this.isLowLatency$=new fe(!1);this.liveDuration$=new fe(0);this.liveSeekableDuration$=new fe(0);this.liveAvailabilityStartTime$=new fe(0);this.liveStreamStatus$=new fe(void 0);this.bufferLength$=new fe(0);this.liveLatency$=new fe(void 0);this.liveLoadBufferLength$=new fe(0);this.livePositionFromPlayer$=new fe(0);this.currentStallDuration$=new fe(0);this.videoLastDataObtainedTimestamp$=new fe(0);this.fetcherRecoverableError$=new cl;this.fetcherError$=new cl;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new cl;this.gapWatchdogActive=!1;this.destroyController=new ae;this.initManifest=th(this.destroyController.signal,async function*(e,t,i){var r;this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=Se(t,i,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),(r=this.manifest)!=null&&r.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:Ut.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=th(this.destroyController.signal,async function*(){var n,o;this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(u=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:Ut.NETWORK,message:"Failed to load manifest",thrown:u})});if(!e)return null;let t=null;try{t=Px(e!=null?e:"",this.manifestUrlString)}catch(u){let l=(n=Mu(e))!=null?n:{id:"ManifestParsing",category:Ut.PARSER,message:"Failed to parse MPD manifest",thrown:u};this.error$.next(l)}if(!t)return null;let i=(u,l,d)=>{var c,h,p,f;return!!((h=(c=this.element)==null?void 0:c.canPlayType)!=null&&h.call(c,l)&&((f=(p=vt())==null?void 0:p.isTypeSupported)!=null&&f.call(p,`${l}; codecs="${d}"`))||u==="text")};if(t.live){this.isLive$.next(!!t.live);let{availabilityStartTime:u,latestSegmentPublishTime:l,streamIsUnpublished:d,streamIsAlive:c}=t.live,h=((o=t.duration)!=null?o:0)/1e3;this.liveSeekableDuration$.next(-1*h),this.liveDuration$.next((l-u)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let p="active";c||(p=d?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(p)}let r={text:t.streams.text,video:[],audio:[]};for(let u of["video","audio"]){let d=t.streams[u].filter(({mime:p,codecs:f})=>i(u,p,f)),c=new Set(d.map(({codecs:p})=>p)),h=zu(c);if(h&&(r[u]=d.filter(({codecs:p})=>p.startsWith(h))),u==="video"){let p=this.tuning.preferHDR,f=r.video.some(g=>g.hdr),m=r.video.some(g=>!g.hdr);j.display.isHDR&&p&&f?r.video=r.video.filter(g=>g.hdr):m&&(r.video=r.video.filter(g=>!g.hdr))}}let a={...t,streams:r};return this.tracer.log("updateManifestEnd",no(a)),a}.bind(this));this.initRepresentations=th(this.destroyController.signal,async function*(e,t,i){var h;this.tracer.log("initRepresentationsStart",no({initialVideo:e,initialAudio:t,sourceHls:i})),ps(this.manifest),ps(this.element),this.representationSubscription.unsubscribe(),this.representationSubscription=new sh,this.state$.startTransitionTo("representations_ready");let r=p=>{this.representationSubscription.add(Kt(p,"error").pipe(ll(f=>{var m;return!!((m=this.element)!=null&&m.played.length)})).subscribe(f=>{this.error$.next({id:"VideoSource",category:Ut.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:f})}))};this.source=this.tuning.useManagedMediaSource?nu():new MediaSource;let a=document.createElement("source");if(r(a),a.src=URL.createObjectURL(this.source),this.element.appendChild(a),this.tuning.useManagedMediaSource&&Ur())if(i){let p=document.createElement("source");r(p),p.type="application/x-mpegurl",p.src=i.url,this.element.appendChild(p)}else this.element.disableRemotePlayback=!0;this.isActiveLive$.next(this.isLive$.getValue());let n={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),manifest:this.manifest},o=this.manifest.streams.video.reduce((p,f)=>[...p,...f.representations],[]);if(this.videoBufferManager=new eo("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],oo(t)){let p=this.manifest.streams.audio.reduce((f,m)=>[...f,...m.representations],[]);this.audioBufferManager=new eo("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}so.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new so(this.manifest.streams.text,n)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$));let u=()=>{var p;(p=this.stallWatchdogSubscription)==null||p.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add(vr(...gV.map(p=>Kt(this.element,p))).pipe(fs(p=>this.element?$e(this.element.buffered,this.element.currentTime*1e3):0),ao(),mV(p=>{p>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add(vr(Kt(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe(ao()).subscribe(f=>this.liveStreamEndTimestamp=rh())),this.subscription.add(Kt(this.element,"pause").subscribe(()=>{this.livePauseWatchdogSubscription=ih(1e3).subscribe(f=>{let m=Mi(this.manifestUrlString,2);this.manifestUrlString=Se(this.manifestUrlString,m+1e3,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add(Kt(this.element,"play").subscribe(f=>{var m;return(m=this.livePauseWatchdogSubscription)==null?void 0:m.unsubscribe()})),this.representationSubscription.add(hs({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(fs(({isActiveLive:f,isLowLatency:m})=>f&&m),ao()).subscribe(f=>{this.isManualDecreasePlaybackInLive()||rs(this.element,1)})),this.representationSubscription.add(hs({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(ll(({bufferLength:f,isActiveLive:m,isLowLatency:g})=>m&&g&&!!f)).subscribe(({bufferLength:f})=>this.liveBuffer.next(f))),this.representationSubscription.add(this.videoBufferManager.currentLowLatencySegmentLength$.subscribe(f=>{if(!this.isActiveLive$.getValue()&&!this.isLowLatency$.getValue()&&!f)return;let m=this.liveSeekableDuration$.getValue()-f/1e3;this.liveSeekableDuration$.next(Math.max(m,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+f/1e3)})),this.representationSubscription.add(hs({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(ll(({isLive:f})=>f),ao((f,m)=>m.bufferLength<f.bufferLength),fs(({rtt:f,bufferLength:m,segmentServerLatency:g})=>{let S=Mi(this.manifestUrlString,2);return(f/2+m+g+S)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(hs({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:f,isActiveLive:m,isLowLatency:g})=>{if(!g||!m)return;let S=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,v=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,y=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,I=f-S;if(this.isManualDecreasePlaybackInLive())return;let T=1;Math.abs(I)>v&&(T=1+Math.sign(I)*y),rs(this.element,T)})),this.representationSubscription.add(this.bufferLength$.subscribe(f=>{var g,S;let m=0;if(f){let v=((S=(g=this.element)==null?void 0:g.currentTime)!=null?S:0)*1e3;m=Math.min(...this.bufferManagers.map(I=>{var T,E;return(E=(T=I.getLiveSegmentsToLoadState(this.manifest))==null?void 0:T.to)!=null?E:v}))-v}this.liveLoadBufferLength$.getValue()!==m&&this.liveLoadBufferLength$.next(m)}));let p=0;this.representationSubscription.add(hs({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(Dx(1e3)).subscribe(async({liveLoadBufferLength:f,bufferLength:m})=>{if(!this.element||this.isUpdatingLive)return;let g=this.element.playbackRate,S=Mi(this.manifestUrlString,2),v=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,y=Math.min(v,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*g),I=this.tuning.dashCmafLive.normalizedActualBufferOffset*g,T=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*g,E=isFinite(f)?f:m,O=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),L=v<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(L);let w="none";if(O?w="active_low_latency":this.isLowLatency$.getValue()&&L?(this.bufferManagers.forEach(P=>P.proceedLowLatencyLive()),w="active_low_latency"):S!==0&&E<y?w="live_forward_buffering":E<y+T&&(w="live_with_target_offset"),isFinite(f)&&(p=f>p?f:p),w==="live_forward_buffering"||w==="live_with_target_offset"){let P=p-(y+I),C=this.normolizeLiveOffset(Math.trunc(S+P/g)),M=Math.abs(C-S),R=0;!f||M<=this.tuning.dashCmafLive.offsetCalculationError?R=S:C>0&&M>this.tuning.dashCmafLive.offsetCalculationError&&(R=C),this.manifestUrlString=Se(this.manifestUrlString,R,2)}(w==="live_with_target_offset"||w==="live_forward_buffering")&&(p=0,await this.updateLive())},f=>{this.error$.next({id:"updateLive",category:Ut.VIDEO_PIPELINE,thrown:f,message:"Failed to update live with subscription"})}))}let l=vr(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe(fs(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),d=vr(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe(fs(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue()))),c=hs({allBuffersFull:l,someBufferEnded:d}).pipe(ao(),fs(({allBuffersFull:p,someBufferEnded:f})=>p&&f),ll(p=>p));if(this.representationSubscription.add(vr(this.forceEnded$,c).subscribe(()=>{var p;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(f=>!f.updating))try{(p=this.source)==null||p.endOfStream()}catch(f){this.error$.next({id:"EndOfStream",category:Ut.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:f})}})),this.representationSubscription.add(vr(...this.bufferManagers.map(p=>p.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.representationSubscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.representationSubscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.liveTextManager&&this.representationSubscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$)),this.source.readyState!=="open"){let p=this.tuning.dash.sourceOpenTimeout>=0;yield new Promise(f=>{var m;p&&(this.timeoutSourceOpenId=setTimeout(()=>{var g;if(((g=this.source)==null?void 0:g.readyState)==="open"){f();return}this.error$.next({id:"OpenOfStream",category:Ut.VIDEO_PIPELINE,message:"Failed to open MediaSource",thrown:new Error("Timeout reject when wait sourceopen event"),traceAsLog:!0})},this.tuning.dash.sourceOpenTimeout)),(m=this.source)==null||m.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),f()},{once:!0})})}if(!this.isLive$.getValue()){let p=[(h=this.manifest.duration)!=null?h:0,...(0,ah.default)((0,ah.default)([...this.manifest.streams.audio,...this.manifest.streams.video],f=>f.representations),f=>{let m=[];return f.duration&&m.push(f.duration),Ze(f.segmentReference)&&f.segmentReference.totalSegmentsDurationMs&&m.push(f.segmentReference.totalSegmentsDurationMs),m})];this.source.duration=Math.max(...p)/1e3}this.audioBufferManager&&oo(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")}.bind(this));this.tick=()=>{var t,i,r,a;if(!this.element||!this.videoBufferManager||((t=this.source)==null?void 0:t.readyState)!=="open")return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),(i=this.audioBufferManager)==null||i.maintain(e),(r=this.liveTextManager)==null||r.maintain(e),(this.videoBufferManager.gaps.length||(a=this.audioBufferManager)!=null&&a.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=ih(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),n=>{this.error$.next({id:"GapWatchdog",category:Ut.WTF,message:"Error handling gaps",thrown:n})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.fetcher=new ul({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.subscription.add(this.fetcher.recoverableError$.subscribe(this.fetcherRecoverableError$)),this.subscription.add(this.fetcher.error$.subscribe(this.fetcherError$)),this.liveBuffer=yi.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator}),this.initTracerSubscription()}async seekLive(e){var r,a,n;ps(this.element);let t=this.liveStreamStatus$.getValue()!=="active"?rh()-this.liveStreamEndTimestamp:0,i=this.normolizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=Se(this.manifestUrlString,i,2),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await((r=this.videoBufferManager)==null?void 0:r.seekLive(this.manifest.streams.video)),await((a=this.audioBufferManager)==null?void 0:a.seekLive(this.manifest.streams.audio)),(n=this.liveTextManager)==null||n.seekLive(this.manifest.streams.text))}initBuffer(){ps(this.element),this.state$.setState("running");let e=Kt(this.element,"timeupdate");this.tuning.dash.timeupdateEventTickThrottle&&(e=e.pipe(Dx(this.tuning.dash.timeupdateEventTickThrottle))),this.subscription.add(vr(...bV.map(t=>Kt(this.element,t)),Kt(window,"online"),e).subscribe(()=>this.tick(),t=>{this.error$.next({id:"DashVKPlayer",category:Ut.WTF,message:"Internal logic error",thrown:t})})),this.subscription.add(Kt(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===HTMLMediaElement.HAVE_CURRENT_DATA&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(Kt(this.element,"waiting").subscribe(()=>{var i;this.element&&this.element.readyState===HTMLMediaElement.HAVE_CURRENT_DATA&&!this.element.seeking&&Ne(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let t=()=>{var f,m,g,S,v,y,I,T,E,O,L;if(!this.element||((f=this.source)==null?void 0:f.readyState)!=="open")return;let r=this.currentStallDuration$.getValue();r+=50,this.currentStallDuration$.next(r);let a={timeInWaiting:r},n=rh(),o=100,u=(g=(m=this.videoBufferManager)==null?void 0:m.lastDataObtainedTimestamp)!=null?g:0;this.videoLastDataObtainedTimestamp$.next(u);let l=(v=(S=this.audioBufferManager)==null?void 0:S.lastDataObtainedTimestamp)!=null?v:0,d=(I=(y=this.videoBufferManager)==null?void 0:y.getForwardBufferDuration())!=null?I:0,c=(E=(T=this.audioBufferManager)==null?void 0:T.getForwardBufferDuration())!=null?E:0,h=d<o&&n-u>this.tuning.dash.crashOnStallTWithoutDataTimeout,p=this.audioBufferManager&&c<o&&n-l>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((h||p)&&r>this.tuning.dash.crashOnStallTWithoutDataTimeout||r>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${r} ms`);if(this.isLive$.getValue()&&r%2e3===0){let w=this.normolizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(w).catch(P=>{this.error$.next({id:"stallIntervalCallback",category:Ut.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:P})}),a.liveLastOffset=w}else{let w=this.element.currentTime*1e3;(O=this.videoBufferManager)==null||O.maintain(w),(L=this.audioBufferManager)==null||L.maintain(w),a.position=w}this.tracer.log("stallIntervalCallback",no(a))};(i=this.stallWatchdogSubscription)==null||i.unsubscribe(),this.stallWatchdogSubscription=ih(50).subscribe(t,r=>{this.error$.next({id:"StallWatchdogCallback",category:Ut.NETWORK,message:"Can't restore DASH after stall.",thrown:r})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,i=!1){let r={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return this.tuning.useNewSwitchTo?this.currentStallDuration$.getValue()>0?r==null?void 0:r.switchToWithPreviousAbort(t,i):r==null?void 0:r.switchTo(t,i):r==null?void 0:r.switchToOld(t,i)}async seek(e,t){var r,a,n,o,u;ps(this.element),ps(this.videoBufferManager);let i;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?i=e:i=Math.max((r=this.videoBufferManager.findSegmentStartTime(e))!=null?r:e,(n=(a=this.audioBufferManager)==null?void 0:a.findSegmentStartTime(e))!=null?n:e),this.warmUpMediaSourceIfNeeded(i),Ne(this.element.buffered,i)||await Promise.all([this.videoBufferManager.abort(),(o=this.audioBufferManager)==null?void 0:o.abort()]),!($x(this.element)||$x(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),(u=this.audioBufferManager)==null||u.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",no({requestedPosition:e,forcePrecise:t,position:i})))}warmUpMediaSourceIfNeeded(e=(t=>(t=this.element)==null?void 0:t.currentTime)()){var i;oo(this.element)&&oo(this.source)&&oo(e)&&((i=this.source)==null?void 0:i.readyState)==="ended"&&this.element.duration*1e3-e>this.tuning.dash.seekBiasInTheEnd&&this.bufferManagers.forEach(r=>r.warmUpMediaSource())}get isStreamEnded(){var e;return((e=this.source)==null?void 0:e.readyState)==="ended"}stop(){var e,t,i;this.tracer.log("stop"),(e=this.element)==null||e.querySelectorAll("source").forEach(r=>{URL.revokeObjectURL(r.src),r.remove()}),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(t=this.videoBufferManager)==null||t.destroy(),this.videoBufferManager=null,(i=this.audioBufferManager)==null||i.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){var e;return(e=this.manifest)==null?void 0:e.streams}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){var e;this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),((e=this.source)==null?void 0:e.readyState)==="open"&&Array.from(this.source.sourceBuffers).every(t=>!t.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=fV(this.tracer.error.bind(this.tracer));this.subscription.add(this.error$.subscribe(e("error")))}isManualDecreasePlaybackInLive(){return!this.element||!this.isLive$.getValue()?!1:1-this.element.playbackRate>this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){var e,t;this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&((e=this.bufferManagers)==null||e.forEach(i=>i.updateLive(this.manifest)),(t=this.liveTextManager)==null||t.updateLive(this.manifest)),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getBufferedTo();if(e===null)return;let t=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),i=this.isJumpGapAfterSeekLive,r=this.element.currentTime;this.isJumpGapAfterSeekLive&&!t&&this.element.currentTime>e&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let a=this.element.currentTime*1e3,n=null,o=this.element.readyState===HTMLMediaElement.HAVE_METADATA?this.tuning.endGapTolerance:0;for(let u of this.bufferManagers)for(let l of u.gaps)(l.persistent||u.playingRepresentation$.getValue()===l.representation)&&l.from-o<=a&&l.to+o>a&&(this.element.duration*1e3-l.to<this.tuning.endGapTolerance?n=1/0:(n===null||l.to>n)&&(n=l.to));if(n!==null){let u=n+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,u===1/0?this.forceEnded$.next():(this.element.currentTime=u/1e3,this.tracer.log("jumpGap",no({isJumpGapAfterSeekLive:i,isActiveLowLatency:t,initialCurrentTime:r,jumpTo:u,resultCurrentTime:this.element.currentTime})))}}};import{combine as SV,map as vV,observeElementSize as yV,Subscription as TV,ValueSubject as nh,noop as IV}from"@vkontakte/videoplayer-shared/es2018";var pl=class{constructor(){this.subscription=new TV;this.pipSize$=new nh(void 0);this.videoSize$=new nh(void 0);this.elementSize$=new nh(void 0);this.pictureInPictureWindowRemoveEventListener=IV}connect({observableVideo:e,video:t}){let i=r=>{let a=r.target;this.pipSize$.next({width:a.width,height:a.height})};this.subscription.add(yV(t).subscribe(this.videoSize$)).add(e.enterPip$.subscribe(({pictureInPictureWindow:r})=>{this.pipSize$.next({width:r.width,height:r.height}),r.addEventListener("resize",i),this.pictureInPictureWindowRemoveEventListener=()=>{r.removeEventListener("resize",i)}})).add(e.leavePip$.subscribe(()=>{this.pictureInPictureWindowRemoveEventListener()})).add(SV({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(vV(({videoSize:r,inPip:a,pipSize:n})=>a?n:r)).subscribe(this.elementSize$))}getValue(){return this.elementSize$.getValue()}subscribe(e,t){return this.elementSize$.subscribe(e,t)}getObservable(){return this.elementSize$}destroy(){this.pictureInPictureWindowRemoveEventListener(),this.subscription.unsubscribe()}};var yr=class{constructor(e){this.subscription=new RV;this.videoState=new G("stopped");this.observableVideo=null;this.droppedFramesManager=new Gr;this.stallsManager=new Ju;this.elementSizeManager=new pl;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new $i;this.audioTrackSwitchHistory=new $i;this.selectedRepresentations={audio:null,video:null};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(r.state==="requested"&&(i==null?void 0:i.to)!=="paused"&&e!=="stopped"&&t!=="stopped"&&this.seek(r.position,r.forcePrecise),t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),B(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"),B(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="ready"&&B(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"&&B(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&B(this.params.desiredState.playbackState,"paused");return;default:return EV(e)}}};this.init3DScene=e=>{var i,r,a;if(this.scene3D)return;this.scene3D=new os(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((i=e.projectionData)==null?void 0:i.pose.yaw)||0,y:((r=e.projectionData)==null?void 0:r.pose.pitch)||0,z:((a=e.projectionData)==null?void 0:a.pose.roll)||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSizeManager.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.textTracksManager=new xt(e.source.url),this.params=e,this.video=tt(e.container,e.tuning),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Fe(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.player=new dl({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params;kV(this.observableVideo)&&(this.observableVideo=st(this.video),this.subscription.add(()=>{var n;return(n=this.observableVideo)==null?void 0:n.destroy()}));let i=this.constructor.name,r=n=>{e.error$.next({id:i,category:Cx.WTF,message:`${i} internal logic error`,thrown:n})},a=(n,o)=>this.subscription.add(n.subscribe(o,r));return{output:e,desiredState:t,observableVideo:this.observableVideo,genericErrorListener:r,connect:a}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:a}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(oh(c=>!!c.length),Ox()).subscribe(c=>{this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:c})}));let n=this.params.desiredState.seekState.stateChangeEnded$.pipe(uh(c=>c.to.state!=="none"),hl());this.stallsManager.init({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$,videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,tuning:this.params.tuning.stallsManager,abrParams:this.params.tuning.autoTrackSelection,isBuffering$:i.isBuffering$,looped$:i.looped$,playing$:i.playing$}),a(i.ended$,e.endedEvent$),a(i.looped$,e.loopedEvent$),a(i.error$,e.error$),a(i.isBuffering$,e.isBuffering$),a(i.currentBuffer$,e.currentBuffer$),a(i.playing$,e.firstFrameEvent$),a(i.canplay$,e.canplay$),a(i.inPiP$,e.inPiP$),a(i.inFullscreen$,e.inFullscreen$),a(i.loadedMetadata$,e.loadedMetadataEvent$),a(this.player.error$,e.error$),a(this.player.fetcherRecoverableError$,e.fetcherRecoverableError$),a(this.player.fetcherError$,e.fetcherError$),a(this.player.lastConnectionType$,e.httpConnectionType$),a(this.player.lastConnectionReused$,e.httpConnectionReused$),a(this.player.isLive$,e.isLive$),a(this.player.lastRequestFirstBytes$.pipe(oh(Vx),Ox()),e.firstBytesEvent$),a(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),a(this.videoState.stateChangeEnded$.pipe(uh(c=>c.to)),this.params.output.playbackState$),this.subscription.add(i.looped$.subscribe(()=>this.player.warmUpMediaSourceIfNeeded(),r)),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(zt(this.video,t.isLooped,r)),this.subscription.add(rt(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(It(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),a(Et(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),B(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),B(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:c})=>{if(c==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let h=this.player.getStreams();if(wV(h,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let f=[];for(let m of h.audio){f.push(zp(m));let g=[];for(let S of m.representations){let v=gx(S);g.push(v),this.audioTracksMap.set(v,{stream:m,representation:S})}this.audioStreamsMap.set(m,g)}this.params.output.availableAudioStreams$.next(f)}let p=[];for(let f of h.video){p.push(Qp(f));let m=[];for(let g of f.representations){let S=bx({...g,streamId:f.id});S&&(m.push(S),this.videoTracksMap.set(S,{stream:f,representation:g}))}this.videoStreamsMap.set(f,m)}this.params.output.availableVideoStreams$.next(p);for(let f of h.text)for(let m of f.representations){let g=Sx(f,m);this.textTracksMap.set(g,{stream:f,representation:m})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else c==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r));let{vktvAbrThrottle:o}=this.params.tuning.dash,u=o&&Tx(o)||null;this.subscription.add(fl(this.player.currentStallDuration$,this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,this.elementSizeManager.getObservable(),this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,PV(this.video,"progress")).pipe(oh(()=>this.videoTracksMap.size>0)).subscribe(async()=>{let c=this.player.state$.getState(),h=this.player.state$.getTransition();if(c!=="manifest_ready"&&c!=="running"||h||c==="running"&&u&&!u())return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState()),this.selectVideoAudioRepresentations();let{video:p,audio:f}=this.selectedRepresentations;if(!p)return;let m=br(this.videoTracksMap.keys(),S=>{var v;return((v=this.videoTracksMap.get(S))==null?void 0:v.representation.id)===p.id});Vx(m)&&(this.stallsManager.lastVideoTrackSelected=m);let g=this.params.desiredState.autoVideoTrackLimits.getTransition();if(g&&this.params.output.autoVideoTrackLimits$.next(g.to),c==="manifest_ready")await this.player.initRepresentations(p.id,f==null?void 0:f.id,this.params.sourceHls);else if(await this.player.switchRepresentation("video",p.id),f){let S=!!t.audioStream.getTransition();await this.player.switchRepresentation("audio",f.id,S)}},r)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:c})=>{this.scene3D&&c&&this.scene3D.pointCameraTo(c.x,c.y)})),this.subscription.add(this.elementSizeManager.subscribe(c=>{this.scene3D&&c&&this.scene3D.setViewportSize(c.width,c.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(hl()).subscribe(c=>{let h=br(this.videoTracksMap.entries(),([,{representation:g}])=>g.id===c);if(!h){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[p,{stream:f}]=h,m=this.params.desiredState.videoStream.getTransition();m&&m.to&&m.to.id===f.id&&this.params.desiredState.videoStream.setState(m.to),e.currentVideoTrack$.next(p),e.currentVideoStream$.next(Qp(f))},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(hl()).subscribe(c=>{let h=br(this.audioTracksMap.entries(),([,{representation:g}])=>g.id===c);if(!h){e.currentAudioStream$.next(void 0);return}let[p,{stream:f}]=h,m=this.params.desiredState.audioStream.getTransition();m&&m.to&&m.to.id===f.id&&this.params.desiredState.audioStream.setState(m.to),e.currentAudioStream$.next(zp(f))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(c=>{var h,p;if(c!=null&&c.is3dVideo&&((h=this.params.tuning.spherical)!=null&&h.enabled))try{this.init3DScene(c),e.is3DVideo$.next(!0)}catch(f){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${f}`})}else this.destroy3DScene(),(p=this.params.tuning.spherical)!=null&&p.enabled&&e.is3DVideo$.next(!1)},r)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,r)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,r)),this.textTracksManager.connect(this.video,t,e);let l=t.playbackState.stateChangeStarted$.pipe(uh(({to:c})=>c==="ready"),hl());this.subscription.add(fl(l,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,lh(["init"])).subscribe(()=>{let c=t.autoVideoTrackSwitching.getState(),p=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:c?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(p)})),this.subscription.add(fl(l,this.player.state$.stateChangeEnded$,lh(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let d=fl(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,lh(["init"])).pipe(AV(0));this.subscription.add(d.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){var L,w,P,C,M,R,Q,U,A,F,k,x;if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?Ma:Ra,t=this.params.tuning.useNewAutoSelectVideoTrack?xu:Iu,i=this.params.tuning.useNewAutoSelectVideoTrack?Wt:Tu,{desiredState:r,output:a}=this.params,n=r.autoVideoTrackSwitching.getState(),o=(L=r.videoTrack.getState())==null?void 0:L.id,u=br(this.videoTracksMap.keys(),$=>$.id===o),l=a.currentVideoTrack$.getValue(),d=((C=(P=r.videoStream.getState())!=null?P:u&&((w=this.videoTracksMap.get(u))==null?void 0:w.stream))!=null?C:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!d)return;let c=br(this.videoStreamsMap.keys(),$=>$.id===d.id),h=c&&this.videoStreamsMap.get(c);if(!h)return;let p=$e(this.video.buffered,this.video.currentTime*1e3),f;this.player.isActiveLive$.getValue()?f=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?f=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:f=n?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let m=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,g=Math.min(p/Math.min(f,m||1/0),1),S=(M=r.audioStream.getState())!=null?M:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,v=(S==null?void 0:S.id)&&br(this.audioStreamsMap.keys(),$=>$.id===S.id)||this.audioStreamsMap.keys().next().value,y=0;if(v){if(u&&!n){let $=e(u,h,(R=this.audioStreamsMap.get(v))!=null?R:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);y=Math.max(y,(Q=$==null?void 0:$.bitrate)!=null?Q:-1/0)}if(l){let $=e(l,h,(U=this.audioStreamsMap.get(v))!=null?U:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);y=Math.max(y,(A=$==null?void 0:$.bitrate)!=null?A:-1/0)}}let I=u;(n||!I)&&(I=i(h,{container:this.elementSizeManager.getValue(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.stallsManager.abrTuningParams,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:y,forwardBufferHealth:g,current:l,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,stallsVideoMaxQualityLimit:this.stallsManager.videoMaxQualityLimit,stallsPredictedThroughput:this.stallsManager.predictedThroughput,abrLogger:this.params.dependencies.abrLogger}));let T=v&&t(I,h,(F=this.audioStreamsMap.get(v))!=null?F:[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.stallsManager.abrTuningParams,forwardBufferHealth:g,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),E=(k=this.videoTracksMap.get(I))==null?void 0:k.representation,O=T&&((x=this.audioTracksMap.get(T))==null?void 0:x.representation);E&&O?(this.selectedRepresentations.video=E,this.selectedRepresentations.audio=O):E&&!O&&this.audioTracksMap.size===0&&(this.selectedRepresentations.video=E,this.selectedRepresentations.audio=null)}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){at(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),B(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Cx.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.stallsManager.destroy(),this.elementSizeManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),this.params.output.currentVideoStream$.next(void 0),it(this.video),this.tracer.end()}};var uo=class extends yr{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};import{combine as ch,merge as _x,filter as Fx,filterChanged as MV,isNullable as dh,map as Nx,ValueSubject as ph,isNonNullable as LV}from"@vkontakte/videoplayer-shared/es2018";var lo=class extends yr{constructor(e){super(e),this.textTracksManager.destroy()}subscribe(){super.subscribe();let e=-1,{output:t,observableVideo:i,desiredState:r,connect:a}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),a(i.timeUpdate$,t.liveBufferTime$),a(this.player.liveSeekableDuration$,t.duration$),a(this.player.liveLatency$,t.liveLatency$);let n=new ph(1);a(i.playbackRateState$,n),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(r.isLowLatency.stateChangeEnded$.pipe(Nx(o=>o.to)).subscribe(this.player.isLowLatency$)).add(ch({liveBufferTime:t.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(Nx(({liveBufferTime:o,liveAvailabilityStartTime:u})=>o&&u?o+u:void 0)).subscribe(t.liveTime$)).add(this.player.liveStreamStatus$.pipe(Fx(o=>LV(o))).subscribe(o=>t.isLiveEnded$.next(o!=="active"&&t.position$.getValue()===0))).add(ch({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:_x(i.playbackRateState$,new ph(1))}).pipe(Fx(({liveStreamStatus:o,liveDuration:u})=>o==="active"&&!!u)).subscribe(({liveDuration:o,playbackRate:u})=>{let l=t.liveBufferTime$.getValue(),d=t.position$.getValue(),{playbackCatchupSpeedup:c}=this.params.tuning.dashCmafLive.lowLatency;d||u<1-c||this.video.paused||dh(l)||(e=o-l)})).add(ch({time:t.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:_x(i.playbackRateState$,new ph(1))}).pipe(MV((o,u)=>this.player.liveStreamStatus$.getValue()==="active"?o.liveDuration===u.liveDuration:o.time===u.time)).subscribe(({time:o,liveDuration:u,playbackRate:l})=>{let d=t.position$.getValue(),{playbackCatchupSpeedup:c}=this.params.tuning.dashCmafLive.lowLatency;if(!d&&!this.video.paused&&l>=1-c||dh(o)||dh(u))return;let h=-1*(u-o-e);t.position$.next(Math.min(h,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(o=>{if(o){let u=vx(o);this.params.output.availableTextTracks$.next([u])}}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=Math.trunc(t/1e3<=Math.abs(this.params.output.duration$.getValue())?t:0);this.player.seekLive(i).then(()=>{this.params.output.position$.next(e/1e3)})}};var Ux="X-Playback-Duration",hh=async s=>{var r;let e=await wt(s),t=await e.text(),i=(r=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t))==null?void 0:r[1];return i?parseInt(i,10):e.headers.has(Ux)?parseInt(e.headers.get(Ux),10):void 0};import{assertNever as qV,combine as jV,debounce as HV,ErrorCategory as gl,filter as zV,filterChanged as QV,isNonNullable as Hx,isNullable as Sl,map as zx,merge as GV,observableFrom as WV,Subscription as YV,ValueSubject as bh,VideoQuality as KV}from"@vkontakte/videoplayer-shared/es2018";var mh=N(qc(),1);import{videoSizeToQuality as BV,getExponentialDelay as $V}from"@vkontakte/videoplayer-shared/es2018";var DV=s=>{let e=null;if(s.QUALITY&&(e=Bi(s.QUALITY)),!e&&s.RESOLUTION){let[t,i]=s.RESOLUTION.split("x").map(r=>parseInt(r,10));e=BV({width:t,height:i})}return e!=null?e:null},CV=(s,e)=>{var a,n;let t=s.split(`
186
+ `),i=[],r=[];for(let o=0;o<t.length;o++){let u=t[o],l=u.match(/^#EXT-X-STREAM-INF:(.+)/),d=u.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!l&&!d)){if(l){let c=(0,mh.default)(l[1].split(",").map(v=>v.split("="))),h=(a=c.QUALITY)!=null?a:`stream-${c.BANDWIDTH}`,p=DV(c),f;c.BANDWIDTH&&(f=parseInt(c.BANDWIDTH,10)/1e3||void 0),!f&&c["AVERAGE-BANDWIDTH"]&&(f=parseInt(c["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let m=c["FRAME-RATE"]?parseFloat(c["FRAME-RATE"]):void 0,g;if(c.RESOLUTION){let[v,y]=c.RESOLUTION.split("x").map(I=>parseInt(I,10));v&&y&&(g={width:v,height:y})}let S=new URL(t[++o],e).toString();p&&i.push({id:h,quality:p,url:S,bandwidth:f,size:g,fps:m})}if(d){let c=(0,mh.default)(d[1].split(",").map(m=>{let g=m.indexOf("=");return[m.substring(0,g),m.substring(g+1)]}).map(([m,g])=>[m,g.replace(/^"|"$/g,"")])),h=(n=c.URI)==null?void 0:n.replace(/playlist$/,"subtitles.vtt"),p=c.LANGUAGE,f=c.NAME;h&&p&&r.push({type:"internal",id:p,label:f,language:p,url:h,isAuto:!1})}}}if(!i.length)throw new Error("Empty manifest");return{qualityManifests:i,textTracks:r}},VV=s=>new Promise(e=>{setTimeout(()=>{e()},s)}),fh=0,qx=async(s,e=s,t,i)=>{let a=await(await wt(s,i)).text();fh+=1;try{let{qualityManifests:n,textTracks:o}=CV(a,e);return{qualityManifests:n,textTracks:o}}catch(n){if(fh<=t.manifestRetryMaxCount)return await VV($V(fh-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),qx(s,e,t)}return{qualityManifests:[],textTracks:[]}},ml=qx;import{isNonNullable as OV,Subscription as _V,throttle as FV,ValueSubject as jx,Subject as NV,ErrorCategory as UV}from"@vkontakte/videoplayer-shared/es2018";var bl=class{constructor(e,t,i,r,a){this.subscription=new _V;this.abortControllers={destroy:new ae,nextManifest:null};this.prepareUrl=void 0;this.currentTextTrackData=null;this.availableTextTracks$=new jx(null);this.getCurrentTime$=new jx(null);this.error$=new NV;this.params={fetchManifestData:i,sourceUrl:r,downloadThreshold:a},this.subscription.add(e.pipe(FV(1e3)).subscribe(n=>{this.processLiveTime(n)})),this.getCurrentTime$.next(()=>this.currentTextTrackData?this.currentTextTrackData.playlist.segmentStartTime/1e3+t.currentTime:0)}destroy(){this.subscription.unsubscribe(),this.abortControllers.destroy.abort()}async prepare(e){try{let t=new URL(e);t.searchParams.set("enable-subtitles","yes"),this.prepareUrl=t.toString();let{textTracks:i}=await this.fetchManifestData();await this.processTextTracks(i,this.params.sourceUrl)}catch(t){this.error("prepare",t)}}async processTextTracks(e,t){try{let i=await this.parseTextTracks(e,t);i&&(this.currentTextTrackData=i)}catch(i){this.error("processTextTracks",i)}}async parseTextTracks(e,t){for(let i of e){let r=new URL(i.url,t).toString(),n=await(await wt(r,{signal:this.abortControllers.destroy.signal})).text(),o=this.parsePlaylist(n,r);return{textTrack:i,playlist:o}}}parsePlaylist(e,t){let i={mediaSequence:0,programDateTime:"",segments:[],targetDuration:0,vkPlaybackDuration:0,segmentStartTime:0,vkStartTime:""},r=e.split(`
187
+ `),a=0;for(let n=0;n<r.length;++n){let o=r[n];switch(!0){case o.startsWith("#EXTINF:"):{let u=r[++n],l=new URL(u,t).toString(),d=Number(this.extractPlaylistRowValue("#EXTINF:",o))*1e3;if(i.segments.push({time:{from:a,to:a+d},url:l}),a=a+d,!i.segmentStartTime){let c=new Date(i.vkStartTime).valueOf(),h=new Date(i.programDateTime).valueOf();i.segmentStartTime=h-c}break}case o.startsWith("#EXT-X-TARGETDURATION:"):i.targetDuration=Number(this.extractPlaylistRowValue("#EXT-X-TARGETDURATION:",o));break;case o.startsWith("#EXT-X-MEDIA-SEQUENCE:"):i.mediaSequence=Number(this.extractPlaylistRowValue("#EXT-X-MEDIA-SEQUENCE:",o));break;case o.startsWith("#EXT-X-VK-PLAYBACK-DURATION:"):i.vkPlaybackDuration=Number(this.extractPlaylistRowValue("#EXT-X-VK-PLAYBACK-DURATION:",o));break;case o.startsWith("#EXT-X-PROGRAM-DATE-TIME:"):{let u=this.extractPlaylistRowValue("#EXT-X-PROGRAM-DATE-TIME:",o);i.programDateTime=u;let l=new Date(u);l.setMilliseconds(0),a=l.valueOf();break}case o.startsWith("#EXT-X-VK-START-TIME:"):i.vkStartTime=this.extractPlaylistRowValue("#EXT-X-VK-START-TIME:",o);break}}return i}extractPlaylistRowValue(e,t){switch(e){case"#EXTINF:":return t.substring(e.length,t.length-1);default:return t.substring(e.length)}}processLiveTime(e){if(OV(e)&&this.currentTextTrackData){let{segments:t}=this.currentTextTrackData.playlist,{from:i}=t[0].time,{to:r}=t[t.length-1].time;if(e<i||e>r)return;r-e<this.params.downloadThreshold&&this.fetchNextManifestData();for(let n of t)if(n.time.from<=e&&n.time.to>=e){this.availableTextTracks$.next([{...this.currentTextTrackData.textTrack,url:n.url,isAuto:!0}]);break}}}async fetchNextManifestData(){try{if(this.abortControllers.nextManifest)return;this.abortControllers.nextManifest=new ae;let{textTracks:e}=await this.fetchManifestData(),t=await this.parseTextTracks(e,this.params.sourceUrl);this.currentTextTrackData&&t&&(this.currentTextTrackData.playlist.segments=t.playlist.segments)}catch(e){this.error("fetchNextManifestData",e)}finally{this.abortControllers.nextManifest=null}}async fetchManifestData(){var t;let e=(t=this.prepareUrl)!=null?t:this.params.sourceUrl;return await this.params.fetchManifestData(e,{signal:this.abortControllers.destroy.signal})}error(e,t){this.error$.next({id:"[LiveTextManager][HLS_LIVE_CMAF]",category:UV.WTF,thrown:t,message:e})}};var co=class{constructor(e){this.subscription=new YV;this.videoState=new G("stopped");this.textTracksManager=null;this.liveTextManager=null;this.manifests$=new bh([]);this.liveOffset=new or;this.manifestStartTime$=new bh(void 0);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),B(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"?B(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),B(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"&&B(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"&&(B(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return qV(t)}};var i;this.params=e,this.video=tt(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:KV.INVARIANT,url:this.params.source.url};let t=(r,a)=>ml(r,this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},a);this.params.tuning.useHlsLiveNewTextManager?this.liveTextManager=new bl(this.params.output.liveTime$,this.video,t,this.params.source.url,this.params.tuning.hlsLiveNewTextManagerDownloadThreshold):this.textTracksManager=new xt(e.source.url),t(this.generateLiveUrl()).then(({qualityManifests:r,textTracks:a})=>{var n;r.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:gl.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),(n=this.liveTextManager)==null||n.processTextTracks(a,this.params.source.url),this.manifests$.next([this.masterManifest,...r])}).catch(r=>{this.params.output.error$.next({id:"ExtractHlsQualities",category:gl.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:r})}),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Fe(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new bh((i=e.source.maxSeekBackTime)!=null?i:1/0),this.subscribe()}selectManifest(){var u,l,d,c;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),a=(c=(d=(u=r==null?void 0:r.to)==null?void 0:u.id)!=null?d:(l=t.getState())==null?void 0:l.id)!=null?c:"master",n=this.manifests$.getValue();if(!n.length)return;let o=i?"master":a;return i&&!r&&t.startTransitionTo(this.masterManifest),n.find(h=>h.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsLiveProvider",category:gl.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},r=st(this.video);this.subscription.add(()=>r.destroy());let a=(o,u)=>this.subscription.add(o.subscribe(u,i));a(r.ended$,e.endedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.loadedMetadata$,e.loadedMetadataEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(rt(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(It(this.video,t.playbackRate,r.playbackRateState$,i)),a(Et(this.video),e.elementVisible$),this.liveTextManager?(a(this.liveTextManager.getCurrentTime$,this.params.output.getCurrentTime$),a(this.liveTextManager.error$,this.params.output.error$)):this.textTracksManager&&this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),B(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),B(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.liveTextManager&&this.subscription.add(this.liveTextManager.availableTextTracks$.subscribe(o=>{o&&this.params.output.availableTextTracks$.next(o)})),this.subscription.add(this.maxSeekBackTime$.pipe(QV(),zx(o=>-o/1e3)).subscribe(this.params.output.duration$,i)),this.subscription.add(r.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&Hx(l.to)){let c=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let h=this.manifests$.getValue().find(p=>p.id===c);h&&(this.params.output.currentVideoTrack$.next(h),this.params.output.hostname$.next(Fe(h.url)))}d&&this.params.desiredState.autoVideoTrackSwitching.setState(d.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o&&o.state==="requested"&&this.seek(o.position)},i)),this.subscription.add(r.loadedData$.subscribe(()=>{var u,l,d;let o=(d=(l=(u=this.video)==null?void 0:u.getStartDate)==null?void 0:l.call(u))==null?void 0:d.getTime();this.manifestStartTime$.next(o||void 0)},i)),this.subscription.add(jV({startTime:this.manifestStartTime$.pipe(zV(Hx)),currentTime:r.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),i)),this.subscription.add(this.manifests$.pipe(zx(o=>o.map(({id:u,quality:l,size:d,bandwidth:c,fps:h})=>({id:u,quality:l,size:d,fps:h,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,i));let n=GV(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,WV(["init"])).pipe(HV(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){var e,t;this.subscription.unsubscribe(),(e=this.textTracksManager)==null||e.destroy(),(t=this.liveTextManager)==null||t.destroy(),this.params.output.element$.next(void 0),it(this.video)}prepare(){var o,u,l;let e=this.selectManifest();if(Sl(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:d,min:c}=(u=(o=t==null?void 0:t.to)!=null?o:i)!=null?u:{};for(let[h,p]of[[d,"mq"],[c,"lq"]]){let f=String(parseFloat(h||""));p&&h&&r.searchParams.set(p,f)}}let a=this.params.format==="HLS_LIVE_CMAF"?2:0,n=Se(r.toString(),this.liveOffset.getTotalOffset(),a);(l=this.liveTextManager)==null||l.prepare(n),this.video.setAttribute("src",n),this.video.load(),hh(n).then(d=>{var c;if(!Sl(d))this.maxSeekBackTime$.next(d);else{let h=(c=this.params.source.maxSeekBackTime)!=null?c:this.maxSeekBackTime$.getValue();(Sl(h)||!isFinite(h))&&wt(n).then(p=>p.text()).then(p=>{var m;let f=(m=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(p))==null?void 0:m[1];if(f){let g=new URL(f,n).toString();hh(g).then(S=>{Sl(S)||this.maxSeekBackTime$.next(S)})}}).catch(()=>{})}})}playIfAllowed(){at(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),B(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:gl.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3),this.params.output.seekedEvent$.next()}generateLiveUrl(){let e=Se(this.params.source.url);if(this.params.tuning.useHlsLiveNewTextManager){let t=new URL(e);t.searchParams.set("enable-subtitles","yes"),e=t.toString()}return e}};import{assertNever as XV,debounce as JV,ErrorCategory as gh,fromEvent as Sh,isNonNullable as ZV,isNullable as eO,map as Qx,merge as Gx,observableFrom as Wx,Subscription as tO,ValueSubject as iO,VideoQuality as rO}from"@vkontakte/videoplayer-shared/es2018";var po=class{constructor(e){this.subscription=new tO;this.videoState=new G("stopped");this.manifests$=new iO([]);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),B(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"?B(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),B(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"&&B(this.params.desiredState.playbackState,"playing");return;case"paused":i==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&B(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return XV(t)}};this.textTracksManager=new xt(e.source.url),this.params=e,this.video=tt(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:rO.INVARIANT,url:this.params.source.url},this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Fe(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),ml(Se(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:t,textTracks:i})=>{this.manifests$.next([this.masterManifest,...t]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(i)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:gh.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){var u,l,d,c;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),a=(c=(d=(u=r==null?void 0:r.to)==null?void 0:u.id)!=null?d:(l=t.getState())==null?void 0:l.id)!=null?c:"master",n=this.manifests$.getValue();if(!n.length)return;let o=i?"master":a;return i&&(!r||!r.from)&&t.startTransitionTo(this.masterManifest),n.find(h=>h.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsProvider",category:gh.WTF,message:"HlsProvider internal logic error",thrown:o})},r=st(this.video);this.subscription.add(()=>r.destroy());let a=(o,u)=>this.subscription.add(o.subscribe(u));if(a(r.timeUpdate$,e.position$),a(r.durationChange$,e.duration$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.loadedMetadata$,e.loadedMetadataEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.seeked$,e.seekedEvent$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),a(this.videoState.stateChangeEnded$.pipe(Qx(o=>o.to)),this.params.output.playbackState$),this.subscription.add(zt(this.video,t.isLooped,i)),this.subscription.add(rt(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(It(this.video,t.playbackRate,r.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),B(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),B(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i).add(r.loadedMetadata$.subscribe(()=>{var p;let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&ZV(l.to)){let f=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let m=this.manifests$.getValue().find(g=>g.id===f);m&&(this.params.output.currentVideoTrack$.next(m),this.params.output.hostname$.next(Fe(m.url)))}let c=this.params.desiredState.playbackRate.getState(),h=(p=this.params.output.element$.getValue())==null?void 0:p.playbackRate;if(c!==h){let f=this.params.output.element$.getValue();f&&(this.params.desiredState.playbackRate.setState(c),f.playbackRate=c)}d&&this.params.desiredState.autoVideoTrackSwitching.setState(d.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o.state==="requested"&&this.seek(o.position)},i))),this.subscription.add(this.manifests$.pipe(Qx(o=>o.map(({id:u,quality:l,size:d,bandwidth:c,fps:h})=>({id:u,quality:l,size:d,fps:h,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,i)),!j.device.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(Gx(Sh(o,"addtrack"),Sh(o,"removetrack"),Sh(o,"change"),Wx(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},i))}let n=Gx(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,Wx(["init"])).pipe(JV(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),it(this.video)}prepare(){var a,n;let e=this.selectManifest();if(eO(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:o,min:u}=(n=(a=t==null?void 0:t.to)!=null?a:i)!=null?n:{};for(let[l,d]of[[o,"mq"],[u,"lq"]]){let c=String(parseFloat(l||""));d&&l&&r.searchParams.set(d,c)}}this.video.setAttribute("src",r.toString()),this.video.load()}playIfAllowed(){at(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),B(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:gh.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var Xx=N(Ji(),1),vh=N(nr(),1),Jx=N(Ot(),1);import{assertNever as sO,assertNonNullable as Yx,debounce as aO,ErrorCategory as Kx,isHigherOrEqual as nO,isLowerOrEqual as oO,isNonNullable as uO,merge as lO,observableFrom as cO,Subscription as dO,map as pO}from"@vkontakte/videoplayer-shared/es2018";var ho=class{constructor(e){this.subscription=new dO;this.videoState=new G("stopped");this.trackUrls={};this.textTracksManager=new xt;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),B(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"?B(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),B(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"&&B(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&B(this.params.desiredState.playbackState,"paused");return;default:return sO(e)}};this.params=e,this.video=tt(e.container,e.tuning),this.params.output.element$.next(this.video),(0,Xx.default)(this.params.source).reverse().forEach(([t,i],r)=>{let a=r.toString(10);this.trackUrls[a]={track:{quality:t,id:a},url:i}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next((0,vh.default)(this.trackUrls).map(({track:t})=>t)),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.subscribe()}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"MpegProvider",category:Kx.WTF,message:"MpegProvider internal logic error",thrown:o})},r=st(this.video);this.subscription.add(()=>r.destroy());let a=(o,u)=>this.subscription.add(o.subscribe(u,i));a(r.timeUpdate$,e.position$),a(r.durationChange$,e.duration$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.loadedMetadata$,e.loadedMetadataEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.seeked$,e.seekedEvent$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),a(this.videoState.stateChangeEnded$.pipe(pO(o=>o.to)),this.params.output.playbackState$),this.subscription.add(zt(this.video,t.isLooped,i)),this.subscription.add(rt(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(It(this.video,t.playbackRate,r.playbackRateState$,i)),a(Et(this.video),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),B(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),B(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var u,l;((u=this.videoState.getTransition())==null?void 0:u.to)==="ready"&&this.videoState.setState("ready");let o=this.params.desiredState.videoTrack.getTransition();if(o&&uO(o.to)){this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to.id].track);let d=this.params.desiredState.playbackRate.getState(),c=(l=this.params.output.element$.getValue())==null?void 0:l.playbackRate;if(d!==c){let h=this.params.output.element$.getValue();h&&(this.params.desiredState.playbackRate.setState(d),h.playbackRate=d)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.textTracksManager.connect(this.video,t,e);let n=lO(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,cO(["init"])).pipe(aO(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),it(this.video)}prepare(){var i;let e=(i=this.params.desiredState.videoTrack.getState())==null?void 0:i.id;Yx(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];Yx(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=Vi(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(Fe(t))}playIfAllowed(){at(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),B(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Kx.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){var l,d;this.params.output.autoVideoTrackLimits$.next(e);let t=c=>{this.params.output.currentVideoTrack$.next(c),this.params.desiredState.videoTrack.startTransitionTo(c)},i=c=>{let h=Wt(n,{container:this.video.getBoundingClientRect(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,limits:c,abrLogger:this.params.dependencies.abrLogger});t(h)},r=(l=this.params.output.currentVideoTrack$.getValue())==null?void 0:l.quality,a=!!(e.max||e.min),n=(0,vh.default)(this.trackUrls).map(c=>c.track);if(!r||!a||qr(e,n[0].quality,(d=(0,Jx.default)(n,-1))==null?void 0:d.quality)){i();return}let o=e.max?oO(r,e.max):!0,u=e.min?nO(r,e.min):!0;o&&u||i(e)}};import{assertNever as eE,debounce as bO,merge as tE,observableFrom as gO,Subscription as SO,map as iE,ValueSubject as vO,ErrorCategory as Th,VideoQuality as yO}from"@vkontakte/videoplayer-shared/es2018";import{ErrorCategory as hO}from"@vkontakte/videoplayer-shared/es2018";var Zx=["stun:videostun.mycdn.me:80"],fO=1e3,mO=3,yh=()=>null,vl=class{constructor(e,t){this.ws=null;this.peerConnection=null;this.serverUrl="";this.streamKey="";this.stream=null;this.signalingType="JOIN";this.retryCount=0;this.externalStartCallback=yh;this.externalStopCallback=yh;this.externalErrorCallback=yh;this.options=this.normalizeOptions(t);let i=e.split("/");this.serverUrl=i.slice(0,i.length-1).join("/"),this.streamKey=i[i.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{let t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}async handleUpdateMessage(e){try{let t=await this.createOffer();this.peerConnection&&await this.peerConnection.setLocalDescription(t),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}}async handleLogin(){try{let e={iceServers:[{urls:Zx}]};this.peerConnection=new RTCPeerConnection(e),this.peerConnection.ontrack=this.onPeerConnectionStream.bind(this),this.peerConnection.onicecandidate=this.onPeerConnectionIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onPeerConnectionIceConnectionStateChange.bind(this);let t=await this.createOffer();await this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}}async handleAnswer(e){try{this.peerConnection&&await this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e}))}catch(t){this.handleRTCError(t)}}async handleCandidate(e){if(e)try{this.peerConnection&&await this.peerConnection.addIceCandidate(e)}catch(t){this.handleRTCError(t)}}handleUnpublished(){try{this.closeConnections(),this.externalStopCallback()}catch(e){this.handleRTCError(e)}}handleSystemError(e){this.options.errorChanel&&this.options.errorChanel.next({id:"webrtc-provider-error",category:hO.WTF,message:e.message})}async onPeerConnectionStream(e){let t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){let e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}async createOffer(){let e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");let t=await this.peerConnection.createOffer(e),i=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(i))throw new Error("No h264 codec support error");return t}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch(t){throw new Error("Can not parse socket message")}}closeConnections(){let e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),fO)}normalizeOptions(e={}){let t={stunServerList:Zx,maxRetryNumber:mO,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var fo=class{constructor(e){this.videoState=new G("stopped");this.maxSeekBackTime$=new vO(0);this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.pause(),this.video.srcObject=null,this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),B(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"),B(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"&&B(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&B(this.params.desiredState.playbackState,"paused");return;default:return eE(e)}};this.subscription=new SO,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=tt(e.container,e.tuning),this.liveStreamClient=new vl(this.params.source.url,{maxRetryNumber:this.params.tuning.webrtc.connectionRetryMaxNumber,errorChanel:this.params.output.error$}),this.liveStreamClient.onStart(this.onLiveStreamStart.bind(this)),this.liveStreamClient.onStop(this.onLiveStreamStop.bind(this)),this.liveStreamClient.onError(this.onLiveStreamError.bind(this)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),it(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,i=n=>{e.error$.next({id:"WebRTCLiveProvider",category:Th.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};this.subscription.add(tE(this.videoState.stateChangeStarted$.pipe(iE(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(iE(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})}));let r=st(this.video);this.subscription.add(()=>r.destroy());let a=(n,o)=>this.subscription.add(n.subscribe(o,i));a(r.timeUpdate$,e.liveTime$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(Et(this.video),this.params.output.elementVisible$),this.subscription.add(r.durationChange$.subscribe(n=>{e.duration$.next(n===1/0?0:n)})).add(r.canplay$.subscribe(()=>{var n;((n=this.videoState.getTransition())==null?void 0:n.to)==="ready"&&this.videoState.setState("ready")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused")},i)).add(r.playing$.subscribe(()=>{this.videoState.setState("playing")},i)).add(r.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(rt(this.video,t.volume,r.volumeState$,i)).add(r.volumeState$.subscribe(e.volume$,i)).add(this.videoState.stateChangeEnded$.subscribe(n=>{switch(n.to){case"stopped":e.position$.next(0),e.duration$.next(0),t.playbackState.setState("stopped");break;case"ready":break;case"paused":t.playbackState.setState("paused");break;case"playing":t.playbackState.setState("playing");break;default:return eE(n.to)}},i)).add(tE(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,gO(["init"])).pipe(bO(0)).subscribe(this.syncPlayback.bind(this),i)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),i))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(Fe(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.currentVideoTrack$.next({id:"webrtc",quality:yO.INVARIANT}),this.video.srcObject=e,B(this.params.desiredState.playbackState,"playing")}onLiveStreamStop(){this.videoState.startTransitionTo("stopped"),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.params.output.endedEvent$.next()}onLiveStreamError(e){this.onLiveStreamStop(),this.params.output.error$.next({id:"WebRTC stream runtime error",category:Th.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){at(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),B(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Th.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var mo=class{constructor(e){this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next()}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return!!this.current.done}};import{assertNever as go,assertNonNullable as Ni,ErrorCategory as yl,filter as uE,isNonNullable as lE,isNullable as PO,map as kO,merge as RO,once as MO,Subject as De,Subscription as cE,ValueSubject as W,flattenObject as Ih}from"@vkontakte/videoplayer-shared/es2018";import{Observable as TO,map as rE,Subscription as IO,Subject as xO}from"@vkontakte/videoplayer-shared/es2018";var sE=s=>new TO(e=>{let t=new IO,i=s.desiredPlaybackState$.stateChangeStarted$.pipe(rE(({from:l,to:d})=>`${l}-${d}`)),r=s.desiredPlaybackState$.stateChangeEnded$,a=s.providerChanged$.pipe(rE(({type:l})=>l!==void 0)),n=new xO,o=0,u="unknown";return t.add(i.subscribe(l=>{o&&window.clearTimeout(o),u=l,o=window.setTimeout(()=>n.next(l),s.maxTransitionInterval)})),t.add(r.subscribe(()=>{window.clearTimeout(o),u="unknown",o=0})),t.add(a.subscribe(l=>{o&&(window.clearTimeout(o),o=0,l&&(o=window.setTimeout(()=>n.next(u),s.maxTransitionInterval)))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});import{ErrorCategory as EO,Subscription as wO,combine as AO,filter as nE,once as oE}from"@vkontakte/videoplayer-shared/es2018";function aE(){return new(window.AudioContext||window.webkitAudioContext)}var bo=class bo{constructor(e,t,i,r){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=i;this.volumeMultiplier=r;this.destroyController=new ae;this.subscriptions=new wO;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe(nE(a=>!!a.type),oE()).subscribe(({type:a})=>this.subscribe(a)))}subscribe(e){j.browser.isSafari&&e!=="MPEG"||this.subscriptions.add(AO({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(nE(({playbackState:t,video:i,volume:{muted:r,volume:a}})=>t==="playing"&&!!i&&!r&&!!a),oE()).subscribe(({video:t})=>{this.initAudioContextOnce(t).then(i=>{i||this.destroy()}).catch(i=>{this.handleError(i),this.destroy()})}))}static isSupported(){return"AudioContext"in window&&"GainNode"in window&&"MediaElementAudioSourceNode"in window}async initAudioContextOnce(e){let{volumeMultiplier:t}=this,i=aE();this.audioContext=i;let r=i.createGain();if(this.gainNode=r,r.gain.value=t,r.connect(i.destination),i.state==="suspended"&&(await i.resume(),this.destroyController.signal.aborted))return!1;let a=i.createMediaElementSource(e);return this.mediaElementSource=a,a.connect(r),!0}cleanup(){this.mediaElementSource&&(this.mediaElementSource.disconnect(),this.mediaElementSource=null),this.gainNode&&(this.gainNode.disconnect(),this.gainNode=null),this.audioContext&&(this.audioContext.state!=="closed"&&this.audioContext.close(),this.audioContext=null)}destroy(){this.destroyController.abort(),this.subscriptions.unsubscribe(),this.cleanup()}handleError(e){var t;this.volumeMultiplierError$.next({id:bo.errorId,category:EO.VIDEO_PIPELINE,message:(t=e==null?void 0:e.message)!=null?t:`${bo.errorId} exception`,thrown:e})}};bo.errorId="VolumeMultiplierManager";var ms=bo;var LO={chunkDuration:5e3,maxParallelRequests:5},So=class{constructor(e){this.current$=new W({type:void 0});this.providerError$=new De;this.noAvailableProvidersError$=new De;this.volumeMultiplierError$=new De;this.providerOutput={position$:new W(0),duration$:new W(1/0),volume$:new W({muted:!1,volume:1}),availableVideoStreams$:new W([]),currentVideoStream$:new W(void 0),availableVideoTracks$:new W([]),currentVideoTrack$:new W(void 0),availableAudioStreams$:new W([]),currentAudioStream$:new W(void 0),availableAudioTracks$:new W([]),currentVideoSegmentLength$:new W(0),currentAudioSegmentLength$:new W(0),isAudioAvailable$:new W(!0),autoVideoTrackLimitingAvailable$:new W(!1),autoVideoTrackLimits$:new W(void 0),currentBuffer$:new W(void 0),isBuffering$:new W(!0),error$:new De,fetcherError$:new De,fetcherRecoverableError$:new De,warning$:new De,willSeekEvent$:new De,soundProhibitedEvent$:new De,seekedEvent$:new De,loopedEvent$:new De,endedEvent$:new De,firstBytesEvent$:new De,loadedMetadataEvent$:new De,firstFrameEvent$:new De,canplay$:new De,isLive$:new W(void 0),isLiveEnded$:new W(null),isLowLatency$:new W(!1),canChangePlaybackSpeed$:new W(!0),liveTime$:new W(void 0),liveBufferTime$:new W(void 0),liveLatency$:new W(void 0),severeStallOccurred$:new De,availableTextTracks$:new W([]),currentTextTrack$:new W(void 0),hostname$:new W(void 0),httpConnectionType$:new W(void 0),httpConnectionReused$:new W(void 0),inPiP$:new W(!1),inFullscreen$:new W(!1),element$:new W(void 0),elementVisible$:new W(!0),availableSources$:new W(void 0),is3DVideo$:new W(!1),playbackState$:new W(""),getCurrentTime$:new W(null)};this.subscription=new cE;this.volumeMultiplierManager=null;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer"),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name);let t=UI([...jI(this.params.tuning),...qI(this.params.tuning)],this.params.tuning).filter(l=>lE(e.sources[l])),{forceFormat:i,formatsToAvoid:r}=this.params.tuning,a=[];i?a=[i]:r.length?a=[...t.filter(l=>!(0,xh.default)(r,l)),...t.filter(l=>(0,xh.default)(r,l))]:a=t,this.log({message:`Selected formats: ${a.join(" > ")}`}),this.tracer.log("Selected formats",Ih(a)),this.screenFormatsIterator=new mo(a);let n=[...xp(!0),...xp(!1)];this.chromecastFormatsIterator=new mo(n.filter(l=>lE(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:o=1,tuning:{useVolumeMultiplier:u}}=this.params;u&&o!==1&&ms.isSupported()&&(this.volumeMultiplierManager=new ms(this.providerOutput,this.current$,this.volumeMultiplierError$,o))}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()}))}destroy(){var e;this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe(),(e=this.volumeMultiplierManager)==null||e.destroy(),this.volumeMultiplierManager=null,this.tracer.end()}initProvider(){let e=this.chooseDestination(),t=this.chooseFormat(e);if(PO(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:yl.WTF,message:"Failed to create provider",thrown:r})}i?this.current$.next({type:t,provider:i,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.tracer.log("reinitProvider"),this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.tracer.log("switchToNextProvider",{destination:e}),this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}destroyProvider(){let e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"}),this.tracer.log("destroyProvider"),e.destroy();let t=this.providerOutput.position$.getValue()*1e3,i=this.params.desiredState.seekState.getState(),r=i.state!=="none";if(this.params.desiredState.seekState.setState({state:"requested",position:r?i.position:t,forcePrecise:r?i.forcePrecise:!1}),e.scene3D){let n=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:n.x,y:n.y})}let a=this.providerOutput.isBuffering$;a.getValue()||a.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),this.tracer.log("createProvider",{destination:e,format:t}),e){case"SCREEN":return this.createScreenProvider(t);case"CHROMECAST":return this.createChromecastProvider(t);default:return go(e)}}createScreenProvider(e){let{sources:t,container:i,desiredState:r,panelSize:a}=this.params,n=this.providerOutput,o={container:i,source:null,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning,panelSize:a};switch(e){case"DASH_SEP":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_ONDEMAND":case"DASH_STREAMS":{let u=this.applyFailoverHost(t[e]),l=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return Ni(u),this.params.tuning.useNewDashProvider?new uo({...o,source:u,sourceHls:l}):new wn({...o,source:u,sourceHls:l})}case"DASH_LIVE_CMAF":{let u=this.applyFailoverHost(t[e]);return Ni(u),this.params.tuning.useNewDashProvider?new lo({...o,source:u}):new An({...o,source:u})}case"HLS":case"HLS_ONDEMAND":{let u=this.applyFailoverHost(t[e]);return Ni(u),new po({...o,source:u})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let u=this.applyFailoverHost(t[e]);return Ni(u),new co({...o,source:u,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let u=this.applyFailoverHost(t[e]);return Ni(u),new ho({...o,source:u})}case"DASH_LIVE":{let u=this.applyFailoverHost(t[e]);return Ni(u),new Uy({...o,source:u,config:{...LO,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let u=this.applyFailoverHost(t[e]);return Ni(u),new fo({container:i,source:u,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return go(e)}}createChromecastProvider(e){let{sources:t,container:i,desiredState:r,meta:a}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return Ni(o),new xa({connection:o,meta:a,container:i,source:t,format:e,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?"CHROMECAST":"SCREEN"}chooseFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case"CHROMECAST":return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return go(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return go(e)}}handleNoFormatsError(e){switch(e){case"SCREEN":this.noAvailableProvidersError$.next(this.params.tuning.forceFormat),this.current$.next({type:void 0});return;case"CHROMECAST":this.params.dependencies.chromecastInitializer.disconnect();return;default:return go(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;let t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;let i=r=>{let a=new URL(r);return a.host=t,a.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return{...e,url:i(e.url)}}return(0,pE.default)((0,dE.default)(e).map(([r,a])=>[r,i(a)]))}initProviderErrorHandling(){let e=new cE,t=!1,i=0;return e.add(RO(this.providerOutput.error$.pipe(uE(r=>!this.params.tuning.ignoreAudioRendererError||!r.message||!/AUDIO_RENDERER_ERROR/ig.test(r.message))),sE({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(kO(r=>({id:`ProviderHangup:${r}`,category:yl.WTF,message:`A ${r} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.providerOutput.fetcherError$.subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;let r=this.params.desiredState.playbackState.transitionEnded$.pipe(uE(({to:a})=>a==="playing"),MO()).subscribe(()=>t=!0);e.add(r)})),e.add(this.providerError$.subscribe(r=>{let a=this.current$.getValue().destination,n={error:r,currentDestination:a};if(a==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("SCREEN"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let o=r.category===yl.NETWORK,u=r.category===yl.FATAL,l=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),d=i<this.params.tuning.providerErrorLimit&&!u,c=l&&!u&&(o&&t||!d);n={...n,isNetworkError:o,isFatalError:u,haveFailoverHost:l,tryFailover:c,canReinitProvider:d},d?(i++,this.reinitProvider()):c?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):(i=0,this.switchToNextProvider(a!=null?a:"SCREEN"))}r.traceAsLog?this.tracer.log("providerInfo",Ih(n)):this.tracer.error("providerError",Ih(n))})),e}};import{fromEvent as Tl,once as BO,combine as $O,Subscription as hE,ValueSubject as Eh,map as DO,filter as CO,isNonNullable as Il,now as yt,safeStorage as wh}from"@vkontakte/videoplayer-shared/es2018";var VO=5e3,fE="one_video_throughput",mE="one_video_rtt",Ei=window.navigator.connection,bE=()=>{let s=Ei==null?void 0:Ei.downlink;if(Il(s)&&s!==10)return s*1e3},gE=()=>{let s=Ei==null?void 0:Ei.rtt;if(Il(s)&&s!==3e3)return s},SE=(s,e,t)=>{let i=t*8,r=i/s;return i/(r+e)},Ah=class s{constructor(e){this.subscription=new hE;this.concurrentDownloads=new Set;var r,a;this.tuningConfig=e;let t=s.load(fE)||(e.useBrowserEstimation?bE():void 0)||VO,i=(a=(r=s.load(mE))!=null?r:e.useBrowserEstimation?gE():void 0)!=null?a:0;if(this.throughput$=new Eh(t),this.rtt$=new Eh(i),this.rttAdjustedThroughput$=new Eh(SE(t,i,e.rttPenaltyRequestSize)),this.throughput=yi.getSmoothedValue(t,-1,e),this.rtt=yi.getSmoothedValue(i,1,e),e.useBrowserEstimation){let n=()=>{let u=bE();u&&this.throughput.next(u);let l=gE();Il(l)&&this.rtt.next(l)};Ei&&"onchange"in Ei&&this.subscription.add(Tl(Ei,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{wh.set(fE,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{wh.set(mE,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add($O({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(DO(({throughput:n,rtt:o})=>SE(n,o,e.rttPenaltyRequestSize)),CO(n=>{let o=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(n-o)/o>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,i=yt(),r=new hE;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add(Tl(e,"progress").pipe(BO()).subscribe(a=>{t=a.loaded,i=yt()}));break;case 1:case 0:r.add(Tl(e,"loadstart").subscribe(()=>{t=0,i=yt()}));break}r.add(Tl(e,"loadend").subscribe(a=>{if(e.status===200){let n=a.loaded,o=yt(),u=n-t,l=o-i;this.addRawSpeed(u,l,1)}this.concurrentDownloads.delete(e),r.unsubscribe()}))}trackStream(e,t=!1){let i=e.getReader();if(!i){e.cancel("Could not get reader");return}let r=0,a=yt(),n=0,o=yt(),u=d=>{this.concurrentDownloads.delete(e),i.releaseLock(),e.cancel(`Throughput Estimator error: ${d}`).catch(()=>{})},l=async({done:d,value:c})=>{if(d)!t&&this.addRawSpeed(r,yt()-a,1),this.concurrentDownloads.delete(e);else if(c){if(t){let h=yt();if(h-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||h-a>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let f=o-a;f&&this.addRawSpeed(n,f,1,t),n=c.byteLength,a=yt()}else n+=c.byteLength;o=yt()}else r+=c.byteLength,n+=c.byteLength,n>=this.tuningConfig.streamMinSampleSize&&yt()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,yt()-o,this.concurrentDownloads.size),n=0,o=yt());await(i==null?void 0:i.read().then(l,u))}};this.concurrentDownloads.add(e),i==null||i.read().then(l,u)}addRawSpeed(e,t,i=1,r=!1){if(s.sanityCheck(e,t,r)){let a=e*8/t;this.throughput.next(a*i)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,i=!1){let r=e*8/t;return!(!r||!isFinite(r)||r>1e6||r<30||i&&e<1e4||!i&&e<10*1024||!i&&t<=20)}static load(e){var i;let t=wh.get(e);if(Il(t))return(i=parseInt(t,10))!=null?i:void 0}},vE=Ah;import{fillWithDefault as OO,VideoQuality as xl}from"@vkontakte/videoplayer-shared/es2018";var yE={configName:["core"],throughputEstimator:{type:"EmaAndMa",emaAlphaSlow:.2,emaAlphaFast:.7,emaAlpha:.45,basisTrendChangeCount:10,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1*1024*1024,streamMinSampleSize:10*1024,streamMinSampleTime:300,deviationDepth:20,deviationFactor:.5,lowLatency:{continuesByteSequenceInterval:50,maxLastEvaluationTimeout:300}},autoTrackSelection:{maxBitrateFactorAtEmptyBuffer:4,bitrateFactorAtEmptyBuffer:2.8,minBitrateFactorAtEmptyBuffer:1.5,bitrateAudioFactorAtEmptyBuffer:10,maxBitrateFactorAtFullBuffer:3,bitrateFactorAtFullBuffer:2,minBitrateFactorAtFullBuffer:1,bitrateAudioFactorAtFullBuffer:7,minVideoAudioRatio:5,minAvailableThroughputAudioRatio:5,usePixelRatio:!0,pixelRatioMultiplier:void 0,pixelRatioLogBase:3,pixelRatioLogCoefficients:[1,0,1],limitByContainer:!0,maxContainerSizeFactor:2,containerSizeFactor:1.3,minContainerSizeFactor:1,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldownIncreaseQuality:15e3,trackCooldownDecreaseQuality:3e3,backgroundVideoQualityLimit:xl.Q_4320P,activeVideoAreaThreshold:.1,highQualityLimit:xl.Q_720P,trafficSavingLimit:xl.Q_480P},stallsManager:{enabled:!1,stallDurationNoDataBeforeQualityDecrease:500,stallDurationToBeCount:100,stallCountBeforeQualityDecrease:3,resetQualityRestrictionTimeout:1e4,ignoreStallsOnSeek:!0,stallsMetricsHistoryLength:5,maxPossibleStallDuration:3e4,minTvtToBeCounted:5,maxTvtToBeCounted:10800,significantTvt:600,targetStallsDurationPerTvt:1,deviationStallsDurationPerTvt:.5,criticalStallsDurationPerTvt:6,abrAdjustingSpeed:.1,emaAlpha:.6,useTotalStallsDurationPerTvt:!0,useAverageStallsDurationPerTvt:!0,useEmaStallsDurationPerTvt:!0},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:xl.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,seekBiasInTheEnd:2e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,crashOnStallTimeout:25e3,crashOnStallTWithoutDataTimeout:5e3,enableSubSegmentBufferFeeding:!0,bufferEmptinessTolerance:100,useFetchPriorityHints:!0,enableBaseUrlSupport:!0,maxSegmentRetryCount:5,sourceOpenTimeout:1e3,vktvAbrThrottle:0,timeupdateEventTickThrottle:300},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,maxLiveDuration:7200,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:250,playbackCatchupSpeedup:.05,isActiveOnDefault:!1,bufferEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:"07A4434E",useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"dash",preferCMAF:!1,preferWebRTC:!1,preferMultiStream:!1,preferHDR:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,seekNearDurationBias:1,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useHlsJs:!1,useNativeHLSTextTracks:!1,useManagedMediaSource:!0,useNewSwitchTo:!1,useNewDashProvider:!1,useNewAutoSelectVideoTrack:!1,useSafariEndlessRequestBugfix:!0,useRefactoredSearchGap:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,audioVideoSyncRate:20,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50},useVolumeMultiplier:!1,ignoreAudioRendererError:!1,useEnableSubtitlesParam:!1,useOldMSEDetection:!1,useHlsLiveNewTextManager:!1,exposeInternalsToGlobal:!1,hlsLiveNewTextManagerDownloadThreshold:4e3,disableYandexPiP:!1,asyncResolveClientChecker:!1,autostartOnlyIfVisible:!1},TE=s=>{var e;return{...OO(s,yE),configName:[...(e=s.configName)!=null?e:[],...yE.configName]}};import{assertNonNullable as El,combine as wi,ErrorCategory as wl,filter as z,filterChanged as te,fromEvent as kh,isNonNullable as wE,isNullable as HO,Logger as zO,map as Z,mapTo as AE,merge as Ui,now as Al,once as Y,Subject as ie,Subscription as PE,tap as Rh,ValueSubject as D,isHigher as QO,isInvariantQuality as kE,flattenObject as qi,throttle as Mh,getTraceSubscriptionMethod as RE,TracerFactory as GO,InternalsExposure as WO}from"@vkontakte/videoplayer-shared/es2018";import{merge as _O,map as FO,filter as IE,isNonNullable as NO}from"@vkontakte/videoplayer-shared/es2018";var Ph=({seekState:s,position$:e})=>_O(s.stateChangeEnded$.pipe(FO(({to:t})=>{var i;return t.state==="none"?void 0:((i=t.position)!=null?i:NaN)/1e3}),IE(NO)),e.pipe(IE(()=>s.getState().state==="none")));import{assertNonNullable as UO}from"@vkontakte/videoplayer-shared/es2018";var xE=s=>{let e=typeof s.container=="string"?document.getElementById(s.container):s.container;return UO(e,`Wrong container or containerId {${s.container}}`),e};import{filter as qO,once as jO}from"@vkontakte/videoplayer-shared/es2018";var EE=(s,e,t,i)=>{s!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&(t==null?void 0:t.getValue().length)===0?t.pipe(qO(r=>r.length>0),jO()).subscribe(r=>{r.find(i)&&e.startTransitionTo(s)}):(s===void 0||t!=null&&t.getValue().find(i))&&e.startTransitionTo(s)};var Pl=class{constructor(e={configName:[]},t=GO.createRootTracer(!1)){this.subscription=new PE;this.logger=new zO;this.abrLogger=this.logger.createComponentLog("ABR");this.internalsExposure=null;this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new D(!1);this.hasLiveOffsetByPausedTimer=0;this.playerInitRequest=0;this.playerInited=new D(!1);this.wasSetStartedQuality=!1;this.desiredState={playbackState:new G("stopped"),seekState:new G({state:"none"}),volume:new G({volume:1,muted:!1}),videoTrack:new G(void 0),videoStream:new G(void 0),audioStream:new G(void 0),autoVideoTrackSwitching:new G(!0),autoVideoTrackLimits:new G({}),isLooped:new G(!1),isLowLatency:new G(!1),playbackRate:new G(1),externalTextTracks:new G([]),internalTextTracks:new G([]),currentTextTrack:new G(void 0),textTrackCuesSettings:new G({}),cameraOrientation:new G({x:0,y:0})};this.info={playbackState$:new D(void 0),position$:new D(0),duration$:new D(1/0),muted$:new D(!1),volume$:new D(1),availableVideoStreams$:new D([]),currentVideoStream$:new D(void 0),availableQualities$:new D([]),availableQualitiesFps$:new D({}),currentQuality$:new D(void 0),isAutoQualityEnabled$:new D(!0),autoQualityLimitingAvailable$:new D(!1),autoQualityLimits$:new D({}),predefinedQualityLimitType$:new D("unknown"),availableAudioStreams$:new D([]),currentAudioStream$:new D(void 0),availableAudioTracks$:new D([]),isAudioAvailable$:new D(!0),currentPlaybackRate$:new D(1),currentBuffer$:new D({start:0,end:0}),isBuffering$:new D(!0),isStalled$:new D(!1),isEnded$:new D(!1),isLooped$:new D(!1),isLive$:new D(void 0),isLiveEnded$:new D(null),canChangePlaybackSpeed$:new D(void 0),atLiveEdge$:new D(void 0),atLiveDurationEdge$:new D(void 0),liveTime$:new D(void 0),liveBufferTime$:new D(void 0),liveLatency$:new D(void 0),currentFormat$:new D(void 0),availableTextTracks$:new D([]),currentTextTrack$:new D(void 0),throughputEstimation$:new D(void 0),rttEstimation$:new D(void 0),videoBitrate$:new D(void 0),hostname$:new D(void 0),httpConnectionType$:new D(void 0),httpConnectionReused$:new D(void 0),surface$:new D("none"),chromecastState$:new D("NOT_AVAILABLE"),chromecastDeviceName$:new D(void 0),intrinsicVideoSize$:new D(void 0),availableSources$:new D(void 0),is3DVideo$:new D(!1),currentVideoSegmentLength$:new D(0),currentAudioSegmentLength$:new D(0)};this.events={inited$:new ie,ready$:new ie,started$:new ie,playing$:new ie,paused$:new ie,stopped$:new ie,willReady$:new ie,willStart$:new ie,willResume$:new ie,willPause$:new ie,willStop$:new ie,willDestruct$:new ie,watchCoverageRecord$:new ie,watchCoverageLive$:new ie,managedError$:new ie,fatalError$:new ie,fetcherRecoverableError$:new ie,ended$:new ie,looped$:new ie,seeked$:new ie,willSeek$:new ie,autoplaySoundProhibited$:new ie,firstBytes$:new ie,loadedMetadata$:new ie,firstFrame$:new ie,canplay$:new ie,log$:new ie,fetcherError$:new ie,severeStallOccured$:new ie};this.experimental={element$:new D(void 0),tuningConfigName$:new D([]),enableDebugTelemetry$:new D(!1),dumpTelemetry:hy,getCurrentTime$:new D(null)};if(this.initLogs(),this.tuning=TE(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new Ao({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new vE(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new WO("CORE"),this.internalsExposure.expose({player:this})),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(i,r,a)=>{let n=Reflect.get(i,r,a);return typeof n!="function"?n:(...o)=>{try{return n.apply(i,o)}catch(u){let l=o.map(h=>JSON.stringify(h,(p,f)=>{let m=typeof f;return(0,ME.default)(["number","string","boolean"],m)?f:f===null?null:`<${m}>`})),d=`Player.${String(r)}`,c=`Exception calling ${d} (${l.join(", ")})`;throw this.events.fatalError$.next({id:d,category:wl.WTF,message:c,thrown:u}),u}}}})}initVideo(e){var a;this.config=e,(a=this.internalsExposure)==null||a.expose({config:e,logger:this.logger,tuning:this.tuning}),this.setMuted(this.tuning.isAudioDisabled);let t=()=>{var u,l,d;let{container:n,...o}=e;this.tracer.log("initVideo",qi(o)),this.domContainer=xE(e),this.chromecastInitializer.contentId=(u=e.meta)==null?void 0:u.videoId,this.providerContainer=new So({sources:e.sources,meta:(l=e.meta)!=null?l:{},failoverHosts:(d=e.failoverHosts)!=null?d:[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,tracer:this.tracer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning,volumeMultiplier:e.volumeMultiplier,panelSize:e.panelSize}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.initTracerSubscription(),this.providerContainer.init(),this.setLiveLowLatency(this.tuning.dashCmafLive.lowLatency.isActiveOnDefault),this.initDebugTelemetry(),this.initWakeLock(),this.playerInited.next(!0)},i=()=>{this.tuning.autostartOnlyIfVisible&&window.requestAnimationFrame?this.playerInitRequest=window.requestAnimationFrame(()=>t()):t()},r=()=>{this.tuning.asyncResolveClientChecker?j.isInited$.pipe(z(n=>!!n),Y()).subscribe(()=>{console.log("Core SDK async start"),i()}):i()};return this.isNotActiveTabCase()?(this.tracer.log("request play from hidden tab"),kh(document,"visibilitychange").pipe(Y()).subscribe(r)):r(),this}destroy(){var e,t;this.tracer.log("destroy"),window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.playerInitRequest&&window.cancelAnimationFrame(this.playerInitRequest),this.events.willDestruct$.next(),this.stop(),(e=this.providerContainer)==null||e.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe(),this.tracer.end(),(t=this.internalsExposure)==null||t.destroy()}prepare(){return this.subscription.add(this.playerInited.pipe(z(e=>!!e),Y()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("prepare",{currentPlayBackState:e.getState()}),e.getState()==="stopped"&&e.startTransitionTo("ready")})),this}play(){return this.subscription.add(this.playerInited.pipe(z(e=>!!e),Y()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("play",{currentPlayBackState:e.getState()}),e.getState()!=="playing"&&e.startTransitionTo("playing")})),this}pause(){return this.subscription.add(this.playerInited.pipe(z(e=>!!e),Y()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("pause",{currentPlayBackState:e.getState()}),e.getState()!=="paused"&&e.startTransitionTo("paused")})),this}stop(){return this.subscription.add(this.playerInited.pipe(z(e=>!!e),Y()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("stop",{currentPlayBackState:e.getState()}),e.getState()!=="stopped"&&e.startTransitionTo("stopped")})),this}seekTime(e,t=!0){return this.subscription.add(this.playerInited.pipe(z(i=>!!i),Y()).subscribe(()=>{let i=this.info.duration$.getValue(),r=this.info.isLive$.getValue(),a=e;e>=i&&!r&&(a=i-this.tuning.seekNearDurationBias),this.tracer.log("seekTime",{duration:i,isLive:r,time:e,calculatedTime:a,forcePrecise:t}),Number.isFinite(a)&&(this.events.willSeek$.next({from:this.getExactTime(),to:a}),this.desiredState.seekState.setState({state:"requested",position:a*1e3,forcePrecise:t}))})),this}seekPercent(e){return this.subscription.add(this.playerInited.pipe(z(t=>!!t),Y()).subscribe(()=>{let t=this.info.duration$.getValue();this.tracer.log("seekPercent",{percent:e,duration:t}),isFinite(t)&&this.seekTime(Math.abs(t)*e,!1)})),this}setVolume(e,t){return this.subscription.add(this.playerInited.pipe(z(i=>!!i),Y()).subscribe(()=>{var o;let i=this.desiredState.volume,r=i.getTransition(),a=(o=r==null?void 0:r.to.muted)!=null?o:this.info.muted$.getValue(),n=t!=null?t:this.tuning.isAudioDisabled||a;this.tracer.log("setVolume",{volume:e,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:n}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setVolume(e):i.startTransitionTo({volume:e,muted:n})})),this}setMuted(e,t=!1){return this.subscription.add(this.playerInited.pipe(z(i=>!!i),Y()).subscribe(()=>{var o;let i=this.desiredState.volume,r=this.tuning.isAudioDisabled&&!t||e,a=i.getTransition(),n=(o=a==null?void 0:a.to.volume)!=null?o:this.info.volume$.getValue();this.tracer.log("setMuted",{isMuted:e,nextMuted:r,volume:n,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue()}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setMuted(r):i.startTransitionTo({volume:n,muted:r})})),this}setVideoStream(e){return this.subscription.add(this.playerInited.pipe(z(t=>!!t),Y()).subscribe(()=>{this.desiredState.videoStream.startTransitionTo(e)})),this}setAudioStream(e){return this.subscription.add(this.playerInited.pipe(z(t=>!!t),Y()).subscribe(()=>{this.desiredState.audioStream.startTransitionTo(e)})),this}setQuality(e){return this.subscription.add(this.playerInited.pipe(z(t=>!!t),Y()).subscribe(()=>{El(this.providerContainer);let t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();this.tracer.log("setQuality",{isDelayed:t.length===0,quality:e}),this.desiredState.videoTrack.getState()===void 0&&this.desiredState.videoTrack.getPrevState()===void 0&&t.length===0?this.wasSetStartedQuality?this.providerContainer.providerOutput.availableVideoTracks$.pipe(z(i=>i.length>0),Y()).subscribe(i=>{this.setVideoTrackIdByQuality(i,e)}):this.explicitInitialQuality=e:t.length>0&&this.setVideoTrackIdByQuality(t,e)})),this}setAutoQuality(e){return this.subscription.add(this.playerInited.pipe(z(t=>!!t),Y()).subscribe(()=>{this.tracer.log("setAutoQuality",{enable:e}),this.desiredState.autoVideoTrackSwitching.startTransitionTo(e)})),this}setAutoQualityLimits(e){return this.subscription.add(this.playerInited.pipe(z(t=>!!t),Y()).subscribe(()=>{this.tracer.log("setAutoQualityLimits",qi(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e)})),this}setPredefinedQualityLimits(e){return this.subscription.add(this.playerInited.pipe(z(t=>!!t),Y()).subscribe(()=>{if(this.info.predefinedQualityLimitType$.getValue()===e)return this;let{highQualityLimit:t,trafficSavingLimit:i}=this.tuning.autoTrackSelection,r;switch(e){case"high_quality":r={min:t,max:void 0};break;case"traffic_saving":r={max:i,min:void 0};break;default:r={max:void 0,min:void 0}}this.setAutoQualityLimits(r)})),this}setPlaybackRate(e){return this.subscription.add(this.playerInited.pipe(z(t=>!!t),Y()).subscribe(()=>{var i;El(this.providerContainer);let t=(i=this.providerContainer)==null?void 0:i.providerOutput.element$.getValue();this.tracer.log("setPlaybackRate",{playbackRate:e,isVideoElementAvailable:!!t}),t&&(this.desiredState.playbackRate.setState(e),t.playbackRate=e)})),this}setExternalTextTracks(e){return this.subscription.add(this.playerInited.pipe(z(t=>!!t),Y()).subscribe(()=>{e.length&&this.tracer.log("setExternalTextTracks",qi(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t})))})),this}selectTextTrack(e){return this.subscription.add(this.playerInited.pipe(z(t=>!!t),Y()).subscribe(()=>{var t;EE(e,this.desiredState.currentTextTrack,(t=this.providerContainer)==null?void 0:t.providerOutput.availableTextTracks$,i=>i.id===e),this.tracer.log("selectTextTrack",{textTrackId:e})})),this}setTextTrackCueSettings(e){return this.subscription.add(this.playerInited.pipe(z(t=>!!t),Y()).subscribe(()=>{this.tracer.log("setTextTrackCueSettings",{...e}),this.desiredState.textTrackCuesSettings.startTransitionTo(e)})),this}setLiveLowLatency(e){let t=this.info.isLive$.getValue(),i=this.desiredState.isLowLatency.getState();return!t||i===e?this:(this.tracer.log("live switch to low latency "+e),this.desiredState.isLowLatency.setState(e),this.seekTime(0))}setLooped(e){return this.subscription.add(this.playerInited.pipe(z(t=>!!t),Y()).subscribe(()=>{this.tracer.log("setLooped",{isLooped:e}),this.desiredState.isLooped.startTransitionTo(e)})),this}toggleChromecast(){this.tracer.log("toggleChromecast"),this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){return this.subscription.add(this.playerInited.pipe(z(i=>!!i),Y()).subscribe(()=>{let i=this.getScene3D();this.tracer.log("startCameraManualRotation",{isScene3DAvailable:!!i,mx:e,my:t}),i&&i.startCameraManualRotation(e,t)})),this}stopCameraManualRotation(e=!1){return this.subscription.add(this.playerInited.pipe(z(t=>!!t),Y()).subscribe(()=>{let t=this.getScene3D();this.tracer.log("stopCameraManualRotation",{isScene3DAvailable:!!t,immediate:e}),t&&t.stopCameraManualRotation(e)})),this}moveCameraFocusPX(e,t){return this.subscription.add(this.playerInited.pipe(z(i=>!!i),Y()).subscribe(()=>{let i=this.getScene3D();if(this.tracer.log("moveCameraFocusPX",{isScene3DAvailable:!!i,dxpx:e,dypx:t}),i){let r=i.getCameraRotation(),a=i.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:r.x+a.x,y:r.y+a.y})}})),this}holdCamera(){return this.subscription.add(this.playerInited.pipe(z(e=>e),Y()).subscribe(()=>{let e=this.getScene3D();e&&e.holdCamera()})),this}releaseCamera(){return this.subscription.add(this.playerInited.pipe(z(e=>!!e),Y()).subscribe(()=>{let e=this.getScene3D();e&&e.releaseCamera()})),this}getExactTime(){if(!this.providerContainer)return 0;let e=this.providerContainer.providerOutput.element$.getValue();if(HO(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),i=t.state==="none"?void 0:t.position;return wE(i)?i/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){var t,i;let e=(t=this.providerContainer)==null?void 0:t.current$.getValue();if((i=e==null?void 0:e.provider)!=null&&i.scene3D)return e.provider.scene3D}setIntrinsicVideoSize(...e){let t={width:e.reduce((i,{width:r})=>i||r||0,0),height:e.reduce((i,{height:r})=>i||r||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(Ui(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(Z(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(Z(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(Z(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(Z(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(Z(e=>e.to)).subscribe(e=>{this.info.autoQualityLimits$.next(e);let{highQualityLimit:t,trafficSavingLimit:i}=this.tuning.autoTrackSelection;this.info.predefinedQualityLimitType$.next(Nd(e,t,i))})),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(z(({from:e})=>e==="stopped"),Y()).subscribe(()=>{this.initedAt=Al(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case"ready":this.events.ready$.next();break;case"playing":this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case"paused":this.events.paused$.next();break;case"stopped":this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case"ready":this.events.willReady$.next();break;case"paused":this.events.willPause$.next();break;case"playing":this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case"stopped":this.events.willStop$.next();break;default:}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("willSeekEvent",qi(n)),n.state==="requested"?this.desiredState.seekState.setState({...n,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:wl.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe(Y()).subscribe(this.events.autoplaySoundProhibited$)).add(e.providerOutput.severeStallOccurred$.subscribe(this.events.severeStallOccured$)).add(e.providerOutput.seekedEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("seekedEvent",qi(n)),n.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe(Z(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(Z(n=>n.destination),te()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(wi({availableVideoTracks:e.providerOutput.availableVideoTracks$,currentVideoStream:e.providerOutput.currentVideoStream$}).pipe(Z(({availableVideoTracks:n,currentVideoStream:o})=>n.filter(u=>o?o.id===u.streamId:!0).map(({quality:u})=>u).sort((u,l)=>kE(u)?1:kE(l)?-1:QO(l,u)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(n=>{let o={};for(let u of n)u.fps&&(o[u.quality]=u.fps);this.info.availableQualitiesFps$.next(o)})).add(e.providerOutput.availableAudioStreams$.subscribe(this.info.availableAudioStreams$)).add(e.providerOutput.currentVideoStream$.subscribe(this.info.currentVideoStream$)).add(e.providerOutput.currentAudioStream$.subscribe(this.info.currentAudioStream$)).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.pipe(te()).subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.pipe(z(n=>wE(n))).subscribe(n=>{this.info.currentQuality$.next(n==null?void 0:n.quality),this.info.videoBitrate$.next(n==null?void 0:n.bitrate)})).add(e.providerOutput.currentVideoSegmentLength$.pipe(te((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe(te((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(te()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(te()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(te()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.autoVideoTrackLimits$.subscribe(n=>{this.desiredState.autoVideoTrackLimits.setState(n!=null?n:{})})).add(e.providerOutput.currentBuffer$.pipe(Z(n=>n?{start:n.from,end:n.to}:{start:0,end:0})).subscribe(this.info.currentBuffer$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.isLiveEnded$.pipe(Rh(n=>n&&this.stop())).subscribe(this.info.isLiveEnded$)).add(e.providerOutput.canChangePlaybackSpeed$.subscribe(this.info.canChangePlaybackSpeed$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.liveBufferTime$.subscribe(this.info.liveBufferTime$)).add(e.providerOutput.liveLatency$.subscribe(this.info.liveLatency$)).add(wi({hasLiveOffsetByPaused:Ui(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(Z(n=>n.to),te(),Z(n=>n==="paused")),isLowLatency:e.providerOutput.isLowLatency$}).subscribe(({hasLiveOffsetByPaused:n,isLowLatency:o})=>{if(window.clearTimeout(this.hasLiveOffsetByPausedTimer),n){this.hasLiveOffsetByPausedTimer=window.setTimeout(()=>{this.hasLiveOffsetByPaused.next(!0)},this.getActiveLiveDelay(o));return}this.hasLiveOffsetByPaused.next(!1)})).add(wi({atLiveEdge:wi({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Ph({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(Z(({isLive:n,position:o,isLowLatency:u})=>{let l=this.getActiveLiveDelay(u);return n&&Math.abs(o)<l/1e3}),te(),Rh(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(Z(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add(wi({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(Z(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),te(),Rh(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(Z(n=>n.muted),te()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(Z(n=>n.volume),te()).subscribe(this.info.volume$)).add(Ph({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(Ui(e.providerOutput.endedEvent$.pipe(AE(!0)),e.providerOutput.seekedEvent$.pipe(AE(!1))).pipe(te()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.providerOutput.fetcherRecoverableError$.subscribe(this.events.fetcherRecoverableError$)).add(e.providerOutput.fetcherError$.subscribe(this.events.fatalError$)).add(e.volumeMultiplierError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe(Z(n=>({id:n?`No${n}`:"NoProviders",category:wl.VIDEO_PIPELINE,message:n?`${n} was forced but failed or not available`:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.getCurrentTime$.subscribe(this.experimental.getCurrentTime$)).add(e.providerOutput.firstBytesEvent$.pipe(Y(),Z(n=>n!=null?n:Al()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(Y(),Z(()=>Al()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(Y(),Z(()=>Al()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$)).add(e.providerOutput.availableSources$.subscribe(this.info.availableSources$));let t=new D(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let i=new D(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(z(({to:n})=>n==="playing"),Y()).subscribe(()=>i.next(!1)));let r=0,a=Ui(e.providerOutput.isBuffering$,t,i).pipe(Z(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||i.getValue();return n&&!o}),te());this.subscription.add(a.subscribe(n=>{n?r=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(r),this.info.isStalled$.next(!1))})),this.subscription.add(Ui(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{let n=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n==null?void 0:n.videoWidth,height:n==null?void 0:n.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{var u,l;let o=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:(u=n==null?void 0:n.size)==null?void 0:u.width,height:(l=n==null?void 0:n.size)==null?void 0:l.height},{width:o==null?void 0:o.videoWidth,height:o==null?void 0:o.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add(Ui(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,e.providerOutput.elementVisible$,this.chromecastInitializer.castState$).subscribe(()=>{let n=e.providerOutput.inPiP$.getValue(),o=e.providerOutput.inFullscreen$.getValue(),u=e.providerOutput.element$.getValue(),l=e.providerOutput.elementVisible$.getValue(),d=this.chromecastInitializer.castState$.getValue(),c;d==="CONNECTED"?c="second_screen":u?l?n?c="pip":o?c="fullscreen":c="inline":c="invisible":c="none",this.info.surface$.getValue()!==c&&this.info.surface$.next(c)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(Z(e=>e==null?void 0:e.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new PE;this.subscription.add(t),this.subscription.add(e.current$.pipe(te((i,r)=>i.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(z(i=>i.length>0),Y()).subscribe(i=>{this.setStartingVideoTrack(i)}))}))}setStartingVideoTrack(e){var r;let t;this.wasSetStartedQuality=!0;let i=(r=this.explicitInitialQuality)!=null?r:this.info.currentQuality$.getValue();i&&(t=e.find(({quality:a})=>a===i),t||this.setAutoQuality(!0)),t||(t=Wt(e,{container:this.domContainer.getBoundingClientRect(),panelSize:this.config.panelSize,estimatedThroughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),playbackRate:this.info.currentPlaybackRate$.getValue(),forwardBufferHealth:0,abrLogger:this.abrLogger})),this.desiredState.videoTrack.startTransitionTo(t),this.info.currentQuality$.next(t.quality),this.info.videoBitrate$.next(t.bitrate)}initLogs(){this.subscription.add(Ui(this.desiredState.videoTrack.stateChangeStarted$.pipe(Z(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(Z(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(Z(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(Z(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(Z(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(Z(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(Z(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(Z(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(Z(e=>({component:"desiredState",message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`}))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){var t;let e=(t=this.providerContainer)==null?void 0:t.providerOutput;El(this.providerContainer),El(e),py(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(i=>dy(i)),this.providerContainer.current$.subscribe(({type:i})=>ka("provider",i)),e.duration$.subscribe(i=>ka("duration",i)),e.availableVideoTracks$.pipe(z(i=>!!i.length),Y()).subscribe(i=>ka("tracks",i)),this.events.fatalError$.subscribe(new Ke("fatalError")),this.events.managedError$.subscribe(new Ke("managedError")),e.position$.subscribe(new Ke("position")),e.currentVideoTrack$.pipe(Z(i=>i==null?void 0:i.quality)).subscribe(new Ke("quality")),this.info.currentBuffer$.subscribe(new Ke("buffer")),e.isBuffering$.subscribe(new Ke("isBuffering"))].forEach(i=>this.subscription.add(i)),ka("codecs",j.video.supportedCodecs)}initTracerSubscription(){let e=RE(this.tracer.log.bind(this.tracer)),t=RE(this.tracer.error.bind(this.tracer));this.subscription.add(this.info.playbackState$.subscribe(e("playbackState"))).add(this.info.isLooped$.subscribe(e("isLooped"))).add(this.info.currentPlaybackRate$.pipe(te()).subscribe(e("currentPlaybackRate"))).add(this.info.isAutoQualityEnabled$.subscribe(e("isAutoQualityEnabled"))).add(this.info.autoQualityLimits$.subscribe(e("autoQualityLimits"))).add(this.info.currentFormat$.subscribe(e("currentFormat"))).add(this.info.availableQualities$.subscribe(e("availableQualities"))).add(this.info.availableQualitiesFps$.subscribe(e("availableQualitiesFps"))).add(this.info.availableAudioTracks$.subscribe(e("availableAudioTracks"))).add(this.info.isAudioAvailable$.subscribe(e("isAudioAvailable"))).add(wi({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe(z(({currentQuality:i,videoBitrate:r})=>!!i&&!!r),te((i,r)=>i.currentQuality===r.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe(z(i=>i>0),te()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe(z(i=>i>0),te()).subscribe(e("currentAudioSegmentLength"))).add(this.info.hostname$.subscribe(e("hostname"))).add(this.info.currentTextTrack$.subscribe(e("currentTextTrack"))).add(this.info.availableTextTracks$.subscribe(e("availableTextTracks"))).add(this.info.autoQualityLimitingAvailable$.subscribe(e("autoQualityLimitingAvailable"))).add(wi({currentBuffer:this.info.currentBuffer$.pipe(z(i=>i.end>0),te((i,r)=>i.end===r.end&&i.start===r.start)),position:this.info.position$.pipe(te())}).pipe(Mh(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe(te()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe(te()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe(te()).subscribe(e("canChangePlaybackSpeed"))).add(wi({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(z(({liveTime:i,liveBufferTime:r})=>!!i&&!!r),Mh(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(te(),z(i=>i===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(te(),z(i=>i===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe(te()).subscribe(e("muted"))).add(this.info.volume$.pipe(te()).subscribe(e("volume"))).add(this.info.isEnded$.pipe(te(),z(i=>i===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add(wi({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(z(({throughputEstimation:i,rtt:r})=>!!i&&!!r),Mh(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(te(),z(i=>i===!0)).subscribe(e("is3DVideo"))).add(this.info.surface$.subscribe(e("surface"))).add(this.events.ended$.subscribe(e("ended"))).add(this.events.looped$.subscribe(e("looped"))).add(this.events.managedError$.subscribe(t("managedError"))).add(this.events.fatalError$.subscribe(t("fatalError"))).add(this.events.firstBytes$.subscribe(e("firstBytes"))).add(this.events.firstFrame$.subscribe(e("firstFrame"))).add(this.events.canplay$.subscribe(e("canplay")))}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e,t=()=>{e==null||e.release(),e=void 0},i=async()=>{t(),e=await window.navigator.wakeLock.request("screen").catch(r=>{r instanceof DOMException&&r.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:wl.DOM,message:String(r)})})};this.subscription.add(Ui(kh(document,"visibilitychange"),kh(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let r=document.visibilityState==="visible",a=this.desiredState.playbackState.getState()==="playing",n=!!e&&!(e!=null&&e.released);r&&a?n||i():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let i=e.find(r=>r.quality===t);this.tracer.log("setVideoTrackIdByQuality",qi({quality:t,availableTracks:qi(e),track:qi(i),isAutoQuality:!i})),i?this.desiredState.videoTrack.startTransitionTo(i):this.setAutoQuality(!0)}getActiveLiveDelay(e=!1){return e?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay}isNotActiveTabCase(){return document.hidden&&this.tuning.autoplayOnlyInActiveTab&&!Ca()}};import{Subscription as yee,Observable as Tee,Subject as Iee,ValueSubject as xee,VideoQuality as Eee}from"@vkontakte/videoplayer-shared/es2018";var wee=`@vkontakte/videoplayer-core@${Bh}`;export{vo as ChromecastState,Cl as HttpConnectionType,Tee as Observable,et as PlaybackState,Pl as Player,yo as PredefinedQualityLimits,wee as SDK_VERSION,Iee as Subject,yee as Subscription,Vl as Surface,Bh as VERSION,xee as ValueSubject,di as VideoFormat,Eee as VideoQuality,j as clientChecker,Pa as isMobile};