@vkontakte/videoplayer-core 2.0.134-dev.29c5fea5.0 → 2.0.134-dev.ae2fd074.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,12 +1,12 @@
1
1
  /**
2
- * @vkontakte/videoplayer-core v2.0.134-dev.29c5fea5.0
3
- * Thu, 05 Jun 2025 09:46:22 GMT
2
+ * @vkontakte/videoplayer-core v2.0.134-dev.ae2fd074.0
3
+ * Thu, 05 Jun 2025 13:16:35 GMT
4
4
  * https://st.mycdn.me/static/vkontakte-videoplayer/2-0-134/doc/
5
5
  */
6
- var FE=Object.create;var Vh=Object.defineProperty;var NE=Object.getOwnPropertyDescriptor;var UE=Object.getOwnPropertyNames;var qE=Object.getPrototypeOf,jE=Object.prototype.hasOwnProperty;var b=(s,e)=>()=>(e||s((e={exports:{}}).exports,e),e.exports);var HE=(s,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of UE(e))!jE.call(s,r)&&r!==t&&Vh(s,r,{get:()=>e[r],enumerable:!(i=NE(e,r))||i.enumerable});return s};var N=(s,e,t)=>(t=s!=null?FE(qE(s)):{},HE(e||!s||!s.__esModule?Vh(t,"default",{value:s,enumerable:!0}):t,s));var ve=b((jl,_h)=>{"use strict";var sa=function(s){return s&&s.Math===Math&&s};_h.exports=sa(typeof globalThis=="object"&&globalThis)||sa(typeof window=="object"&&window)||sa(typeof self=="object"&&self)||sa(typeof global=="object"&&global)||sa(typeof jl=="object"&&jl)||function(){return this}()||Function("return this")()});var _e=b((h_,Fh)=>{"use strict";Fh.exports=function(s){try{return!!s()}catch(e){return!0}}});var aa=b((f_,Nh)=>{"use strict";var GE=_e();Nh.exports=!GE(function(){var s=function(){}.bind();return typeof s!="function"||s.hasOwnProperty("prototype")})});var Hl=b((m_,Hh)=>{"use strict";var zE=aa(),jh=Function.prototype,Uh=jh.apply,qh=jh.call;Hh.exports=typeof Reflect=="object"&&Reflect.apply||(zE?qh.bind(Uh):function(){return qh.apply(Uh,arguments)})});var $e=b((b_,Qh)=>{"use strict";var Gh=aa(),zh=Function.prototype,Gl=zh.call,QE=Gh&&zh.bind.bind(Gl,Gl);Qh.exports=Gh?QE:function(s){return function(){return Gl.apply(s,arguments)}}});var Ki=b((g_,Yh)=>{"use strict";var Wh=$e(),WE=Wh({}.toString),YE=Wh("".slice);Yh.exports=function(s){return YE(WE(s),8,-1)}});var zl=b((S_,Kh)=>{"use strict";var KE=Ki(),XE=$e();Kh.exports=function(s){if(KE(s)==="Function")return XE(s)}});var ge=b((v_,Xh)=>{"use strict";var Ql=typeof document=="object"&&document.all;Xh.exports=typeof Ql=="undefined"&&Ql!==void 0?function(s){return typeof s=="function"||s===Ql}:function(s){return typeof s=="function"}});var gt=b((y_,Jh)=>{"use strict";var JE=_e();Jh.exports=!JE(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var St=b((T_,Zh)=>{"use strict";var ZE=aa(),Ao=Function.prototype.call;Zh.exports=ZE?Ao.bind(Ao):function(){return Ao.apply(Ao,arguments)}});var Wl=b(rf=>{"use strict";var ef={}.propertyIsEnumerable,tf=Object.getOwnPropertyDescriptor,ew=tf&&!ef.call({1:2},1);rf.f=ew?function(e){var t=tf(this,e);return!!t&&t.enumerable}:ef});var na=b((x_,sf)=>{"use strict";sf.exports=function(s,e){return{enumerable:!(s&1),configurable:!(s&2),writable:!(s&4),value:e}}});var nf=b((E_,af)=>{"use strict";var tw=$e(),iw=_e(),rw=Ki(),Yl=Object,sw=tw("".split);af.exports=iw(function(){return!Yl("z").propertyIsEnumerable(0)})?function(s){return rw(s)==="String"?sw(s,""):Yl(s)}:Yl});var xr=b((w_,of)=>{"use strict";of.exports=function(s){return s==null}});var Ri=b((P_,uf)=>{"use strict";var aw=xr(),nw=TypeError;uf.exports=function(s){if(aw(s))throw new nw("Can't call method on "+s);return s}});var Xi=b((A_,lf)=>{"use strict";var ow=nf(),uw=Ri();lf.exports=function(s){return ow(uw(s))}});var vt=b((k_,cf)=>{"use strict";var lw=ge();cf.exports=function(s){return typeof s=="object"?s!==null:lw(s)}});var Er=b((R_,df)=>{"use strict";df.exports={}});var mi=b((L_,hf)=>{"use strict";var Kl=Er(),Xl=ve(),cw=ge(),pf=function(s){return cw(s)?s:void 0};hf.exports=function(s,e){return arguments.length<2?pf(Kl[s])||pf(Xl[s]):Kl[s]&&Kl[s][e]||Xl[s]&&Xl[s][e]}});var oa=b((M_,ff)=>{"use strict";var dw=$e();ff.exports=dw({}.isPrototypeOf)});var Ji=b(($_,gf)=>{"use strict";var pw=ve(),mf=pw.navigator,bf=mf&&mf.userAgent;gf.exports=bf?String(bf):""});var Zl=b((B_,xf)=>{"use strict";var If=ve(),Jl=Ji(),Sf=If.process,vf=If.Deno,yf=Sf&&Sf.versions||vf&&vf.version,Tf=yf&&yf.v8,Dt,ko;Tf&&(Dt=Tf.split("."),ko=Dt[0]>0&&Dt[0]<4?1:+(Dt[0]+Dt[1]));!ko&&Jl&&(Dt=Jl.match(/Edge\/(\d+)/),(!Dt||Dt[1]>=74)&&(Dt=Jl.match(/Chrome\/(\d+)/),Dt&&(ko=+Dt[1])));xf.exports=ko});var ec=b((D_,wf)=>{"use strict";var Ef=Zl(),hw=_e(),fw=ve(),mw=fw.String;wf.exports=!!Object.getOwnPropertySymbols&&!hw(function(){var s=Symbol("symbol detection");return!mw(s)||!(Object(s)instanceof Symbol)||!Symbol.sham&&Ef&&Ef<41})});var tc=b((C_,Pf)=>{"use strict";var bw=ec();Pf.exports=bw&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var ic=b((V_,Af)=>{"use strict";var gw=mi(),Sw=ge(),vw=oa(),yw=tc(),Tw=Object;Af.exports=yw?function(s){return typeof s=="symbol"}:function(s){var e=gw("Symbol");return Sw(e)&&vw(e.prototype,Tw(s))}});var ua=b((O_,kf)=>{"use strict";var Iw=String;kf.exports=function(s){try{return Iw(s)}catch(e){return"Object"}}});var Gt=b((__,Rf)=>{"use strict";var xw=ge(),Ew=ua(),ww=TypeError;Rf.exports=function(s){if(xw(s))return s;throw new ww(Ew(s)+" is not a function")}});var la=b((F_,Lf)=>{"use strict";var Pw=Gt(),Aw=xr();Lf.exports=function(s,e){var t=s[e];return Aw(t)?void 0:Pw(t)}});var $f=b((N_,Mf)=>{"use strict";var rc=St(),sc=ge(),ac=vt(),kw=TypeError;Mf.exports=function(s,e){var t,i;if(e==="string"&&sc(t=s.toString)&&!ac(i=rc(t,s))||sc(t=s.valueOf)&&!ac(i=rc(t,s))||e!=="string"&&sc(t=s.toString)&&!ac(i=rc(t,s)))return i;throw new kw("Can't convert object to primitive value")}});var Ct=b((U_,Bf)=>{"use strict";Bf.exports=!0});var Vf=b((q_,Cf)=>{"use strict";var Df=ve(),Rw=Object.defineProperty;Cf.exports=function(s,e){try{Rw(Df,s,{value:e,configurable:!0,writable:!0})}catch(t){Df[s]=e}return e}});var ca=b((j_,Ff)=>{"use strict";var Lw=Ct(),Mw=ve(),$w=Vf(),Of="__core-js_shared__",_f=Ff.exports=Mw[Of]||$w(Of,{});(_f.versions||(_f.versions=[])).push({version:"3.38.0",mode:Lw?"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 nc=b((H_,Uf)=>{"use strict";var Nf=ca();Uf.exports=function(s,e){return Nf[s]||(Nf[s]=e||{})}});var wr=b((G_,qf)=>{"use strict";var Bw=Ri(),Dw=Object;qf.exports=function(s){return Dw(Bw(s))}});var Vt=b((z_,jf)=>{"use strict";var Cw=$e(),Vw=wr(),Ow=Cw({}.hasOwnProperty);jf.exports=Object.hasOwn||function(e,t){return Ow(Vw(e),t)}});var oc=b((Q_,Hf)=>{"use strict";var _w=$e(),Fw=0,Nw=Math.random(),Uw=_w(1 .toString);Hf.exports=function(s){return"Symbol("+(s===void 0?"":s)+")_"+Uw(++Fw+Nw,36)}});var Fe=b((W_,zf)=>{"use strict";var qw=ve(),jw=nc(),Gf=Vt(),Hw=oc(),Gw=ec(),zw=tc(),Pr=qw.Symbol,uc=jw("wks"),Qw=zw?Pr.for||Pr:Pr&&Pr.withoutSetter||Hw;zf.exports=function(s){return Gf(uc,s)||(uc[s]=Gw&&Gf(Pr,s)?Pr[s]:Qw("Symbol."+s)),uc[s]}});var Kf=b((Y_,Yf)=>{"use strict";var Ww=St(),Qf=vt(),Wf=ic(),Yw=la(),Kw=$f(),Xw=Fe(),Jw=TypeError,Zw=Xw("toPrimitive");Yf.exports=function(s,e){if(!Qf(s)||Wf(s))return s;var t=Yw(s,Zw),i;if(t){if(e===void 0&&(e="default"),i=Ww(t,s,e),!Qf(i)||Wf(i))return i;throw new Jw("Can't convert object to primitive value")}return e===void 0&&(e="number"),Kw(s,e)}});var lc=b((K_,Xf)=>{"use strict";var eP=Kf(),tP=ic();Xf.exports=function(s){var e=eP(s,"string");return tP(e)?e:e+""}});var Ro=b((X_,Zf)=>{"use strict";var iP=ve(),Jf=vt(),cc=iP.document,rP=Jf(cc)&&Jf(cc.createElement);Zf.exports=function(s){return rP?cc.createElement(s):{}}});var dc=b((J_,em)=>{"use strict";var sP=gt(),aP=_e(),nP=Ro();em.exports=!sP&&!aP(function(){return Object.defineProperty(nP("div"),"a",{get:function(){return 7}}).a!==7})});var rm=b(im=>{"use strict";var oP=gt(),uP=St(),lP=Wl(),cP=na(),dP=Xi(),pP=lc(),hP=Vt(),fP=dc(),tm=Object.getOwnPropertyDescriptor;im.f=oP?tm:function(e,t){if(e=dP(e),t=pP(t),fP)try{return tm(e,t)}catch(i){}if(hP(e,t))return cP(!uP(lP.f,e,t),e[t])}});var pc=b((eF,sm)=>{"use strict";var mP=_e(),bP=ge(),gP=/#|\.prototype\./,da=function(s,e){var t=vP[SP(s)];return t===TP?!0:t===yP?!1:bP(e)?mP(e):!!e},SP=da.normalize=function(s){return String(s).replace(gP,".").toLowerCase()},vP=da.data={},yP=da.NATIVE="N",TP=da.POLYFILL="P";sm.exports=da});var Ar=b((tF,nm)=>{"use strict";var am=zl(),IP=Gt(),xP=aa(),EP=am(am.bind);nm.exports=function(s,e){return IP(s),e===void 0?s:xP?EP(s,e):function(){return s.apply(e,arguments)}}});var hc=b((iF,om)=>{"use strict";var wP=gt(),PP=_e();om.exports=wP&&PP(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var zt=b((rF,um)=>{"use strict";var AP=vt(),kP=String,RP=TypeError;um.exports=function(s){if(AP(s))return s;throw new RP(kP(s)+" is not an object")}});var Zi=b(cm=>{"use strict";var LP=gt(),MP=dc(),$P=hc(),Lo=zt(),lm=lc(),BP=TypeError,fc=Object.defineProperty,DP=Object.getOwnPropertyDescriptor,mc="enumerable",bc="configurable",gc="writable";cm.f=LP?$P?function(e,t,i){if(Lo(e),t=lm(t),Lo(i),typeof e=="function"&&t==="prototype"&&"value"in i&&gc in i&&!i[gc]){var r=DP(e,t);r&&r[gc]&&(e[t]=i.value,i={configurable:bc in i?i[bc]:r[bc],enumerable:mc in i?i[mc]:r[mc],writable:!1})}return fc(e,t,i)}:fc:function(e,t,i){if(Lo(e),t=lm(t),Lo(i),MP)try{return fc(e,t,i)}catch(r){}if("get"in i||"set"in i)throw new BP("Accessors not supported");return"value"in i&&(e[t]=i.value),e}});var kr=b((aF,dm)=>{"use strict";var CP=gt(),VP=Zi(),OP=na();dm.exports=CP?function(s,e,t){return VP.f(s,e,OP(1,t))}:function(s,e,t){return s[e]=t,s}});var Ee=b((nF,hm)=>{"use strict";var pa=ve(),_P=Hl(),FP=zl(),NP=ge(),UP=rm().f,qP=pc(),Rr=Er(),jP=Ar(),Lr=kr(),pm=Vt();ca();var HP=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 _P(s,this,arguments)};return e.prototype=s.prototype,e};hm.exports=function(s,e){var t=s.target,i=s.global,r=s.stat,a=s.proto,n=i?pa:r?pa[t]:pa[t]&&pa[t].prototype,o=i?Rr:Rr[t]||Lr(Rr,t,{})[t],u=o.prototype,l,d,c,h,p,f,m,g,S;for(h in e)l=qP(i?h:t+(r?".":"#")+h,s.forced),d=!l&&n&&pm(n,h),f=o[h],d&&(s.dontCallGetSet?(S=UP(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=jP(p,pa):s.wrap&&d?g=HP(p):a&&NP(p)?g=FP(p):g=p,(s.sham||p&&p.sham||f&&f.sham)&&Lr(g,"sham",!0),Lr(o,h,g),a&&(c=t+"Prototype",pm(Rr,c)||Lr(Rr,c,{}),Lr(Rr[c],h,p),s.real&&u&&(l||!u[h])&&Lr(u,h,p)))}});var mm=b((oF,fm)=>{"use strict";var GP=Math.ceil,zP=Math.floor;fm.exports=Math.trunc||function(e){var t=+e;return(t>0?zP:GP)(t)}});var ha=b((uF,bm)=>{"use strict";var QP=mm();bm.exports=function(s){var e=+s;return e!==e||e===0?0:QP(e)}});var Sm=b((lF,gm)=>{"use strict";var WP=ha(),YP=Math.max,KP=Math.min;gm.exports=function(s,e){var t=WP(s);return t<0?YP(t+e,0):KP(t,e)}});var Sc=b((cF,vm)=>{"use strict";var XP=ha(),JP=Math.min;vm.exports=function(s){var e=XP(s);return e>0?JP(e,9007199254740991):0}});var Mr=b((dF,ym)=>{"use strict";var ZP=Sc();ym.exports=function(s){return ZP(s.length)}});var vc=b((pF,Im)=>{"use strict";var eA=Xi(),tA=Sm(),iA=Mr(),Tm=function(s){return function(e,t,i){var r=eA(e),a=iA(r);if(a===0)return!s&&-1;var n=tA(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}};Im.exports={includes:Tm(!0),indexOf:Tm(!1)}});var fa=b((hF,xm)=>{"use strict";xm.exports=function(){}});var Em=b(()=>{"use strict";var rA=Ee(),sA=vc().includes,aA=_e(),nA=fa(),oA=aA(function(){return!Array(1).includes()});rA({target:"Array",proto:!0,forced:oA},{includes:function(e){return sA(this,e,arguments.length>1?arguments[1]:void 0)}});nA("includes")});var Li=b((bF,wm)=>{"use strict";var uA=mi();wm.exports=uA});var Am=b((gF,Pm)=>{"use strict";Em();var lA=Li();Pm.exports=lA("Array","includes")});var Rm=b((SF,km)=>{"use strict";var cA=Am();km.exports=cA});var yt=b((vF,Lm)=>{"use strict";var dA=Rm();Lm.exports=dA});var Bo=b((MF,_m)=>{"use strict";var vA=nc(),yA=oc(),Om=vA("keys");_m.exports=function(s){return Om[s]||(Om[s]=yA(s))}});var Nm=b(($F,Fm)=>{"use strict";var TA=_e();Fm.exports=!TA(function(){function s(){}return s.prototype.constructor=null,Object.getPrototypeOf(new s)!==s.prototype})});var Do=b((BF,qm)=>{"use strict";var IA=Vt(),xA=ge(),EA=wr(),wA=Bo(),PA=Nm(),Um=wA("IE_PROTO"),Ic=Object,AA=Ic.prototype;qm.exports=PA?Ic.getPrototypeOf:function(s){var e=EA(s);if(IA(e,Um))return e[Um];var t=e.constructor;return xA(t)&&e instanceof t?t.prototype:e instanceof Ic?AA:null}});var Co=b((DF,jm)=>{"use strict";jm.exports={}});var zm=b((CF,Gm)=>{"use strict";var kA=$e(),xc=Vt(),RA=Xi(),LA=vc().indexOf,MA=Co(),Hm=kA([].push);Gm.exports=function(s,e){var t=RA(s),i=0,r=[],a;for(a in t)!xc(MA,a)&&xc(t,a)&&Hm(r,a);for(;e.length>i;)xc(t,a=e[i++])&&(~LA(r,a)||Hm(r,a));return r}});var Ec=b((VF,Qm)=>{"use strict";Qm.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var wc=b((OF,Wm)=>{"use strict";var $A=zm(),BA=Ec();Wm.exports=Object.keys||function(e){return $A(e,BA)}});var Pc=b((_F,Zm)=>{"use strict";var Km=gt(),DA=_e(),Xm=$e(),CA=Do(),VA=wc(),OA=Xi(),_A=Wl().f,Jm=Xm(_A),FA=Xm([].push),NA=Km&&DA(function(){var s=Object.create(null);return s[2]=2,!Jm(s,2)}),Ym=function(s){return function(e){for(var t=OA(e),i=VA(t),r=NA&&CA(t)===null,a=i.length,n=0,o=[],u;a>n;)u=i[n++],(!Km||(r?u in t:Jm(t,u)))&&FA(o,s?[u,t[u]]:t[u]);return o}};Zm.exports={entries:Ym(!0),values:Ym(!1)}});var eb=b(()=>{"use strict";var UA=Ee(),qA=Pc().entries;UA({target:"Object",stat:!0},{entries:function(e){return qA(e)}})});var ib=b((UF,tb)=>{"use strict";eb();var jA=Er();tb.exports=jA.Object.entries});var sb=b((qF,rb)=>{"use strict";var HA=ib();rb.exports=HA});var er=b((jF,ab)=>{"use strict";var GA=sb();ab.exports=GA});var tr=b((HF,nb)=>{"use strict";nb.exports={}});var lb=b((GF,ub)=>{"use strict";var zA=ve(),QA=ge(),ob=zA.WeakMap;ub.exports=QA(ob)&&/native code/.test(String(ob))});var Lc=b((zF,pb)=>{"use strict";var WA=lb(),db=ve(),YA=vt(),KA=kr(),Ac=Vt(),kc=ca(),XA=Bo(),JA=Co(),cb="Object already initialized",Rc=db.TypeError,ZA=db.WeakMap,Vo,ma,Oo,ek=function(s){return Oo(s)?ma(s):Vo(s,{})},tk=function(s){return function(e){var t;if(!YA(e)||(t=ma(e)).type!==s)throw new Rc("Incompatible receiver, "+s+" required");return t}};WA||kc.state?(Ot=kc.state||(kc.state=new ZA),Ot.get=Ot.get,Ot.has=Ot.has,Ot.set=Ot.set,Vo=function(s,e){if(Ot.has(s))throw new Rc(cb);return e.facade=s,Ot.set(s,e),e},ma=function(s){return Ot.get(s)||{}},Oo=function(s){return Ot.has(s)}):(ir=XA("state"),JA[ir]=!0,Vo=function(s,e){if(Ac(s,ir))throw new Rc(cb);return e.facade=s,KA(s,ir,e),e},ma=function(s){return Ac(s,ir)?s[ir]:{}},Oo=function(s){return Ac(s,ir)});var Ot,ir;pb.exports={set:Vo,get:ma,has:Oo,enforce:ek,getterFor:tk}});var Bc=b((QF,fb)=>{"use strict";var Mc=gt(),ik=Vt(),hb=Function.prototype,rk=Mc&&Object.getOwnPropertyDescriptor,$c=ik(hb,"name"),sk=$c&&function(){}.name==="something",ak=$c&&(!Mc||Mc&&rk(hb,"name").configurable);fb.exports={EXISTS:$c,PROPER:sk,CONFIGURABLE:ak}});var bb=b(mb=>{"use strict";var nk=gt(),ok=hc(),uk=Zi(),lk=zt(),ck=Xi(),dk=wc();mb.f=nk&&!ok?Object.defineProperties:function(e,t){lk(e);for(var i=ck(t),r=dk(t),a=r.length,n=0,o;a>n;)uk.f(e,o=r[n++],i[o]);return e}});var Dc=b((YF,gb)=>{"use strict";var pk=mi();gb.exports=pk("document","documentElement")});var _c=b((KF,Eb)=>{"use strict";var hk=zt(),fk=bb(),Sb=Ec(),mk=Co(),bk=Dc(),gk=Ro(),Sk=Bo(),vb=">",yb="<",Vc="prototype",Oc="script",Ib=Sk("IE_PROTO"),Cc=function(){},xb=function(s){return yb+Oc+vb+s+yb+"/"+Oc+vb},Tb=function(s){s.write(xb("")),s.close();var e=s.parentWindow.Object;return s=null,e},vk=function(){var s=gk("iframe"),e="java"+Oc+":",t;return s.style.display="none",bk.appendChild(s),s.src=String(e),t=s.contentWindow.document,t.open(),t.write(xb("document.F=Object")),t.close(),t.F},_o,Fo=function(){try{_o=new ActiveXObject("htmlfile")}catch(e){}Fo=typeof document!="undefined"?document.domain&&_o?Tb(_o):vk():Tb(_o);for(var s=Sb.length;s--;)delete Fo[Vc][Sb[s]];return Fo()};mk[Ib]=!0;Eb.exports=Object.create||function(e,t){var i;return e!==null?(Cc[Vc]=hk(e),i=new Cc,Cc[Vc]=null,i[Ib]=e):i=Fo(),t===void 0?i:fk.f(i,t)}});var $r=b((XF,wb)=>{"use strict";var yk=kr();wb.exports=function(s,e,t,i){return i&&i.enumerable?s[e]=t:yk(s,e,t),s}});var qc=b((JF,kb)=>{"use strict";var Tk=_e(),Ik=ge(),xk=vt(),Ek=_c(),Pb=Do(),wk=$r(),Pk=Fe(),Ak=Ct(),Uc=Pk("iterator"),Ab=!1,bi,Fc,Nc;[].keys&&(Nc=[].keys(),"next"in Nc?(Fc=Pb(Pb(Nc)),Fc!==Object.prototype&&(bi=Fc)):Ab=!0);var kk=!xk(bi)||Tk(function(){var s={};return bi[Uc].call(s)!==s});kk?bi={}:Ak&&(bi=Ek(bi));Ik(bi[Uc])||wk(bi,Uc,function(){return this});kb.exports={IteratorPrototype:bi,BUGGY_SAFARI_ITERATORS:Ab}});var No=b((ZF,Lb)=>{"use strict";var Rk=Fe(),Lk=Rk("toStringTag"),Rb={};Rb[Lk]="z";Lb.exports=String(Rb)==="[object z]"});var ba=b((eN,Mb)=>{"use strict";var Mk=No(),$k=ge(),Uo=Ki(),Bk=Fe(),Dk=Bk("toStringTag"),Ck=Object,Vk=Uo(function(){return arguments}())==="Arguments",Ok=function(s,e){try{return s[e]}catch(t){}};Mb.exports=Mk?Uo:function(s){var e,t,i;return s===void 0?"Undefined":s===null?"Null":typeof(t=Ok(e=Ck(s),Dk))=="string"?t:Vk?Uo(e):(i=Uo(e))==="Object"&&$k(e.callee)?"Arguments":i}});var Bb=b((tN,$b)=>{"use strict";var _k=No(),Fk=ba();$b.exports=_k?{}.toString:function(){return"[object "+Fk(this)+"]"}});var ga=b((iN,Cb)=>{"use strict";var Nk=No(),Uk=Zi().f,qk=kr(),jk=Vt(),Hk=Bb(),Gk=Fe(),Db=Gk("toStringTag");Cb.exports=function(s,e,t,i){var r=t?s:s&&s.prototype;r&&(jk(r,Db)||Uk(r,Db,{configurable:!0,value:e}),i&&!Nk&&qk(r,"toString",Hk))}});var Ob=b((rN,Vb)=>{"use strict";var zk=qc().IteratorPrototype,Qk=_c(),Wk=na(),Yk=ga(),Kk=tr(),Xk=function(){return this};Vb.exports=function(s,e,t,i){var r=e+" Iterator";return s.prototype=Qk(zk,{next:Wk(+!i,t)}),Yk(s,r,!1,!0),Kk[r]=Xk,s}});var Fb=b((sN,_b)=>{"use strict";var Jk=$e(),Zk=Gt();_b.exports=function(s,e,t){try{return Jk(Zk(Object.getOwnPropertyDescriptor(s,e)[t]))}catch(i){}}});var Ub=b((aN,Nb)=>{"use strict";var eR=vt();Nb.exports=function(s){return eR(s)||s===null}});var jb=b((nN,qb)=>{"use strict";var tR=Ub(),iR=String,rR=TypeError;qb.exports=function(s){if(tR(s))return s;throw new rR("Can't set "+iR(s)+" as a prototype")}});var jc=b((oN,Hb)=>{"use strict";var sR=Fb(),aR=vt(),nR=Ri(),oR=jb();Hb.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var s=!1,e={},t;try{t=sR(Object.prototype,"__proto__","set"),t(e,[]),s=e instanceof Array}catch(i){}return function(r,a){return nR(r),oR(a),aR(r)&&(s?t(r,a):r.__proto__=a),r}}():void 0)});var tg=b((uN,eg)=>{"use strict";var uR=Ee(),lR=St(),qo=Ct(),Jb=Bc(),cR=ge(),dR=Ob(),Gb=Do(),zb=jc(),pR=ga(),hR=kr(),Hc=$r(),fR=Fe(),Qb=tr(),Zb=qc(),mR=Jb.PROPER,bR=Jb.CONFIGURABLE,Wb=Zb.IteratorPrototype,jo=Zb.BUGGY_SAFARI_ITERATORS,Sa=fR("iterator"),Yb="keys",va="values",Kb="entries",Xb=function(){return this};eg.exports=function(s,e,t,i,r,a,n){dR(t,e,i);var o=function(S){if(S===r&&h)return h;if(!jo&&S&&S in d)return d[S];switch(S){case Yb:return function(){return new t(this,S)};case va:return function(){return new t(this,S)};case Kb:return function(){return new t(this,S)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,d=s.prototype,c=d[Sa]||d["@@iterator"]||r&&d[r],h=!jo&&c||o(r),p=e==="Array"&&d.entries||c,f,m,g;if(p&&(f=Gb(p.call(new s)),f!==Object.prototype&&f.next&&(!qo&&Gb(f)!==Wb&&(zb?zb(f,Wb):cR(f[Sa])||Hc(f,Sa,Xb)),pR(f,u,!0,!0),qo&&(Qb[u]=Xb))),mR&&r===va&&c&&c.name!==va&&(!qo&&bR?hR(d,"name",va):(l=!0,h=function(){return lR(c,this)})),r)if(m={values:o(va),keys:a?h:o(Yb),entries:o(Kb)},n)for(g in m)(jo||l||!(g in d))&&Hc(d,g,m[g]);else uR({target:e,proto:!0,forced:jo||l},m);return(!qo||n)&&d[Sa]!==h&&Hc(d,Sa,h,{name:r}),Qb[e]=h,m}});var rg=b((lN,ig)=>{"use strict";ig.exports=function(s,e){return{value:s,done:e}}});var zc=b((cN,ug)=>{"use strict";var gR=Xi(),Gc=fa(),sg=tr(),ng=Lc(),SR=Zi().f,vR=tg(),Ho=rg(),yR=Ct(),TR=gt(),og="Array Iterator",IR=ng.set,xR=ng.getterFor(og);ug.exports=vR(Array,"Array",function(s,e){IR(this,{type:og,target:gR(s),index:0,kind:e})},function(){var s=xR(this),e=s.target,t=s.index++;if(!e||t>=e.length)return s.target=void 0,Ho(void 0,!0);switch(s.kind){case"keys":return Ho(t,!1);case"values":return Ho(e[t],!1)}return Ho([t,e[t]],!1)},"values");var ag=sg.Arguments=sg.Array;Gc("keys");Gc("values");Gc("entries");if(!yR&&TR&&ag.name!=="values")try{SR(ag,"name",{value:"values"})}catch(s){}});var cg=b((dN,lg)=>{"use strict";var ER=Fe(),wR=tr(),PR=ER("iterator"),AR=Array.prototype;lg.exports=function(s){return s!==void 0&&(wR.Array===s||AR[PR]===s)}});var Qc=b((pN,pg)=>{"use strict";var kR=ba(),dg=la(),RR=xr(),LR=tr(),MR=Fe(),$R=MR("iterator");pg.exports=function(s){if(!RR(s))return dg(s,$R)||dg(s,"@@iterator")||LR[kR(s)]}});var fg=b((hN,hg)=>{"use strict";var BR=St(),DR=Gt(),CR=zt(),VR=ua(),OR=Qc(),_R=TypeError;hg.exports=function(s,e){var t=arguments.length<2?OR(s):e;if(DR(t))return CR(BR(t,s));throw new _R(VR(s)+" is not iterable")}});var gg=b((fN,bg)=>{"use strict";var FR=St(),mg=zt(),NR=la();bg.exports=function(s,e,t){var i,r;mg(s);try{if(i=NR(s,"return"),!i){if(e==="throw")throw t;return t}i=FR(i,s)}catch(a){r=!0,i=a}if(e==="throw")throw t;if(r)throw i;return mg(i),t}});var zo=b((mN,Tg)=>{"use strict";var UR=Ar(),qR=St(),jR=zt(),HR=ua(),GR=cg(),zR=Mr(),Sg=oa(),QR=fg(),WR=Qc(),vg=gg(),YR=TypeError,Go=function(s,e){this.stopped=s,this.result=e},yg=Go.prototype;Tg.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=UR(e,i),l,d,c,h,p,f,m,g=function(v){return l&&vg(l,"normal",v),new Go(!0,v)},S=function(v){return r?(jR(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=WR(s),!d)throw new YR(HR(s)+" is not iterable");if(GR(d)){for(c=0,h=zR(s);h>c;c++)if(p=S(s[c]),p&&Sg(yg,p))return p;return new Go(!1)}l=QR(s,d)}for(f=a?s.next:l.next;!(m=qR(f,l)).done;){try{p=S(m.value)}catch(v){vg(l,"throw",v)}if(typeof p=="object"&&p&&Sg(yg,p))return p}return new Go(!1)}});var xg=b((bN,Ig)=>{"use strict";var KR=gt(),XR=Zi(),JR=na();Ig.exports=function(s,e,t){KR?XR.f(s,e,JR(0,t)):s[e]=t}});var Eg=b(()=>{"use strict";var ZR=Ee(),eL=zo(),tL=xg();ZR({target:"Object",stat:!0},{fromEntries:function(e){var t={};return eL(e,function(i,r){tL(t,i,r)},{AS_ENTRIES:!0}),t}})});var Pg=b((vN,wg)=>{"use strict";zc();Eg();var iL=Er();wg.exports=iL.Object.fromEntries});var kg=b((yN,Ag)=>{"use strict";Ag.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 Lg=b(()=>{"use strict";zc();var rL=kg(),sL=ve(),aL=ga(),Rg=tr();for(Qo in rL)aL(sL[Qo],Qo),Rg[Qo]=Rg.Array;var Qo});var $g=b((xN,Mg)=>{"use strict";var nL=Pg();Lg();Mg.exports=nL});var Wc=b((EN,Bg)=>{"use strict";var oL=$g();Bg.exports=oL});var Dg=b(()=>{"use strict"});var Yc=b((AN,Cg)=>{"use strict";var ya=ve(),uL=Ji(),lL=Ki(),Wo=function(s){return uL.slice(0,s.length)===s};Cg.exports=function(){return Wo("Bun/")?"BUN":Wo("Cloudflare-Workers")?"CLOUDFLARE":Wo("Deno/")?"DENO":Wo("Node.js/")?"NODE":ya.Bun&&typeof Bun.version=="string"?"BUN":ya.Deno&&typeof Deno.version=="object"?"DENO":lL(ya.process)==="process"?"NODE":ya.window&&ya.document?"BROWSER":"REST"}()});var Yo=b((kN,Vg)=>{"use strict";var cL=Yc();Vg.exports=cL==="NODE"});var _g=b((RN,Og)=>{"use strict";var dL=Zi();Og.exports=function(s,e,t){return dL.f(s,e,t)}});var Ug=b((LN,Ng)=>{"use strict";var pL=mi(),hL=_g(),fL=Fe(),mL=gt(),Fg=fL("species");Ng.exports=function(s){var e=pL(s);mL&&e&&!e[Fg]&&hL(e,Fg,{configurable:!0,get:function(){return this}})}});var jg=b((MN,qg)=>{"use strict";var bL=oa(),gL=TypeError;qg.exports=function(s,e){if(bL(e,s))return s;throw new gL("Incorrect invocation")}});var Xc=b(($N,Hg)=>{"use strict";var SL=$e(),vL=ge(),Kc=ca(),yL=SL(Function.toString);vL(Kc.inspectSource)||(Kc.inspectSource=function(s){return yL(s)});Hg.exports=Kc.inspectSource});var Zc=b((BN,Yg)=>{"use strict";var TL=$e(),IL=_e(),Gg=ge(),xL=ba(),EL=mi(),wL=Xc(),zg=function(){},Qg=EL("Reflect","construct"),Jc=/^\s*(?:class|function)\b/,PL=TL(Jc.exec),AL=!Jc.test(zg),Ta=function(e){if(!Gg(e))return!1;try{return Qg(zg,[],e),!0}catch(t){return!1}},Wg=function(e){if(!Gg(e))return!1;switch(xL(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return AL||!!PL(Jc,wL(e))}catch(t){return!0}};Wg.sham=!0;Yg.exports=!Qg||IL(function(){var s;return Ta(Ta.call)||!Ta(Object)||!Ta(function(){s=!0})||s})?Wg:Ta});var Xg=b((DN,Kg)=>{"use strict";var kL=Zc(),RL=ua(),LL=TypeError;Kg.exports=function(s){if(kL(s))return s;throw new LL(RL(s)+" is not a constructor")}});var ed=b((CN,Zg)=>{"use strict";var Jg=zt(),ML=Xg(),$L=xr(),BL=Fe(),DL=BL("species");Zg.exports=function(s,e){var t=Jg(s).constructor,i;return t===void 0||$L(i=Jg(t)[DL])?e:ML(i)}});var tS=b((VN,eS)=>{"use strict";var CL=$e();eS.exports=CL([].slice)});var rS=b((ON,iS)=>{"use strict";var VL=TypeError;iS.exports=function(s,e){if(s<e)throw new VL("Not enough arguments");return s}});var td=b((_N,sS)=>{"use strict";var OL=Ji();sS.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(OL)});var cd=b((FN,hS)=>{"use strict";var Tt=ve(),_L=Hl(),FL=Ar(),aS=ge(),NL=Vt(),pS=_e(),nS=Dc(),UL=tS(),oS=Ro(),qL=rS(),jL=td(),HL=Yo(),od=Tt.setImmediate,ud=Tt.clearImmediate,GL=Tt.process,id=Tt.Dispatch,zL=Tt.Function,uS=Tt.MessageChannel,QL=Tt.String,rd=0,Ia={},lS="onreadystatechange",xa,rr,sd,ad;pS(function(){xa=Tt.location});var ld=function(s){if(NL(Ia,s)){var e=Ia[s];delete Ia[s],e()}},nd=function(s){return function(){ld(s)}},cS=function(s){ld(s.data)},dS=function(s){Tt.postMessage(QL(s),xa.protocol+"//"+xa.host)};(!od||!ud)&&(od=function(e){qL(arguments.length,1);var t=aS(e)?e:zL(e),i=UL(arguments,1);return Ia[++rd]=function(){_L(t,void 0,i)},rr(rd),rd},ud=function(e){delete Ia[e]},HL?rr=function(s){GL.nextTick(nd(s))}:id&&id.now?rr=function(s){id.now(nd(s))}:uS&&!jL?(sd=new uS,ad=sd.port2,sd.port1.onmessage=cS,rr=FL(ad.postMessage,ad)):Tt.addEventListener&&aS(Tt.postMessage)&&!Tt.importScripts&&xa&&xa.protocol!=="file:"&&!pS(dS)?(rr=dS,Tt.addEventListener("message",cS,!1)):lS in oS("script")?rr=function(s){nS.appendChild(oS("script"))[lS]=function(){nS.removeChild(this),ld(s)}}:rr=function(s){setTimeout(nd(s),0)});hS.exports={set:od,clear:ud}});var bS=b((NN,mS)=>{"use strict";var fS=ve(),WL=gt(),YL=Object.getOwnPropertyDescriptor;mS.exports=function(s){if(!WL)return fS[s];var e=YL(fS,s);return e&&e.value}});var dd=b((UN,SS)=>{"use strict";var gS=function(){this.head=null,this.tail=null};gS.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}}};SS.exports=gS});var yS=b((qN,vS)=>{"use strict";var KL=Ji();vS.exports=/ipad|iphone|ipod/i.test(KL)&&typeof Pebble!="undefined"});var IS=b((jN,TS)=>{"use strict";var XL=Ji();TS.exports=/web0s(?!.*chrome)/i.test(XL)});var RS=b((HN,kS)=>{"use strict";var Dr=ve(),JL=bS(),xS=Ar(),pd=cd().set,ZL=dd(),eM=td(),tM=yS(),iM=IS(),hd=Yo(),ES=Dr.MutationObserver||Dr.WebKitMutationObserver,wS=Dr.document,PS=Dr.process,Ko=Dr.Promise,bd=JL("queueMicrotask"),Br,fd,md,Xo,AS;bd||(Ea=new ZL,wa=function(){var s,e;for(hd&&(s=PS.domain)&&s.exit();e=Ea.get();)try{e()}catch(t){throw Ea.head&&Br(),t}s&&s.enter()},!eM&&!hd&&!iM&&ES&&wS?(fd=!0,md=wS.createTextNode(""),new ES(wa).observe(md,{characterData:!0}),Br=function(){md.data=fd=!fd}):!tM&&Ko&&Ko.resolve?(Xo=Ko.resolve(void 0),Xo.constructor=Ko,AS=xS(Xo.then,Xo),Br=function(){AS(wa)}):hd?Br=function(){PS.nextTick(wa)}:(pd=xS(pd,Dr),Br=function(){pd(wa)}),bd=function(s){Ea.head||Br(),Ea.add(s)});var Ea,wa;kS.exports=bd});var MS=b((GN,LS)=>{"use strict";LS.exports=function(s,e){try{arguments.length===1?console.error(s):console.error(s,e)}catch(t){}}});var Jo=b((zN,$S)=>{"use strict";$S.exports=function(s){try{return{error:!1,value:s()}}catch(e){return{error:!0,value:e}}}});var sr=b((QN,BS)=>{"use strict";var rM=ve();BS.exports=rM.Promise});var Cr=b((WN,OS)=>{"use strict";var sM=ve(),Pa=sr(),aM=ge(),nM=pc(),oM=Xc(),uM=Fe(),DS=Yc(),lM=Ct(),gd=Zl(),CS=Pa&&Pa.prototype,cM=uM("species"),Sd=!1,VS=aM(sM.PromiseRejectionEvent),dM=nM("Promise",function(){var s=oM(Pa),e=s!==String(Pa);if(!e&&gd===66||lM&&!(CS.catch&&CS.finally))return!0;if(!gd||gd<51||!/native code/.test(s)){var t=new Pa(function(a){a(1)}),i=function(a){a(function(){},function(){})},r=t.constructor={};if(r[cM]=i,Sd=t.then(function(){})instanceof i,!Sd)return!0}return!e&&(DS==="BROWSER"||DS==="DENO")&&!VS});OS.exports={CONSTRUCTOR:dM,REJECTION_EVENT:VS,SUBCLASSING:Sd}});var Vr=b((YN,FS)=>{"use strict";var _S=Gt(),pM=TypeError,hM=function(s){var e,t;this.promise=new s(function(i,r){if(e!==void 0||t!==void 0)throw new pM("Bad Promise constructor");e=i,t=r}),this.resolve=_S(e),this.reject=_S(t)};FS.exports.f=function(s){return new hM(s)}});var sv=b(()=>{"use strict";var fM=Ee(),mM=Ct(),iu=Yo(),Mi=ve(),Nr=St(),NS=$r(),US=jc(),bM=ga(),gM=Ug(),SM=Gt(),tu=ge(),vM=vt(),yM=jg(),TM=ed(),zS=cd().set,xd=RS(),IM=MS(),xM=Jo(),EM=dd(),QS=Lc(),ru=sr(),Ed=Cr(),WS=Vr(),su="Promise",YS=Ed.CONSTRUCTOR,wM=Ed.REJECTION_EVENT,PM=Ed.SUBCLASSING,vd=QS.getterFor(su),AM=QS.set,Or=ru&&ru.prototype,ar=ru,Zo=Or,KS=Mi.TypeError,yd=Mi.document,wd=Mi.process,Td=WS.f,kM=Td,RM=!!(yd&&yd.createEvent&&Mi.dispatchEvent),XS="unhandledrejection",LM="rejectionhandled",qS=0,JS=1,MM=2,Pd=1,ZS=2,eu,jS,$M,HS,ev=function(s){var e;return vM(s)&&tu(e=s.then)?e:!1},tv=function(s,e){var t=e.value,i=e.state===JS,r=i?s.ok:s.fail,a=s.resolve,n=s.reject,o=s.domain,u,l,d;try{r?(i||(e.rejection===ZS&&DM(e),e.rejection=Pd),r===!0?u=t:(o&&o.enter(),u=r(t),o&&(o.exit(),d=!0)),u===s.promise?n(new KS("Promise-chain cycle")):(l=ev(u))?Nr(l,u,a,n):a(u)):n(t)}catch(c){o&&!d&&o.exit(),n(c)}},iv=function(s,e){s.notified||(s.notified=!0,xd(function(){for(var t=s.reactions,i;i=t.get();)tv(i,s);s.notified=!1,e&&!s.rejection&&BM(s)}))},rv=function(s,e,t){var i,r;RM?(i=yd.createEvent("Event"),i.promise=e,i.reason=t,i.initEvent(s,!1,!0),Mi.dispatchEvent(i)):i={promise:e,reason:t},!wM&&(r=Mi["on"+s])?r(i):s===XS&&IM("Unhandled promise rejection",t)},BM=function(s){Nr(zS,Mi,function(){var e=s.facade,t=s.value,i=GS(s),r;if(i&&(r=xM(function(){iu?wd.emit("unhandledRejection",t,e):rv(XS,e,t)}),s.rejection=iu||GS(s)?ZS:Pd,r.error))throw r.value})},GS=function(s){return s.rejection!==Pd&&!s.parent},DM=function(s){Nr(zS,Mi,function(){var e=s.facade;iu?wd.emit("rejectionHandled",e):rv(LM,e,s.value)})},_r=function(s,e,t){return function(i){s(e,i,t)}},Fr=function(s,e,t){s.done||(s.done=!0,t&&(s=t),s.value=e,s.state=MM,iv(s,!0))},Id=function(s,e,t){if(!s.done){s.done=!0,t&&(s=t);try{if(s.facade===e)throw new KS("Promise can't be resolved itself");var i=ev(e);i?xd(function(){var r={done:!1};try{Nr(i,e,_r(Id,r,s),_r(Fr,r,s))}catch(a){Fr(r,a,s)}}):(s.value=e,s.state=JS,iv(s,!1))}catch(r){Fr({done:!1},r,s)}}};if(YS&&(ar=function(e){yM(this,Zo),SM(e),Nr(eu,this);var t=vd(this);try{e(_r(Id,t),_r(Fr,t))}catch(i){Fr(t,i)}},Zo=ar.prototype,eu=function(e){AM(this,{type:su,done:!1,notified:!1,parent:!1,reactions:new EM,rejection:!1,state:qS,value:void 0})},eu.prototype=NS(Zo,"then",function(e,t){var i=vd(this),r=Td(TM(this,ar));return i.parent=!0,r.ok=tu(e)?e:!0,r.fail=tu(t)&&t,r.domain=iu?wd.domain:void 0,i.state===qS?i.reactions.add(r):xd(function(){tv(r,i)}),r.promise}),jS=function(){var s=new eu,e=vd(s);this.promise=s,this.resolve=_r(Id,e),this.reject=_r(Fr,e)},WS.f=Td=function(s){return s===ar||s===$M?new jS(s):kM(s)},!mM&&tu(ru)&&Or!==Object.prototype)){HS=Or.then,PM||NS(Or,"then",function(e,t){var i=this;return new ar(function(r,a){Nr(HS,i,r,a)}).then(e,t)},{unsafe:!0});try{delete Or.constructor}catch(s){}US&&US(Or,Zo)}fM({global:!0,constructor:!0,wrap:!0,forced:YS},{Promise:ar});bM(ar,su,!1,!0);gM(su)});var lv=b((JN,uv)=>{"use strict";var CM=Fe(),nv=CM("iterator"),ov=!1;try{av=0,Ad={next:function(){return{done:!!av++}},return:function(){ov=!0}},Ad[nv]=function(){return this},Array.from(Ad,function(){throw 2})}catch(s){}var av,Ad;uv.exports=function(s,e){try{if(!e&&!ov)return!1}catch(r){return!1}var t=!1;try{var i={};i[nv]=function(){return{next:function(){return{done:t=!0}}}},s(i)}catch(r){}return t}});var kd=b((ZN,cv)=>{"use strict";var VM=sr(),OM=lv(),_M=Cr().CONSTRUCTOR;cv.exports=_M||!OM(function(s){VM.all(s).then(void 0,function(){})})});var dv=b(()=>{"use strict";var FM=Ee(),NM=St(),UM=Gt(),qM=Vr(),jM=Jo(),HM=zo(),GM=kd();FM({target:"Promise",stat:!0,forced:GM},{all:function(e){var t=this,i=qM.f(t),r=i.resolve,a=i.reject,n=jM(function(){var o=UM(t.resolve),u=[],l=0,d=1;HM(e,function(c){var h=l++,p=!1;d++,NM(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 hv=b(()=>{"use strict";var zM=Ee(),QM=Ct(),WM=Cr().CONSTRUCTOR,Ld=sr(),YM=mi(),KM=ge(),XM=$r(),pv=Ld&&Ld.prototype;zM({target:"Promise",proto:!0,forced:WM,real:!0},{catch:function(s){return this.then(void 0,s)}});!QM&&KM(Ld)&&(Rd=YM("Promise").prototype.catch,pv.catch!==Rd&&XM(pv,"catch",Rd,{unsafe:!0}));var Rd});var fv=b(()=>{"use strict";var JM=Ee(),ZM=St(),e$=Gt(),t$=Vr(),i$=Jo(),r$=zo(),s$=kd();JM({target:"Promise",stat:!0,forced:s$},{race:function(e){var t=this,i=t$.f(t),r=i.reject,a=i$(function(){var n=e$(t.resolve);r$(e,function(o){ZM(n,t,o).then(i.resolve,r)})});return a.error&&r(a.value),i.promise}})});var mv=b(()=>{"use strict";var a$=Ee(),n$=Vr(),o$=Cr().CONSTRUCTOR;a$({target:"Promise",stat:!0,forced:o$},{reject:function(e){var t=n$.f(this),i=t.reject;return i(e),t.promise}})});var Md=b((uU,bv)=>{"use strict";var u$=zt(),l$=vt(),c$=Vr();bv.exports=function(s,e){if(u$(s),l$(e)&&e.constructor===s)return e;var t=c$.f(s),i=t.resolve;return i(e),t.promise}});var vv=b(()=>{"use strict";var d$=Ee(),p$=mi(),gv=Ct(),h$=sr(),Sv=Cr().CONSTRUCTOR,f$=Md(),m$=p$("Promise"),b$=gv&&!Sv;d$({target:"Promise",stat:!0,forced:gv||Sv},{resolve:function(e){return f$(b$&&this===m$?h$:this,e)}})});var yv=b(()=>{"use strict";sv();dv();hv();fv();mv();vv()});var Ev=b(()=>{"use strict";var g$=Ee(),S$=Ct(),au=sr(),v$=_e(),Iv=mi(),xv=ge(),y$=ed(),Tv=Md(),T$=$r(),Bd=au&&au.prototype,I$=!!au&&v$(function(){Bd.finally.call({then:function(){}},function(){})});g$({target:"Promise",proto:!0,real:!0,forced:I$},{finally:function(s){var e=y$(this,Iv("Promise")),t=xv(s);return this.then(t?function(i){return Tv(e,s()).then(function(){return i})}:s,t?function(i){return Tv(e,s()).then(function(){throw i})}:s)}});!S$&&xv(au)&&($d=Iv("Promise").prototype.finally,Bd.finally!==$d&&T$(Bd,"finally",$d,{unsafe:!0}));var $d});var Pv=b((mU,wv)=>{"use strict";Dg();yv();Ev();var x$=Li();wv.exports=x$("Promise","finally")});var kv=b((bU,Av)=>{"use strict";var E$=Pv();Av.exports=E$});var Aa=b((gU,Rv)=>{"use strict";var w$=kv();Rv.exports=w$});var qv=b(()=>{"use strict";var F$=Ee(),N$=Pc().values;F$({target:"Object",stat:!0},{values:function(e){return N$(e)}})});var Hv=b((t1,jv)=>{"use strict";qv();var U$=Er();jv.exports=U$.Object.values});var zv=b((i1,Gv)=>{"use strict";var q$=Hv();Gv.exports=q$});var ur=b((r1,Qv)=>{"use strict";var j$=zv();Qv.exports=j$});var cy=b(()=>{"use strict";var pB=Ee(),hB=wr(),fB=Mr(),mB=ha(),bB=fa();pB({target:"Array",proto:!0},{at:function(e){var t=hB(this),i=fB(t),r=mB(e),a=r>=0?r:i+r;return a<0||a>=i?void 0:t[a]}});bB("at")});var py=b((pq,dy)=>{"use strict";cy();var gB=Li();dy.exports=gB("Array","at")});var fy=b((hq,hy)=>{"use strict";var SB=py();hy.exports=SB});var _t=b((fq,my)=>{"use strict";var vB=fy();my.exports=vB});var ip=b((Zj,Wy)=>{"use strict";var ZB=Ki();Wy.exports=Array.isArray||function(e){return ZB(e)==="Array"}});var Ky=b((eH,Yy)=>{"use strict";var eD=TypeError,tD=9007199254740991;Yy.exports=function(s){if(s>tD)throw eD("Maximum allowed index exceeded");return s}});var Zy=b((tH,Jy)=>{"use strict";var iD=ip(),rD=Mr(),sD=Ky(),aD=Ar(),Xy=function(s,e,t,i,r,a,n,o){for(var u=r,l=0,d=n?aD(n,o):!1,c,h;l<i;)l in t&&(c=d?d(t[l],l,e):t[l],a>0&&iD(c)?(h=rD(c),u=Xy(s,e,c,h,u,a-1)-1):(sD(u+1),s[u]=c),u++),l++;return u};Jy.exports=Xy});var rT=b((iH,iT)=>{"use strict";var eT=ip(),nD=Zc(),oD=vt(),uD=Fe(),lD=uD("species"),tT=Array;iT.exports=function(s){var e;return eT(s)&&(e=s.constructor,nD(e)&&(e===tT||eT(e.prototype))?e=void 0:oD(e)&&(e=e[lD],e===null&&(e=void 0))),e===void 0?tT:e}});var aT=b((rH,sT)=>{"use strict";var cD=rT();sT.exports=function(s,e){return new(cD(s))(e===0?0:e)}});var nT=b(()=>{"use strict";var dD=Ee(),pD=Zy(),hD=Gt(),fD=wr(),mD=Mr(),bD=aT();dD({target:"Array",proto:!0},{flatMap:function(e){var t=fD(this),i=mD(t),r;return hD(e),r=bD(t,0),r.length=pD(r,t,t,i,0,1,e,arguments.length>1?arguments[1]:void 0),r}})});var oT=b(()=>{"use strict";var gD=fa();gD("flatMap")});var lT=b((uH,uT)=>{"use strict";nT();oT();var SD=Li();uT.exports=SD("Array","flatMap")});var dT=b((lH,cT)=>{"use strict";var vD=lT();cT.exports=vD});var ja=b((cH,pT)=>{"use strict";var yD=dT();pT.exports=yD});var Ha=b((dH,hT)=>{"use strict";var TD=ba(),ID=String;hT.exports=function(s){if(TD(s)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return ID(s)}});var rp=b((pH,fT)=>{"use strict";fT.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 gT=b((hH,bT)=>{"use strict";var xD=$e(),ED=Ri(),wD=Ha(),ap=rp(),mT=xD("".replace),PD=RegExp("^["+ap+"]+"),AD=RegExp("(^|[^"+ap+"])["+ap+"]+$"),sp=function(s){return function(e){var t=wD(ED(e));return s&1&&(t=mT(t,PD,"")),s&2&&(t=mT(t,AD,"$1")),t}};bT.exports={start:sp(1),end:sp(2),trim:sp(3)}});var TT=b((fH,yT)=>{"use strict";var kD=Bc().PROPER,RD=_e(),ST=rp(),vT="\u200B\x85\u180E";yT.exports=function(s){return RD(function(){return!!ST[s]()||vT[s]()!==vT||kD&&ST[s].name!==s})}});var np=b((mH,IT)=>{"use strict";var LD=gT().start,MD=TT();IT.exports=MD("trimStart")?function(){return LD(this)}:"".trimStart});var ET=b(()=>{"use strict";var $D=Ee(),xT=np();$D({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==xT},{trimLeft:xT})});var PT=b(()=>{"use strict";ET();var BD=Ee(),wT=np();BD({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==wT},{trimStart:wT})});var kT=b((yH,AT)=>{"use strict";PT();var DD=Li();AT.exports=DD("String","trimLeft")});var LT=b((TH,RT)=>{"use strict";var CD=kT();RT.exports=CD});var $T=b((IH,MT)=>{"use strict";var VD=LT();MT.exports=VD});var QT=b(()=>{"use strict"});var WT=b(()=>{"use strict"});var KT=b((iG,YT)=>{"use strict";var a0=vt(),n0=Ki(),o0=Fe(),u0=o0("match");YT.exports=function(s){var e;return a0(s)&&((e=s[u0])!==void 0?!!e:n0(s)==="RegExp")}});var JT=b((rG,XT)=>{"use strict";var l0=zt();XT.exports=function(){var s=l0(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 tI=b((sG,eI)=>{"use strict";var c0=St(),d0=Vt(),p0=oa(),h0=JT(),ZT=RegExp.prototype;eI.exports=function(s){var e=s.flags;return e===void 0&&!("flags"in ZT)&&!d0(s,"flags")&&p0(ZT,s)?c0(h0,s):e}});var rI=b((aG,iI)=>{"use strict";var pp=$e(),f0=wr(),m0=Math.floor,cp=pp("".charAt),b0=pp("".replace),dp=pp("".slice),g0=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,S0=/\$([$&'`]|\d{1,2})/g;iI.exports=function(s,e,t,i,r,a){var n=t+s.length,o=i.length,u=S0;return r!==void 0&&(r=f0(r),u=g0),b0(a,u,function(l,d){var c;switch(cp(d,0)){case"$":return"$";case"&":return s;case"`":return dp(e,0,t);case"'":return dp(e,n);case"<":c=r[dp(d,1,-1)];break;default:var h=+d;if(h===0)return l;if(h>o){var p=m0(h/10);return p===0?l:p<=o?i[p-1]===void 0?cp(d,1):i[p-1]+cp(d,1):l}c=i[h-1]}return c===void 0?"":c})}});var nI=b(()=>{"use strict";var v0=Ee(),y0=St(),fp=$e(),sI=Ri(),T0=ge(),I0=xr(),x0=KT(),es=Ha(),E0=la(),w0=tI(),P0=rI(),A0=Fe(),k0=Ct(),R0=A0("replace"),L0=TypeError,hp=fp("".indexOf),M0=fp("".replace),aI=fp("".slice),$0=Math.max;v0({target:"String",proto:!0},{replaceAll:function(e,t){var i=sI(this),r,a,n,o,u,l,d,c,h,p,f=0,m="";if(!I0(e)){if(r=x0(e),r&&(a=es(sI(w0(e))),!~hp(a,"g")))throw new L0("`.replaceAll` does not allow non-global regexes");if(n=E0(e,R0),n)return y0(n,e,i,t);if(k0&&r)return M0(es(i),e,t)}for(o=es(i),u=es(e),l=T0(t),l||(t=es(t)),d=u.length,c=$0(1,d),h=hp(o,u);h!==-1;)p=l?es(t(u,h,o)):P0(u,o,h,[],void 0,t),m+=aI(o,f,h)+p,f=h+d,h=h+c>o.length?-1:hp(o,u,h+c);return f<o.length&&(m+=aI(o,f)),m}})});var uI=b((uG,oI)=>{"use strict";QT();WT();nI();var B0=Li();oI.exports=B0("String","replaceAll")});var cI=b((lG,lI)=>{"use strict";var D0=uI();lI.exports=D0});var mp=b((cG,dI)=>{"use strict";var C0=cI();dI.exports=C0});var hI=b((dG,pI)=>{"use strict";var V0=ha(),O0=Ha(),_0=Ri(),F0=RangeError;pI.exports=function(e){var t=O0(_0(this)),i="",r=V0(e);if(r<0||r===1/0)throw new F0("Wrong number of repetitions");for(;r>0;(r>>>=1)&&(t+=t))r&1&&(i+=t);return i}});var SI=b((pG,gI)=>{"use strict";var bI=$e(),N0=Sc(),fI=Ha(),U0=hI(),q0=Ri(),j0=bI(U0),H0=bI("".slice),G0=Math.ceil,mI=function(s){return function(e,t,i){var r=fI(q0(e)),a=N0(t),n=r.length,o=i===void 0?" ":fI(i),u,l;return a<=n||o===""?r:(u=a-n,l=j0(o,G0(u/o.length)),l.length>u&&(l=H0(l,0,u)),s?r+l:l+r)}};gI.exports={start:mI(!1),end:mI(!0)}});var yI=b((hG,vI)=>{"use strict";var z0=Ji();vI.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(z0)});var TI=b(()=>{"use strict";var Q0=Ee(),W0=SI().start,Y0=yI();Q0({target:"String",proto:!0,forced:Y0},{padStart:function(e){return W0(this,e,arguments.length>1?arguments[1]:void 0)}})});var xI=b((bG,II)=>{"use strict";TI();var K0=Li();II.exports=K0("String","padStart")});var wI=b((gG,EI)=>{"use strict";var X0=xI();EI.exports=X0});var bp=b((SG,PI)=>{"use strict";var J0=wI();PI.exports=J0});var Oh="2.0.134-dev.29c5fea5.0";var at=(r=>(r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused",r))(at||{}),fi=(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))(fi||{});var wo=(r=>(r.NOT_AVAILABLE="NOT_AVAILABLE",r.AVAILABLE="AVAILABLE",r.CONNECTING="CONNECTING",r.CONNECTED="CONNECTED",r))(wo||{}),Ul=(i=>(i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic",i))(Ul||{});var ql=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(ql||{}),Po=(i=>(i.TRAFFIC_SAVING="traffic_saving",i.HIGH_QUALITY="high_quality",i.UNKNOWN="unknown",i))(Po||{});var _E=N(yt(),1);import{assertNever as Vm,assertNonNullable as pA,isNonNullable as Mo,ValueSubject as yc,Subject as hA,Subscription as fA,merge as mA,observableFrom as bA,fromEvent as $m,map as Bm,tap as Dm,filterChanged as gA,isNullable as Tc,ErrorCategory as Cm}from"@vkontakte/videoplayer-shared/es2018";var Mm=s=>new Promise((e,t)=>{let i=document.createElement("script");i.setAttribute("src",s),i.onload=()=>e(),i.onerror=r=>t(r),document.body.appendChild(i)});var $o=class{constructor(e){this.connection$=new yc(void 0);this.castState$=new yc("NOT_AVAILABLE");this.errorEvent$=new hA;this.realCastState$=new yc("NOT_AVAILABLE");this.subscription=new fA;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=Mo((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||Mm("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:Cm.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(){Mo(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();Tc(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();Tc(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.isDestroyed=!0,this.subscription.unsubscribe()}initListeners(){let e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),i=cast.framework.CastContext.getInstance();this.subscription.add($m(i,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(r=>{var a,n,o;switch(r.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(o=(n=(a=i.getCurrentSession())==null?void 0:a.getMediaSession())==null?void 0:n.media)==null?void 0:o.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return Vm(r.sessionState)}})).add(mA($m(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(Dm(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),Bm(r=>r.castState)),bA([i.getCastState()])).pipe(gA(),Bm(SA),Dm(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{var o,u;let a=r==="CONNECTED",n=Mo(this.connection$.getValue());if(a&&!n){let l=i.getCurrentSession();pA(l);let d=l.getCastDevice(),c=(u=(o=l.getMediaSession())==null?void 0:o.media)==null?void 0:u.contentId;(Tc(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"?Mo(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:Cm.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:a})}}},SA=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 Vm(s)}};var kh=N(yt(),1),vE=N(er(),1),yE=N(Wc(),1);var Fv=N(Aa(),1);import{assertNever as Lv}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:Lv(t)}return s},$i=(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:Lv(e)}};var R=(s,e,t=!1)=>{let i=s.getTransition();(t||!i||i.to===e)&&s.setState(e)};import{isNonNullable as P$,Subject as nu,merge as Mv}from"@vkontakte/videoplayer-shared/es2018";var H=class{constructor(e){this.transitionStarted$=new nu;this.transitionEnded$=new nu;this.transitionUpdated$=new nu;this.forceChanged$=new nu;this.stateChangeStarted$=Mv(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=Mv(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||P$(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 A$}from"@vkontakte/videoplayer-shared/es2018";var $v=s=>{switch(s){case"MPEG":case"DASH":case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":case"HLS":case"HLS_ONDEMAND":return!1;case"DASH_LIVE":case"DASH_LIVE_CMAF":case"HLS_LIVE":case"HLS_LIVE_CMAF":case"DASH_LIVE_WEBM":case"WEB_RTC_LIVE":return!0;default:return A$(s)}};import{assertNever as Ur,assertNonNullable as nr,debounce as Bv,ErrorCategory as Dv,fromEvent as or,isNonNullable as Cv,map as Vv,merge as Ov,observableFrom as k$,Subject as R$,Subscription as Dd,timeout as L$,getHighestQuality as M$}from"@vkontakte/videoplayer-shared/es2018";var $$=5,B$=5,D$=500,_v=7e3,ka=class{constructor(e){this.subscription=new Dd;this.loadMediaTimeoutSubscription=new Dd;this.videoState=new H("stopped");this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(a)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.stop());return}if(!t){if((r==null?void 0:r.to)!=="paused"&&a.state==="requested"&&e!=="stopped"){this.seek(a.position/1e3);return}switch(i){case"ready":{switch(e){case"playing":case"paused":case"ready":break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:Ur(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:Ur(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:Ur(e)}break}default:Ur(i)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next($v(e.format)),this.params.output.isAudioAvailable$.next(!0),this.handleRemoteVolumeChange({volume:this.params.connection.remotePlayer.volumeLevel,muted:this.params.connection.remotePlayer.isMuted});let t=this.params.connection.session.getMediaSession();t&&this.restoreSession(t),this.subscribe()}destroy(){this.log({message:"[destroy]"}),this.subscription.unsubscribe()}subscribe(){this.subscription.add(this.loadMediaTimeoutSubscription);let e=new Dd;this.subscription.add(e),this.subscription.add(Ov(this.videoState.stateChangeStarted$.pipe(Vv(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe(Vv(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 R$;e.add(r.pipe(Bv(D$)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let a=NaN;e.add(or(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)>$$)&&r.next(o),a=o})),e.add(or(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(or(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(or(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t(or(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),r=>{this.logRemoteEvent(r);let{remotePlayer:a}=this.params.connection,n=r.value,o=this.params.output.isBuffering$.getValue(),u=n===chrome.cast.media.PlayerState.BUFFERING;switch(o!==u&&this.params.output.isBuffering$.next(u),n){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&a.duration-a.currentTime<B$&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),R(this.params.desiredState.playbackState,"stopped");break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:Ur(n)}}),t(or(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t(or(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});let i=Ov(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,k$(["init"])).pipe(Bv(0));t(i,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});let{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState("paused"),R(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),R(this.params.desiredState.playbackState,"playing"));let i=this.params.output.isLive$.getValue();this.params.output.duration$.next(i?0:t.duration),this.params.output.position$.next(i?0:t.currentTime),this.params.desiredState.seekState.setState({state:"none"})}}prepare(){let e=this.params.format;this.log({message:`[prepare] format: ${e}`});let t=this.createMediaInfo(e),i=this.createLoadRequest(t);this.loadMedia(i)}handleRemotePause(){let e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="paused"||e==="playing")&&(this.videoState.setState("paused"),R(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="playing"||e==="paused")&&(this.videoState.setState("playing"),R(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){var t;let e=this.videoState.getTransition();(e==null?void 0:e.to)==="ready"&&this.videoState.setState("ready"),((t=this.params.desiredState.playbackState.getTransition())==null?void 0:t.to)==="ready"&&R(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){var r,a;let t=this.params.output.volume$.getValue(),i={volume:(r=e.volume)!=null?r:t.volume,muted:(a=e.muted)!=null?a:t.muted};(i.volume!==t.volume||i.muted!==i.muted)&&this.params.output.volume$.next(i)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:i}=this.params.connection;t.currentTime=e,i.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){var l;let t=this.params.source,i,r,a;switch(e){case"MPEG":{let d=t[e];nr(d);let c=M$(Object.keys(d));nr(c);let h=d[c];nr(h),i=h,r="video/mp4",a=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let d=t[e];nr(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];nr(d),i=d.url,r="application/dash+xml",a=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let d=t[e];nr(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];nr(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:Dv.VIDEO_PIPELINE,message:d,thrown:c}),c}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return Ur(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 Cv(o)&&(n.metadata.title=o),Cv(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(L$(_v).subscribe(()=>a(`timeout(${_v})`)))});(0,Fv.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:Dv.VIDEO_PIPELINE,message:a,thrown:r})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var ep=N(yt(),1);import{clearVideoElement as Uv}from"@vkontakte/videoplayer-shared/es2018";import{clearVideoElement as C$}from"@vkontakte/videoplayer-shared/es2018";var Nv=s=>{try{s.pause(),s.playbackRate=0,C$(s),s.remove()}catch(e){console.error(e)}};import{fromEvent as V$,Subscription as O$}from"@vkontakte/videoplayer-shared/es2018";var Cd=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)}},Vd=window.WeakMap?new WeakMap:new Cd,Od=window.WeakMap?new WeakMap:new Map,_$=(s,e=20)=>{let t=0;return V$(s,"ratechange").subscribe(i=>{t++,t>=e&&(s.currentTime=s.currentTime,t=0)})},Ne=(s,{audioVideoSyncRate:e,disableYandexPiP:t})=>{let i=s.querySelector("video"),r=!!i;i?Uv(i):(i=document.createElement("video"),s.appendChild(i)),Vd.set(i,r);let a=new O$;return a.add(_$(i,e)),Od.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},Ue=s=>{let e=Od.get(s);e==null||e.unsubscribe(),Od.delete(s);let t=Vd.get(s);Vd.delete(s),t?Uv(s):Nv(s)};var Fd=N(ur(),1);import{assertNonNullable as Ra,isNonNullable as Wt,isNullable as z$,fromEvent as qr,merge as Wv,observableFrom as Yv,filterChanged as Kv,map as La,Subject as Xv,Subscription as Q$,ValueSubject as W$,ErrorCategory as Y$}from"@vkontakte/videoplayer-shared/es2018";import{isNonNullable as _d,isNullable as H$,Subscription as G$}from"@vkontakte/videoplayer-shared/es2018";var ou=(s,e,t,{equal:i=(n,o)=>n===o,changed$:r,onError:a}={})=>{let n=s.getState(),o=e(),u=H$(r),l=new G$;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},wt=(s,e,t)=>ou(e,()=>s.loop,i=>{_d(i)&&(s.loop=i)},{onError:t}),qe=(s,e,t,i)=>ou(e,()=>({muted:s.muted,volume:s.volume}),r=>{_d(r)&&(s.muted=r.muted,s.volume=r.volume)},{equal:(r,a)=>r===a||(r==null?void 0:r.muted)===(a==null?void 0:a.muted)&&(r==null?void 0:r.volume)===(a==null?void 0:a.volume),changed$:t,onError:i}),nt=(s,e,t,i)=>ou(e,()=>s.playbackRate,r=>{_d(r)&&(s.playbackRate=r)},{changed$:t,onError:i}),Bi=ou;var K$=s=>["__",s.language,s.label].join("|"),X$=(s,e)=>{if(s.id===e)return!0;let[t,i,r]=e.split("|");return s.language===i&&s.label===r},Nd=class s{constructor(e){this.available$=new Xv;this.current$=new W$(void 0);this.error$=new Xv;this.subscription=new Q$;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:Y$.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(Bi(t.internalTextTracks,()=>(0,Fd.default)(this.internalTracks),a=>{Wt(a)&&this.setInternal(a)},{equal:(a,n)=>Wt(a)&&Wt(n)&&a.length===n.length&&a.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(La(a=>a.filter(({type:n})=>n==="internal"))),onError:r})),this.subscription.add(Bi(t.externalTextTracks,()=>(0,Fd.default)(this.externalTracks),a=>{Wt(a)&&this.setExternal(a)},{equal:(a,n)=>Wt(a)&&Wt(n)&&a.length===n.length&&a.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(La(a=>a.filter(({type:n})=>n==="external"))),onError:r})),this.subscription.add(Bi(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(Bi(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let a of this.htmlTextTracksAsArray())this.applyCueSettings(a.cues),this.applyCueSettings(a.activeCues)}))}subscribe(){Ra(this.video);let{textTracks:e}=this.video;this.subscription.add(qr(e,"addtrack").subscribe(()=>{let i=this.current$.getValue();i&&this.select(i)})),this.subscription.add(Wv(qr(e,"addtrack"),qr(e,"removetrack"),Yv(["init"])).pipe(La(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),Kv((i,r)=>i.length===r.length&&i.every(({id:a},n)=>a===r[n].id))).subscribe(this.available$)),this.subscription.add(Wv(qr(e,"change"),Yv(["init"])).pipe(La(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),La(i=>i&&this.htmlTextTrackToITextTrack(i).id),Kv()).subscribe(this.current$));let t=i=>{var r,a;return this.applyCueSettings((a=(r=i.target)==null?void 0:r.activeCues)!=null?a:null)};this.subscription.add(qr(e,"addtrack").subscribe(i=>{var a,n;(a=i.track)==null||a.addEventListener("cuechange",t);let r=o=>{var l,d,c,h,p;let u=(d=(l=o.target)==null?void 0:l.cues)!=null?d:null;u&&u.length&&(this.applyCueSettings((h=(c=o.target)==null?void 0:c.cues)!=null?h:null),(p=o.target)==null||p.removeEventListener("cuechange",r))};(n=i.track)==null||n.addEventListener("cuechange",r)})),this.subscription.add(qr(e,"removetrack").subscribe(i=>{var r;(r=i.track)==null||r.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;let t=this.cueSettings.getState();for(let i of Array.from(e)){let r=i;Wt(t.align)&&(r.align=t.align),Wt(t.position)&&(r.position=t.position),Wt(t.size)&&(r.size=t.size),Wt(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){Ra(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:K$(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){Ra(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(z$(e)||!X$(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){Ra(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){Ra(this.video);let t=Array.prototype.find.call(this.video.getElementsByTagName("track"),i=>i.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}},ot=Nd;var lr=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 Jv=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},Ud=s=>{let e=Jv(s);return!!(e&&e.fullscreenElement&&e.fullscreenElement===s)},Zv=s=>{let e=Jv(s);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===s)};import{fromEvent as et,map as Yt,merge as fu,filterChanged as oy,isNonNullable as uy,Subject as nB,filter as jd,mapTo as Hd,combine as oB,once as uB,throttle as lB,ErrorCategory as cB,ValueSubject as ly,Subscription as dB}from"@vkontakte/videoplayer-shared/es2018";var J$=3,ey=(s,e,t=J$)=>{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 uu=class{constructor(){this._isMiuiBrowser=!1}get current(){return this._current}get isYandex(){return this.current==="Yandex"}get isSafari(){return this.current==="Safari"}get isFirefox(){return this.current==="Firefox"}get isSamsungBrowser(){return this.current==="SamsungBrowser"}get safariVersion(){return this._safariVersion}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.isSafari&&this.detectSafariVersion()}detectSafariVersion(){try{let{userAgent:e}=window.navigator,t=e.match(/Version\/(\d+)/);if(!t)return;let i=t[1],r=parseInt(i,10);if(isNaN(r))return;this._safariVersion=r}catch(e){console.error(e)}}};var ty=N(yt(),1);var Ma=()=>{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 lu=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,ty.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=Ma()}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 cu=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 It=()=>window.ManagedMediaSource||window.MediaSource,jr=()=>{var s,e;return!!(window.ManagedMediaSource&&((e=(s=window.ManagedSourceBuffer)==null?void 0:s.prototype)!=null&&e.appendBuffer))},iy=()=>{var s,e;return!!(window.MediaSource&&((e=(s=window.SourceBuffer)==null?void 0:s.prototype)!=null&&e.appendBuffer))},du=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var Z$=document.createElement("video"),eB='video/mp4; codecs="avc1.42000a,mp4a.40.2"',tB='video/mp4; codecs="hev1.1.6.L93.B0"',ry='video/webm; codecs="vp09.00.10.08"',sy='video/webm; codecs="av01.0.00M.08"',iB='audio/mp4; codecs="mp4a.40.2"',rB='audio/webm; codecs="opus"',ay,sB=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:sy}}),window.navigator.mediaCapabilities.decodingInfo({...s,video:{...s.video,contentType:ry}})]);ay={DASH_WEBM_AV1:e,DASH_WEBM:t}};sB().catch(s=>{console.log(Z$),console.error(s)});var pu=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 ay}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:jr(),mse:iy(),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=It())==null?void 0:l.isTypeSupported)!=null&&d.call(l,eB)),E=!!((h=(c=It())==null?void 0:c.isTypeSupported)!=null&&h.call(c,tB)),O=!!((f=(p=It())==null?void 0:p.isTypeSupported)!=null&&f.call(p,iB));this._codecs={h264:T,h265:E,vp9:!!((g=(m=It())==null?void 0:m.isTypeSupported)!=null&&g.call(m,ry)),av1:!!((v=(S=It())==null?void 0:S.isTypeSupported)!=null&&v.call(S,sy)),aac:O,opus:!!((I=(y=It())==null?void 0:y.isTypeSupported)!=null&&I.call(y,rB)),mpeg:(T||E)&&O},this._nativeHlsSupported=this._protocols.hls&&this._containers.mp4}catch(T){console.error(T)}this.destroyVideoElement()}destroyVideoElement(){var t;if(!this._video)return;if(this._video.pause(),this._video.currentTime=0,this._video.removeAttribute("src"),this._video.src="",this._video.load(),this._video.remove){this._video.remove(),this._video=null;return}this._video.parentNode&&this._video.parentNode.removeChild(this._video);let e=this._video.cloneNode(!1);(t=this._video.parentNode)==null||t.replaceChild(e,this._video),this._video=null}};var ny="audio/mpeg",hu=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,ny))},this._codecs={mp3:!!((r=(i=It())==null?void 0:i.isTypeSupported)!=null&&r.call(i,ny))}}catch(a){console.error(a)}this.destroyAudioElement()}destroyAudioElement(){var t;if(!this._audio)return;if(this._audio.pause(),this._audio.currentTime=0,this._audio.removeAttribute("src"),this._audio.src="",this._audio.load(),this._audio.remove){this._audio.remove(),this._audio=null;return}this._audio.parentNode&&this._audio.parentNode.removeChild(this._audio);let e=this._audio.cloneNode(!1);(t=this._audio.parentNode)==null||t.replaceChild(e,this._audio),this._audio=null}};import{ValueSubject as aB}from"@vkontakte/videoplayer-shared/es2018";var qd=class{constructor(){this.isInited$=new aB(!1);this._displayChecker=new cu,this._deviceChecker=new lu(this._displayChecker),this._browserChecker=new uu,this._videoChecker=new pu(this._deviceChecker,this._browserChecker),this._audioChecker=new hu,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)}},q=new qd;var je=s=>{let e=A=>et(s,A).pipe(Hd(void 0)),t=new dB,i=()=>t.unsubscribe(),r=fu(et(s,"progress"),et(s,"timeupdate")).pipe(Yt(()=>ey(s.buffered,s.currentTime))),a=q.browser.isSafari?oB({play:e("play").pipe(uB()),playing:e("playing")}).pipe(Hd(void 0)):e("playing"),n=et(s,"volumechange").pipe(Yt(()=>({muted:s.muted,volume:s.volume}))),o=et(s,"ratechange").pipe(Yt(()=>s.playbackRate)),u=et(s,"error").pipe(jd(()=>!!(s.error||s.played.length)),Yt(()=>{var C;let A=s.error;return{id:A?`MediaError#${A.code}`:"HtmlVideoError",category:cB.VIDEO_PIPELINE,message:A?A.message:"Error event from HTML video element",thrown:(C=s.error)!=null?C:void 0}})),l=et(s,"timeupdate").pipe(Yt(()=>s.currentTime)),d=["waiting","seeking","seeked","timeupdate"],c=new nB,h=.3,p;t.add(fu(...d.map(A=>et(s,A))).subscribe(A=>{let C=s.currentTime;s.loop&&uy(p)&&uy(C)&&p>=s.duration-h&&C<=h&&c.next(p),p=C}));let f=e("pause").pipe(jd(()=>!s.error&&p!==s.duration)),m=et(s,"enterpictureinpicture"),g=et(s,"leavepictureinpicture"),S=new ly(Zv(s));t.add(m.subscribe(()=>S.next(!0))),t.add(g.subscribe(()=>S.next(!1)));let v=new ly(Ud(s)),y=et(s,"fullscreenchange");t.add(y.pipe(Yt(()=>Ud(s))).subscribe(v));let I=.1,T=1e3,E=et(s,"timeupdate").pipe(Yt(A=>s.duration-s.currentTime<I),oy()),O=fu(E.pipe(jd(A=>!s.loop&&A)),et(s,"ended")).pipe(lB(T),Hd(void 0)),w=fu(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(A=>et(s,A)),E.pipe(Yt(A=>({type:A?"ended":"unknown"})))).pipe(Yt(A=>q.browser.isFirefox&&A.type==="ended"?s.readyState<2:s.readyState<3),oy());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$:et(s,"durationchange").pipe(Yt(()=>s.duration)),isBuffering$:w,currentBuffer$:r,volumeState$:n,playbackRateState$:o,inPiP$:S,inFullscreen$:v,enterPip$:m,leavePip$:g,destroy:i}};import{VideoQuality as Di}from"@vkontakte/videoplayer-shared/es2018";var Kt=s=>{switch(s){case"mobile":return Di.Q_144P;case"lowest":return Di.Q_240P;case"low":return Di.Q_360P;case"sd":case"medium":return Di.Q_480P;case"hd":case"high":return Di.Q_720P;case"fullhd":case"full":return Di.Q_1080P;case"quadhd":case"quad":return Di.Q_1440P;case"ultrahd":case"ultra":return Di.Q_2160P}};var it=N(_t(),1),Qd=N(yt(),1),cr=N(er(),1);import{isNonNullable as ie,isNullable as vu,now as wy,isHigher as yu,isHigherOrEqual as Gr,isInvariantQuality as Tu,isLowerOrEqual as zr,videoSizeToQuality as Py,assertNotEmptyArray as Iu,assertNonNullable as Ay}from"@vkontakte/videoplayer-shared/es2018";var Gd=!1,gi={},by=s=>{Gd=s},gy=()=>{gi={}},Sy=s=>{s(gi)},$a=(s,e)=>{var t;Gd&&(gi.meta=(t=gi.meta)!=null?t:{},gi.meta[s]=e)},tt=class{constructor(e){this.name=e}next(e){var i,r;if(!Gd)return;gi.series=(i=gi.series)!=null?i:{};let t=(r=gi.series[this.name])!=null?r:[];t.push([Date.now(),e]),gi.series[this.name]=t}};import{isHigher as yB,isHigherOrEqual as yq,isLower as vy,isLowerOrEqual as Tq,isNonNullable as mu,isNullable as TB,videoHeightToQuality as bu}from"@vkontakte/videoplayer-shared/es2018";function zd(s,e,t){return!s.max&&s.min===e?"high_quality":!s.min&&s.max===t?"traffic_saving":"unknown"}function gu(s,e,t){return!!s&&zd(s,e,t)==="high_quality"}function Hr(s,e,t){return TB(s)||mu(s.min)&&mu(s.max)&&vy(s.max,s.min)||mu(s.min)&&e&&yB(s.min,e)||mu(s.max)&&t&&vy(s.max,t)}function yy({limits:s,highestAvailableHeight:e,lowestAvailableHeight:t}){return Hr({max:s!=null&&s.max?bu(s.max):void 0,min:s!=null&&s.min?bu(s.min):void 0},e?bu(e):void 0,t?bu(t):void 0)}var ky=new tt("best_bitrate"),xu=(s,e,t)=>(e-t)*Math.pow(2,-10*s)+t;var Qr=s=>(e,t)=>s*(Number(e.bitrate)-Number(t.bitrate)),Ci=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=wy()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},Eu='Assertion "ABR Tracks is empty array" failed',Su=new WeakMap,Ty=new WeakMap,Iy=new WeakMap,Ba=(s,e,t,i)=>{var u;let r=[...e].sort(Qr(1)),a=[...t].sort(Qr(1)),n=a.filter(l=>ie(l.bitrate)&&ie(s.bitrate)?s.bitrate/l.bitrate>i:!0),o=(u=(0,it.default)(a,Math.round(a.length*r.indexOf(s)/(r.length+1))))!=null?u:(0,it.default)(a,-1);return o&&(0,Qd.default)(n,o)?o:n.length?(0,it.default)(n,-1):(0,it.default)(a,0)},Da=(s,e,t,i)=>{var u;let r=Su.get(e);r||(r=[...e].sort(Qr(1)),Su.set(e,r));let a=Su.get(t);a||(a=[...t].sort(Qr(1)),Su.set(t,a));let n=Iy.get(s);n||(n=a.filter(l=>ie(l.bitrate)&&ie(s.bitrate)?s.bitrate/l.bitrate>i:!0),Iy.set(s,n));let o=(u=(0,it.default)(a,Math.round(a.length*r.indexOf(s)/(r.length+1))))!=null?u:(0,it.default)(a,-1);return o&&(0,Qd.default)(n,o)?o:n.length?(0,it.default)(n,-1):(0,it.default)(a,0)},xy=s=>"quality"in s,wu=(s,e,t,i)=>{var n;let r=ie((n=i==null?void 0:i.last)==null?void 0:n.bitrate)&&ie(t==null?void 0:t.bitrate)&&i.last.bitrate<t.bitrate?s.trackCooldownIncreaseQuality:s.trackCooldownDecreaseQuality,a=t&&i&&i.history[t.id]&&wy()-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=xy(o)?"video":"audio",l=xy(o)?o.quality:o.bitrate;return e({message:`
6
+ var FE=Object.create;var Oh=Object.defineProperty;var NE=Object.getOwnPropertyDescriptor;var UE=Object.getOwnPropertyNames;var qE=Object.getPrototypeOf,jE=Object.prototype.hasOwnProperty;var b=(s,e)=>()=>(e||s((e={exports:{}}).exports,e),e.exports);var HE=(s,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of UE(e))!jE.call(s,r)&&r!==t&&Oh(s,r,{get:()=>e[r],enumerable:!(i=NE(e,r))||i.enumerable});return s};var N=(s,e,t)=>(t=s!=null?FE(qE(s)):{},HE(e||!s||!s.__esModule?Oh(t,"default",{value:s,enumerable:!0}):t,s));var ve=b((Hl,Fh)=>{"use strict";var ra=function(s){return s&&s.Math===Math&&s};Fh.exports=ra(typeof globalThis=="object"&&globalThis)||ra(typeof window=="object"&&window)||ra(typeof self=="object"&&self)||ra(typeof global=="object"&&global)||ra(typeof Hl=="object"&&Hl)||function(){return this}()||Function("return this")()});var Oe=b((h_,Nh)=>{"use strict";Nh.exports=function(s){try{return!!s()}catch(e){return!0}}});var sa=b((f_,Uh)=>{"use strict";var GE=Oe();Uh.exports=!GE(function(){var s=function(){}.bind();return typeof s!="function"||s.hasOwnProperty("prototype")})});var Gl=b((m_,Gh)=>{"use strict";var zE=sa(),Hh=Function.prototype,qh=Hh.apply,jh=Hh.call;Gh.exports=typeof Reflect=="object"&&Reflect.apply||(zE?jh.bind(qh):function(){return jh.apply(qh,arguments)})});var $e=b((b_,Wh)=>{"use strict";var zh=sa(),Qh=Function.prototype,zl=Qh.call,QE=zh&&Qh.bind.bind(zl,zl);Wh.exports=zh?QE:function(s){return function(){return zl.apply(s,arguments)}}});var Ki=b((g_,Kh)=>{"use strict";var Yh=$e(),WE=Yh({}.toString),YE=Yh("".slice);Kh.exports=function(s){return YE(WE(s),8,-1)}});var Ql=b((S_,Xh)=>{"use strict";var KE=Ki(),XE=$e();Xh.exports=function(s){if(KE(s)==="Function")return XE(s)}});var ge=b((v_,Jh)=>{"use strict";var Wl=typeof document=="object"&&document.all;Jh.exports=typeof Wl=="undefined"&&Wl!==void 0?function(s){return typeof s=="function"||s===Wl}:function(s){return typeof s=="function"}});var bt=b((y_,Zh)=>{"use strict";var JE=Oe();Zh.exports=!JE(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var gt=b((T_,ef)=>{"use strict";var ZE=sa(),Po=Function.prototype.call;ef.exports=ZE?Po.bind(Po):function(){return Po.apply(Po,arguments)}});var Yl=b(sf=>{"use strict";var tf={}.propertyIsEnumerable,rf=Object.getOwnPropertyDescriptor,ew=rf&&!tf.call({1:2},1);sf.f=ew?function(e){var t=rf(this,e);return!!t&&t.enumerable}:tf});var aa=b((x_,af)=>{"use strict";af.exports=function(s,e){return{enumerable:!(s&1),configurable:!(s&2),writable:!(s&4),value:e}}});var of=b((E_,nf)=>{"use strict";var tw=$e(),iw=Oe(),rw=Ki(),Kl=Object,sw=tw("".split);nf.exports=iw(function(){return!Kl("z").propertyIsEnumerable(0)})?function(s){return rw(s)==="String"?sw(s,""):Kl(s)}:Kl});var xr=b((w_,uf)=>{"use strict";uf.exports=function(s){return s==null}});var Ri=b((P_,lf)=>{"use strict";var aw=xr(),nw=TypeError;lf.exports=function(s){if(aw(s))throw new nw("Can't call method on "+s);return s}});var Xi=b((A_,cf)=>{"use strict";var ow=of(),uw=Ri();cf.exports=function(s){return ow(uw(s))}});var St=b((k_,df)=>{"use strict";var lw=ge();df.exports=function(s){return typeof s=="object"?s!==null:lw(s)}});var Er=b((R_,pf)=>{"use strict";pf.exports={}});var mi=b((L_,ff)=>{"use strict";var Xl=Er(),Jl=ve(),cw=ge(),hf=function(s){return cw(s)?s:void 0};ff.exports=function(s,e){return arguments.length<2?hf(Xl[s])||hf(Jl[s]):Xl[s]&&Xl[s][e]||Jl[s]&&Jl[s][e]}});var na=b((M_,mf)=>{"use strict";var dw=$e();mf.exports=dw({}.isPrototypeOf)});var Ji=b(($_,Sf)=>{"use strict";var pw=ve(),bf=pw.navigator,gf=bf&&bf.userAgent;Sf.exports=gf?String(gf):""});var ec=b((B_,Ef)=>{"use strict";var xf=ve(),Zl=Ji(),vf=xf.process,yf=xf.Deno,Tf=vf&&vf.versions||yf&&yf.version,If=Tf&&Tf.v8,Dt,Ao;If&&(Dt=If.split("."),Ao=Dt[0]>0&&Dt[0]<4?1:+(Dt[0]+Dt[1]));!Ao&&Zl&&(Dt=Zl.match(/Edge\/(\d+)/),(!Dt||Dt[1]>=74)&&(Dt=Zl.match(/Chrome\/(\d+)/),Dt&&(Ao=+Dt[1])));Ef.exports=Ao});var tc=b((D_,Pf)=>{"use strict";var wf=ec(),hw=Oe(),fw=ve(),mw=fw.String;Pf.exports=!!Object.getOwnPropertySymbols&&!hw(function(){var s=Symbol("symbol detection");return!mw(s)||!(Object(s)instanceof Symbol)||!Symbol.sham&&wf&&wf<41})});var ic=b((C_,Af)=>{"use strict";var bw=tc();Af.exports=bw&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var rc=b((V_,kf)=>{"use strict";var gw=mi(),Sw=ge(),vw=na(),yw=ic(),Tw=Object;kf.exports=yw?function(s){return typeof s=="symbol"}:function(s){var e=gw("Symbol");return Sw(e)&&vw(e.prototype,Tw(s))}});var oa=b((O_,Rf)=>{"use strict";var Iw=String;Rf.exports=function(s){try{return Iw(s)}catch(e){return"Object"}}});var Gt=b((__,Lf)=>{"use strict";var xw=ge(),Ew=oa(),ww=TypeError;Lf.exports=function(s){if(xw(s))return s;throw new ww(Ew(s)+" is not a function")}});var ua=b((F_,Mf)=>{"use strict";var Pw=Gt(),Aw=xr();Mf.exports=function(s,e){var t=s[e];return Aw(t)?void 0:Pw(t)}});var Bf=b((N_,$f)=>{"use strict";var sc=gt(),ac=ge(),nc=St(),kw=TypeError;$f.exports=function(s,e){var t,i;if(e==="string"&&ac(t=s.toString)&&!nc(i=sc(t,s))||ac(t=s.valueOf)&&!nc(i=sc(t,s))||e!=="string"&&ac(t=s.toString)&&!nc(i=sc(t,s)))return i;throw new kw("Can't convert object to primitive value")}});var Ct=b((U_,Df)=>{"use strict";Df.exports=!0});var Of=b((q_,Vf)=>{"use strict";var Cf=ve(),Rw=Object.defineProperty;Vf.exports=function(s,e){try{Rw(Cf,s,{value:e,configurable:!0,writable:!0})}catch(t){Cf[s]=e}return e}});var la=b((j_,Nf)=>{"use strict";var Lw=Ct(),Mw=ve(),$w=Of(),_f="__core-js_shared__",Ff=Nf.exports=Mw[_f]||$w(_f,{});(Ff.versions||(Ff.versions=[])).push({version:"3.38.0",mode:Lw?"pure":"global",copyright:"\xA9 2014-2024 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.38.0/LICENSE",source:"https://github.com/zloirock/core-js"})});var oc=b((H_,qf)=>{"use strict";var Uf=la();qf.exports=function(s,e){return Uf[s]||(Uf[s]=e||{})}});var wr=b((G_,jf)=>{"use strict";var Bw=Ri(),Dw=Object;jf.exports=function(s){return Dw(Bw(s))}});var Vt=b((z_,Hf)=>{"use strict";var Cw=$e(),Vw=wr(),Ow=Cw({}.hasOwnProperty);Hf.exports=Object.hasOwn||function(e,t){return Ow(Vw(e),t)}});var uc=b((Q_,Gf)=>{"use strict";var _w=$e(),Fw=0,Nw=Math.random(),Uw=_w(1 .toString);Gf.exports=function(s){return"Symbol("+(s===void 0?"":s)+")_"+Uw(++Fw+Nw,36)}});var _e=b((W_,Qf)=>{"use strict";var qw=ve(),jw=oc(),zf=Vt(),Hw=uc(),Gw=tc(),zw=ic(),Pr=qw.Symbol,lc=jw("wks"),Qw=zw?Pr.for||Pr:Pr&&Pr.withoutSetter||Hw;Qf.exports=function(s){return zf(lc,s)||(lc[s]=Gw&&zf(Pr,s)?Pr[s]:Qw("Symbol."+s)),lc[s]}});var Xf=b((Y_,Kf)=>{"use strict";var Ww=gt(),Wf=St(),Yf=rc(),Yw=ua(),Kw=Bf(),Xw=_e(),Jw=TypeError,Zw=Xw("toPrimitive");Kf.exports=function(s,e){if(!Wf(s)||Yf(s))return s;var t=Yw(s,Zw),i;if(t){if(e===void 0&&(e="default"),i=Ww(t,s,e),!Wf(i)||Yf(i))return i;throw new Jw("Can't convert object to primitive value")}return e===void 0&&(e="number"),Kw(s,e)}});var cc=b((K_,Jf)=>{"use strict";var eP=Xf(),tP=rc();Jf.exports=function(s){var e=eP(s,"string");return tP(e)?e:e+""}});var ko=b((X_,em)=>{"use strict";var iP=ve(),Zf=St(),dc=iP.document,rP=Zf(dc)&&Zf(dc.createElement);em.exports=function(s){return rP?dc.createElement(s):{}}});var pc=b((J_,tm)=>{"use strict";var sP=bt(),aP=Oe(),nP=ko();tm.exports=!sP&&!aP(function(){return Object.defineProperty(nP("div"),"a",{get:function(){return 7}}).a!==7})});var sm=b(rm=>{"use strict";var oP=bt(),uP=gt(),lP=Yl(),cP=aa(),dP=Xi(),pP=cc(),hP=Vt(),fP=pc(),im=Object.getOwnPropertyDescriptor;rm.f=oP?im:function(e,t){if(e=dP(e),t=pP(t),fP)try{return im(e,t)}catch(i){}if(hP(e,t))return cP(!uP(lP.f,e,t),e[t])}});var hc=b((eF,am)=>{"use strict";var mP=Oe(),bP=ge(),gP=/#|\.prototype\./,ca=function(s,e){var t=vP[SP(s)];return t===TP?!0:t===yP?!1:bP(e)?mP(e):!!e},SP=ca.normalize=function(s){return String(s).replace(gP,".").toLowerCase()},vP=ca.data={},yP=ca.NATIVE="N",TP=ca.POLYFILL="P";am.exports=ca});var Ar=b((tF,om)=>{"use strict";var nm=Ql(),IP=Gt(),xP=sa(),EP=nm(nm.bind);om.exports=function(s,e){return IP(s),e===void 0?s:xP?EP(s,e):function(){return s.apply(e,arguments)}}});var fc=b((iF,um)=>{"use strict";var wP=bt(),PP=Oe();um.exports=wP&&PP(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var zt=b((rF,lm)=>{"use strict";var AP=St(),kP=String,RP=TypeError;lm.exports=function(s){if(AP(s))return s;throw new RP(kP(s)+" is not an object")}});var Zi=b(dm=>{"use strict";var LP=bt(),MP=pc(),$P=fc(),Ro=zt(),cm=cc(),BP=TypeError,mc=Object.defineProperty,DP=Object.getOwnPropertyDescriptor,bc="enumerable",gc="configurable",Sc="writable";dm.f=LP?$P?function(e,t,i){if(Ro(e),t=cm(t),Ro(i),typeof e=="function"&&t==="prototype"&&"value"in i&&Sc in i&&!i[Sc]){var r=DP(e,t);r&&r[Sc]&&(e[t]=i.value,i={configurable:gc in i?i[gc]:r[gc],enumerable:bc in i?i[bc]:r[bc],writable:!1})}return mc(e,t,i)}:mc:function(e,t,i){if(Ro(e),t=cm(t),Ro(i),MP)try{return mc(e,t,i)}catch(r){}if("get"in i||"set"in i)throw new BP("Accessors not supported");return"value"in i&&(e[t]=i.value),e}});var kr=b((aF,pm)=>{"use strict";var CP=bt(),VP=Zi(),OP=aa();pm.exports=CP?function(s,e,t){return VP.f(s,e,OP(1,t))}:function(s,e,t){return s[e]=t,s}});var Ee=b((nF,fm)=>{"use strict";var da=ve(),_P=Gl(),FP=Ql(),NP=ge(),UP=sm().f,qP=hc(),Rr=Er(),jP=Ar(),Lr=kr(),hm=Vt();la();var HP=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 _P(s,this,arguments)};return e.prototype=s.prototype,e};fm.exports=function(s,e){var t=s.target,i=s.global,r=s.stat,a=s.proto,n=i?da:r?da[t]:da[t]&&da[t].prototype,o=i?Rr:Rr[t]||Lr(Rr,t,{})[t],u=o.prototype,l,d,c,h,p,f,m,g,S;for(h in e)l=qP(i?h:t+(r?".":"#")+h,s.forced),d=!l&&n&&hm(n,h),f=o[h],d&&(s.dontCallGetSet?(S=UP(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=jP(p,da):s.wrap&&d?g=HP(p):a&&NP(p)?g=FP(p):g=p,(s.sham||p&&p.sham||f&&f.sham)&&Lr(g,"sham",!0),Lr(o,h,g),a&&(c=t+"Prototype",hm(Rr,c)||Lr(Rr,c,{}),Lr(Rr[c],h,p),s.real&&u&&(l||!u[h])&&Lr(u,h,p)))}});var bm=b((oF,mm)=>{"use strict";var GP=Math.ceil,zP=Math.floor;mm.exports=Math.trunc||function(e){var t=+e;return(t>0?zP:GP)(t)}});var pa=b((uF,gm)=>{"use strict";var QP=bm();gm.exports=function(s){var e=+s;return e!==e||e===0?0:QP(e)}});var vm=b((lF,Sm)=>{"use strict";var WP=pa(),YP=Math.max,KP=Math.min;Sm.exports=function(s,e){var t=WP(s);return t<0?YP(t+e,0):KP(t,e)}});var vc=b((cF,ym)=>{"use strict";var XP=pa(),JP=Math.min;ym.exports=function(s){var e=XP(s);return e>0?JP(e,9007199254740991):0}});var Mr=b((dF,Tm)=>{"use strict";var ZP=vc();Tm.exports=function(s){return ZP(s.length)}});var yc=b((pF,xm)=>{"use strict";var eA=Xi(),tA=vm(),iA=Mr(),Im=function(s){return function(e,t,i){var r=eA(e),a=iA(r);if(a===0)return!s&&-1;var n=tA(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}};xm.exports={includes:Im(!0),indexOf:Im(!1)}});var ha=b((hF,Em)=>{"use strict";Em.exports=function(){}});var wm=b(()=>{"use strict";var rA=Ee(),sA=yc().includes,aA=Oe(),nA=ha(),oA=aA(function(){return!Array(1).includes()});rA({target:"Array",proto:!0,forced:oA},{includes:function(e){return sA(this,e,arguments.length>1?arguments[1]:void 0)}});nA("includes")});var Li=b((bF,Pm)=>{"use strict";var uA=mi();Pm.exports=uA});var km=b((gF,Am)=>{"use strict";wm();var lA=Li();Am.exports=lA("Array","includes")});var Lm=b((SF,Rm)=>{"use strict";var cA=km();Rm.exports=cA});var vt=b((vF,Mm)=>{"use strict";var dA=Lm();Mm.exports=dA});var $o=b((MF,Fm)=>{"use strict";var vA=oc(),yA=uc(),_m=vA("keys");Fm.exports=function(s){return _m[s]||(_m[s]=yA(s))}});var Um=b(($F,Nm)=>{"use strict";var TA=Oe();Nm.exports=!TA(function(){function s(){}return s.prototype.constructor=null,Object.getPrototypeOf(new s)!==s.prototype})});var Bo=b((BF,jm)=>{"use strict";var IA=Vt(),xA=ge(),EA=wr(),wA=$o(),PA=Um(),qm=wA("IE_PROTO"),xc=Object,AA=xc.prototype;jm.exports=PA?xc.getPrototypeOf:function(s){var e=EA(s);if(IA(e,qm))return e[qm];var t=e.constructor;return xA(t)&&e instanceof t?t.prototype:e instanceof xc?AA:null}});var Do=b((DF,Hm)=>{"use strict";Hm.exports={}});var Qm=b((CF,zm)=>{"use strict";var kA=$e(),Ec=Vt(),RA=Xi(),LA=yc().indexOf,MA=Do(),Gm=kA([].push);zm.exports=function(s,e){var t=RA(s),i=0,r=[],a;for(a in t)!Ec(MA,a)&&Ec(t,a)&&Gm(r,a);for(;e.length>i;)Ec(t,a=e[i++])&&(~LA(r,a)||Gm(r,a));return r}});var wc=b((VF,Wm)=>{"use strict";Wm.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var Pc=b((OF,Ym)=>{"use strict";var $A=Qm(),BA=wc();Ym.exports=Object.keys||function(e){return $A(e,BA)}});var Ac=b((_F,eb)=>{"use strict";var Xm=bt(),DA=Oe(),Jm=$e(),CA=Bo(),VA=Pc(),OA=Xi(),_A=Yl().f,Zm=Jm(_A),FA=Jm([].push),NA=Xm&&DA(function(){var s=Object.create(null);return s[2]=2,!Zm(s,2)}),Km=function(s){return function(e){for(var t=OA(e),i=VA(t),r=NA&&CA(t)===null,a=i.length,n=0,o=[],u;a>n;)u=i[n++],(!Xm||(r?u in t:Zm(t,u)))&&FA(o,s?[u,t[u]]:t[u]);return o}};eb.exports={entries:Km(!0),values:Km(!1)}});var tb=b(()=>{"use strict";var UA=Ee(),qA=Ac().entries;UA({target:"Object",stat:!0},{entries:function(e){return qA(e)}})});var rb=b((UF,ib)=>{"use strict";tb();var jA=Er();ib.exports=jA.Object.entries});var ab=b((qF,sb)=>{"use strict";var HA=rb();sb.exports=HA});var er=b((jF,nb)=>{"use strict";var GA=ab();nb.exports=GA});var tr=b((HF,ob)=>{"use strict";ob.exports={}});var cb=b((GF,lb)=>{"use strict";var zA=ve(),QA=ge(),ub=zA.WeakMap;lb.exports=QA(ub)&&/native code/.test(String(ub))});var Mc=b((zF,hb)=>{"use strict";var WA=cb(),pb=ve(),YA=St(),KA=kr(),kc=Vt(),Rc=la(),XA=$o(),JA=Do(),db="Object already initialized",Lc=pb.TypeError,ZA=pb.WeakMap,Co,fa,Vo,ek=function(s){return Vo(s)?fa(s):Co(s,{})},tk=function(s){return function(e){var t;if(!YA(e)||(t=fa(e)).type!==s)throw new Lc("Incompatible receiver, "+s+" required");return t}};WA||Rc.state?(Ot=Rc.state||(Rc.state=new ZA),Ot.get=Ot.get,Ot.has=Ot.has,Ot.set=Ot.set,Co=function(s,e){if(Ot.has(s))throw new Lc(db);return e.facade=s,Ot.set(s,e),e},fa=function(s){return Ot.get(s)||{}},Vo=function(s){return Ot.has(s)}):(ir=XA("state"),JA[ir]=!0,Co=function(s,e){if(kc(s,ir))throw new Lc(db);return e.facade=s,KA(s,ir,e),e},fa=function(s){return kc(s,ir)?s[ir]:{}},Vo=function(s){return kc(s,ir)});var Ot,ir;hb.exports={set:Co,get:fa,has:Vo,enforce:ek,getterFor:tk}});var Dc=b((QF,mb)=>{"use strict";var $c=bt(),ik=Vt(),fb=Function.prototype,rk=$c&&Object.getOwnPropertyDescriptor,Bc=ik(fb,"name"),sk=Bc&&function(){}.name==="something",ak=Bc&&(!$c||$c&&rk(fb,"name").configurable);mb.exports={EXISTS:Bc,PROPER:sk,CONFIGURABLE:ak}});var gb=b(bb=>{"use strict";var nk=bt(),ok=fc(),uk=Zi(),lk=zt(),ck=Xi(),dk=Pc();bb.f=nk&&!ok?Object.defineProperties:function(e,t){lk(e);for(var i=ck(t),r=dk(t),a=r.length,n=0,o;a>n;)uk.f(e,o=r[n++],i[o]);return e}});var Cc=b((YF,Sb)=>{"use strict";var pk=mi();Sb.exports=pk("document","documentElement")});var Fc=b((KF,wb)=>{"use strict";var hk=zt(),fk=gb(),vb=wc(),mk=Do(),bk=Cc(),gk=ko(),Sk=$o(),yb=">",Tb="<",Oc="prototype",_c="script",xb=Sk("IE_PROTO"),Vc=function(){},Eb=function(s){return Tb+_c+yb+s+Tb+"/"+_c+yb},Ib=function(s){s.write(Eb("")),s.close();var e=s.parentWindow.Object;return s=null,e},vk=function(){var s=gk("iframe"),e="java"+_c+":",t;return s.style.display="none",bk.appendChild(s),s.src=String(e),t=s.contentWindow.document,t.open(),t.write(Eb("document.F=Object")),t.close(),t.F},Oo,_o=function(){try{Oo=new ActiveXObject("htmlfile")}catch(e){}_o=typeof document!="undefined"?document.domain&&Oo?Ib(Oo):vk():Ib(Oo);for(var s=vb.length;s--;)delete _o[Oc][vb[s]];return _o()};mk[xb]=!0;wb.exports=Object.create||function(e,t){var i;return e!==null?(Vc[Oc]=hk(e),i=new Vc,Vc[Oc]=null,i[xb]=e):i=_o(),t===void 0?i:fk.f(i,t)}});var $r=b((XF,Pb)=>{"use strict";var yk=kr();Pb.exports=function(s,e,t,i){return i&&i.enumerable?s[e]=t:yk(s,e,t),s}});var jc=b((JF,Rb)=>{"use strict";var Tk=Oe(),Ik=ge(),xk=St(),Ek=Fc(),Ab=Bo(),wk=$r(),Pk=_e(),Ak=Ct(),qc=Pk("iterator"),kb=!1,bi,Nc,Uc;[].keys&&(Uc=[].keys(),"next"in Uc?(Nc=Ab(Ab(Uc)),Nc!==Object.prototype&&(bi=Nc)):kb=!0);var kk=!xk(bi)||Tk(function(){var s={};return bi[qc].call(s)!==s});kk?bi={}:Ak&&(bi=Ek(bi));Ik(bi[qc])||wk(bi,qc,function(){return this});Rb.exports={IteratorPrototype:bi,BUGGY_SAFARI_ITERATORS:kb}});var Fo=b((ZF,Mb)=>{"use strict";var Rk=_e(),Lk=Rk("toStringTag"),Lb={};Lb[Lk]="z";Mb.exports=String(Lb)==="[object z]"});var ma=b((eN,$b)=>{"use strict";var Mk=Fo(),$k=ge(),No=Ki(),Bk=_e(),Dk=Bk("toStringTag"),Ck=Object,Vk=No(function(){return arguments}())==="Arguments",Ok=function(s,e){try{return s[e]}catch(t){}};$b.exports=Mk?No:function(s){var e,t,i;return s===void 0?"Undefined":s===null?"Null":typeof(t=Ok(e=Ck(s),Dk))=="string"?t:Vk?No(e):(i=No(e))==="Object"&&$k(e.callee)?"Arguments":i}});var Db=b((tN,Bb)=>{"use strict";var _k=Fo(),Fk=ma();Bb.exports=_k?{}.toString:function(){return"[object "+Fk(this)+"]"}});var ba=b((iN,Vb)=>{"use strict";var Nk=Fo(),Uk=Zi().f,qk=kr(),jk=Vt(),Hk=Db(),Gk=_e(),Cb=Gk("toStringTag");Vb.exports=function(s,e,t,i){var r=t?s:s&&s.prototype;r&&(jk(r,Cb)||Uk(r,Cb,{configurable:!0,value:e}),i&&!Nk&&qk(r,"toString",Hk))}});var _b=b((rN,Ob)=>{"use strict";var zk=jc().IteratorPrototype,Qk=Fc(),Wk=aa(),Yk=ba(),Kk=tr(),Xk=function(){return this};Ob.exports=function(s,e,t,i){var r=e+" Iterator";return s.prototype=Qk(zk,{next:Wk(+!i,t)}),Yk(s,r,!1,!0),Kk[r]=Xk,s}});var Nb=b((sN,Fb)=>{"use strict";var Jk=$e(),Zk=Gt();Fb.exports=function(s,e,t){try{return Jk(Zk(Object.getOwnPropertyDescriptor(s,e)[t]))}catch(i){}}});var qb=b((aN,Ub)=>{"use strict";var eR=St();Ub.exports=function(s){return eR(s)||s===null}});var Hb=b((nN,jb)=>{"use strict";var tR=qb(),iR=String,rR=TypeError;jb.exports=function(s){if(tR(s))return s;throw new rR("Can't set "+iR(s)+" as a prototype")}});var Hc=b((oN,Gb)=>{"use strict";var sR=Nb(),aR=St(),nR=Ri(),oR=Hb();Gb.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var s=!1,e={},t;try{t=sR(Object.prototype,"__proto__","set"),t(e,[]),s=e instanceof Array}catch(i){}return function(r,a){return nR(r),oR(a),aR(r)&&(s?t(r,a):r.__proto__=a),r}}():void 0)});var ig=b((uN,tg)=>{"use strict";var uR=Ee(),lR=gt(),Uo=Ct(),Zb=Dc(),cR=ge(),dR=_b(),zb=Bo(),Qb=Hc(),pR=ba(),hR=kr(),Gc=$r(),fR=_e(),Wb=tr(),eg=jc(),mR=Zb.PROPER,bR=Zb.CONFIGURABLE,Yb=eg.IteratorPrototype,qo=eg.BUGGY_SAFARI_ITERATORS,ga=fR("iterator"),Kb="keys",Sa="values",Xb="entries",Jb=function(){return this};tg.exports=function(s,e,t,i,r,a,n){dR(t,e,i);var o=function(S){if(S===r&&h)return h;if(!qo&&S&&S in d)return d[S];switch(S){case Kb:return function(){return new t(this,S)};case Sa:return function(){return new t(this,S)};case Xb:return function(){return new t(this,S)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,d=s.prototype,c=d[ga]||d["@@iterator"]||r&&d[r],h=!qo&&c||o(r),p=e==="Array"&&d.entries||c,f,m,g;if(p&&(f=zb(p.call(new s)),f!==Object.prototype&&f.next&&(!Uo&&zb(f)!==Yb&&(Qb?Qb(f,Yb):cR(f[ga])||Gc(f,ga,Jb)),pR(f,u,!0,!0),Uo&&(Wb[u]=Jb))),mR&&r===Sa&&c&&c.name!==Sa&&(!Uo&&bR?hR(d,"name",Sa):(l=!0,h=function(){return lR(c,this)})),r)if(m={values:o(Sa),keys:a?h:o(Kb),entries:o(Xb)},n)for(g in m)(qo||l||!(g in d))&&Gc(d,g,m[g]);else uR({target:e,proto:!0,forced:qo||l},m);return(!Uo||n)&&d[ga]!==h&&Gc(d,ga,h,{name:r}),Wb[e]=h,m}});var sg=b((lN,rg)=>{"use strict";rg.exports=function(s,e){return{value:s,done:e}}});var Qc=b((cN,lg)=>{"use strict";var gR=Xi(),zc=ha(),ag=tr(),og=Mc(),SR=Zi().f,vR=ig(),jo=sg(),yR=Ct(),TR=bt(),ug="Array Iterator",IR=og.set,xR=og.getterFor(ug);lg.exports=vR(Array,"Array",function(s,e){IR(this,{type:ug,target:gR(s),index:0,kind:e})},function(){var s=xR(this),e=s.target,t=s.index++;if(!e||t>=e.length)return s.target=void 0,jo(void 0,!0);switch(s.kind){case"keys":return jo(t,!1);case"values":return jo(e[t],!1)}return jo([t,e[t]],!1)},"values");var ng=ag.Arguments=ag.Array;zc("keys");zc("values");zc("entries");if(!yR&&TR&&ng.name!=="values")try{SR(ng,"name",{value:"values"})}catch(s){}});var dg=b((dN,cg)=>{"use strict";var ER=_e(),wR=tr(),PR=ER("iterator"),AR=Array.prototype;cg.exports=function(s){return s!==void 0&&(wR.Array===s||AR[PR]===s)}});var Wc=b((pN,hg)=>{"use strict";var kR=ma(),pg=ua(),RR=xr(),LR=tr(),MR=_e(),$R=MR("iterator");hg.exports=function(s){if(!RR(s))return pg(s,$R)||pg(s,"@@iterator")||LR[kR(s)]}});var mg=b((hN,fg)=>{"use strict";var BR=gt(),DR=Gt(),CR=zt(),VR=oa(),OR=Wc(),_R=TypeError;fg.exports=function(s,e){var t=arguments.length<2?OR(s):e;if(DR(t))return CR(BR(t,s));throw new _R(VR(s)+" is not iterable")}});var Sg=b((fN,gg)=>{"use strict";var FR=gt(),bg=zt(),NR=ua();gg.exports=function(s,e,t){var i,r;bg(s);try{if(i=NR(s,"return"),!i){if(e==="throw")throw t;return t}i=FR(i,s)}catch(a){r=!0,i=a}if(e==="throw")throw t;if(r)throw i;return bg(i),t}});var Go=b((mN,Ig)=>{"use strict";var UR=Ar(),qR=gt(),jR=zt(),HR=oa(),GR=dg(),zR=Mr(),vg=na(),QR=mg(),WR=Wc(),yg=Sg(),YR=TypeError,Ho=function(s,e){this.stopped=s,this.result=e},Tg=Ho.prototype;Ig.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=UR(e,i),l,d,c,h,p,f,m,g=function(v){return l&&yg(l,"normal",v),new Ho(!0,v)},S=function(v){return r?(jR(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=WR(s),!d)throw new YR(HR(s)+" is not iterable");if(GR(d)){for(c=0,h=zR(s);h>c;c++)if(p=S(s[c]),p&&vg(Tg,p))return p;return new Ho(!1)}l=QR(s,d)}for(f=a?s.next:l.next;!(m=qR(f,l)).done;){try{p=S(m.value)}catch(v){yg(l,"throw",v)}if(typeof p=="object"&&p&&vg(Tg,p))return p}return new Ho(!1)}});var Eg=b((bN,xg)=>{"use strict";var KR=bt(),XR=Zi(),JR=aa();xg.exports=function(s,e,t){KR?XR.f(s,e,JR(0,t)):s[e]=t}});var wg=b(()=>{"use strict";var ZR=Ee(),eL=Go(),tL=Eg();ZR({target:"Object",stat:!0},{fromEntries:function(e){var t={};return eL(e,function(i,r){tL(t,i,r)},{AS_ENTRIES:!0}),t}})});var Ag=b((vN,Pg)=>{"use strict";Qc();wg();var iL=Er();Pg.exports=iL.Object.fromEntries});var Rg=b((yN,kg)=>{"use strict";kg.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 Mg=b(()=>{"use strict";Qc();var rL=Rg(),sL=ve(),aL=ba(),Lg=tr();for(zo in rL)aL(sL[zo],zo),Lg[zo]=Lg.Array;var zo});var Bg=b((xN,$g)=>{"use strict";var nL=Ag();Mg();$g.exports=nL});var Yc=b((EN,Dg)=>{"use strict";var oL=Bg();Dg.exports=oL});var Cg=b(()=>{"use strict"});var Kc=b((AN,Vg)=>{"use strict";var va=ve(),uL=Ji(),lL=Ki(),Qo=function(s){return uL.slice(0,s.length)===s};Vg.exports=function(){return Qo("Bun/")?"BUN":Qo("Cloudflare-Workers")?"CLOUDFLARE":Qo("Deno/")?"DENO":Qo("Node.js/")?"NODE":va.Bun&&typeof Bun.version=="string"?"BUN":va.Deno&&typeof Deno.version=="object"?"DENO":lL(va.process)==="process"?"NODE":va.window&&va.document?"BROWSER":"REST"}()});var Wo=b((kN,Og)=>{"use strict";var cL=Kc();Og.exports=cL==="NODE"});var Fg=b((RN,_g)=>{"use strict";var dL=Zi();_g.exports=function(s,e,t){return dL.f(s,e,t)}});var qg=b((LN,Ug)=>{"use strict";var pL=mi(),hL=Fg(),fL=_e(),mL=bt(),Ng=fL("species");Ug.exports=function(s){var e=pL(s);mL&&e&&!e[Ng]&&hL(e,Ng,{configurable:!0,get:function(){return this}})}});var Hg=b((MN,jg)=>{"use strict";var bL=na(),gL=TypeError;jg.exports=function(s,e){if(bL(e,s))return s;throw new gL("Incorrect invocation")}});var Jc=b(($N,Gg)=>{"use strict";var SL=$e(),vL=ge(),Xc=la(),yL=SL(Function.toString);vL(Xc.inspectSource)||(Xc.inspectSource=function(s){return yL(s)});Gg.exports=Xc.inspectSource});var ed=b((BN,Kg)=>{"use strict";var TL=$e(),IL=Oe(),zg=ge(),xL=ma(),EL=mi(),wL=Jc(),Qg=function(){},Wg=EL("Reflect","construct"),Zc=/^\s*(?:class|function)\b/,PL=TL(Zc.exec),AL=!Zc.test(Qg),ya=function(e){if(!zg(e))return!1;try{return Wg(Qg,[],e),!0}catch(t){return!1}},Yg=function(e){if(!zg(e))return!1;switch(xL(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return AL||!!PL(Zc,wL(e))}catch(t){return!0}};Yg.sham=!0;Kg.exports=!Wg||IL(function(){var s;return ya(ya.call)||!ya(Object)||!ya(function(){s=!0})||s})?Yg:ya});var Jg=b((DN,Xg)=>{"use strict";var kL=ed(),RL=oa(),LL=TypeError;Xg.exports=function(s){if(kL(s))return s;throw new LL(RL(s)+" is not a constructor")}});var td=b((CN,eS)=>{"use strict";var Zg=zt(),ML=Jg(),$L=xr(),BL=_e(),DL=BL("species");eS.exports=function(s,e){var t=Zg(s).constructor,i;return t===void 0||$L(i=Zg(t)[DL])?e:ML(i)}});var iS=b((VN,tS)=>{"use strict";var CL=$e();tS.exports=CL([].slice)});var sS=b((ON,rS)=>{"use strict";var VL=TypeError;rS.exports=function(s,e){if(s<e)throw new VL("Not enough arguments");return s}});var id=b((_N,aS)=>{"use strict";var OL=Ji();aS.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(OL)});var dd=b((FN,fS)=>{"use strict";var yt=ve(),_L=Gl(),FL=Ar(),nS=ge(),NL=Vt(),hS=Oe(),oS=Cc(),UL=iS(),uS=ko(),qL=sS(),jL=id(),HL=Wo(),ud=yt.setImmediate,ld=yt.clearImmediate,GL=yt.process,rd=yt.Dispatch,zL=yt.Function,lS=yt.MessageChannel,QL=yt.String,sd=0,Ta={},cS="onreadystatechange",Ia,rr,ad,nd;hS(function(){Ia=yt.location});var cd=function(s){if(NL(Ta,s)){var e=Ta[s];delete Ta[s],e()}},od=function(s){return function(){cd(s)}},dS=function(s){cd(s.data)},pS=function(s){yt.postMessage(QL(s),Ia.protocol+"//"+Ia.host)};(!ud||!ld)&&(ud=function(e){qL(arguments.length,1);var t=nS(e)?e:zL(e),i=UL(arguments,1);return Ta[++sd]=function(){_L(t,void 0,i)},rr(sd),sd},ld=function(e){delete Ta[e]},HL?rr=function(s){GL.nextTick(od(s))}:rd&&rd.now?rr=function(s){rd.now(od(s))}:lS&&!jL?(ad=new lS,nd=ad.port2,ad.port1.onmessage=dS,rr=FL(nd.postMessage,nd)):yt.addEventListener&&nS(yt.postMessage)&&!yt.importScripts&&Ia&&Ia.protocol!=="file:"&&!hS(pS)?(rr=pS,yt.addEventListener("message",dS,!1)):cS in uS("script")?rr=function(s){oS.appendChild(uS("script"))[cS]=function(){oS.removeChild(this),cd(s)}}:rr=function(s){setTimeout(od(s),0)});fS.exports={set:ud,clear:ld}});var gS=b((NN,bS)=>{"use strict";var mS=ve(),WL=bt(),YL=Object.getOwnPropertyDescriptor;bS.exports=function(s){if(!WL)return mS[s];var e=YL(mS,s);return e&&e.value}});var pd=b((UN,vS)=>{"use strict";var SS=function(){this.head=null,this.tail=null};SS.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}}};vS.exports=SS});var TS=b((qN,yS)=>{"use strict";var KL=Ji();yS.exports=/ipad|iphone|ipod/i.test(KL)&&typeof Pebble!="undefined"});var xS=b((jN,IS)=>{"use strict";var XL=Ji();IS.exports=/web0s(?!.*chrome)/i.test(XL)});var LS=b((HN,RS)=>{"use strict";var Dr=ve(),JL=gS(),ES=Ar(),hd=dd().set,ZL=pd(),eM=id(),tM=TS(),iM=xS(),fd=Wo(),wS=Dr.MutationObserver||Dr.WebKitMutationObserver,PS=Dr.document,AS=Dr.process,Yo=Dr.Promise,gd=JL("queueMicrotask"),Br,md,bd,Ko,kS;gd||(xa=new ZL,Ea=function(){var s,e;for(fd&&(s=AS.domain)&&s.exit();e=xa.get();)try{e()}catch(t){throw xa.head&&Br(),t}s&&s.enter()},!eM&&!fd&&!iM&&wS&&PS?(md=!0,bd=PS.createTextNode(""),new wS(Ea).observe(bd,{characterData:!0}),Br=function(){bd.data=md=!md}):!tM&&Yo&&Yo.resolve?(Ko=Yo.resolve(void 0),Ko.constructor=Yo,kS=ES(Ko.then,Ko),Br=function(){kS(Ea)}):fd?Br=function(){AS.nextTick(Ea)}:(hd=ES(hd,Dr),Br=function(){hd(Ea)}),gd=function(s){xa.head||Br(),xa.add(s)});var xa,Ea;RS.exports=gd});var $S=b((GN,MS)=>{"use strict";MS.exports=function(s,e){try{arguments.length===1?console.error(s):console.error(s,e)}catch(t){}}});var Xo=b((zN,BS)=>{"use strict";BS.exports=function(s){try{return{error:!1,value:s()}}catch(e){return{error:!0,value:e}}}});var sr=b((QN,DS)=>{"use strict";var rM=ve();DS.exports=rM.Promise});var Cr=b((WN,_S)=>{"use strict";var sM=ve(),wa=sr(),aM=ge(),nM=hc(),oM=Jc(),uM=_e(),CS=Kc(),lM=Ct(),Sd=ec(),VS=wa&&wa.prototype,cM=uM("species"),vd=!1,OS=aM(sM.PromiseRejectionEvent),dM=nM("Promise",function(){var s=oM(wa),e=s!==String(wa);if(!e&&Sd===66||lM&&!(VS.catch&&VS.finally))return!0;if(!Sd||Sd<51||!/native code/.test(s)){var t=new wa(function(a){a(1)}),i=function(a){a(function(){},function(){})},r=t.constructor={};if(r[cM]=i,vd=t.then(function(){})instanceof i,!vd)return!0}return!e&&(CS==="BROWSER"||CS==="DENO")&&!OS});_S.exports={CONSTRUCTOR:dM,REJECTION_EVENT:OS,SUBCLASSING:vd}});var Vr=b((YN,NS)=>{"use strict";var FS=Gt(),pM=TypeError,hM=function(s){var e,t;this.promise=new s(function(i,r){if(e!==void 0||t!==void 0)throw new pM("Bad Promise constructor");e=i,t=r}),this.resolve=FS(e),this.reject=FS(t)};NS.exports.f=function(s){return new hM(s)}});var av=b(()=>{"use strict";var fM=Ee(),mM=Ct(),tu=Wo(),Mi=ve(),Nr=gt(),US=$r(),qS=Hc(),bM=ba(),gM=qg(),SM=Gt(),eu=ge(),vM=St(),yM=Hg(),TM=td(),QS=dd().set,Ed=LS(),IM=$S(),xM=Xo(),EM=pd(),WS=Mc(),iu=sr(),wd=Cr(),YS=Vr(),ru="Promise",KS=wd.CONSTRUCTOR,wM=wd.REJECTION_EVENT,PM=wd.SUBCLASSING,yd=WS.getterFor(ru),AM=WS.set,Or=iu&&iu.prototype,ar=iu,Jo=Or,XS=Mi.TypeError,Td=Mi.document,Pd=Mi.process,Id=YS.f,kM=Id,RM=!!(Td&&Td.createEvent&&Mi.dispatchEvent),JS="unhandledrejection",LM="rejectionhandled",jS=0,ZS=1,MM=2,Ad=1,ev=2,Zo,HS,$M,GS,tv=function(s){var e;return vM(s)&&eu(e=s.then)?e:!1},iv=function(s,e){var t=e.value,i=e.state===ZS,r=i?s.ok:s.fail,a=s.resolve,n=s.reject,o=s.domain,u,l,d;try{r?(i||(e.rejection===ev&&DM(e),e.rejection=Ad),r===!0?u=t:(o&&o.enter(),u=r(t),o&&(o.exit(),d=!0)),u===s.promise?n(new XS("Promise-chain cycle")):(l=tv(u))?Nr(l,u,a,n):a(u)):n(t)}catch(c){o&&!d&&o.exit(),n(c)}},rv=function(s,e){s.notified||(s.notified=!0,Ed(function(){for(var t=s.reactions,i;i=t.get();)iv(i,s);s.notified=!1,e&&!s.rejection&&BM(s)}))},sv=function(s,e,t){var i,r;RM?(i=Td.createEvent("Event"),i.promise=e,i.reason=t,i.initEvent(s,!1,!0),Mi.dispatchEvent(i)):i={promise:e,reason:t},!wM&&(r=Mi["on"+s])?r(i):s===JS&&IM("Unhandled promise rejection",t)},BM=function(s){Nr(QS,Mi,function(){var e=s.facade,t=s.value,i=zS(s),r;if(i&&(r=xM(function(){tu?Pd.emit("unhandledRejection",t,e):sv(JS,e,t)}),s.rejection=tu||zS(s)?ev:Ad,r.error))throw r.value})},zS=function(s){return s.rejection!==Ad&&!s.parent},DM=function(s){Nr(QS,Mi,function(){var e=s.facade;tu?Pd.emit("rejectionHandled",e):sv(LM,e,s.value)})},_r=function(s,e,t){return function(i){s(e,i,t)}},Fr=function(s,e,t){s.done||(s.done=!0,t&&(s=t),s.value=e,s.state=MM,rv(s,!0))},xd=function(s,e,t){if(!s.done){s.done=!0,t&&(s=t);try{if(s.facade===e)throw new XS("Promise can't be resolved itself");var i=tv(e);i?Ed(function(){var r={done:!1};try{Nr(i,e,_r(xd,r,s),_r(Fr,r,s))}catch(a){Fr(r,a,s)}}):(s.value=e,s.state=ZS,rv(s,!1))}catch(r){Fr({done:!1},r,s)}}};if(KS&&(ar=function(e){yM(this,Jo),SM(e),Nr(Zo,this);var t=yd(this);try{e(_r(xd,t),_r(Fr,t))}catch(i){Fr(t,i)}},Jo=ar.prototype,Zo=function(e){AM(this,{type:ru,done:!1,notified:!1,parent:!1,reactions:new EM,rejection:!1,state:jS,value:void 0})},Zo.prototype=US(Jo,"then",function(e,t){var i=yd(this),r=Id(TM(this,ar));return i.parent=!0,r.ok=eu(e)?e:!0,r.fail=eu(t)&&t,r.domain=tu?Pd.domain:void 0,i.state===jS?i.reactions.add(r):Ed(function(){iv(r,i)}),r.promise}),HS=function(){var s=new Zo,e=yd(s);this.promise=s,this.resolve=_r(xd,e),this.reject=_r(Fr,e)},YS.f=Id=function(s){return s===ar||s===$M?new HS(s):kM(s)},!mM&&eu(iu)&&Or!==Object.prototype)){GS=Or.then,PM||US(Or,"then",function(e,t){var i=this;return new ar(function(r,a){Nr(GS,i,r,a)}).then(e,t)},{unsafe:!0});try{delete Or.constructor}catch(s){}qS&&qS(Or,Jo)}fM({global:!0,constructor:!0,wrap:!0,forced:KS},{Promise:ar});bM(ar,ru,!1,!0);gM(ru)});var cv=b((JN,lv)=>{"use strict";var CM=_e(),ov=CM("iterator"),uv=!1;try{nv=0,kd={next:function(){return{done:!!nv++}},return:function(){uv=!0}},kd[ov]=function(){return this},Array.from(kd,function(){throw 2})}catch(s){}var nv,kd;lv.exports=function(s,e){try{if(!e&&!uv)return!1}catch(r){return!1}var t=!1;try{var i={};i[ov]=function(){return{next:function(){return{done:t=!0}}}},s(i)}catch(r){}return t}});var Rd=b((ZN,dv)=>{"use strict";var VM=sr(),OM=cv(),_M=Cr().CONSTRUCTOR;dv.exports=_M||!OM(function(s){VM.all(s).then(void 0,function(){})})});var pv=b(()=>{"use strict";var FM=Ee(),NM=gt(),UM=Gt(),qM=Vr(),jM=Xo(),HM=Go(),GM=Rd();FM({target:"Promise",stat:!0,forced:GM},{all:function(e){var t=this,i=qM.f(t),r=i.resolve,a=i.reject,n=jM(function(){var o=UM(t.resolve),u=[],l=0,d=1;HM(e,function(c){var h=l++,p=!1;d++,NM(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 fv=b(()=>{"use strict";var zM=Ee(),QM=Ct(),WM=Cr().CONSTRUCTOR,Md=sr(),YM=mi(),KM=ge(),XM=$r(),hv=Md&&Md.prototype;zM({target:"Promise",proto:!0,forced:WM,real:!0},{catch:function(s){return this.then(void 0,s)}});!QM&&KM(Md)&&(Ld=YM("Promise").prototype.catch,hv.catch!==Ld&&XM(hv,"catch",Ld,{unsafe:!0}));var Ld});var mv=b(()=>{"use strict";var JM=Ee(),ZM=gt(),e$=Gt(),t$=Vr(),i$=Xo(),r$=Go(),s$=Rd();JM({target:"Promise",stat:!0,forced:s$},{race:function(e){var t=this,i=t$.f(t),r=i.reject,a=i$(function(){var n=e$(t.resolve);r$(e,function(o){ZM(n,t,o).then(i.resolve,r)})});return a.error&&r(a.value),i.promise}})});var bv=b(()=>{"use strict";var a$=Ee(),n$=Vr(),o$=Cr().CONSTRUCTOR;a$({target:"Promise",stat:!0,forced:o$},{reject:function(e){var t=n$.f(this),i=t.reject;return i(e),t.promise}})});var $d=b((uU,gv)=>{"use strict";var u$=zt(),l$=St(),c$=Vr();gv.exports=function(s,e){if(u$(s),l$(e)&&e.constructor===s)return e;var t=c$.f(s),i=t.resolve;return i(e),t.promise}});var yv=b(()=>{"use strict";var d$=Ee(),p$=mi(),Sv=Ct(),h$=sr(),vv=Cr().CONSTRUCTOR,f$=$d(),m$=p$("Promise"),b$=Sv&&!vv;d$({target:"Promise",stat:!0,forced:Sv||vv},{resolve:function(e){return f$(b$&&this===m$?h$:this,e)}})});var Tv=b(()=>{"use strict";av();pv();fv();mv();bv();yv()});var wv=b(()=>{"use strict";var g$=Ee(),S$=Ct(),su=sr(),v$=Oe(),xv=mi(),Ev=ge(),y$=td(),Iv=$d(),T$=$r(),Dd=su&&su.prototype,I$=!!su&&v$(function(){Dd.finally.call({then:function(){}},function(){})});g$({target:"Promise",proto:!0,real:!0,forced:I$},{finally:function(s){var e=y$(this,xv("Promise")),t=Ev(s);return this.then(t?function(i){return Iv(e,s()).then(function(){return i})}:s,t?function(i){return Iv(e,s()).then(function(){throw i})}:s)}});!S$&&Ev(su)&&(Bd=xv("Promise").prototype.finally,Dd.finally!==Bd&&T$(Dd,"finally",Bd,{unsafe:!0}));var Bd});var Av=b((mU,Pv)=>{"use strict";Cg();Tv();wv();var x$=Li();Pv.exports=x$("Promise","finally")});var Rv=b((bU,kv)=>{"use strict";var E$=Av();kv.exports=E$});var Pa=b((gU,Lv)=>{"use strict";var w$=Rv();Lv.exports=w$});var jv=b(()=>{"use strict";var F$=Ee(),N$=Ac().values;F$({target:"Object",stat:!0},{values:function(e){return N$(e)}})});var Gv=b((t1,Hv)=>{"use strict";jv();var U$=Er();Hv.exports=U$.Object.values});var Qv=b((i1,zv)=>{"use strict";var q$=Gv();zv.exports=q$});var ur=b((r1,Wv)=>{"use strict";var j$=Qv();Wv.exports=j$});var dy=b(()=>{"use strict";var pB=Ee(),hB=wr(),fB=Mr(),mB=pa(),bB=ha();pB({target:"Array",proto:!0},{at:function(e){var t=hB(this),i=fB(t),r=mB(e),a=r>=0?r:i+r;return a<0||a>=i?void 0:t[a]}});bB("at")});var hy=b((pq,py)=>{"use strict";dy();var gB=Li();py.exports=gB("Array","at")});var my=b((hq,fy)=>{"use strict";var SB=hy();fy.exports=SB});var _t=b((fq,by)=>{"use strict";var vB=my();by.exports=vB});var rp=b((Zj,Yy)=>{"use strict";var ZB=Ki();Yy.exports=Array.isArray||function(e){return ZB(e)==="Array"}});var Xy=b((eH,Ky)=>{"use strict";var eD=TypeError,tD=9007199254740991;Ky.exports=function(s){if(s>tD)throw eD("Maximum allowed index exceeded");return s}});var eT=b((tH,Zy)=>{"use strict";var iD=rp(),rD=Mr(),sD=Xy(),aD=Ar(),Jy=function(s,e,t,i,r,a,n,o){for(var u=r,l=0,d=n?aD(n,o):!1,c,h;l<i;)l in t&&(c=d?d(t[l],l,e):t[l],a>0&&iD(c)?(h=rD(c),u=Jy(s,e,c,h,u,a-1)-1):(sD(u+1),s[u]=c),u++),l++;return u};Zy.exports=Jy});var sT=b((iH,rT)=>{"use strict";var tT=rp(),nD=ed(),oD=St(),uD=_e(),lD=uD("species"),iT=Array;rT.exports=function(s){var e;return tT(s)&&(e=s.constructor,nD(e)&&(e===iT||tT(e.prototype))?e=void 0:oD(e)&&(e=e[lD],e===null&&(e=void 0))),e===void 0?iT:e}});var nT=b((rH,aT)=>{"use strict";var cD=sT();aT.exports=function(s,e){return new(cD(s))(e===0?0:e)}});var oT=b(()=>{"use strict";var dD=Ee(),pD=eT(),hD=Gt(),fD=wr(),mD=Mr(),bD=nT();dD({target:"Array",proto:!0},{flatMap:function(e){var t=fD(this),i=mD(t),r;return hD(e),r=bD(t,0),r.length=pD(r,t,t,i,0,1,e,arguments.length>1?arguments[1]:void 0),r}})});var uT=b(()=>{"use strict";var gD=ha();gD("flatMap")});var cT=b((uH,lT)=>{"use strict";oT();uT();var SD=Li();lT.exports=SD("Array","flatMap")});var pT=b((lH,dT)=>{"use strict";var vD=cT();dT.exports=vD});var qa=b((cH,hT)=>{"use strict";var yD=pT();hT.exports=yD});var ja=b((dH,fT)=>{"use strict";var TD=ma(),ID=String;fT.exports=function(s){if(TD(s)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return ID(s)}});var sp=b((pH,mT)=>{"use strict";mT.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 ST=b((hH,gT)=>{"use strict";var xD=$e(),ED=Ri(),wD=ja(),np=sp(),bT=xD("".replace),PD=RegExp("^["+np+"]+"),AD=RegExp("(^|[^"+np+"])["+np+"]+$"),ap=function(s){return function(e){var t=wD(ED(e));return s&1&&(t=bT(t,PD,"")),s&2&&(t=bT(t,AD,"$1")),t}};gT.exports={start:ap(1),end:ap(2),trim:ap(3)}});var IT=b((fH,TT)=>{"use strict";var kD=Dc().PROPER,RD=Oe(),vT=sp(),yT="\u200B\x85\u180E";TT.exports=function(s){return RD(function(){return!!vT[s]()||yT[s]()!==yT||kD&&vT[s].name!==s})}});var op=b((mH,xT)=>{"use strict";var LD=ST().start,MD=IT();xT.exports=MD("trimStart")?function(){return LD(this)}:"".trimStart});var wT=b(()=>{"use strict";var $D=Ee(),ET=op();$D({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==ET},{trimLeft:ET})});var AT=b(()=>{"use strict";wT();var BD=Ee(),PT=op();BD({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==PT},{trimStart:PT})});var RT=b((yH,kT)=>{"use strict";AT();var DD=Li();kT.exports=DD("String","trimLeft")});var MT=b((TH,LT)=>{"use strict";var CD=RT();LT.exports=CD});var BT=b((IH,$T)=>{"use strict";var VD=MT();$T.exports=VD});var WT=b(()=>{"use strict"});var YT=b(()=>{"use strict"});var XT=b((i3,KT)=>{"use strict";var a0=St(),n0=Ki(),o0=_e(),u0=o0("match");KT.exports=function(s){var e;return a0(s)&&((e=s[u0])!==void 0?!!e:n0(s)==="RegExp")}});var ZT=b((r3,JT)=>{"use strict";var l0=zt();JT.exports=function(){var s=l0(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 iI=b((s3,tI)=>{"use strict";var c0=gt(),d0=Vt(),p0=na(),h0=ZT(),eI=RegExp.prototype;tI.exports=function(s){var e=s.flags;return e===void 0&&!("flags"in eI)&&!d0(s,"flags")&&p0(eI,s)?c0(h0,s):e}});var sI=b((a3,rI)=>{"use strict";var hp=$e(),f0=wr(),m0=Math.floor,dp=hp("".charAt),b0=hp("".replace),pp=hp("".slice),g0=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,S0=/\$([$&'`]|\d{1,2})/g;rI.exports=function(s,e,t,i,r,a){var n=t+s.length,o=i.length,u=S0;return r!==void 0&&(r=f0(r),u=g0),b0(a,u,function(l,d){var c;switch(dp(d,0)){case"$":return"$";case"&":return s;case"`":return pp(e,0,t);case"'":return pp(e,n);case"<":c=r[pp(d,1,-1)];break;default:var h=+d;if(h===0)return l;if(h>o){var p=m0(h/10);return p===0?l:p<=o?i[p-1]===void 0?dp(d,1):i[p-1]+dp(d,1):l}c=i[h-1]}return c===void 0?"":c})}});var oI=b(()=>{"use strict";var v0=Ee(),y0=gt(),mp=$e(),aI=Ri(),T0=ge(),I0=xr(),x0=XT(),es=ja(),E0=ua(),w0=iI(),P0=sI(),A0=_e(),k0=Ct(),R0=A0("replace"),L0=TypeError,fp=mp("".indexOf),M0=mp("".replace),nI=mp("".slice),$0=Math.max;v0({target:"String",proto:!0},{replaceAll:function(e,t){var i=aI(this),r,a,n,o,u,l,d,c,h,p,f=0,m="";if(!I0(e)){if(r=x0(e),r&&(a=es(aI(w0(e))),!~fp(a,"g")))throw new L0("`.replaceAll` does not allow non-global regexes");if(n=E0(e,R0),n)return y0(n,e,i,t);if(k0&&r)return M0(es(i),e,t)}for(o=es(i),u=es(e),l=T0(t),l||(t=es(t)),d=u.length,c=$0(1,d),h=fp(o,u);h!==-1;)p=l?es(t(u,h,o)):P0(u,o,h,[],void 0,t),m+=nI(o,f,h)+p,f=h+d,h=h+c>o.length?-1:fp(o,u,h+c);return f<o.length&&(m+=nI(o,f)),m}})});var lI=b((u3,uI)=>{"use strict";WT();YT();oI();var B0=Li();uI.exports=B0("String","replaceAll")});var dI=b((l3,cI)=>{"use strict";var D0=lI();cI.exports=D0});var bp=b((c3,pI)=>{"use strict";var C0=dI();pI.exports=C0});var fI=b((d3,hI)=>{"use strict";var V0=pa(),O0=ja(),_0=Ri(),F0=RangeError;hI.exports=function(e){var t=O0(_0(this)),i="",r=V0(e);if(r<0||r===1/0)throw new F0("Wrong number of repetitions");for(;r>0;(r>>>=1)&&(t+=t))r&1&&(i+=t);return i}});var vI=b((p3,SI)=>{"use strict";var gI=$e(),N0=vc(),mI=ja(),U0=fI(),q0=Ri(),j0=gI(U0),H0=gI("".slice),G0=Math.ceil,bI=function(s){return function(e,t,i){var r=mI(q0(e)),a=N0(t),n=r.length,o=i===void 0?" ":mI(i),u,l;return a<=n||o===""?r:(u=a-n,l=j0(o,G0(u/o.length)),l.length>u&&(l=H0(l,0,u)),s?r+l:l+r)}};SI.exports={start:bI(!1),end:bI(!0)}});var TI=b((h3,yI)=>{"use strict";var z0=Ji();yI.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(z0)});var II=b(()=>{"use strict";var Q0=Ee(),W0=vI().start,Y0=TI();Q0({target:"String",proto:!0,forced:Y0},{padStart:function(e){return W0(this,e,arguments.length>1?arguments[1]:void 0)}})});var EI=b((b3,xI)=>{"use strict";II();var K0=Li();xI.exports=K0("String","padStart")});var PI=b((g3,wI)=>{"use strict";var X0=EI();wI.exports=X0});var gp=b((S3,AI)=>{"use strict";var J0=PI();AI.exports=J0});var _h="2.0.134-dev.ae2fd074.0";var st=(r=>(r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused",r))(st||{}),fi=(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))(fi||{});var Eo=(r=>(r.NOT_AVAILABLE="NOT_AVAILABLE",r.AVAILABLE="AVAILABLE",r.CONNECTING="CONNECTING",r.CONNECTED="CONNECTED",r))(Eo||{}),ql=(i=>(i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic",i))(ql||{});var jl=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(jl||{}),wo=(i=>(i.TRAFFIC_SAVING="traffic_saving",i.HIGH_QUALITY="high_quality",i.UNKNOWN="unknown",i))(wo||{});var _E=N(vt(),1);import{assertNever as Om,assertNonNullable as pA,isNonNullable as Lo,ValueSubject as Tc,Subject as hA,Subscription as fA,merge as mA,observableFrom as bA,fromEvent as Bm,map as Dm,tap as Cm,filterChanged as gA,isNullable as Ic,ErrorCategory as Vm}from"@vkontakte/videoplayer-shared/es2018";var $m=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 Mo=class{constructor(e){this.connection$=new Tc(void 0);this.castState$=new Tc("NOT_AVAILABLE");this.errorEvent$=new hA;this.realCastState$=new Tc("NOT_AVAILABLE");this.subscription=new fA;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=Lo((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||$m("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:Vm.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(){Lo(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();Ic(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();Ic(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.isDestroyed=!0,this.subscription.unsubscribe()}initListeners(){let e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),i=cast.framework.CastContext.getInstance();this.subscription.add(Bm(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 Om(r.sessionState)}})).add(mA(Bm(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(Cm(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),Dm(r=>r.castState)),bA([i.getCastState()])).pipe(gA(),Dm(SA),Cm(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{var o,u;let a=r==="CONNECTED",n=Lo(this.connection$.getValue());if(a&&!n){let l=i.getCurrentSession();pA(l);let d=l.getCastDevice(),c=(u=(o=l.getMediaSession())==null?void 0:o.media)==null?void 0:u.contentId;(Ic(c)||c===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:l,castDevice:d}))}else!a&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(r==="CONNECTED"?Lo(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:Vm.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:a})}}},SA=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 Om(s)}};var Rh=N(vt(),1),vE=N(er(),1),yE=N(Yc(),1);var Nv=N(Pa(),1);import{assertNever as Mv}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:Mv(t)}return s},$i=(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:Mv(e)}};var R=(s,e,t=!1)=>{let i=s.getTransition();(t||!i||i.to===e)&&s.setState(e)};import{isNonNullable as P$,Subject as au,merge as $v}from"@vkontakte/videoplayer-shared/es2018";var H=class{constructor(e){this.transitionStarted$=new au;this.transitionEnded$=new au;this.transitionUpdated$=new au;this.forceChanged$=new au;this.stateChangeStarted$=$v(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=$v(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||P$(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 A$}from"@vkontakte/videoplayer-shared/es2018";var Bv=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 A$(s)}};import{assertNever as Ur,assertNonNullable as nr,debounce as Dv,ErrorCategory as Cv,fromEvent as or,isNonNullable as Vv,map as Ov,merge as _v,observableFrom as k$,Subject as R$,Subscription as Cd,timeout as L$,getHighestQuality as M$}from"@vkontakte/videoplayer-shared/es2018";var $$=5,B$=5,D$=500,Fv=7e3,Aa=class{constructor(e){this.subscription=new Cd;this.loadMediaTimeoutSubscription=new Cd;this.videoState=new H("stopped");this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(a)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.stop());return}if(!t){if((r==null?void 0:r.to)!=="paused"&&a.state==="requested"&&e!=="stopped"){this.seek(a.position/1e3);return}switch(i){case"ready":{switch(e){case"playing":case"paused":case"ready":break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:Ur(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:Ur(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:Ur(e)}break}default:Ur(i)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(Bv(e.format)),this.params.output.isAudioAvailable$.next(!0),this.handleRemoteVolumeChange({volume:this.params.connection.remotePlayer.volumeLevel,muted:this.params.connection.remotePlayer.isMuted});let t=this.params.connection.session.getMediaSession();t&&this.restoreSession(t),this.subscribe()}destroy(){this.log({message:"[destroy]"}),this.subscription.unsubscribe()}subscribe(){this.subscription.add(this.loadMediaTimeoutSubscription);let e=new Cd;this.subscription.add(e),this.subscription.add(_v(this.videoState.stateChangeStarted$.pipe(Ov(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe(Ov(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 R$;e.add(r.pipe(Dv(D$)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let a=NaN;e.add(or(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)>$$)&&r.next(o),a=o})),e.add(or(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(or(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(or(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t(or(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),r=>{this.logRemoteEvent(r);let{remotePlayer:a}=this.params.connection,n=r.value,o=this.params.output.isBuffering$.getValue(),u=n===chrome.cast.media.PlayerState.BUFFERING;switch(o!==u&&this.params.output.isBuffering$.next(u),n){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&a.duration-a.currentTime<B$&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),R(this.params.desiredState.playbackState,"stopped");break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:Ur(n)}}),t(or(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t(or(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});let i=_v(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,k$(["init"])).pipe(Dv(0));t(i,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});let{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState("paused"),R(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),R(this.params.desiredState.playbackState,"playing"));let i=this.params.output.isLive$.getValue();this.params.output.duration$.next(i?0:t.duration),this.params.output.position$.next(i?0:t.currentTime),this.params.desiredState.seekState.setState({state:"none"})}}prepare(){let e=this.params.format;this.log({message:`[prepare] format: ${e}`});let t=this.createMediaInfo(e),i=this.createLoadRequest(t);this.loadMedia(i)}handleRemotePause(){let e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="paused"||e==="playing")&&(this.videoState.setState("paused"),R(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="playing"||e==="paused")&&(this.videoState.setState("playing"),R(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){var t;let e=this.videoState.getTransition();(e==null?void 0:e.to)==="ready"&&this.videoState.setState("ready"),((t=this.params.desiredState.playbackState.getTransition())==null?void 0:t.to)==="ready"&&R(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){var r,a;let t=this.params.output.volume$.getValue(),i={volume:(r=e.volume)!=null?r:t.volume,muted:(a=e.muted)!=null?a:t.muted};(i.volume!==t.volume||i.muted!==i.muted)&&this.params.output.volume$.next(i)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:i}=this.params.connection;t.currentTime=e,i.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){var l;let t=this.params.source,i,r,a;switch(e){case"MPEG":{let d=t[e];nr(d);let c=M$(Object.keys(d));nr(c);let h=d[c];nr(h),i=h,r="video/mp4",a=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let d=t[e];nr(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];nr(d),i=d.url,r="application/dash+xml",a=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let d=t[e];nr(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];nr(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:Cv.VIDEO_PIPELINE,message:d,thrown:c}),c}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return Ur(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 Vv(o)&&(n.metadata.title=o),Vv(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(L$(Fv).subscribe(()=>a(`timeout(${Fv})`)))});(0,Nv.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:Cv.VIDEO_PIPELINE,message:a,thrown:r})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var tp=N(vt(),1);import{clearVideoElement as qv}from"@vkontakte/videoplayer-shared/es2018";import{clearVideoElement as C$}from"@vkontakte/videoplayer-shared/es2018";var Uv=s=>{try{s.pause(),s.playbackRate=0,C$(s),s.remove()}catch(e){console.error(e)}};import{fromEvent as V$,Subscription as O$}from"@vkontakte/videoplayer-shared/es2018";var Vd=class{constructor(){this.attribute="data-pool-reused"}get(e){return e.hasAttribute(this.attribute)}set(e,t){e.toggleAttribute(this.attribute,t)}delete(e){e.removeAttribute(this.attribute)}},Od=window.WeakMap?new WeakMap:new Vd,_d=window.WeakMap?new WeakMap:new Map,_$=(s,e=20)=>{let t=0;return V$(s,"ratechange").subscribe(i=>{t++,t>=e&&(s.currentTime=s.currentTime,t=0)})},Fe=(s,{audioVideoSyncRate:e,disableYandexPiP:t})=>{let i=s.querySelector("video"),r=!!i;i?qv(i):(i=document.createElement("video"),s.appendChild(i)),Od.set(i,r);let a=new O$;return a.add(_$(i,e)),_d.set(i,a),i.setAttribute("crossorigin","anonymous"),i.setAttribute("playsinline","playsinline"),t&&i.setAttribute("x-yandex-pip","false"),i.controls=!1,i.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),i},Ne=s=>{let e=_d.get(s);e==null||e.unsubscribe(),_d.delete(s);let t=Od.get(s);Od.delete(s),t?qv(s):Uv(s)};var Nd=N(ur(),1);import{assertNonNullable as ka,isNonNullable as Wt,isNullable as z$,fromEvent as qr,merge as Yv,observableFrom as Kv,filterChanged as Xv,map as Ra,Subject as Jv,Subscription as Q$,ValueSubject as W$,ErrorCategory as Y$}from"@vkontakte/videoplayer-shared/es2018";import{isNonNullable as Fd,isNullable as H$,Subscription as G$}from"@vkontakte/videoplayer-shared/es2018";var nu=(s,e,t,{equal:i=(n,o)=>n===o,changed$:r,onError:a}={})=>{let n=s.getState(),o=e(),u=H$(r),l=new G$;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},wt=(s,e,t)=>nu(e,()=>s.loop,i=>{Fd(i)&&(s.loop=i)},{onError:t}),Ue=(s,e,t,i)=>nu(e,()=>({muted:s.muted,volume:s.volume}),r=>{Fd(r)&&(s.muted=r.muted,s.volume=r.volume)},{equal:(r,a)=>r===a||(r==null?void 0:r.muted)===(a==null?void 0:a.muted)&&(r==null?void 0:r.volume)===(a==null?void 0:a.volume),changed$:t,onError:i}),at=(s,e,t,i)=>nu(e,()=>s.playbackRate,r=>{Fd(r)&&(s.playbackRate=r)},{changed$:t,onError:i}),Bi=nu;var K$=s=>["__",s.language,s.label].join("|"),X$=(s,e)=>{if(s.id===e)return!0;let[t,i,r]=e.split("|");return s.language===i&&s.label===r},Ud=class s{constructor(e){this.available$=new Jv;this.current$=new W$(void 0);this.error$=new Jv;this.subscription=new Q$;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:Y$.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(Bi(t.internalTextTracks,()=>(0,Nd.default)(this.internalTracks),a=>{Wt(a)&&this.setInternal(a)},{equal:(a,n)=>Wt(a)&&Wt(n)&&a.length===n.length&&a.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(Ra(a=>a.filter(({type:n})=>n==="internal"))),onError:r})),this.subscription.add(Bi(t.externalTextTracks,()=>(0,Nd.default)(this.externalTracks),a=>{Wt(a)&&this.setExternal(a)},{equal:(a,n)=>Wt(a)&&Wt(n)&&a.length===n.length&&a.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(Ra(a=>a.filter(({type:n})=>n==="external"))),onError:r})),this.subscription.add(Bi(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(Bi(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let a of this.htmlTextTracksAsArray())this.applyCueSettings(a.cues),this.applyCueSettings(a.activeCues)}))}subscribe(){ka(this.video);let{textTracks:e}=this.video;this.subscription.add(qr(e,"addtrack").subscribe(()=>{let i=this.current$.getValue();i&&this.select(i)})),this.subscription.add(Yv(qr(e,"addtrack"),qr(e,"removetrack"),Kv(["init"])).pipe(Ra(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),Xv((i,r)=>i.length===r.length&&i.every(({id:a},n)=>a===r[n].id))).subscribe(this.available$)),this.subscription.add(Yv(qr(e,"change"),Kv(["init"])).pipe(Ra(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),Ra(i=>i&&this.htmlTextTrackToITextTrack(i).id),Xv()).subscribe(this.current$));let t=i=>{var r,a;return this.applyCueSettings((a=(r=i.target)==null?void 0:r.activeCues)!=null?a:null)};this.subscription.add(qr(e,"addtrack").subscribe(i=>{var a,n;(a=i.track)==null||a.addEventListener("cuechange",t);let r=o=>{var l,d,c,h,p;let u=(d=(l=o.target)==null?void 0:l.cues)!=null?d:null;u&&u.length&&(this.applyCueSettings((h=(c=o.target)==null?void 0:c.cues)!=null?h:null),(p=o.target)==null||p.removeEventListener("cuechange",r))};(n=i.track)==null||n.addEventListener("cuechange",r)})),this.subscription.add(qr(e,"removetrack").subscribe(i=>{var r;(r=i.track)==null||r.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;let t=this.cueSettings.getState();for(let i of Array.from(e)){let r=i;Wt(t.align)&&(r.align=t.align),Wt(t.position)&&(r.position=t.position),Wt(t.size)&&(r.size=t.size),Wt(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){ka(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:K$(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){ka(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(z$(e)||!X$(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){ka(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){ka(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)}},nt=Ud;var lr=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 Zv=s=>{let e=s;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e==null?void 0:e.parentNode;return e!=null?e:void 0},qd=s=>{let e=Zv(s);return!!(e&&e.fullscreenElement&&e.fullscreenElement===s)},ey=s=>{let e=Zv(s);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===s)};import{fromEvent as Ze,map as Yt,merge as hu,filterChanged as uy,isNonNullable as ly,Subject as nB,filter as Hd,mapTo as Gd,combine as oB,once as uB,throttle as lB,ErrorCategory as cB,ValueSubject as cy,Subscription as dB}from"@vkontakte/videoplayer-shared/es2018";var J$=3,ty=(s,e,t=J$)=>{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 ou=class{constructor(){this._isMiuiBrowser=!1}get current(){return this._current}get isYandex(){return this.current==="Yandex"}get isSafari(){return this.current==="Safari"}get isFirefox(){return this.current==="Firefox"}get isSamsungBrowser(){return this.current==="SamsungBrowser"}get safariVersion(){return this._safariVersion}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.isSafari&&this.detectSafariVersion()}detectSafariVersion(){try{let{userAgent:e}=window.navigator,t=e.match(/Version\/(\d+)/);if(!t)return;let i=t[1],r=parseInt(i,10);if(isNaN(r))return;this._safariVersion=r}catch(e){console.error(e)}}};var iy=N(vt(),1);var La=()=>{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 uu=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,iy.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=La()}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 lu=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 Tt=()=>window.ManagedMediaSource||window.MediaSource,jr=()=>{var s,e;return!!(window.ManagedMediaSource&&((e=(s=window.ManagedSourceBuffer)==null?void 0:s.prototype)!=null&&e.appendBuffer))},ry=()=>{var s,e;return!!(window.MediaSource&&((e=(s=window.SourceBuffer)==null?void 0:s.prototype)!=null&&e.appendBuffer))},cu=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var Z$=document.createElement("video"),eB='video/mp4; codecs="avc1.42000a,mp4a.40.2"',tB='video/mp4; codecs="hev1.1.6.L93.B0"',sy='video/webm; codecs="vp09.00.10.08"',ay='video/webm; codecs="av01.0.00M.08"',iB='audio/mp4; codecs="mp4a.40.2"',rB='audio/webm; codecs="opus"',ny,sB=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:ay}}),window.navigator.mediaCapabilities.decodingInfo({...s,video:{...s.video,contentType:sy}})]);ny={DASH_WEBM_AV1:e,DASH_WEBM:t}};sB().catch(s=>{console.log(Z$),console.error(s)});var du=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 ny}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:jr(),mse:ry(),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=Tt())==null?void 0:l.isTypeSupported)!=null&&d.call(l,eB)),E=!!((h=(c=Tt())==null?void 0:c.isTypeSupported)!=null&&h.call(c,tB)),O=!!((f=(p=Tt())==null?void 0:p.isTypeSupported)!=null&&f.call(p,iB));this._codecs={h264:T,h265:E,vp9:!!((g=(m=Tt())==null?void 0:m.isTypeSupported)!=null&&g.call(m,sy)),av1:!!((v=(S=Tt())==null?void 0:S.isTypeSupported)!=null&&v.call(S,ay)),aac:O,opus:!!((I=(y=Tt())==null?void 0:y.isTypeSupported)!=null&&I.call(y,rB)),mpeg:(T||E)&&O},this._nativeHlsSupported=this._protocols.hls&&this._containers.mp4}catch(T){console.error(T)}this.destroyVideoElement()}destroyVideoElement(){var t;if(!this._video)return;if(this._video.pause(),this._video.currentTime=0,this._video.removeAttribute("src"),this._video.src="",this._video.load(),this._video.remove){this._video.remove(),this._video=null;return}this._video.parentNode&&this._video.parentNode.removeChild(this._video);let e=this._video.cloneNode(!1);(t=this._video.parentNode)==null||t.replaceChild(e,this._video),this._video=null}};var oy="audio/mpeg",pu=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,oy))},this._codecs={mp3:!!((r=(i=Tt())==null?void 0:i.isTypeSupported)!=null&&r.call(i,oy))}}catch(a){console.error(a)}this.destroyAudioElement()}destroyAudioElement(){var t;if(!this._audio)return;if(this._audio.pause(),this._audio.currentTime=0,this._audio.removeAttribute("src"),this._audio.src="",this._audio.load(),this._audio.remove){this._audio.remove(),this._audio=null;return}this._audio.parentNode&&this._audio.parentNode.removeChild(this._audio);let e=this._audio.cloneNode(!1);(t=this._audio.parentNode)==null||t.replaceChild(e,this._audio),this._audio=null}};import{ValueSubject as aB}from"@vkontakte/videoplayer-shared/es2018";var jd=class{constructor(){this.isInited$=new aB(!1);this._displayChecker=new lu,this._deviceChecker=new uu(this._displayChecker),this._browserChecker=new ou,this._videoChecker=new du(this._deviceChecker,this._browserChecker),this._audioChecker=new pu,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)}},q=new jd;var qe=s=>{let e=A=>Ze(s,A).pipe(Gd(void 0)),t=new dB,i=()=>t.unsubscribe(),r=hu(Ze(s,"progress"),Ze(s,"timeupdate")).pipe(Yt(()=>ty(s.buffered,s.currentTime))),a=q.browser.isSafari?oB({play:e("play").pipe(uB()),playing:e("playing")}).pipe(Gd(void 0)):e("playing"),n=Ze(s,"volumechange").pipe(Yt(()=>({muted:s.muted,volume:s.volume}))),o=Ze(s,"ratechange").pipe(Yt(()=>s.playbackRate)),u=Ze(s,"error").pipe(Hd(()=>!!(s.error||s.played.length)),Yt(()=>{var C;let A=s.error;return{id:A?`MediaError#${A.code}`:"HtmlVideoError",category:cB.VIDEO_PIPELINE,message:A?A.message:"Error event from HTML video element",thrown:(C=s.error)!=null?C:void 0}})),l=Ze(s,"timeupdate").pipe(Yt(()=>s.currentTime)),d=["waiting","seeking","seeked","timeupdate"],c=new nB,h=.3,p;t.add(hu(...d.map(A=>Ze(s,A))).subscribe(A=>{let C=s.currentTime;s.loop&&ly(p)&&ly(C)&&p>=s.duration-h&&C<=h&&c.next(p),p=C}));let f=e("pause").pipe(Hd(()=>!s.error&&p!==s.duration)),m=Ze(s,"enterpictureinpicture"),g=Ze(s,"leavepictureinpicture"),S=new cy(ey(s));t.add(m.subscribe(()=>S.next(!0))),t.add(g.subscribe(()=>S.next(!1)));let v=new cy(qd(s)),y=Ze(s,"fullscreenchange");t.add(y.pipe(Yt(()=>qd(s))).subscribe(v));let I=.1,T=1e3,E=Ze(s,"timeupdate").pipe(Yt(A=>s.duration-s.currentTime<I),uy()),O=hu(E.pipe(Hd(A=>!s.loop&&A)),Ze(s,"ended")).pipe(lB(T),Gd(void 0)),w=hu(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(A=>Ze(s,A)),E.pipe(Yt(A=>({type:A?"ended":"unknown"})))).pipe(Yt(A=>q.browser.isFirefox&&A.type==="ended"?s.readyState<2:s.readyState<3),uy());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$:Ze(s,"durationchange").pipe(Yt(()=>s.duration)),isBuffering$:w,currentBuffer$:r,volumeState$:n,playbackRateState$:o,inPiP$:S,inFullscreen$:v,enterPip$:m,leavePip$:g,destroy:i}};import{VideoQuality as Di}from"@vkontakte/videoplayer-shared/es2018";var Kt=s=>{switch(s){case"mobile":return Di.Q_144P;case"lowest":return Di.Q_240P;case"low":return Di.Q_360P;case"sd":case"medium":return Di.Q_480P;case"hd":case"high":return Di.Q_720P;case"fullhd":case"full":return Di.Q_1080P;case"quadhd":case"quad":return Di.Q_1440P;case"ultrahd":case"ultra":return Di.Q_2160P}};var tt=N(_t(),1),Wd=N(vt(),1),cr=N(er(),1);import{isNonNullable as ie,isNullable as Su,now as Py,isHigher as vu,isHigherOrEqual as Gr,isInvariantQuality as yu,isLowerOrEqual as zr,videoSizeToQuality as Ay,assertNotEmptyArray as Tu,assertNonNullable as ky}from"@vkontakte/videoplayer-shared/es2018";var zd=!1,gi={},gy=s=>{zd=s},Sy=()=>{gi={}},vy=s=>{s(gi)},Ma=(s,e)=>{var t;zd&&(gi.meta=(t=gi.meta)!=null?t:{},gi.meta[s]=e)},et=class{constructor(e){this.name=e}next(e){var i,r;if(!zd)return;gi.series=(i=gi.series)!=null?i:{};let t=(r=gi.series[this.name])!=null?r:[];t.push([Date.now(),e]),gi.series[this.name]=t}};import{isHigher as yB,isHigherOrEqual as yq,isLower as yy,isLowerOrEqual as Tq,isNonNullable as fu,isNullable as TB,videoHeightToQuality as mu}from"@vkontakte/videoplayer-shared/es2018";function Qd(s,e,t){return!s.max&&s.min===e?"high_quality":!s.min&&s.max===t?"traffic_saving":"unknown"}function bu(s,e,t){return!!s&&Qd(s,e,t)==="high_quality"}function Hr(s,e,t){return TB(s)||fu(s.min)&&fu(s.max)&&yy(s.max,s.min)||fu(s.min)&&e&&yB(s.min,e)||fu(s.max)&&t&&yy(s.max,t)}function Ty({limits:s,highestAvailableHeight:e,lowestAvailableHeight:t}){return Hr({max:s!=null&&s.max?mu(s.max):void 0,min:s!=null&&s.min?mu(s.min):void 0},e?mu(e):void 0,t?mu(t):void 0)}var Ry=new et("best_bitrate"),Iu=(s,e,t)=>(e-t)*Math.pow(2,-10*s)+t;var Qr=s=>(e,t)=>s*(Number(e.bitrate)-Number(t.bitrate)),Ci=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=Py()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},xu='Assertion "ABR Tracks is empty array" failed',gu=new WeakMap,Iy=new WeakMap,xy=new WeakMap,$a=(s,e,t,i)=>{var u;let r=[...e].sort(Qr(1)),a=[...t].sort(Qr(1)),n=a.filter(l=>ie(l.bitrate)&&ie(s.bitrate)?s.bitrate/l.bitrate>i:!0),o=(u=(0,tt.default)(a,Math.round(a.length*r.indexOf(s)/(r.length+1))))!=null?u:(0,tt.default)(a,-1);return o&&(0,Wd.default)(n,o)?o:n.length?(0,tt.default)(n,-1):(0,tt.default)(a,0)},Ba=(s,e,t,i)=>{var u;let r=gu.get(e);r||(r=[...e].sort(Qr(1)),gu.set(e,r));let a=gu.get(t);a||(a=[...t].sort(Qr(1)),gu.set(t,a));let n=xy.get(s);n||(n=a.filter(l=>ie(l.bitrate)&&ie(s.bitrate)?s.bitrate/l.bitrate>i:!0),xy.set(s,n));let o=(u=(0,tt.default)(a,Math.round(a.length*r.indexOf(s)/(r.length+1))))!=null?u:(0,tt.default)(a,-1);return o&&(0,Wd.default)(n,o)?o:n.length?(0,tt.default)(n,-1):(0,tt.default)(a,0)},Ey=s=>"quality"in s,Eu=(s,e,t,i)=>{var n;let r=ie((n=i==null?void 0:i.last)==null?void 0:n.bitrate)&&ie(t==null?void 0:t.bitrate)&&i.last.bitrate<t.bitrate?s.trackCooldownIncreaseQuality:s.trackCooldownDecreaseQuality,a=t&&i&&i.history[t.id]&&Py()-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=Ey(o)?"video":"audio",l=Ey(o)?o.quality:o.bitrate;return e({message:`
8
8
  [last ${u} selected] ${l}
9
- `}),o}return i==null||i.recordSwitch(t),t},IB=(s,e)=>Math.log(e)/Math.log(s),Ry=({tuning:s,container:e,limits:t,panelSize:i})=>{let r=s.containerSizeFactor;if(i)return{containerSizeLimit:i,containerSizeFactor:r};if(s.usePixelRatio&&q.display.pixelRatio){let a=q.display.pixelRatio;if(s.pixelRatioMultiplier)r*=s.pixelRatioMultiplier*(a-1)+1;else{let n=s.pixelRatioLogBase,[o=0,u=0,l=0]=s.pixelRatioLogCoefficients,d=IB(n,o*a+u)+l;Number.isFinite(d)&&(r*=d)}}return gu(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}},Ey=new WeakMap,Xt=(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 L,Q,U,P,F;Iu(s,Eu);let{containerSizeFactor:g,containerSizeLimit:S}=Ry({container:e,tuning:i,limits:r,panelSize:m}),v=i.considerPlaybackRate&&ie(o)?o:1,y=Ey.get(s);y||(y=s.filter(k=>!Tu(k.quality)).sort((k,x)=>yu(k.quality,x.quality)?-1:1),Ey.set(s,y));let I=(L=(0,it.default)(y,-1))==null?void 0:L.quality,T=(Q=(0,it.default)(y,0))==null?void 0:Q.quality,E=Hr(r,T,I),O=v*xu(n!=null?n:.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),$={},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 Oe=S&&Py(S);x=Oe?zr(k.quality,Oe):!0}if(!x){$[k.quality]="FitsContainer";continue}let B=p||t,oe=ie(B)&&isFinite(B)&&ie(k.bitrate)?B-a>=k.bitrate*O:!0,Ve=gu(r,i.highQualityLimit,i.trafficSavingLimit)&&(r==null?void 0:r.min)===k.quality;if(!oe&&!Ve){$[k.quality]="FitsThroughput";continue}if(i.lazyQualitySwitch&&ie(i.minBufferToSwitchUp)&&u&&!Tu(u.quality)&&(n!=null?n:0)<i.minBufferToSwitchUp&&yu(k.quality,u.quality)){$[k.quality]="Buffer";continue}if(!!c&&Gr(k.quality,c)&&!Ve){$[k.quality]="DroppedFramesLimit";continue}if(!!h&&Gr(k.quality,h)&&!Ve){$[k.quality]="StallsLimit";continue}let Te=E||(vu(r==null?void 0:r.max)||zr(k.quality,r.max))&&(vu(r==null?void 0:r.min)||Gr(k.quality,r.min)),Ie=ie(d)&&!d?zr(k.quality,i.backgroundVideoQualityLimit):!0;if(!Te||!Ie){$[k.quality]="FitsQualityLimits";continue}w||(w=k)}w&&w.bitrate&&ky.next(w.bitrate);let A=(U=w!=null?w:(0,it.default)(y,-1))!=null?U:s[0],C=l==null?void 0:l.last,M=wu(i,f,A,l);return ie(l)&&M.quality!==(C==null?void 0:C.quality)&&f({message:`
9
+ `}),o}return i==null||i.recordSwitch(t),t},IB=(s,e)=>Math.log(e)/Math.log(s),Ly=({tuning:s,container:e,limits:t,panelSize:i})=>{let r=s.containerSizeFactor;if(i)return{containerSizeLimit:i,containerSizeFactor:r};if(s.usePixelRatio&&q.display.pixelRatio){let a=q.display.pixelRatio;if(s.pixelRatioMultiplier)r*=s.pixelRatioMultiplier*(a-1)+1;else{let n=s.pixelRatioLogBase,[o=0,u=0,l=0]=s.pixelRatioLogCoefficients,d=IB(n,o*a+u)+l;Number.isFinite(d)&&(r*=d)}}return bu(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}},wy=new WeakMap,Xt=(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 L,Q,U,P,F;Tu(s,xu);let{containerSizeFactor:g,containerSizeLimit:S}=Ly({container:e,tuning:i,limits:r,panelSize:m}),v=i.considerPlaybackRate&&ie(o)?o:1,y=wy.get(s);y||(y=s.filter(k=>!yu(k.quality)).sort((k,x)=>vu(k.quality,x.quality)?-1:1),wy.set(s,y));let I=(L=(0,tt.default)(y,-1))==null?void 0:L.quality,T=(Q=(0,tt.default)(y,0))==null?void 0:Q.quality,E=Hr(r,T,I),O=v*Iu(n!=null?n:.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),$={},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&&Ay(S);x=Ve?zr(k.quality,Ve):!0}if(!x){$[k.quality]="FitsContainer";continue}let B=p||t,oe=ie(B)&&isFinite(B)&&ie(k.bitrate)?B-a>=k.bitrate*O:!0,Ce=bu(r,i.highQualityLimit,i.trafficSavingLimit)&&(r==null?void 0:r.min)===k.quality;if(!oe&&!Ce){$[k.quality]="FitsThroughput";continue}if(i.lazyQualitySwitch&&ie(i.minBufferToSwitchUp)&&u&&!yu(u.quality)&&(n!=null?n:0)<i.minBufferToSwitchUp&&vu(k.quality,u.quality)){$[k.quality]="Buffer";continue}if(!!c&&Gr(k.quality,c)&&!Ce){$[k.quality]="DroppedFramesLimit";continue}if(!!h&&Gr(k.quality,h)&&!Ce){$[k.quality]="StallsLimit";continue}let Te=E||(Su(r==null?void 0:r.max)||zr(k.quality,r.max))&&(Su(r==null?void 0:r.min)||Gr(k.quality,r.min)),Ie=ie(d)&&!d?zr(k.quality,i.backgroundVideoQualityLimit):!0;if(!Te||!Ie){$[k.quality]="FitsQualityLimits";continue}w||(w=k)}w&&w.bitrate&&Ry.next(w.bitrate);let A=(U=w!=null?w:(0,tt.default)(y,-1))!=null?U:s[0],C=l==null?void 0:l.last,M=Eu(i,f,A,l);return ie(l)&&M.quality!==(C==null?void 0:C.quality)&&f({message:`
10
10
  [VIDEO TRACKS ABR]
11
11
  [available video tracks]
12
12
  ${s.map(k=>{var x,B;return`{ id: ${k.id}, quality: ${k.quality}, bitrate: ${k.bitrate}, size: ${(x=k.size)==null?void 0:x.width}:${(B=k.size)==null?void 0:B.height} }`}).join(`
@@ -39,7 +39,7 @@ var FE=Object.create;var Vh=Object.defineProperty;var NE=Object.getOwnPropertyDe
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},Pu=(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,P,F,k;Iu(s,Eu);let{containerSizeFactor:g,containerSizeLimit:S}=Ry({container:e,tuning:i,limits:r,panelSize:m}),v=i.considerPlaybackRate&&ie(o)?o:1,y=s.filter(x=>!Tu(x.quality)).sort((x,B)=>yu(x.quality,B.quality)?-1:1),I=(Q=(0,it.default)(y,-1))==null?void 0:Q.quality,T=(U=(0,it.default)(y,0))==null?void 0:U.quality,E=Hr(r,T,I),O=v*xu(n!=null?n:.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),$={},A=y.filter(x=>{let B=!0;if(S)if(x.size)B=x.size.width<=S.width&&x.size.height<=S.height;else{let Et=S&&Py(S);B=Et?zr(x.quality,Et):!0}if(!B)return $[x.quality]="FitsContainer",!1;let oe=p||t,Ve=ie(oe)&&isFinite(oe)&&ie(x.bitrate)?oe-a>=x.bitrate*O:!0,se=gu(r,i.highQualityLimit,i.trafficSavingLimit)&&(r==null?void 0:r.min)===x.quality;if(!Ve&&!se)return $[x.quality]="FitsThroughput",!1;if(i.lazyQualitySwitch&&ie(i.minBufferToSwitchUp)&&u&&!Tu(u.quality)&&(n!=null?n:0)<i.minBufferToSwitchUp&&yu(x.quality,u.quality))return $[x.quality]="Buffer",!1;if(!!c&&Gr(x.quality,c)&&!se)return $[x.quality]="DroppedFramesLimit",!1;if(!!h&&Gr(x.quality,h)&&!se)return $[x.quality]="StallsLimit",!1;let Ie=E||(vu(r==null?void 0:r.max)||zr(x.quality,r.max))&&(vu(r==null?void 0:r.min)||Gr(x.quality,r.min)),Oe=ie(d)&&!d?zr(x.quality,i.backgroundVideoQualityLimit):!0;return!Ie||!Oe?($[x.quality]="FitsQualityLimits",!1):!0})[0];A&&A.bitrate&&ky.next(A.bitrate);let C=(P=A!=null?A:(0,it.default)(y,-1))!=null?P:s[0],M=l==null?void 0:l.last,L=wu(i,f,C,l);return ie(l)&&L.quality!==(M==null?void 0:M.quality)&&f({message:`
42
+ `}),M},wu=(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,P,F,k;Tu(s,xu);let{containerSizeFactor:g,containerSizeLimit:S}=Ly({container:e,tuning:i,limits:r,panelSize:m}),v=i.considerPlaybackRate&&ie(o)?o:1,y=s.filter(x=>!yu(x.quality)).sort((x,B)=>vu(x.quality,B.quality)?-1:1),I=(Q=(0,tt.default)(y,-1))==null?void 0:Q.quality,T=(U=(0,tt.default)(y,0))==null?void 0:U.quality,E=Hr(r,T,I),O=v*Iu(n!=null?n:.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),$={},A=y.filter(x=>{let B=!0;if(S)if(x.size)B=x.size.width<=S.width&&x.size.height<=S.height;else{let Et=S&&Ay(S);B=Et?zr(x.quality,Et):!0}if(!B)return $[x.quality]="FitsContainer",!1;let oe=p||t,Ce=ie(oe)&&isFinite(oe)&&ie(x.bitrate)?oe-a>=x.bitrate*O:!0,se=bu(r,i.highQualityLimit,i.trafficSavingLimit)&&(r==null?void 0:r.min)===x.quality;if(!Ce&&!se)return $[x.quality]="FitsThroughput",!1;if(i.lazyQualitySwitch&&ie(i.minBufferToSwitchUp)&&u&&!yu(u.quality)&&(n!=null?n:0)<i.minBufferToSwitchUp&&vu(x.quality,u.quality))return $[x.quality]="Buffer",!1;if(!!c&&Gr(x.quality,c)&&!se)return $[x.quality]="DroppedFramesLimit",!1;if(!!h&&Gr(x.quality,h)&&!se)return $[x.quality]="StallsLimit",!1;let Ie=E||(Su(r==null?void 0:r.max)||zr(x.quality,r.max))&&(Su(r==null?void 0:r.min)||Gr(x.quality,r.min)),Ve=ie(d)&&!d?zr(x.quality,i.backgroundVideoQualityLimit):!0;return!Ie||!Ve?($[x.quality]="FitsQualityLimits",!1):!0})[0];A&&A.bitrate&&Ry.next(A.bitrate);let C=(P=A!=null?A:(0,tt.default)(y,-1))!=null?P:s[0],M=l==null?void 0:l.last,L=Eu(i,f,C,l);return ie(l)&&L.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 B,oe;return`{ id: ${x.id}, quality: ${x.quality}, bitrate: ${x.bitrate}, size: ${(B=x.size)==null?void 0:B.width}:${(oe=x.size)==null?void 0:oe.height} }`}).join(`
@@ -72,7 +72,7 @@ var FE=Object.create;var Vh=Object.defineProperty;var NE=Object.getOwnPropertyDe
72
72
 
73
73
  [best video track] ${A==null?void 0:A.quality}
74
74
  [selected video track] ${L==null?void 0:L.quality}
75
- `}),L},Au=(s,e,t,{estimatedThroughput:i,tuning:r,playbackRate:a,forwardBufferHealth:n,history:o,abrLogger:u,stallsPredictedThroughput:l})=>{Iu(t,Eu);let d=r.considerPlaybackRate&&ie(a)?a:1,c=[...t].sort(Qr(-1)),h=s.bitrate;Ay(h);let p=d*xu(n!=null?n:.5,r.bitrateAudioFactorAtEmptyBuffer,r.bitrateAudioFactorAtFullBuffer),f,m=Ba(s,e,t,r.minVideoAudioRatio),g=l||i;ie(g)&&isFinite(g)&&(f=c.find(y=>ie(y.bitrate)&&ie(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&&wu(r,u,f,o);return ie(o)&&(v==null?void 0:v.bitrate)!==(S==null?void 0:S.bitrate)&&u({message:`
75
+ `}),L},Pu=(s,e,t,{estimatedThroughput:i,tuning:r,playbackRate:a,forwardBufferHealth:n,history:o,abrLogger:u,stallsPredictedThroughput:l})=>{Tu(t,xu);let d=r.considerPlaybackRate&&ie(a)?a:1,c=[...t].sort(Qr(-1)),h=s.bitrate;ky(h);let p=d*Iu(n!=null?n:.5,r.bitrateAudioFactorAtEmptyBuffer,r.bitrateAudioFactorAtFullBuffer),f,m=$a(s,e,t,r.minVideoAudioRatio),g=l||i;ie(g)&&isFinite(g)&&(f=c.find(y=>ie(y.bitrate)&&ie(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&&Eu(r,u,f,o);return ie(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(`
@@ -93,7 +93,7 @@ var FE=Object.create;var Vh=Object.defineProperty;var NE=Object.getOwnPropertyDe
93
93
  minBufferToSwitchUp: ${r.minBufferToSwitchUp},
94
94
 
95
95
  [selected audio track] ${v==null?void 0:v.id}
96
- `}),v},ku=(s,e,t,{estimatedThroughput:i,tuning:r,playbackRate:a,forwardBufferHealth:n,history:o,abrLogger:u,stallsPredictedThroughput:l})=>{Iu(t,Eu);let d=r.considerPlaybackRate&&ie(a)?a:1,c=Ty.get(t);c||(c=[...t].sort(Qr(-1)),Ty.set(t,c));let h=s.bitrate;Ay(h);let p=d*xu(n!=null?n:.5,r.bitrateAudioFactorAtEmptyBuffer,r.bitrateAudioFactorAtFullBuffer),f,m=Da(s,e,t,r.minVideoAudioRatio),g=l||i;ie(g)&&isFinite(g)&&(f=c.find(y=>ie(y.bitrate)&&ie(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&&wu(r,u,f,o);return ie(o)&&(v==null?void 0:v.bitrate)!==(S==null?void 0:S.bitrate)&&u({message:`
96
+ `}),v},Au=(s,e,t,{estimatedThroughput:i,tuning:r,playbackRate:a,forwardBufferHealth:n,history:o,abrLogger:u,stallsPredictedThroughput:l})=>{Tu(t,xu);let d=r.considerPlaybackRate&&ie(a)?a:1,c=Iy.get(t);c||(c=[...t].sort(Qr(-1)),Iy.set(t,c));let h=s.bitrate;ky(h);let p=d*Iu(n!=null?n:.5,r.bitrateAudioFactorAtEmptyBuffer,r.bitrateAudioFactorAtFullBuffer),f,m=Ba(s,e,t,r.minVideoAudioRatio),g=l||i;ie(g)&&isFinite(g)&&(f=c.find(y=>ie(y.bitrate)&&ie(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&&Eu(r,u,f,o);return ie(o)&&(v==null?void 0:v.bitrate)!==(S==null?void 0:S.bitrate)&&u({message:`
97
97
  [AUDIO TRACKS ABR]
98
98
  [available audio tracks]
99
99
  ${t.map(y=>`{ id: ${y.id}, bitrate: ${y.bitrate} }`).join(`
@@ -114,14 +114,14 @@ var FE=Object.create;var Vh=Object.defineProperty;var NE=Object.getOwnPropertyDe
114
114
  minBufferToSwitchUp: ${r.minBufferToSwitchUp},
115
115
 
116
116
  [selected audio track] ${v==null?void 0:v.id}
117
- `}),v};var we=s=>new URL(s).hostname;import{assertNever as Ny,assertNonNullable as Uy,combine as jB,debounce as HB,ErrorCategory as qy,filter as jy,filterChanged as GB,isNonNullable as Jd,map as $u,merge as Hy,observableFrom as zB,once as QB,Subscription as WB,ValueSubject as Zd,videoQualityToHeight as Gy,videoSizeToQuality as YB}from"@vkontakte/videoplayer-shared/es2018";var Vy=N(_t(),1);var My=N(yt(),1),Ly=s=>{if(s instanceof DOMException&&(0,My.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"))},He=async(s,e)=>{let t=s.muted;try{await s.play()}catch(i){if(!Ly(i))return!1;if(e&&e(),t)return console.warn(i),!1;s.muted=!0;try{await s.play()}catch(r){return Ly(r)&&(s.muted=!1,console.warn(r)),!1}}return!0};import{isNonNullable as Lu,isNullable as wB,assertNonNullable as Oa}from"@vkontakte/videoplayer-shared/es2018";var By=N(ur(),1);import{isNonNullable as $y,assertNonNullable as Ru,now as xB}from"@vkontakte/videoplayer-shared/es2018";function Be(){return xB()}function Wd(s){return Be()-s}function Yd(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 Dy(s,e,t){let i=(...r)=>{t.apply(null,r),s.removeEventListener(e,i)};s.addEventListener(e,i)}function Wr(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;Ru(d);let M=Wd(d),L;if(M<m){L=m-M,setTimeout(g,L);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,L,Q=0,U=()=>(Ru(d),Math.max(d,Math.max(L||0,Q||0)));if(a&&n.addEventListener("progress",P=>{let F=Be();a.updateChunk&&P.loaded>M&&(a.updateChunk(U(),P.loaded-M),M=P.loaded,L=F)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>I())),n.addEventListener("load",()=>{if(u)return;Ru(n);let P=n.status;if(P>=200&&P<300){let{response:F,responseType:k}=n,x=F==null?void 0:F.byteLength;if(typeof x=="number"&&a){let B=x-M;B&&a.updateChunk&&a.updateChunk(U(),B)}k==="json"&&(!F||!(0,By.default)(F).length)?I():(c&&c(),e(F))}else I()}),n.addEventListener("error",()=>{I()}),h){let P=()=>{Ru(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(Q=Be(),n.removeEventListener("readystatechange",P))};n.addEventListener("readystatechange",P)}return n.responseType=p,n.send(),C},C={withBitrateReporting:S,withParallel:T,withJSONResponse:y,withRetryCount:M=>(l=M,C),withRetryInterval:(M,L)=>($y(M)&&(m=M),$y(L)&&(f=L),C),withTimeout:M=>(o=M,C),withFinally:v,send:E,abort:()=>{n&&(n.abort(),n=void 0),u=!0,c&&c()}};return C}var Ca=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 Cy=N(ur(),1);var Va=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=Wr(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,Cy.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 PB}from"@vkontakte/videoplayer-shared/es2018";var Mu=1e4,Kd=3;var AB=6e4,kB=10,RB=1,LB=500,_a=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 PB,this.chunkRateEstimator=new Ca(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=Yd(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setAutoQualityLimits(e){this.autoQualityLimits=e}switchByName(e){let t;for(let i=0;i<this.manifest.length;++i)if(t=this.manifest[i],t.name===e){this._switchToQuality(t);return}}catchUp(){this.rep&&this.rep.stop(),this.currentManifestEntry&&(this.paused=!1,this._initPlayerWith(this.currentManifestEntry),this._notifyBuffering(!0))}stop(){this.params.videoElement.pause(),this.rep&&(this.rep.stop(),this.rep=null)}pause(){this.paused=!0,this.params.videoElement.pause(),this.videoPlayStarted=!1,this._notifyBuffering(!1)}play(){this.paused=!1;let e=this.lowLatency&&this._getBufferSizeSec()>this.sourceJitter+5;this.rep&&!e?(this.bufferStates=[],this.videoPlayStarted=!1,this.shouldPlay()?this._playVideoElement():this._notifyBuffering(!0)):this.catchUp()}startPlay(e,t){this.autoQuality=t,this._initPlayerWith(e)}destroy(){this.destroyed=!0,this.rep&&(this.rep.stop(),this.rep=null),this.manifestRequest&&this.manifestRequest.abort(),this.manifestRefetchTimer&&(clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=void 0)}reinit(e){this.manifestUrl=e,this.urlResolver=Yd(e),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){let e=this.params.videoElement,t=0,i=e.buffered.length;return i!==0&&(t=e.buffered.end(i-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){let{videoElement:e,logger:t}=this.params;e.addEventListener("error",()=>{var r;!!e.error&&!this.destroyed&&(t(`Video element error: ${(r=e.error)==null?void 0:r.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{let i=this._getBufferSizeSec();!this.paused&&i<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(i+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){let{logger:e,videoElement:t}=this.params,i=t.buffered.length,r;i!==0&&!this.waitingForFirstBufferAfterSrcChange&&(r=t.buffered.start(i-1),t.currentTime<r&&(e("Fixup stall"),t.currentTime=r))}_selectQuality(e){let{videoElement:t}=this.params,i,r,a,n=t&&1.62*(q.display.pixelRatio||1)*t.offsetHeight||520;for(let o=0;o<this.manifest.length;++o){a=this.manifest[o];let{max:u,min:l}=this.autoQualityLimits||{};!yy({limits:this.autoQualityLimits,highestAvailableHeight:this.manifest[0].video.height,lowestAvailableHeight:(0,Vy.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||Lu(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=()=>{Dy(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 Va(Kd,Mu,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=Wr(this.urlResolver.resolve(I,!1),T,E,()=>this._retryCallback()).withTimeout(Mu).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Kd).withFinally(()=>{u=null}).send()},p=(I,T,E)=>{Oa(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 A=this.bufferStates[w];I=Math.min(I,A.buf),A.ts<E&&O++}this.bufferStates.splice(0,O),t(`update playback rate; minBuffer=${I} drop=${O} jitter=${this.sourceJitter}`);let $=I-RB;this.sourceJitter>=0?$-=this.sourceJitter/2:this.sourceJitter-=1,$>3?f(1.15):$>1?f(1.1):$>.3?f(1.05):f(1)}},S=I=>{let T,E=()=>T&&T.start?T.start.length:0,O=P=>T.start[P]/1e3,$=P=>T.dur[P]/1e3,w=P=>T.fragIndex+P,A=(P,F)=>({chunkIdx:w(P),startTS:O(P),dur:$(P),discontinuity:F}),C=()=>{let P=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 B=T.dur.length-1;for(;B>=0&&(x-=T.dur[B],!(x<=0));--B);P=Math.min(B,T.dur.length-1-k),P=Math.max(P,0)}return A(P,!0)},M=P=>{let F=E();if(!(F<=0)){if(Lu(P)){for(let k=0;k<F;k++)if(O(k)>P)return A(k)}return C()}},L=P=>{let F=E(),k=P?P.chunkIdx+1:0,x=k-T.fragIndex;if(!(F<=0)){if(!P||x<0||x-F>kB)return t(`Resync: offset=${x} bChunks=${F} chunk=`+JSON.stringify(P)),C();if(!(x>=F))return A(k-T.fragIndex,!1)}},Q=(P,F,k)=>{l&&l.abort(),l=Wr(this.urlResolver.resolve(P,!0,this.lowLatency),F,k,()=>this._retryCallback()).withTimeout(Mu).withRetryCount(Kd).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(P,F)=>{Q(I,k=>{if(!c())return;T=k;let x=!!T.lowLatency;x!==this.lowLatency&&m(x);let B=0;for(let oe=0;oe<T.dur.length;++oe)B+=T.dur[oe];B>0&&(Oa(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(B/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,P(M(F))},()=>this._handleNetworkError())},nextChunk:L}},v=()=>{a=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),Oa(this.filesFetcher),this.filesFetcher.abortAll()};return d={start:I=>{let{videoElement:T,logger:E}=this.params,O=S(e.jidxUrl),$,w,A,C,M=0,L,Q,U,P=()=>{L&&(clearTimeout(L),L=void 0);let K=Math.max(LB,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),ye=M+K,Te=Be(),Ie=Math.min(1e4,ye-Te);M=Te;let Oe=()=>{l||c()&&O.seek(()=>{c()&&(M=Be(),F(),P())})};Ie>0?L=window.setTimeout(()=>{this.paused?P():Oe()},Ie):Oe()},F=()=>{let K;for(;K=O.nextChunk(C);)C=K,Ve(K);let ye=O.nextChunk(A);if(ye){if(A&&ye.discontinuity){E("Detected discontinuity; restarting playback"),this.paused?P():(v(),this._initPlayerWith(e));return}oe(ye)}else P()},k=(K,ye)=>{if(!c()||!this.sourceBuffer)return;let Te,Ie,Oe,Et=At=>{window.setTimeout(()=>{c()&&k(K,ye)},At)};if(this.sourceBuffer.updating)E("Source buffer is updating; delaying appendBuffer"),Et(100);else{let At=Be(),Ht=T.currentTime;!this.paused&&T.buffered.length>1&&Q===Ht&&At-U>500&&(E("Stall suspected; trying to fix"),this._fixupStall()),Q!==Ht&&(Q=Ht,U=At);let ei=this._getBufferSizeSec();if(ei>30)E(`Buffered ${ei} seconds; delaying appendBuffer`),Et(2e3);else try{this.sourceBuffer.appendBuffer(K),this.videoPlayStarted?(this.bufferStates.push({ts:At,buf:ei}),g(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),ye&&ye()}catch(ki){if(ki.name==="QuotaExceededError")E("QuotaExceededError; delaying appendBuffer"),Oe=this.sourceBuffer.buffered.length,Oe!==0&&(Te=this.sourceBuffer.buffered.start(0),Ie=Ht,Ie-Te>4&&this.sourceBuffer.remove(Te,Ie-3)),Et(1e3);else throw ki}}},x=()=>{w&&$&&(E([`Appending chunk, sz=${w.byteLength}:`,JSON.stringify(A)]),k(w,function(){w=null,F()}))},B=K=>e.fragUrlTemplate.replace("%%id%%",K.chunkIdx),oe=K=>{c()&&p(B(K),(ye,Te)=>{if(c()){if(Te/=1e3,w=ye,A=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())},Ve=K=>{c()&&(Oa(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(B(K),!1)))},se=K=>{c()&&(e.cachedHeader=K,k(K,()=>{$=!0,x()}))};a=!0,O.seek(K=>{if(c()){if(M=Be(),!K){P();return}C=K,!wB(I)||K.startTS>I?oe(K):(A=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(),Lu(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,Oa(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return Lu(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&&Wd(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=Wr(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(Mu).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;He(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))},AB))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var Fy=N(er(),1);import{debounce as MB,filter as Oy,fromEvent as $B,interval as BB,isHigher as DB,isInvariantQuality as CB,isLower as VB,merge as OB,Subject as _y,Subscription as _B}from"@vkontakte/videoplayer-shared/es2018";var Xd=class{constructor(){this.onDroopedVideoFramesLimit$=new _y;this.subscription=new _B;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&&!CB(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&&DB(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($B(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=BB(this.droppedFramesChecker.checkTime).pipe(Oy(()=>this.playing),Oy(()=>{let r=!!this.isForceCheckCounter;return r&&(this.isForceCheckCounter-=1),!r})),t=this.forceChecker$.pipe(MB(this.droppedFramesChecker.checkTime)),i=OB(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,Fy.default)(this.limitCounts).filter(([,a])=>a>=this.droppedFramesChecker.countLimit).sort(([a],[n])=>VB(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}},Yr=Xd;import{map as FB,Observable as NB}from"@vkontakte/videoplayer-shared/es2018";import{fromEvent as UB}from"@vkontakte/videoplayer-shared/es2018";var Fa=()=>{var s;return!!((s=window.documentPictureInPicture)!=null&&s.window)||!!document.pictureInPictureElement};var qB=(s,e)=>new NB(t=>{if(!window.IntersectionObserver)return;let i={root:null},r=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||Fa()))},{...i,...e});r.observe(s);let a=UB(document,"visibilitychange").pipe(FB(n=>!document.hidden||Fa())).subscribe(n=>t.next(n));return()=>{r.unobserve(s),a.unsubscribe()}}),ut=qB;var KB=["paused","playing","ready"],XB=["paused","playing","ready"],Na=class{constructor(e){this.subscription=new WB;this.videoState=new H("stopped");this.representations$=new Zd([]);this.droppedFramesManager=new Yr;this.maxSeekBackTime$=new Zd(1/0);this.zeroTime$=new Zd(void 0);this.liveOffset=new lr;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:qy.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=Kt(u.name))!=null?i:YB(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),Jd(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,ep.default)(XB,e)&&(n||o)){this.prepare();return}if((r==null?void 0:r.to)!=="paused"&&a.state==="requested"&&(0,ep.default)(KB,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 Ny(e)}};this.textTracksManager=new ot(e.source.url),this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=r=>{e.output.error$.next({id:"DashLiveProvider",category:qy.WTF,message:"DashLiveProvider internal logic error",thrown:r})};this.subscription.add(Hy(this.videoState.stateChangeStarted$.pipe($u(r=>({transition:r,type:"start"}))),this.videoState.stateChangeEnded$.pipe($u(r=>({transition:r,type:"end"})))).subscribe(({transition:r,type:a})=>{this.log({message:`[videoState change] ${a}: ${JSON.stringify(r)}`})})),this.video=Ne(e.container,e.tuning),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.subscription.add(this.dash.soundProhibitedEvent$.subscribe(this.params.output.soundProhibitedEvent$)),this.params.output.duration$.next(1/0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(we(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);let i=je(this.video);this.subscription.add(()=>i.destroy()),this.subscription.add(this.representations$.pipe($u(r=>r.map(({track:a})=>a)),jy(r=>!!r.length),QB()).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(GB(),$u(r=>-r/1e3)).subscribe(this.params.output.duration$)).add(jB({zeroTime:this.zeroTime$.pipe(jy(Jd)),position:i.timeUpdate$}).subscribe(({zeroTime:r,position:a})=>this.params.output.liveTime$.next(r+a*1e3),t)).add(wt(this.video,this.params.desiredState.isLooped,t)).add(qe(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(nt(this.video,this.params.desiredState.playbackRate,i.playbackRateState$,t)).add(i.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(i.loadedMetadata$.subscribe(this.params.output.loadedMetadataEvent$)).add(i.playing$.subscribe(this.params.output.firstFrameEvent$)).add(i.canplay$.subscribe(this.params.output.canplay$)).add(i.inPiP$.subscribe(this.params.output.inPiP$)).add(i.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(ut(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:r,min:a}})=>{this.dash.setAutoQualityLimits({max:r&&Gy(r),min:a&&Gy(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 Ny(r.to)}},t)).add(Hy(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,zB(["init"])).pipe(HB(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),Ue(this.video)}createLiveDashPlayer(){let e=new _a({videoElement:this.video,videoState:this.videoState,liveOffset:this.liveOffset,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode,manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){var l,d,c,h,p,f;let e=this.representations$.getValue(),t=(d=(l=this.params.desiredState.videoTrack.getTransition())==null?void 0:l.to)!=null?d:this.params.desiredState.videoTrack.getState(),i=(h=(c=this.params.desiredState.autoVideoTrackSwitching.getTransition())==null?void 0:c.to)!=null?h:this.params.desiredState.autoVideoTrackSwitching.getState(),r=!i&&Jd(t)?t:Xt(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;Uy(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;Uy(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 zy=Na;var ax=N(yt(),1);var De=(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 BC,assertNonNullable as DC,debounce as CC,ErrorCategory as ix,filter as Np,filterChanged as sl,fromEvent as VC,isNonNullable as rx,map as Up,merge as al,observableFrom as qp,once as sx,Subscription as OC}from"@vkontakte/videoplayer-shared/es2018";var Bu=class{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,i){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:i})}removeEventListener(e,t){if(!(e in this.listeners))return;let i=this.listeners[e];for(let r=0,a=i.length;r<a;r++)if(i[r].callback===t){i.splice(r,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;let i=this.listeners[e.type].slice();for(let r=0,a=i.length;r<a;r++){let n=i[r];try{n.callback.call(this,e)}catch(o){Promise.resolve().then(()=>{throw o})}n.options&&n.options.once&&this.removeEventListener(e.type,n.callback)}return!e.defaultPrevented}},Kr=class extends Bu{constructor(){super(),this.listeners||Bu.call(this),Object.defineProperty(this,"aborted",{value:!1,writable:!0,configurable:!0}),Object.defineProperty(this,"onabort",{value:null,writable:!0,configurable:!0}),Object.defineProperty(this,"reason",{value:void 0,writable:!0,configurable:!0})}toString(){return"[object AbortSignal]"}dispatchEvent(e){e.type==="abort"&&(this.aborted=!0,typeof this.onabort=="function"&&this.onabort.call(this,e)),super.dispatchEvent(e)}},Ua=class{constructor(){Object.defineProperty(this,"signal",{value:new Kr,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&&(Ua.prototype[Symbol.toStringTag]="AbortController",Kr.prototype[Symbol.toStringTag]="AbortSignal");function Du(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 tp(s){typeof s=="function"&&(s={fetch:s});let{fetch:e,Request:t=e.Request,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r=!1}=s;if(!Du({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 JB=()=>"fetch"in window,qa=JB()&&Du({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),Qy=qa?tp({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,Pt=qa?Qy.fetch:window.fetch,Kj=qa?Qy.Request:window.Request,ae=qa?Ua:window.AbortController,Xj=qa?Kr:window.AbortSignal;var Dp=N(ja(),1);var BT=N($T(),1);import{ErrorCategory as Ga}from"@vkontakte/videoplayer-shared/es2018";var Cu=s=>{if(!s)return{id:"EmptyResponse",category:Ga.PARSER,message:"Empty response"};if(s.length<=2&&s.match(/^\d+$/))return{id:`UVError#${s}`,category:Ga.NETWORK,message:`UV Error ${s}`};let e=(0,BT.default)(s).substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:Ga.NETWORK,message:"Received unexpected HTML, possibly a ISP block"};if(e.startsWith("<?xml"))return new DOMParser().parseFromString(s,"text/xml").querySelector("parsererror")?{id:"InvalidXML",category:Ga.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:Ga.PARSER,message:"Response is valid XML, but parser failed"}};var Ge=(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 Mp,assertNonNullable as os,combine as us,ErrorCategory as Nt,filter as Ku,filterChanged as wn,flattenObject as Pn,fromEvent as xi,getTraceSubscriptionMethod as mC,interval as $p,isNonNullable as An,isNullable as KI,map as ls,merge as fr,now as Bp,Subject as Xu,Subscription as XI,tap as bC,throttle as gC,ValueSubject as he}from"@vkontakte/videoplayer-shared/es2018";var _u=N(yt(),1),rs=N(_t(),1),Fu=N(ja(),1);var OD=(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)},_D=s=>window.clearTimeout(s),DT=s=>typeof s=="function"&&(s==null?void 0:s.toString().endsWith("{ [native code] }")),CT=!DT(window.requestIdleCallback)||!DT(window.cancelIdleCallback),Xr=CT?OD:window.requestIdleCallback,Jt=CT?_D:window.cancelIdleCallback;var NI=N(Aa(),1);import{assertNever as FD,ErrorCategory as VT,Subject as OT}from"@vkontakte/videoplayer-shared/es2018";var ND=18,_T=!1;try{_T=q.browser.isSafari&&!!q.browser.safariVersion&&q.browser.safariVersion<=ND}catch(s){console.error(s)}var op=class{constructor(e){this.bufferFull$=new OT;this.error$=new OT;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:VT.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:VT.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:FD(t)}}},FT=op;var Jr=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 Oi,assertNonNullable as lt,ErrorCategory as yi,fromEvent as wp,getExponentialDelay as Pp,isNonNullable as is,isNullable as ze,now as Ou,once as rC,Subject as sC,Subscription as aC,ValueSubject as hr}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 Zr=class extends X{};var za=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 Qa=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 Wa=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 Ya=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 Ka=class extends X{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Xa=class extends X{constructor(e,t){super(e,t),this.data=this.content}};var dr=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 Ja=class extends X{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};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){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 tn=class extends ue{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var rn=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 sn=class extends X{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var an=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 nn=class extends X{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var on=class extends X{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var un=class extends ue{constructor(e,t){super(e,t),this.sequenceNumber=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.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 dn=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 pn=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 hn=class extends X{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var fn=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 mn=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 qD={ftyp:Qa,moov:Wa,mvhd:Ya,moof:Ka,mdat:Xa,sidx:dr,trak:Ja,mdia:sn,mfhd:un,tkhd:an,traf:ln,tfhd:cn,tfdt:dn,trun:pn,minf:nn,sv3d:Za,st3d:en,prhd:tn,proj:on,equi:rn,uuid:za,stbl:hn,stsd:fn,avc1:mn,unknown:Zr},Si=class s{constructor(e={}){this.options={offset:0,...e}}parse(e){let t=[],i=this.options.offset;for(;i<e.byteLength;)try{let a=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+i+4,4)),n=this.createBox(a,new DataView(e.buffer,e.byteOffset+i));if(!n.size)break;t.push(n),i+=n.size}catch(r){break}return t}createBox(e,t){let i=qD[e];return i?new i(t,new s):new Zr(t,new s)}};var Vi=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 HD=new TextDecoder("ascii"),GD=s=>HD.decode(new DataView(s.buffer,s.byteOffset+4,4))==="ftyp",zD=s=>{let e=new dr(s,new Si),t=e.earliestPresentationTime/e.timescale*1e3,i=s.byteOffset+s.byteLength+e.firstOffset;return e.segments.map(a=>{if(a.referenceType!==0)throw new Error("Unsupported multilevel sidx");let n=a.subsegmentDuration/e.timescale*1e3,o={status:"none",time:{from:t,to:t+n},byte:{from:i,to:i+a.referencedSize-1}};return t+=n,i+=a.referencedSize,o})},QD=(s,e)=>{let i=new Si().parse(s),r=new Vi(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)},WD=s=>{let t=new Si().parse(s),i=new Vi(t),r={},a=i.findAll("uuid");return a.length?a[a.length-1]:r},YD=s=>{var r;let t=new Si().parse(s);return(r=new Vi(t).find("sidx"))==null?void 0:r.timescale},KD=(s,e)=>{let i=new Si().parse(s),a=new Vi(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},XD=s=>{let e={is3dVideo:!1,stereoMode:0,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}},i=new Si().parse(s),r=new Vi(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},NT={validateData:GD,parseInit:XD,getIndexRange:()=>{},parseSegments:zD,parseFeedableSegmentChunk:QD,getChunkEndTime:KD,getServerLatencyTimestamps:WD,getTimescaleFromIndex:YD};var gn=N(yt(),1);import{assertNonNullable as lp,isNonNullable as HT,isNullable as ZD}from"@vkontakte/videoplayer-shared/es2018";import{assertNever as JD}from"@vkontakte/videoplayer-shared/es2018";var UT={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"}},qT=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=bn(s,t),r=i in UT,a=r?UT[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=bn(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}},bn=(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},Ft=(s,e)=>{switch(e){case"int":return s.getInt8(0);case"uint":return bn(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:JD(e)}},pr=(s,e)=>{let t=0;for(;t<s.byteLength;){let i=new DataView(s.buffer,s.byteOffset+t),r=qT(i);if(!e(r))return;r.type==="master"&&pr(r.value,e),t=r.value.byteOffset-s.byteOffset+r.valueSize}},jT=s=>{if(s.getUint32(0)!==440786851)return!1;let e,t,i,r=qT(s);return pr(r.value,({tag:a,type:n,value:o})=>(a===17143?e=Ft(o,n):a===17026?t=Ft(o,n):a===17029&&(i=Ft(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)};var GT=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],e0=[231,22612,22743,167,171,163,160,175],t0=s=>{let e,t,i,r,a=!1,n=!1,o=!1,u,l,d=!1,c=0;return pr(s,({tag:h,type:p,value:f,valueSize:m})=>{if(h===21419){let g=Ft(f,p);l=bn(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=Ft(f,p):h===17545?r=Ft(f,p):h===21420&&l===475249515?u=Ft(f,p):h===374648427?pr(f,({tag:g,type:S,value:v})=>g===30321?(d=Ft(v,S)===1,!1):!0):a&&n&&(0,gn.default)(GT,h)&&(o=!0),!o}),lp(e,"Failed to parse webm Segment start"),lp(t,"Failed to parse webm Segment end"),lp(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}}}},i0=s=>{if(ZD(s.cuesSeekPosition))return;let e=s.segmentStart+s.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},r0=(s,e)=>{let t=!1,i=!1,r=o=>HT(o.time)&&HT(o.position),a=[],n;return pr(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=Ft(l,u));break;case 183:break;case 241:n&&(n.position=Ft(l,u));break;default:t&&(0,gn.default)(GT,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}}})},s0=s=>{let e=0,t=!1;try{pr(s,i=>i.tag===524531317?i.tagSize<=s.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):(0,gn.default)(e0,i.tag)?(e+i.tagSize<=s.byteLength&&(e+=i.tagSize,t||(t=(0,gn.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},zT={validateData:jT,parseInit:t0,getIndexRange:i0,parseSegments:r0,parseFeedableSegmentChunk:s0};var Sn=s=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(s);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return zT;case"mp4":return NT}}throw new ReferenceError(`Unsupported mime type ${s}`)};var Ip=N(mp(),1),CI=N(er(),1),VI=N(bp(),1),OI=N(_t(),1),xp=N(ur(),1);var AI=N(yt(),1),ts=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,AI.default)(["6E","7A","F4"],o)}}return!1};import{isNonNullable as tC,isNullable as BI}from"@vkontakte/videoplayer-shared/es2018";var Vu=s=>{if(s.includes("/")){let e=s.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(s)};var kI=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 we=s=>new URL(s).hostname;import{assertNever as Uy,assertNonNullable as qy,combine as jB,debounce as HB,ErrorCategory as jy,filter as Hy,filterChanged as GB,isNonNullable as Zd,map as Mu,merge as Gy,observableFrom as zB,once as QB,Subscription as WB,ValueSubject as ep,videoQualityToHeight as zy,videoSizeToQuality as YB}from"@vkontakte/videoplayer-shared/es2018";var Oy=N(_t(),1);var $y=N(vt(),1),My=s=>{if(s instanceof DOMException&&(0,$y.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"))},je=async(s,e)=>{let t=s.muted;try{await s.play()}catch(i){if(!My(i))return!1;if(e&&e(),t)return console.warn(i),!1;s.muted=!0;try{await s.play()}catch(r){return My(r)&&(s.muted=!1,console.warn(r)),!1}}return!0};import{isNonNullable as Ru,isNullable as wB,assertNonNullable as Va}from"@vkontakte/videoplayer-shared/es2018";var Dy=N(ur(),1);import{isNonNullable as By,assertNonNullable as ku,now as xB}from"@vkontakte/videoplayer-shared/es2018";function Be(){return xB()}function Yd(s){return Be()-s}function Kd(s){let e=s.split("/"),t=e.slice(0,e.length-1).join("/"),i=/^([a-z]+:)?\/\//i,r=n=>i.test(n);return{resolve:(n,o,u=!1)=>{r(n)||(n.startsWith("/")||(n="/"+n),n=t+n);let l=n.indexOf("?")>-1?"&":"?";return u&&(n+=l+"lowLat=1",l="&"),o&&(n+=l+"_rnd="+Math.floor(999999999*Math.random())),n}}}function Cy(s,e,t){let i=(...r)=>{t.apply(null,r),s.removeEventListener(e,i)};s.addEventListener(e,i)}function Wr(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;ku(d);let M=Yd(d),L;if(M<m){L=m-M,setTimeout(g,L);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,L,Q=0,U=()=>(ku(d),Math.max(d,Math.max(L||0,Q||0)));if(a&&n.addEventListener("progress",P=>{let F=Be();a.updateChunk&&P.loaded>M&&(a.updateChunk(U(),P.loaded-M),M=P.loaded,L=F)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>I())),n.addEventListener("load",()=>{if(u)return;ku(n);let P=n.status;if(P>=200&&P<300){let{response:F,responseType:k}=n,x=F==null?void 0:F.byteLength;if(typeof x=="number"&&a){let B=x-M;B&&a.updateChunk&&a.updateChunk(U(),B)}k==="json"&&(!F||!(0,Dy.default)(F).length)?I():(c&&c(),e(F))}else I()}),n.addEventListener("error",()=>{I()}),h){let P=()=>{ku(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(Q=Be(),n.removeEventListener("readystatechange",P))};n.addEventListener("readystatechange",P)}return n.responseType=p,n.send(),C},C={withBitrateReporting:S,withParallel:T,withJSONResponse:y,withRetryCount:M=>(l=M,C),withRetryInterval:(M,L)=>(By(M)&&(m=M),By(L)&&(f=L),C),withTimeout:M=>(o=M,C),withFinally:v,send:E,abort:()=>{n&&(n.abort(),n=void 0),u=!0,c&&c()}};return C}var Da=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 Vy=N(ur(),1);var Ca=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=Wr(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,Vy.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 PB}from"@vkontakte/videoplayer-shared/es2018";var Lu=1e4,Xd=3;var AB=6e4,kB=10,RB=1,LB=500,Oa=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 PB,this.chunkRateEstimator=new Da(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=Kd(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setAutoQualityLimits(e){this.autoQualityLimits=e}switchByName(e){let t;for(let i=0;i<this.manifest.length;++i)if(t=this.manifest[i],t.name===e){this._switchToQuality(t);return}}catchUp(){this.rep&&this.rep.stop(),this.currentManifestEntry&&(this.paused=!1,this._initPlayerWith(this.currentManifestEntry),this._notifyBuffering(!0))}stop(){this.params.videoElement.pause(),this.rep&&(this.rep.stop(),this.rep=null)}pause(){this.paused=!0,this.params.videoElement.pause(),this.videoPlayStarted=!1,this._notifyBuffering(!1)}play(){this.paused=!1;let e=this.lowLatency&&this._getBufferSizeSec()>this.sourceJitter+5;this.rep&&!e?(this.bufferStates=[],this.videoPlayStarted=!1,this.shouldPlay()?this._playVideoElement():this._notifyBuffering(!0)):this.catchUp()}startPlay(e,t){this.autoQuality=t,this._initPlayerWith(e)}destroy(){this.destroyed=!0,this.rep&&(this.rep.stop(),this.rep=null),this.manifestRequest&&this.manifestRequest.abort(),this.manifestRefetchTimer&&(clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=void 0)}reinit(e){this.manifestUrl=e,this.urlResolver=Kd(e),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){let e=this.params.videoElement,t=0,i=e.buffered.length;return i!==0&&(t=e.buffered.end(i-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){let{videoElement:e,logger:t}=this.params;e.addEventListener("error",()=>{var r;!!e.error&&!this.destroyed&&(t(`Video element error: ${(r=e.error)==null?void 0:r.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{let i=this._getBufferSizeSec();!this.paused&&i<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(i+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){let{logger:e,videoElement:t}=this.params,i=t.buffered.length,r;i!==0&&!this.waitingForFirstBufferAfterSrcChange&&(r=t.buffered.start(i-1),t.currentTime<r&&(e("Fixup stall"),t.currentTime=r))}_selectQuality(e){let{videoElement:t}=this.params,i,r,a,n=t&&1.62*(q.display.pixelRatio||1)*t.offsetHeight||520;for(let o=0;o<this.manifest.length;++o){a=this.manifest[o];let{max:u,min:l}=this.autoQualityLimits||{};!Ty({limits:this.autoQualityLimits,highestAvailableHeight:this.manifest[0].video.height,lowestAvailableHeight:(0,Oy.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||Ru(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=()=>{Cy(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 Ca(Xd,Lu,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=Wr(this.urlResolver.resolve(I,!1),T,E,()=>this._retryCallback()).withTimeout(Lu).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Xd).withFinally(()=>{u=null}).send()},p=(I,T,E)=>{Va(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 A=this.bufferStates[w];I=Math.min(I,A.buf),A.ts<E&&O++}this.bufferStates.splice(0,O),t(`update playback rate; minBuffer=${I} drop=${O} jitter=${this.sourceJitter}`);let $=I-RB;this.sourceJitter>=0?$-=this.sourceJitter/2:this.sourceJitter-=1,$>3?f(1.15):$>1?f(1.1):$>.3?f(1.05):f(1)}},S=I=>{let T,E=()=>T&&T.start?T.start.length:0,O=P=>T.start[P]/1e3,$=P=>T.dur[P]/1e3,w=P=>T.fragIndex+P,A=(P,F)=>({chunkIdx:w(P),startTS:O(P),dur:$(P),discontinuity:F}),C=()=>{let P=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 B=T.dur.length-1;for(;B>=0&&(x-=T.dur[B],!(x<=0));--B);P=Math.min(B,T.dur.length-1-k),P=Math.max(P,0)}return A(P,!0)},M=P=>{let F=E();if(!(F<=0)){if(Ru(P)){for(let k=0;k<F;k++)if(O(k)>P)return A(k)}return C()}},L=P=>{let F=E(),k=P?P.chunkIdx+1:0,x=k-T.fragIndex;if(!(F<=0)){if(!P||x<0||x-F>kB)return t(`Resync: offset=${x} bChunks=${F} chunk=`+JSON.stringify(P)),C();if(!(x>=F))return A(k-T.fragIndex,!1)}},Q=(P,F,k)=>{l&&l.abort(),l=Wr(this.urlResolver.resolve(P,!0,this.lowLatency),F,k,()=>this._retryCallback()).withTimeout(Lu).withRetryCount(Xd).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(P,F)=>{Q(I,k=>{if(!c())return;T=k;let x=!!T.lowLatency;x!==this.lowLatency&&m(x);let B=0;for(let oe=0;oe<T.dur.length;++oe)B+=T.dur[oe];B>0&&(Va(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(B/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,P(M(F))},()=>this._handleNetworkError())},nextChunk:L}},v=()=>{a=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),Va(this.filesFetcher),this.filesFetcher.abortAll()};return d={start:I=>{let{videoElement:T,logger:E}=this.params,O=S(e.jidxUrl),$,w,A,C,M=0,L,Q,U,P=()=>{L&&(clearTimeout(L),L=void 0);let K=Math.max(LB,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(),P())})};Ie>0?L=window.setTimeout(()=>{this.paused?P():Ve()},Ie):Ve()},F=()=>{let K;for(;K=O.nextChunk(C);)C=K,Ce(K);let ye=O.nextChunk(A);if(ye){if(A&&ye.discontinuity){E("Detected discontinuity; restarting playback"),this.paused?P():(v(),this._initPlayerWith(e));return}oe(ye)}else P()},k=(K,ye)=>{if(!c()||!this.sourceBuffer)return;let Te,Ie,Ve,Et=At=>{window.setTimeout(()=>{c()&&k(K,ye)},At)};if(this.sourceBuffer.updating)E("Source buffer is updating; delaying appendBuffer"),Et(100);else{let At=Be(),Ht=T.currentTime;!this.paused&&T.buffered.length>1&&Q===Ht&&At-U>500&&(E("Stall suspected; trying to fix"),this._fixupStall()),Q!==Ht&&(Q=Ht,U=At);let ei=this._getBufferSizeSec();if(ei>30)E(`Buffered ${ei} seconds; delaying appendBuffer`),Et(2e3);else try{this.sourceBuffer.appendBuffer(K),this.videoPlayStarted?(this.bufferStates.push({ts:At,buf:ei}),g(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),ye&&ye()}catch(ki){if(ki.name==="QuotaExceededError")E("QuotaExceededError; delaying appendBuffer"),Ve=this.sourceBuffer.buffered.length,Ve!==0&&(Te=this.sourceBuffer.buffered.start(0),Ie=Ht,Ie-Te>4&&this.sourceBuffer.remove(Te,Ie-3)),Et(1e3);else throw ki}}},x=()=>{w&&$&&(E([`Appending chunk, sz=${w.byteLength}:`,JSON.stringify(A)]),k(w,function(){w=null,F()}))},B=K=>e.fragUrlTemplate.replace("%%id%%",K.chunkIdx),oe=K=>{c()&&p(B(K),(ye,Te)=>{if(c()){if(Te/=1e3,w=ye,A=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()&&(Va(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(B(K),!1)))},se=K=>{c()&&(e.cachedHeader=K,k(K,()=>{$=!0,x()}))};a=!0,O.seek(K=>{if(c()){if(M=Be(),!K){P();return}C=K,!wB(I)||K.startTS>I?oe(K):(A=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(),Ru(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,Va(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return Ru(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,i=c=>{if(!this.autoQuality)return;let h,p,f;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&c<this.bitrate&&(p=this._getBufferSizeSec(),f=c/this.bitrate,p>10&&f>.8||p>15&&f>.5||p>20&&f>.3)){e(`Not switching: buffer=${Math.floor(p)}; bitrate=${this.bitrate}; newRate=${Math.floor(c)}`);return}h=this._selectQuality(c),h?this._switchToQuality(h):e(`Could not find quality by bitrate ${c}`)},a={updateChunk:(h,p)=>{let f=Be();if(this.chunkRateEstimator.addInterval(h,f,p)){let g=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:p,duration:f-h,speed:g}),!0}},get:()=>{let h=this.chunkRateEstimator.getBitRate();return h?h*.85:0}},n=-1/0,o,u=!0,l=()=>{let c=a.get();if(c&&o&&this.autoQuality){if(u&&c>o&&Yd(n)<3e4)return;i(c)}u=this.autoQuality};return{updateChunk:(c,h)=>{let p=a.updateChunk(c,h);return p&&l(),p},notifySwitch:c=>{let h=Be();c<o&&(n=h),o=c}}}_fetchManifest(e,t,i){this.manifestRequest=Wr(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(Lu).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;je(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))},AB))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var Ny=N(er(),1);import{debounce as MB,filter as _y,fromEvent as $B,interval as BB,isHigher as DB,isInvariantQuality as CB,isLower as VB,merge as OB,Subject as Fy,Subscription as _B}from"@vkontakte/videoplayer-shared/es2018";var Jd=class{constructor(){this.onDroopedVideoFramesLimit$=new Fy;this.subscription=new _B;this.playing=!1;this.tracks=[];this.forceChecker$=new Fy;this.isForceCheckCounter=0;this.prevTotalVideoFrames=0;this.prevDroppedVideoFrames=0;this.limitCounts={};this.handleChangeVideoQuality=()=>{let e=this.tracks.find(({size:t})=>(t==null?void 0:t.height)===this.video.videoHeight&&(t==null?void 0:t.width)===this.video.videoWidth);e&&!CB(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&&DB(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($B(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=BB(this.droppedFramesChecker.checkTime).pipe(_y(()=>this.playing),_y(()=>{let r=!!this.isForceCheckCounter;return r&&(this.isForceCheckCounter-=1),!r})),t=this.forceChecker$.pipe(MB(this.droppedFramesChecker.checkTime)),i=OB(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,Ny.default)(this.limitCounts).filter(([,a])=>a>=this.droppedFramesChecker.countLimit).sort(([a],[n])=>VB(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}},Yr=Jd;import{map as FB,Observable as NB}from"@vkontakte/videoplayer-shared/es2018";import{fromEvent as UB}from"@vkontakte/videoplayer-shared/es2018";var _a=()=>{var s;return!!((s=window.documentPictureInPicture)!=null&&s.window)||!!document.pictureInPictureElement};var qB=(s,e)=>new NB(t=>{if(!window.IntersectionObserver)return;let i={root:null},r=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||_a()))},{...i,...e});r.observe(s);let a=UB(document,"visibilitychange").pipe(FB(n=>!document.hidden||_a())).subscribe(n=>t.next(n));return()=>{r.unobserve(s),a.unsubscribe()}}),ot=qB;var KB=["paused","playing","ready"],XB=["paused","playing","ready"],Fa=class{constructor(e){this.subscription=new WB;this.videoState=new H("stopped");this.representations$=new ep([]);this.droppedFramesManager=new Yr;this.maxSeekBackTime$=new ep(1/0);this.zeroTime$=new ep(void 0);this.liveOffset=new lr;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:jy.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=Kt(u.name))!=null?i:YB(u.video),c=u.bitrate/1e3,h={...u.video};if(!d)continue;let p={id:l,quality:d,bitrate:c,size:h};o.push({track:p,representation:u})}this.representations$.next(o),this.params.output.availableVideoTracks$.next(o.map(({track:u})=>u)),((r=this.videoState.getTransition())==null?void 0:r.to)==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let n=e.quality,o=(a=this.representations$.getValue().find(({representation:u})=>u===n))==null?void 0:a.track;this.params.output.hostname$.next(new URL(n.headerUrl,this.params.source.url).hostname),Zd(o)&&this.params.output.currentVideoTrack$.next(o);break}case"bandwidth":{let{size:n,duration:o}=e;this.params.dependencies.throughputEstimator.addRawSpeed(n,o);break}case"index":{this.maxSeekBackTime$.next(e.shiftDuration||0),this.zeroTime$.next(e.zeroTime);break}}};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; seekState: ${JSON.stringify(a)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"));return}if(t)return;let n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if((0,tp.default)(XB,e)&&(n||o)){this.prepare();return}if((r==null?void 0:r.to)!=="paused"&&a.state==="requested"&&(0,tp.default)(KB,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 Uy(e)}};this.textTracksManager=new nt(e.source.url),this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=r=>{e.output.error$.next({id:"DashLiveProvider",category:jy.WTF,message:"DashLiveProvider internal logic error",thrown:r})};this.subscription.add(Gy(this.videoState.stateChangeStarted$.pipe(Mu(r=>({transition:r,type:"start"}))),this.videoState.stateChangeEnded$.pipe(Mu(r=>({transition:r,type:"end"})))).subscribe(({transition:r,type:a})=>{this.log({message:`[videoState change] ${a}: ${JSON.stringify(r)}`})})),this.video=Fe(e.container,e.tuning),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.subscription.add(this.dash.soundProhibitedEvent$.subscribe(this.params.output.soundProhibitedEvent$)),this.params.output.duration$.next(1/0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(we(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);let i=qe(this.video);this.subscription.add(()=>i.destroy()),this.subscription.add(this.representations$.pipe(Mu(r=>r.map(({track:a})=>a)),Hy(r=>!!r.length),QB()).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(GB(),Mu(r=>-r/1e3)).subscribe(this.params.output.duration$)).add(jB({zeroTime:this.zeroTime$.pipe(Hy(Zd)),position:i.timeUpdate$}).subscribe(({zeroTime:r,position:a})=>this.params.output.liveTime$.next(r+a*1e3),t)).add(wt(this.video,this.params.desiredState.isLooped,t)).add(Ue(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(at(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(ot(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:r,min:a}})=>{this.dash.setAutoQualityLimits({max:r&&zy(r),min:a&&zy(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 Uy(r.to)}},t)).add(Gy(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,zB(["init"])).pipe(HB(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),Ne(this.video)}createLiveDashPlayer(){let e=new Oa({videoElement:this.video,videoState:this.videoState,liveOffset:this.liveOffset,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode,manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){var l,d,c,h,p,f;let e=this.representations$.getValue(),t=(d=(l=this.params.desiredState.videoTrack.getTransition())==null?void 0:l.to)!=null?d:this.params.desiredState.videoTrack.getState(),i=(h=(c=this.params.desiredState.autoVideoTrackSwitching.getTransition())==null?void 0:c.to)!=null?h:this.params.desiredState.autoVideoTrackSwitching.getState(),r=!i&&Zd(t)?t:Xt(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;qy(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;qy(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 Qy=Fa;var nx=N(vt(),1);var It=(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 BC,assertNonNullable as DC,debounce as CC,ErrorCategory as rx,filter as Up,filterChanged as sl,fromEvent as VC,isNonNullable as sx,map as qp,merge as al,observableFrom as jp,once as ax,Subscription as OC}from"@vkontakte/videoplayer-shared/es2018";var $u=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}},Kr=class extends $u{constructor(){super(),this.listeners||$u.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)}},Na=class{constructor(){Object.defineProperty(this,"signal",{value:new Kr,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&&(Na.prototype[Symbol.toStringTag]="AbortController",Kr.prototype[Symbol.toStringTag]="AbortSignal");function Bu(s){return s.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof s.Request=="function"&&!s.Request.prototype.hasOwnProperty("signal")||!s.AbortController}function ip(s){typeof s=="function"&&(s={fetch:s});let{fetch:e,Request:t=e.Request,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r=!1}=s;if(!Bu({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 JB=()=>"fetch"in window,Ua=JB()&&Bu({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),Wy=Ua?ip({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,Pt=Ua?Wy.fetch:window.fetch,Kj=Ua?Wy.Request:window.Request,ae=Ua?Na:window.AbortController,Xj=Ua?Kr:window.AbortSignal;var Cp=N(qa(),1);var DT=N(BT(),1);import{ErrorCategory as Ha}from"@vkontakte/videoplayer-shared/es2018";var Du=s=>{if(!s)return{id:"EmptyResponse",category:Ha.PARSER,message:"Empty response"};if(s.length<=2&&s.match(/^\d+$/))return{id:`UVError#${s}`,category:Ha.NETWORK,message:`UV Error ${s}`};let e=(0,DT.default)(s).substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:Ha.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:Ha.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:Ha.PARSER,message:"Response is valid XML, but parser failed"}};var He=(s,e,t=0)=>{for(let i=0;i<s.length;i++)if(s.start(i)*1e3-t<=e&&s.end(i)*1e3+t>e)return!0;return!1};import{abortable as $p,assertNonNullable as ns,combine as os,ErrorCategory as Nt,filter as Ku,filterChanged as En,flattenObject as wn,fromEvent as xi,getTraceSubscriptionMethod as mC,interval as Bp,isNonNullable as Pn,isNullable as XI,map as us,merge as fr,now as Dp,Subject as Xu,Subscription as JI,tap as bC,throttle as gC,ValueSubject as he}from"@vkontakte/videoplayer-shared/es2018";var Ou=N(vt(),1),rs=N(_t(),1),_u=N(qa(),1);var OD=(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)},_D=s=>window.clearTimeout(s),CT=s=>typeof s=="function"&&(s==null?void 0:s.toString().endsWith("{ [native code] }")),VT=!CT(window.requestIdleCallback)||!CT(window.cancelIdleCallback),Xr=VT?OD:window.requestIdleCallback,Jt=VT?_D:window.cancelIdleCallback;var UI=N(Pa(),1);import{assertNever as FD,ErrorCategory as OT,Subject as _T}from"@vkontakte/videoplayer-shared/es2018";var ND=18,FT=!1;try{FT=q.browser.isSafari&&!!q.browser.safariVersion&&q.browser.safariVersion<=ND}catch(s){console.error(s)}var up=class{constructor(e){this.bufferFull$=new _T;this.error$=new _T;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:OT.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)};FT&&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:OT.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:FD(t)}}},NT=up;var Jr=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 Oi,assertNonNullable as ut,ErrorCategory as yi,fromEvent as Pp,getExponentialDelay as Ap,isNonNullable as is,isNullable as Ge,now as Vu,once as rC,Subject as sC,Subscription as aC,ValueSubject as hr}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 Zr=class extends X{};var Ga=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 za=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 Qa=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 Wa=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 Ya=class extends X{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ka=class extends X{constructor(e,t){super(e,t),this.data=this.content}};var dr=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 Xa=class extends X{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ja=class extends X{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Za=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 en=class extends ue{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var tn=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 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.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 an=class extends X{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var nn=class extends X{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var on=class extends ue{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var un=class extends X{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ln=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 cn=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 dn=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 pn=class extends X{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var hn=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 fn=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 qD={ftyp:za,moov:Qa,mvhd:Wa,moof:Ya,mdat:Ka,sidx:dr,trak:Xa,mdia:rn,mfhd:on,tkhd:sn,traf:un,tfhd:ln,tfdt:cn,trun:dn,minf:an,sv3d:Ja,st3d:Za,prhd:en,proj:nn,equi:tn,uuid:Ga,stbl:pn,stsd:hn,avc1:fn,unknown:Zr},Si=class s{constructor(e={}){this.options={offset:0,...e}}parse(e){let t=[],i=this.options.offset;for(;i<e.byteLength;)try{let a=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+i+4,4)),n=this.createBox(a,new DataView(e.buffer,e.byteOffset+i));if(!n.size)break;t.push(n),i+=n.size}catch(r){break}return t}createBox(e,t){let i=qD[e];return i?new i(t,new s):new Zr(t,new s)}};var Vi=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 HD=new TextDecoder("ascii"),GD=s=>HD.decode(new DataView(s.buffer,s.byteOffset+4,4))==="ftyp",zD=s=>{let e=new dr(s,new Si),t=e.earliestPresentationTime/e.timescale*1e3,i=s.byteOffset+s.byteLength+e.firstOffset;return e.segments.map(a=>{if(a.referenceType!==0)throw new Error("Unsupported multilevel sidx");let n=a.subsegmentDuration/e.timescale*1e3,o={status:"none",time:{from:t,to:t+n},byte:{from:i,to:i+a.referencedSize-1}};return t+=n,i+=a.referencedSize,o})},QD=(s,e)=>{let i=new Si().parse(s),r=new Vi(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)},WD=s=>{let t=new Si().parse(s),i=new Vi(t),r={},a=i.findAll("uuid");return a.length?a[a.length-1]:r},YD=s=>{var r;let t=new Si().parse(s);return(r=new Vi(t).find("sidx"))==null?void 0:r.timescale},KD=(s,e)=>{let i=new Si().parse(s),a=new Vi(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},XD=s=>{let e={is3dVideo:!1,stereoMode:0,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}},i=new Si().parse(s),r=new Vi(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},UT={validateData:GD,parseInit:XD,getIndexRange:()=>{},parseSegments:zD,parseFeedableSegmentChunk:QD,getChunkEndTime:KD,getServerLatencyTimestamps:WD,getTimescaleFromIndex:YD};var bn=N(vt(),1);import{assertNonNullable as cp,isNonNullable as GT,isNullable as ZD}from"@vkontakte/videoplayer-shared/es2018";import{assertNever as JD}from"@vkontakte/videoplayer-shared/es2018";var qT={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"}},jT=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=mn(s,t),r=i in qT,a=r?qT[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=mn(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}},mn=(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},Ft=(s,e)=>{switch(e){case"int":return s.getInt8(0);case"uint":return mn(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:JD(e)}},pr=(s,e)=>{let t=0;for(;t<s.byteLength;){let i=new DataView(s.buffer,s.byteOffset+t),r=jT(i);if(!e(r))return;r.type==="master"&&pr(r.value,e),t=r.value.byteOffset-s.byteOffset+r.valueSize}},HT=s=>{if(s.getUint32(0)!==440786851)return!1;let e,t,i,r=jT(s);return pr(r.value,({tag:a,type:n,value:o})=>(a===17143?e=Ft(o,n):a===17026?t=Ft(o,n):a===17029&&(i=Ft(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)};var zT=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],e0=[231,22612,22743,167,171,163,160,175],t0=s=>{let e,t,i,r,a=!1,n=!1,o=!1,u,l,d=!1,c=0;return pr(s,({tag:h,type:p,value:f,valueSize:m})=>{if(h===21419){let g=Ft(f,p);l=mn(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=Ft(f,p):h===17545?r=Ft(f,p):h===21420&&l===475249515?u=Ft(f,p):h===374648427?pr(f,({tag:g,type:S,value:v})=>g===30321?(d=Ft(v,S)===1,!1):!0):a&&n&&(0,bn.default)(zT,h)&&(o=!0),!o}),cp(e,"Failed to parse webm Segment start"),cp(t,"Failed to parse webm Segment end"),cp(r,"Failed to parse webm Segment duration"),i=i!=null?i:1e6,{segmentStart:Math.round(e/1e9*i*1e3),segmentEnd:Math.round(t/1e9*i*1e3),timeScale:i,segmentDuration:Math.round(r/1e9*i*1e3),cuesSeekPosition:u,is3dVideo:d,stereoMode:c,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},i0=s=>{if(ZD(s.cuesSeekPosition))return;let e=s.segmentStart+s.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},r0=(s,e)=>{let t=!1,i=!1,r=o=>GT(o.time)&&GT(o.position),a=[],n;return pr(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=Ft(l,u));break;case 183:break;case 241:n&&(n.position=Ft(l,u));break;default:t&&(0,bn.default)(zT,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}}})},s0=s=>{let e=0,t=!1;try{pr(s,i=>i.tag===524531317?i.tagSize<=s.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):(0,bn.default)(e0,i.tag)?(e+i.tagSize<=s.byteLength&&(e+=i.tagSize,t||(t=(0,bn.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},QT={validateData:HT,parseInit:t0,getIndexRange:i0,parseSegments:r0,parseFeedableSegmentChunk:s0};var gn=s=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(s);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return QT;case"mp4":return UT}}throw new ReferenceError(`Unsupported mime type ${s}`)};var xp=N(bp(),1),VI=N(er(),1),OI=N(gp(),1),_I=N(_t(),1),Ep=N(ur(),1);var kI=N(vt(),1),ts=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,kI.default)(["6E","7A","F4"],o)}}return!1};import{isNonNullable as tC,isNullable as DI}from"@vkontakte/videoplayer-shared/es2018";var Cu=s=>{if(s.includes("/")){let e=s.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(s)};var RI=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 Sp=N(_t(),1);import{videoSizeToQuality as eC}from"@vkontakte/videoplayer-shared/es2018";var RI=({id:s,width:e,height:t,bitrate:i,fps:r,quality:a,streamId:n})=>{var u;let o=(u=a?Kt(a):void 0)!=null?u:eC({width:e,height:t});return o&&{id:s,quality:o,bitrate:i,size:{width:e,height:t},fps:r,streamId:n}},LI=({id:s,bitrate:e})=>({id:s,bitrate:e}),MI=({language:s,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:s,label:e}),$I=({language:s,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:s,label:e}),vp=({id:s,language:e,label:t,codecs:i,isDefault:r})=>({id:s,language:e,label:t,codec:(0,Sp.default)(i.split("."),0),isDefault:r}),yp=({id:s,language:e,label:t,hdr:i,codecs:r})=>({id:s,language:e,hdr:i,label:t,codec:(0,Sp.default)(r.split("."),0)}),Tp=s=>"url"in s,rt=s=>s.type==="template",vn=s=>s instanceof DOMException&&(s.name==="AbortError"||s.code===20);var DI=s=>{if(!(s!=null&&s.startsWith("P")))return;let e=(n,o)=>{let u=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(u)?0:u)*o},i=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(s),r=(i==null?void 0:i[1])==="-"?-1:1,a={days:e(i==null?void 0:i[5],r),hours:e(i==null?void 0:i[6],r),minutes:e(i==null?void 0:i[7],r),seconds:e(i==null?void 0:i[8],r)};return a.days*24*60*60*1e3+a.hours*60*60*1e3+a.minutes*60*1e3+a.seconds*1e3},vi=(s,e)=>{let t=s;t=(0,Ip.default)(t,"$$","$");let i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[r,a]of(0,CI.default)(i)){let n=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=(0,Ip.default)(t,n,(o,u)=>BI(a)?o:BI(u)?a:(0,VI.default)(a,parseInt(u,10),"0"))}return t},_I=(s,e)=>{var w,A,C,M,L,Q,U,P,F,k,x,B,oe,Ve,se,K,ye,Te,Ie,Oe,Et,At,Ht,ei,ki,ys,Ts,Is,xs,Es,ws,Ps,As,ks,Rs,Ls,Ms,$s,Bs,Ds,Cs,Vs,Os,_s,Fs,Ns,Us,qs,js,Hs,Gs,zs,Qs,Ws,Ys,Ks,Xs,Js,Zs,ea,ta;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 _,We;return(We=(_=ce.textContent)==null?void 0:_.trim())!=null?We:""}),o=(w=(0,OI.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=DI(v):(0,xp.default)(T).filter(ce=>ce).length&&!u?S=(0,xp.default)(T).reduce((ce,_)=>{var We;return ce+((We=DI(_))!=null?We:0)},0):m&&(S=parseInt(m,10));let E=0,O=(C=(A=a.getAttribute("profiles"))==null?void 0:A.split(","))!=null?C:[];for(let ce of y.map(_=>_.id))for(let _ of I[ce]){let We=(M=_.getAttribute("id"))!=null?M:"id"+(E++).toString(10),kt=(L=_.getAttribute("mimeType"))!=null?L:"",Gi=(Q=_.getAttribute("codecs"))!=null?Q:"",zi=(U=_.getAttribute("contentType"))!=null?U:kt==null?void 0:kt.split("/")[0],Dl=(F=(P=_.getAttribute("profiles"))==null?void 0:P.split(","))!=null?F:[],ia=(x=kI((k=_.getAttribute("lang"))!=null?k:""))!=null?x:{},ti=(Ve=(oe=(B=_.querySelector("Label"))==null?void 0:B.textContent)==null?void 0:oe.trim())!=null?Ve:void 0,Cl=_.querySelectorAll("Representation"),Vl=_.querySelector("SegmentTemplate"),Ol=(K=(se=_.querySelector("Role"))==null?void 0:se.getAttribute("value"))!=null?K:void 0,dt=zi,G={id:We,language:ia.language,isDefault:Ol==="main",label:ti,codecs:Gi,hdr:dt==="video"&&ts(Gi),mime:kt,representations:[]};for(let V of Cl){let Pe=(ye=V.getAttribute("lang"))!=null?ye:void 0,Rt=(Ie=(Te=ti!=null?ti:_.getAttribute("label"))!=null?Te:V.getAttribute("label"))!=null?Ie:void 0,ii=(At=(Et=(Oe=V.querySelector("BaseURL"))==null?void 0:Oe.textContent)==null?void 0:Et.trim())!=null?At:"",Ye=new URL(ii||o,e).toString(),Ae=(Ht=V.getAttribute("mimeType"))!=null?Ht:kt,ri=(ki=(ei=V.getAttribute("codecs"))!=null?ei:Gi)!=null?ki:"",si;if(zi==="text"){let ke=V.getAttribute("id")||"",ai=((ys=ia.privateuse)==null?void 0:ys.includes("x-auto"))||ke.includes("_auto"),Ke=V.querySelector("SegmentTemplate");if(Ke){let Lt={representationId:(Ts=V.getAttribute("id"))!=null?Ts:void 0,bandwidth:(Is=V.getAttribute("bandwidth"))!=null?Is:void 0},ni=parseInt((xs=V.getAttribute("bandwidth"))!=null?xs:"",10)/1e3,oi=(ws=parseInt((Es=Ke.getAttribute("startNumber"))!=null?Es:"",10))!=null?ws:1,pt=parseInt((Ps=Ke.getAttribute("timescale"))!=null?Ps:"",10),Qi=(As=Ke.querySelectorAll("SegmentTimeline S"))!=null?As:[],ht=Ke.getAttribute("media");if(!ht)continue;let ui=[],li=0,ci="",ft=0,Mt=oi,ee=0;for(let de of Qi){let Xe=parseInt((ks=de.getAttribute("d"))!=null?ks:"",10),ne=parseInt((Rs=de.getAttribute("r"))!=null?Rs:"",10)||0,Re=parseInt((Ls=de.getAttribute("t"))!=null?Ls:"",10);ee=Number.isFinite(Re)?Re:ee;let Je=Xe/pt*1e3,Le=ee/pt*1e3;for(let me=0;me<ne+1;me++){let Me=vi(ht,{...Lt,segmentNumber:Mt.toString(10),segmentTime:(ee+me*Xe).toString(10)}),mt=(Le!=null?Le:0)+me*Je,Bt=mt+Je;Mt++,ui.push({time:{from:mt,to:Bt},url:Me})}ee+=(ne+1)*Xe,li+=(ne+1)*Je}ft=ee/pt*1e3,ci=vi(ht,{...Lt,segmentNumber:Mt.toString(10),segmentTime:ee.toString(10)});let $t={time:{from:ft,to:1/0},url:ci},xe={type:"template",baseUrl:Ye,segmentTemplateUrl:ht,initUrl:"",totalSegmentsDurationMs:li,segments:ui,nextSegmentBeyondManifest:$t,timescale:pt};si={id:ke,kind:"text",segmentReference:xe,profiles:[],duration:S,bitrate:ni,mime:"",codecs:"",width:0,height:0,isAuto:ai}}else si={id:ke,isAuto:ai,kind:"text",url:Ye}}else{let ke=($s=(Ms=V.getAttribute("contentType"))!=null?Ms:Ae==null?void 0:Ae.split("/")[0])!=null?$s:zi,ai=(Ds=(Bs=_.getAttribute("profiles"))==null?void 0:Bs.split(","))!=null?Ds:[],Ke=parseInt((Cs=V.getAttribute("width"))!=null?Cs:"",10),Lt=parseInt((Vs=V.getAttribute("height"))!=null?Vs:"",10),ni=parseInt((Os=V.getAttribute("bandwidth"))!=null?Os:"",10)/1e3,oi=(_s=V.getAttribute("frameRate"))!=null?_s:"",pt=(Fs=V.getAttribute("quality"))!=null?Fs:void 0,Qi=oi?Vu(oi):void 0,ht=(Ns=V.getAttribute("id"))!=null?Ns:"id"+(E++).toString(10),ui=ke==="video"?`${Lt}p`:ke==="audio"?`${ni}Kbps`:ri,li=`${ht}@${ui}`,ci=[...O,...Dl,...ai],ft,Mt=V.querySelector("SegmentBase"),ee=(Us=V.querySelector("SegmentTemplate"))!=null?Us:Vl;if(Mt){let xe=(js=(qs=V.querySelector("SegmentBase Initialization"))==null?void 0:qs.getAttribute("range"))!=null?js:"",[de,Xe]=xe.split("-").map(Me=>parseInt(Me,10)),ne={from:de,to:Xe},Re=(Hs=V.querySelector("SegmentBase"))==null?void 0:Hs.getAttribute("indexRange"),[Je,Le]=Re?Re.split("-").map(Me=>parseInt(Me,10)):[],me=Re?{from:Je,to:Le}:void 0;ft={type:"byteRange",url:Ye,initRange:ne,indexRange:me}}else if(ee){let xe={representationId:(Gs=V.getAttribute("id"))!=null?Gs:void 0,bandwidth:(zs=V.getAttribute("bandwidth"))!=null?zs:void 0},de=parseInt((Qs=ee.getAttribute("timescale"))!=null?Qs:"",10),Xe=(Ws=ee.getAttribute("initialization"))!=null?Ws:"",ne=ee.getAttribute("media"),Re=(Ks=parseInt((Ys=ee.getAttribute("startNumber"))!=null?Ys:"",10))!=null?Ks:1,Je=vi(Xe,xe);if(!ne)throw new ReferenceError("No media attribute in SegmentTemplate");let Le=(Xs=ee.querySelectorAll("SegmentTimeline S"))!=null?Xs:[],me=[],Me=0,mt="",Bt=0;if(Le.length){let di=Re,pe=0;for(let bt of Le){let be=parseInt((Js=bt.getAttribute("d"))!=null?Js:"",10),Ze=parseInt((Zs=bt.getAttribute("r"))!=null?Zs:"",10)||0,pi=parseInt((ea=bt.getAttribute("t"))!=null?ea:"",10);pe=Number.isFinite(pi)?pi:pe;let Wi=be/de*1e3,Yi=pe/de*1e3;for(let hi=0;hi<Ze+1;hi++){let Fl=vi(ne,{...xe,segmentNumber:di.toString(10),segmentTime:(pe+hi*be).toString(10)}),ra=(Yi!=null?Yi:0)+hi*Wi,Nl=ra+Wi;di++,me.push({time:{from:ra,to:Nl},url:Fl})}pe+=(Ze+1)*be,Me+=(Ze+1)*Wi}Bt=pe/de*1e3,mt=vi(ne,{...xe,segmentNumber:di.toString(10),segmentTime:pe.toString(10)})}else if(tC(S)){let pe=parseInt((ta=ee.getAttribute("duration"))!=null?ta:"",10)/de*1e3,bt=Math.ceil(S/pe),be=0;for(let Ze=1;Ze<bt;Ze++){let pi=vi(ne,{...xe,segmentNumber:Ze.toString(10),segmentTime:be.toString(10)});me.push({time:{from:be,to:be+pe},url:pi}),be+=pe}Bt=be,mt=vi(ne,{...xe,segmentNumber:bt.toString(10),segmentTime:be.toString(10)})}let _l={time:{from:Bt,to:1/0},url:mt};ft={type:"template",baseUrl:Ye,segmentTemplateUrl:ne,initUrl:Je,totalSegmentsDurationMs:Me,segments:me,nextSegmentBeyondManifest:_l,timescale:de}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!ke||!Ae)continue;let $t={video:"video",audio:"audio",text:"text"}[ke];if(!$t)continue;dt||(dt=$t),si={id:li,kind:$t,segmentReference:ft,profiles:ci,duration:S,bitrate:ni,mime:Ae,codecs:ri,width:Ke,height:Lt,fps:Qi,quality:pt}}G.language||(G.language=Pe),G.label||(G.label=Rt),G.mime||(G.mime=Ae),G.codecs||(G.codecs=ri),G.hdr||(G.hdr=dt==="video"&&ts(ri)),G.representations.push(si)}if(dt){let V=r[dt].find(Pe=>Pe.id===G.id);if(V&&G.representations.every(Pe=>rt(Pe.segmentReference)))for(let Pe of V.representations){let Rt=G.representations.find(Ae=>Ae.id===Pe.id),ii=Rt==null?void 0:Rt.segmentReference,Ye=Pe.segmentReference;Ye.segments.push(...ii.segments),Ye.nextSegmentBeyondManifest=ii.nextSegmentBeyondManifest}else r[dt].push(G)}}return{duration:S,streams:r,baseUrls:n,live:g}};import{isNonNullable as FI}from"@vkontakte/videoplayer-shared/es2018";var j=(s,e)=>FI(s)&&FI(e)&&s.readyState==="open"&&iC(s,e);function iC(s,e){for(let t=0;t<s.activeSourceBuffers.length;++t)if(s.activeSourceBuffers[t]===e)return!0;return!1}var yn=class{constructor(e,t,i,{fetcher:r,tuning:a,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new hr(0);this.currentLowLatencySegmentLength$=new hr(0);this.currentSegmentLength$=new hr(0);this.onLastSegment$=new hr(!1);this.fullyBuffered$=new hr(!1);this.playingRepresentation$=new hr(void 0);this.playingRepresentationInit$=new hr(void 0);this.error$=new sC;this.gaps=[];this.subscription=new aC;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=Oi(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);lt(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new FT(this.sourceBuffer),this.subscription.add(wp(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:yi.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o!=null||(o={id:"SegmentEjection",category:yi.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),this.error$.next(o)})),this.subscription.add(wp(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:yi.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o||!j(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,Jr(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);lt(i,"No init buffer for starting representation"),lt(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=Oi(this.destroyAbortController.signal,async function*(e,t=!1){if(!j(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);lt(i,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if(ze(a)||ze(r)?yield this.loadInit(i,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),lt(r,"No segments for starting representation"),a=this.initData.get(e),!(!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer||!j(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();is(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=Oi(this.destroyAbortController.signal,async function*(e,t=!1){if(!j(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);lt(i,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if(ze(a)||ze(r)?yield this.loadInit(i,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),lt(r,"No segments for starting representation"),a=this.initData.get(e),!(!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer||!j(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();is(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=Oi(this.destroyAbortController.signal,async function*(e){var u,l;let t=(u=(0,Fu.default)(e,d=>d.representations))!=null?u:[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let d of this.representations.keys()){let c=t.find(f=>f.id===d);c&&this.representations.set(d,c);let h=this.representations.get(d);if(!h||!rt(h.segmentReference))return;let p=this.getActualLiveStartingSegments(h.segmentReference);this.segments.set(h.id,p)}let i=(l=this.switchingToRepresentationId)!=null?l:this.downloadingRepresentationId,r=this.representations.get(i);lt(r);let a=this.segments.get(i);lt(a,"No segments for starting representation");let n=this.initData.get(i);if(lt(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){!j(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new ae,Oi(this.switchAbortController.signal,async function*(i,r=!1){this.switchingToRepresentationId=i;let a=this.representations.get(i);lt(a,`No such representation ${i}`);let n=this.segments.get(i),o=this.initData.get(i);if(ze(o)||ze(n)?yield this.loadInit(a,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(i),lt(n,"No segments for starting representation"),o=this.initData.get(i),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer||!j(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();is(u)&&!this.isLive&&(this.bufferLimit=this.forwardBufferTarget,yield this.pruneBuffer(u,1/0,!0)),this.downloadingRepresentationId=i,this.switchingToRepresentationId=void 0}this.maintain()}}.bind(this))(e,t))}warmUpMediaSource(){!ze(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}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(ze(e)||ze(this.downloadingRepresentationId)||ze(this.playingRepresentationId)||ze(this.sourceBuffer)||!j(this.mediaSource,this.sourceBuffer)||is(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(lt(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;let r=i.find(d=>e>=d.time.from&&e<d.time.to);is(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)&&Jr(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,rs.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,rs.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;is(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,Fu.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,Fu.default)(e==null?void 0:e.streams[this.kind],o=>o.representations))!=null?i:[];if(![...this.segments.values()].every(o=>!o.length))for(let o of t){if(!o||!rt(o.segmentReference))return;let u=o.segmentReference.segments.map(p=>({...p,status:"none",size:void 0})),l=100,d=(r=this.segments.get(o.id))!=null?r:[],c=(n=(a=(0,rs.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;lt(e);let t=this.segments.get(e);if(t!=null&&t.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}updateLowLatencyLiveIfNeeded(e){var i;let t=0;for(let r of this.representations.values()){let a=r.segmentReference;if(!rt(a))return;let n=(i=this.segments.get(r.id))!=null?i:[],o=n.find(l=>Math.floor(l.time.from)===Math.floor(e.time.from));if(o&&!isFinite(o.time.to)&&(o.time.to=e.time.to,t=o.time.to-o.time.from),!!!n.find(l=>Math.floor(l.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let l=Math.round(e.time.to*a.timescale/1e3).toString(10),d=vi(a.segmentTemplateUrl,{segmentTime:l});n.push({status:"none",time:{from:e.time.to,to:1/0},url:d})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){var a,n,o;let t=(n=(a=this.switchingToRepresentationId)!=null?a:this.downloadingRepresentationId)!=null?n:this.playingRepresentationId;if(!t)return;let i=this.segments.get(t);if(!i)return;let r=i.find(u=>u.time.from<=e&&u.time.to>=e);return(o=r==null?void 0:r.time.from)!=null?o:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)==null||e.destroy(),this.gapDetectionIdleCallback&&Jt&&Jt(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&Jt&&Jt(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&&j(this.mediaSource,this.sourceBuffer)&&!(Ge(this.sourceBuffer.buffered,h)&&Ge(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"){rt(t.segmentReference)?await this.loadTemplateSegment(e[0],t,i):await this.loadByteRangeSegments(e,t,i)}async loadTemplateSegment(e,t,i="auto"){e.status="downloading";let r={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(r);let{range:a,url:n,signal:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await Oi(o,async function*(){let d=Pp(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=Ou(),!d)return;let c=new DataView(d),h=Sn(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]),vn(d)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}updateRepresentationsBaseUrlIfNeeded(){if(!this.tuning.dash.enableBaseUrlSupport||!this.baseUrls.length||this.failedDownloads<=this.tuning.dash.maxSegmentRetryCount)return;this.baseUrlsIndex=(this.baseUrlsIndex+1)%this.baseUrls.length;let e=this.baseUrls[this.baseUrlsIndex];for(let t of this.representations.values())rt(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}async loadByteRangeSegments(e,t,i="auto"){if(!e.length)return;for(let u of e)u.status="downloading",this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:r,url:a,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(await Oi(n,async function*(){let u=Pp(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),wp(window,"online").pipe(rC()).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=Ou(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),vn(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(rt(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:(0,rs.default)(e,0).byte.from,to:(0,rs.default)(e,-1).byte.to},{signal:a}=this.downloadAbortController;return{url:i,range:r,signal:a,onProgress:async(o,u)=>{if(!a.aborted)try{this.lastDataObtainedTimestampMs=Ou(),await this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:a,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:yi.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!rt(t.segmentReference))throw new Error("Representation is not template type");let i=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&i.searchParams.set("low-latency","yes");let r=i.toString(),{signal:a}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,d)=>{if(!a.aborted)try{this.lastDataObtainedTimestampMs=Ou();let c=this.onSomeTemplateDataLoaded({dataView:l,loaded:d,signal:a,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(c)}catch(c){this.error$.next({id:"SegmentFeeding",category:yi.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}}:void 0;return{url:r,signal:a,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,_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||!j(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=Sn(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||!j(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=Sn(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(!(ze(this.sourceBuffer)||!j(this.mediaSource,this.sourceBuffer))){!this.isLive&&q.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(Ge(this.sourceBuffer.buffered,e.segment.time.from,100)&&Ge(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:yi.VIDEO_PIPELINE,message:"Browser stuck on empty result of adding segment to source buffer"})),this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",Tp(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=Xr(()=>(0,NI.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?Oi(this.destroyAbortController.signal,async function*(){let o=Pp(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,Sn(e.mime),r)).then(async o=>{if(!o)return;let{init:u,dataView:l,segments:d}=o,c=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,c);let h=d;this.isLive&&rt(e.segmentReference)&&(h=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,h),u&&this.parsedInitData.set(e.id,u)}).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:yi.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n}async dropBuffer(){for(let e of this.segments.values())for(let t of e)t.status="none";await this.pruneBuffer(0,1/0,!0)}async pruneBuffer(e,t,i=!1){if(!this.sourceBuffer||!j(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||ze(e))return!1;let r=[],a=0,n=u=>{u.sort((d,c)=>d.from-c.from);let l=[u[0]];for(let d=1;d<u.length;d++){let{from:c,to:h}=u[d],p=l[l.length-1];p.to>=c?p.to=Math.max(p.to,h):l.push(u[d])}return l},o=u=>{var d;if(a>=t)return r;r.push({...u.time}),r=n(r);let l=Tp(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||!j(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||!j(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||!j(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||ze(e)?0:De(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!(!this.sourceBuffer||!j(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||!j(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=Xr(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:yi.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if(ze(this.sourceBuffer)||!j(this.mediaSource,this.sourceBuffer)||ze(this.playingRepresentationId))return;let e=[];for(let i=0;i<this.sourceBuffer.buffered.length;i++){let r=Math.floor(this.sourceBuffer.buffered.start(i)*1e3),a=Math.ceil(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:r,to:a})}let t=100;for(let i of this.segments.values())for(let r of i){let{status:a}=r;if(a!=="fed"&&a!=="partially_ejected")continue;let n=Math.floor(r.time.from),o=Math.ceil(r.time.to),u=e.some(d=>d.from-t<=n&&d.to+t>=o),l=e.filter(d=>n>=d.from&&n<d.to-t||o>d.from+t&&o<=d.to);u||(l.length===1?r.status="partially_ejected":this.gaps.some(d=>d.from===r.time.from||d.to===r.time.to)?r.status="partially_ejected":r.status="none")}}handleAsyncError(e,t){this.error$.next({id:t,category:yi.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}};var _i=s=>{let e=new URL(s);return e.searchParams.set("quic","1"),e.toString()};var Nu=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 Tn,assertNever as UI,fromEvent as qI,merge as nC,now as In,Subscription as oC,Subject as jI,ValueSubject as Ap,flattenObject as ss,ErrorCategory as xn}from"@vkontakte/videoplayer-shared/es2018";var Uu=s=>{let e=new URL(s);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var as=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:a=!1}){this.lastConnectionType$=new Ap(void 0);this.lastConnectionReused$=new Ap(void 0);this.lastRequestFirstBytes$=new Ap(void 0);this.recoverableError$=new jI;this.error$=new jI;this.abortAllController=new ae;this.subscription=new oC;this.fetchManifest=Tn(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=_i(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=Uu(i));let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(qu);return r?(t.log("success",ss({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(r.headers),r.text()):(t.error("error",ss({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=Tn(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 L=new URL(l,location.href);L.searchParams.append("bytes",`${i.from}-${i.to}`),l=L.toString();break}default:UI(t)}this.requestQuic&&(l=_i(l));let h=this.abortAllController.signal,p;if(n){let L=new ae;if(p=nC(qI(this.abortAllController.signal,"abort"),qI(n,"abort")).subscribe(()=>{try{L.abort()}catch(Q){qu(Q)}}),this.subscription.add(p),this.abortAllController.signal.aborted||n.aborted)try{L.abort()}catch(Q){qu(Q)}h=L.signal}let f=In();c.log("startRequest",ss({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=In();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 L=`Fetch error ${m.status}: ${m.statusText}`;return c.error("error",{message:L}),c.end(),Promise.reject(new Error(`Fetch error ${m.status}: ${m.statusText}`))}if(this.onHeadersReceived(m.headers),!r&&!o){p==null||p.unsubscribe();let L=In(),Q={requestStartedAt:f,requestEndedAt:L,duration:L-f};return c.log("endRequest",ss(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=L=>{p==null||p.unsubscribe(),E=!0,qu(L)},$=Tn(h,async function*({done:L,value:Q}){if(I===0&&this.lastRequestFirstBytes$.next(In()-f),h.aborted){p==null||p.unsubscribe();return}if(!L&&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($,O)}}.bind(this));yield y==null?void 0:y.read().then($,O),p==null||p.unsubscribe();let w=In(),A={failed:E,requestStartedAt:f,requestEndedAt:w,duration:w-f};return E?(c.error("endRequest",ss(A)),c.end(),null):(c.log("endRequest",ss(A)),c.end(),T.buffer)}.bind(this));this.fetchByteRangeRepresentation=Tn(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=Tn(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}=Nu(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:UI(r)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}async doFetch(e,t){let i=await Pt(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:xn.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:xn.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:xn.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:xn.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${a})`,category:xn.FATAL})}}},qu=s=>{if(!vn(s))throw s};var Ti=(s,e,t)=>t*e+(1-t)*s,kp=(s,e)=>s.reduce((t,i)=>t+i,0)/e,HI=(s,e,t,i)=>{let r=0,a=t,n=kp(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 uC,ValueSubject as GI}from"@vkontakte/videoplayer-shared/es2018";var Fi=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 GI(e.initial),this.debounced$=new GI(e.initial);let t=(i=e.label)!=null?i:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new tt(`raw_${t}`),this.smoothedSeries$=new tt(`smoothed_${t}`),this.reportedSeries$=new tt(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,i=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=(this.pastMeasures[o]-this.smoothed)**2,i++);this.takenMeasures=i,t/=i;let r=Math.sqrt(t),a=this.smoothed+this.params.deviationFactor*r,n=this.smoothed-this.params.deviationFactor*r;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>a||this.smoothed<n)&&(uC(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 ju=class extends Fi{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=Ti(this.slow,e,this.params.emaAlphaSlow),this.fast=Ti(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var Hu=class extends Fi{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=kp(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Ti(this.emaSmoothed,e,this.params.emaAlpha);let i=HI(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}};var Gu=class extends Fi{constructor(t){super(t);this.furtherValues=[];this.currentTopExtremumValue=0;this.extremumInterval=t.extremumInterval}next(t){this.currentTopExtremumValue<=t?(this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.length===this.extremumInterval?(super.next(this.currentTopExtremumValue),this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.push(t)}updateSmoothedValue(t){this.smoothed=this.smoothed?Ti(this.smoothed,t,this.params.emaAlpha):t}};var Ii=class{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new ju({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new Hu({initial:e,emaAlpha:i.emaAlpha,basisTrendChangeCount:i.basisTrendChangeCount,changeThreshold:i.changeThreshold,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"})}static getLiveBufferSmoothedValue(e,t){return new Gu({initial:e,label:"liveEdgeDelay",...t})}};var ns=(s,e)=>{s&&s.playbackRate!==e&&(s.playbackRate=e)};import{isNullable as lC,ValueSubject as cC}from"@vkontakte/videoplayer-shared/es2018";var En=class s{constructor(e,t){this.currentRepresentation$=new cC(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(!lC(e))for(let i of this.representations)for(let r of i){let a=r.segmentReference,n=a.segments.length,o=a.segments[0].time.from,u=a.segments[n-1].time.to;if(e<o||e>u)continue;let l=a.segments.find(d=>d.time.from<=e&&d.time.to>=e);!l||((t=this.currentSegment)==null?void 0:t.time.from)===l.time.from&&this.currentSegment.time.to===l.time.to||(this.currentSegment=l,this.currentRepresentation$.next({...r,label:"Live Text",language:"ru",isAuto:!0,url:new URL(l.url,a.baseUrl).toString()}))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e!=null?e:[]){let i=s.filterRepresentations(t.representations);if(i){this.representations[this.representationsCursor]=i,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!(e!=null&&e.some(t=>s.filterRepresentations(t.representations)))}static filterRepresentations(e){return e==null?void 0:e.filter(t=>t.kind==="text"&&"segmentReference"in t&&rt(t.segmentReference))}};var Qu=N(_t(),1);import{assertNever as Wu}from"@vkontakte/videoplayer-shared/es2018";var zI=(s,{useHlsJs:e,useManagedMediaSource:t,useOldMSEDetection:i})=>{let{containers:r,protocols:a,codecs:n,nativeHlsSupported:o}=q.video,u=(n.h264||n.h265)&&n.aac,l=a.mse&&(!i||!!window.MediaStreamTrack)||a.mms&&t;return s.filter(d=>{switch(d){case"DASH_SEP":return l&&r.mp4&&u;case"DASH_WEBM":return l&&r.webm&&n.vp9&&n.opus;case"DASH_WEBM_AV1":return l&&r.webm&&n.av1&&n.opus;case"DASH_STREAMS":return l&&(r.mp4&&u||r.webm&&(n.vp9||n.av1)&&(n.opus||n.aac));case"DASH_LIVE":return l&&r.mp4&&u;case"DASH_LIVE_CMAF":return l&&r.mp4&&u&&r.cmaf;case"DASH_ONDEMAND":return l&&r.mp4&&u;case"HLS":case"HLS_ONDEMAND":return o||e&&l&&r.mp4&&u;case"HLS_LIVE":case"HLS_LIVE_CMAF":return o;case"MPEG":return r.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return a.webrtc&&a.ws&&n.h264&&(r.mp4||r.webm);default:return Wu(d)}})},zu=s=>{let{webmDecodingInfo:e}=q.video,t="DASH_WEBM",i="DASH_WEBM_AV1";switch(s){case"vp9":return[t,i];case"av1":return[i,t];case"none":return[];case"smooth":return e?e[i].smooth?[i,t]:e[t].smooth?[t,i]:[i,t]:[t,i];case"power_efficient":return e?e[i].powerEfficient?[i,t]:e[t].powerEfficient?[t,i]:[i,t]:[t,i];default:Wu(s)}return[t,i]},QI=({webmCodec:s,androidPreferredFormat:e,preferMultiStream:t})=>{let i=[...t?["DASH_STREAMS"]:[],...zu(s),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],r=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(q.device.isAndroid)switch(e){case"mpeg":return["MPEG",...i,"HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...i,"MPEG"];case"dash":return[...i,"HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return[...r,"MPEG",...zu(s),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...zu(s),"MPEG",...r,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...zu(s),...r,"HLS","HLS_ONDEMAND"];default:Wu(e)}return q.video.nativeHlsSupported?[...i,"HLS","HLS_ONDEMAND","MPEG"]:[...i,"HLS","HLS_ONDEMAND","MPEG"]},WI=({androidPreferredFormat:s,preferCMAF:e,preferWebRTC:t})=>{let i=e?["DASH_LIVE_CMAF","DASH_LIVE"]:["DASH_LIVE","DASH_LIVE_CMAF"],r=e?["HLS_LIVE_CMAF","HLS_LIVE"]:["HLS_LIVE","HLS_LIVE_CMAF"],a=[...i,...r],n=[...r,...i],o,u=q.device.isMac&&q.browser.isSafari;if(q.device.isAndroid)switch(s){case"dash":case"dash_any_mpeg":case"dash_any_webm":case"dash_sep":{o=a;break}case"hls":case"mpeg":{o=n;break}default:Wu(s)}else q.video.nativeHlsSupported&&!u?o=n:u?o=e?["DASH_LIVE_CMAF","HLS_LIVE_CMAF","HLS_LIVE","DASH_LIVE"]:["HLS_LIVE","DASH_LIVE","DASH_LIVE_CMAF","HLS_LIVE_CMAF"]:o=a;return t?["WEB_RTC_LIVE",...o]:[...o,"WEB_RTC_LIVE"]},Rp=s=>s?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],Yu=s=>{if(s.size===0)return;if(s.size===1){let t=s.values().next();return(0,Qu.default)(t.value.split("."),0)}for(let t of s){let i=(0,Qu.default)(t.split("."),0);if(i==="opus"||i==="vp09"||i==="av01")return i}let e=s.values().next();return(0,Qu.default)(e.value.split("."),0)};var SC=["timeupdate","progress","play","seeked","stalled","waiting"],vC=["timeupdate","progress","loadeddata","playing","seeked"];var Ju=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new XI;this.representationSubscription=new XI;this.state$=new H("none");this.currentVideoRepresentation$=new he(void 0);this.currentVideoRepresentationInit$=new he(void 0);this.currentAudioRepresentation$=new he(void 0);this.currentVideoSegmentLength$=new he(0);this.currentAudioSegmentLength$=new he(0);this.error$=new Xu;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 Xu;this.fetcherError$=new Xu;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new Xu;this.gapWatchdogActive=!1;this.destroyController=new ae;this.initManifest=Mp(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:Nt.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=Mp(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:Nt.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=Cu(e))!=null?n:{id:"ManifestParsing",category:Nt.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=It())==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=Yu(c);if(h&&(r[u]=d.filter(({codecs:p})=>p.startsWith(h))),u==="video"){let p=this.tuning.preferHDR,f=r.video.some(g=>g.hdr),m=r.video.some(g=>!g.hdr);q.display.isHDR&&p&&f?r.video=r.video.filter(g=>g.hdr):m&&(r.video=r.video.filter(g=>!g.hdr))}}let a={...t,streams:r};return this.tracer.log("updateManifestEnd",Pn(a)),a}.bind(this));this.initRepresentations=Mp(this.destroyController.signal,async function*(e,t,i){var h;this.tracer.log("initRepresentationsStart",Pn({initialVideo:e,initialAudio:t,sourceHls:i})),os(this.manifest),os(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let r=p=>{this.representationSubscription.add(xi(p,"error").pipe(Ku(f=>{var m;return!!((m=this.element)!=null&&m.played.length)})).subscribe(f=>{this.error$.next({id:"VideoSource",category:Nt.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:f})}))};this.source=this.tuning.useManagedMediaSource?du():new MediaSource;let a=document.createElement("source");if(r(a),a.src=URL.createObjectURL(this.source),this.element.appendChild(a),this.tuning.useManagedMediaSource&&jr())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 yn("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],An(t)){let p=this.manifest.streams.audio.reduce((f,m)=>[...f,...m.representations],[]);this.audioBufferManager=new yn("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}En.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new En(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(fr(...vC.map(p=>xi(this.element,p))).pipe(ls(p=>this.element?De(this.element.buffered,this.element.currentTime*1e3):0),wn(),bC(p=>{p>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add(fr(xi(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe(wn()).subscribe(f=>this.liveStreamEndTimestamp=Bp())),this.subscription.add(xi(this.element,"pause").subscribe(()=>{this.livePauseWatchdogSubscription=$p(1e3).subscribe(f=>{let m=$i(this.manifestUrlString,2);this.manifestUrlString=Se(this.manifestUrlString,m+1e3,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add(xi(this.element,"play").subscribe(f=>{var m;return(m=this.livePauseWatchdogSubscription)==null?void 0:m.unsubscribe()})),this.representationSubscription.add(us({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(ls(({isActiveLive:f,isLowLatency:m})=>f&&m),wn()).subscribe(f=>{this.isManualDecreasePlaybackInLive()||ns(this.element,1)})),this.representationSubscription.add(us({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(Ku(({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(us({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(Ku(({isLive:f})=>f),wn((f,m)=>m.bufferLength<f.bufferLength),ls(({rtt:f,bufferLength:m,segmentServerLatency:g})=>{let S=$i(this.manifestUrlString,2);return(f/2+m+g+S)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(us({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),ns(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(us({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(gC(1e3)).subscribe(async({liveLoadBufferLength:f,bufferLength:m})=>{if(!this.element||this.isUpdatingLive)return;let g=this.element.playbackRate,S=$i(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(),$=v<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next($);let w="none";if(O?w="active_low_latency":this.isLowLatency$.getValue()&&$?(this.bufferManagers.forEach(A=>A.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 A=p-(y+I),C=this.normolizeLiveOffset(Math.trunc(S+A/g)),M=Math.abs(C-S),L=0;!f||M<=this.tuning.dashCmafLive.offsetCalculationError?L=S:C>0&&M>this.tuning.dashCmafLive.offsetCalculationError&&(L=C),this.manifestUrlString=Se(this.manifestUrlString,L,2)}(w==="live_with_target_offset"||w==="live_forward_buffering")&&(p=0,await this.updateLive())},f=>{this.error$.next({id:"updateLive",category:Nt.VIDEO_PIPELINE,thrown:f,message:"Failed to update live with subscription"})}))}let l=fr(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe(ls(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),d=fr(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe(ls(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue()))),c=us({allBuffersFull:l,someBufferEnded:d}).pipe(wn(),ls(({allBuffersFull:p,someBufferEnded:f})=>p&&f),Ku(p=>p));if(this.representationSubscription.add(fr(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:Nt.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:f})}})),this.representationSubscription.add(fr(...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:Nt.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,Dp.default)((0,Dp.default)([...this.manifest.streams.audio,...this.manifest.streams.video],f=>f.representations),f=>{let m=[];return f.duration&&m.push(f.duration),rt(f.segmentReference)&&f.segmentReference.totalSegmentsDurationMs&&m.push(f.segmentReference.totalSegmentsDurationMs),m})];this.source.duration=Math.max(...p)/1e3}this.audioBufferManager&&An(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=$p(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),n=>{this.error$.next({id:"GapWatchdog",category:Nt.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 as({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.subscription.add(this.fetcher.recoverableError$.subscribe(this.fetcherRecoverableError$)),this.subscription.add(this.fetcher.error$.subscribe(this.fetcherError$)),this.liveBuffer=Ii.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator}),this.initTracerSubscription()}async seekLive(e){var r,a,n;os(this.element);let t=this.liveStreamStatus$.getValue()!=="active"?Bp()-this.liveStreamEndTimestamp:0,i=this.normolizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=Se(this.manifestUrlString,i,2),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await((r=this.videoBufferManager)==null?void 0:r.seekLive(this.manifest.streams.video)),await((a=this.audioBufferManager)==null?void 0:a.seekLive(this.manifest.streams.audio)),(n=this.liveTextManager)==null||n.seekLive(this.manifest.streams.text))}initBuffer(){os(this.element),this.state$.setState("running"),this.subscription.add(fr(...SC.map(e=>xi(this.element,e)),xi(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:Nt.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(xi(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(xi(this.element,"waiting").subscribe(()=>{var t;this.element&&this.element.readyState===2&&!this.element.seeking&&Ge(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=Bp(),n=100,o=(m=(f=this.videoBufferManager)==null?void 0:f.lastDataObtainedTimestamp)!=null?m:0;this.videoLastDataObtainedTimestamp$.next(o);let u=(S=(g=this.audioBufferManager)==null?void 0:g.lastDataObtainedTimestamp)!=null?S:0,l=(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 $=this.normolizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive($).catch(w=>{this.error$.next({id:"stallIntervalCallback",category:Nt.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:w})}),r.liveLastOffset=$}else{let $=this.element.currentTime*1e3;(E=this.videoBufferManager)==null||E.maintain($),(O=this.audioBufferManager)==null||O.maintain($),r.position=$}this.tracer.log("stallIntervalCallback",Pn(r))};(t=this.stallWatchdogSubscription)==null||t.unsubscribe(),this.stallWatchdogSubscription=$p(50).subscribe(e,i=>{this.error$.next({id:"StallWatchdogCallback",category:Nt.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;os(this.element),os(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),Ge(this.element.buffered,i)||await Promise.all([this.videoBufferManager.abort(),(o=this.audioBufferManager)==null?void 0:o.abort()]),!(KI(this.element)||KI(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),(u=this.audioBufferManager)==null||u.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",Pn({requestedPosition:e,forcePrecise:t,position:i})))}warmUpMediaSourceIfNeeded(e=(t=>(t=this.element)==null?void 0:t.currentTime)()){var i;An(this.element)&&An(this.source)&&An(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=mC(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",Pn(i)))}}};var Zu=class{constructor(e,t){this.fov=e,this.orientation=t}};var el=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 ZI=`attribute vec2 a_vertex;
124
+ `})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(d,"i")}var vp=N(_t(),1);import{videoSizeToQuality as eC}from"@vkontakte/videoplayer-shared/es2018";var LI=({id:s,width:e,height:t,bitrate:i,fps:r,quality:a,streamId:n})=>{var u;let o=(u=a?Kt(a):void 0)!=null?u:eC({width:e,height:t});return o&&{id:s,quality:o,bitrate:i,size:{width:e,height:t},fps:r,streamId:n}},MI=({id:s,bitrate:e})=>({id:s,bitrate:e}),$I=({language:s,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:s,label:e}),BI=({language:s,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:s,label:e}),yp=({id:s,language:e,label:t,codecs:i,isDefault:r})=>({id:s,language:e,label:t,codec:(0,vp.default)(i.split("."),0),isDefault:r}),Tp=({id:s,language:e,label:t,hdr:i,codecs:r})=>({id:s,language:e,hdr:i,label:t,codec:(0,vp.default)(r.split("."),0)}),Ip=s=>"url"in s,it=s=>s.type==="template",Sn=s=>s instanceof DOMException&&(s.name==="AbortError"||s.code===20);var CI=s=>{if(!(s!=null&&s.startsWith("P")))return;let e=(n,o)=>{let u=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(u)?0:u)*o},i=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(s),r=(i==null?void 0:i[1])==="-"?-1:1,a={days:e(i==null?void 0:i[5],r),hours:e(i==null?void 0:i[6],r),minutes:e(i==null?void 0:i[7],r),seconds:e(i==null?void 0:i[8],r)};return a.days*24*60*60*1e3+a.hours*60*60*1e3+a.minutes*60*1e3+a.seconds*1e3},vi=(s,e)=>{let t=s;t=(0,xp.default)(t,"$$","$");let i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[r,a]of(0,VI.default)(i)){let n=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=(0,xp.default)(t,n,(o,u)=>DI(a)?o:DI(u)?a:(0,OI.default)(a,parseInt(u,10),"0"))}return t},FI=(s,e)=>{var w,A,C,M,L,Q,U,P,F,k,x,B,oe,Ce,se,K,ye,Te,Ie,Ve,Et,At,Ht,ei,ki,vs,ys,Ts,Is,xs,Es,ws,Ps,As,ks,Rs,Ls,Ms,$s,Bs,Ds,Cs,Vs,Os,_s,Fs,Ns,Us,qs,js,Hs,Gs,zs,Qs,Ws,Ys,Ks,Xs,Js,Zs,ea;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 _,Qe;return(Qe=(_=ce.textContent)==null?void 0:_.trim())!=null?Qe:""}),o=(w=(0,_I.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=CI(v):(0,Ep.default)(T).filter(ce=>ce).length&&!u?S=(0,Ep.default)(T).reduce((ce,_)=>{var Qe;return ce+((Qe=CI(_))!=null?Qe:0)},0):m&&(S=parseInt(m,10));let E=0,O=(C=(A=a.getAttribute("profiles"))==null?void 0:A.split(","))!=null?C:[];for(let ce of y.map(_=>_.id))for(let _ of I[ce]){let Qe=(M=_.getAttribute("id"))!=null?M:"id"+(E++).toString(10),kt=(L=_.getAttribute("mimeType"))!=null?L:"",Gi=(Q=_.getAttribute("codecs"))!=null?Q:"",zi=(U=_.getAttribute("contentType"))!=null?U:kt==null?void 0:kt.split("/")[0],Cl=(F=(P=_.getAttribute("profiles"))==null?void 0:P.split(","))!=null?F:[],ta=(x=RI((k=_.getAttribute("lang"))!=null?k:""))!=null?x:{},ti=(Ce=(oe=(B=_.querySelector("Label"))==null?void 0:B.textContent)==null?void 0:oe.trim())!=null?Ce:void 0,Vl=_.querySelectorAll("Representation"),Ol=_.querySelector("SegmentTemplate"),_l=(K=(se=_.querySelector("Role"))==null?void 0:se.getAttribute("value"))!=null?K:void 0,ct=zi,G={id:Qe,language:ta.language,isDefault:_l==="main",label:ti,codecs:Gi,hdr:ct==="video"&&ts(Gi),mime:kt,representations:[]};for(let V of Vl){let Pe=(ye=V.getAttribute("lang"))!=null?ye:void 0,Rt=(Ie=(Te=ti!=null?ti:_.getAttribute("label"))!=null?Te:V.getAttribute("label"))!=null?Ie:void 0,ii=(At=(Et=(Ve=V.querySelector("BaseURL"))==null?void 0:Ve.textContent)==null?void 0:Et.trim())!=null?At:"",We=new URL(ii||o,e).toString(),Ae=(Ht=V.getAttribute("mimeType"))!=null?Ht:kt,ri=(ki=(ei=V.getAttribute("codecs"))!=null?ei:Gi)!=null?ki:"",si;if(zi==="text"){let ke=V.getAttribute("id")||"",ai=((vs=ta.privateuse)==null?void 0:vs.includes("x-auto"))||ke.includes("_auto"),Ye=V.querySelector("SegmentTemplate");if(Ye){let Lt={representationId:(ys=V.getAttribute("id"))!=null?ys:void 0,bandwidth:(Ts=V.getAttribute("bandwidth"))!=null?Ts:void 0},ni=parseInt((Is=V.getAttribute("bandwidth"))!=null?Is:"",10)/1e3,oi=(Es=parseInt((xs=Ye.getAttribute("startNumber"))!=null?xs:"",10))!=null?Es:1,dt=parseInt((ws=Ye.getAttribute("timescale"))!=null?ws:"",10),Qi=(Ps=Ye.querySelectorAll("SegmentTimeline S"))!=null?Ps:[],pt=Ye.getAttribute("media");if(!pt)continue;let ui=[],li=0,ci="",ht=0,Mt=oi,ee=0;for(let de of Qi){let Ke=parseInt((As=de.getAttribute("d"))!=null?As:"",10),ne=parseInt((ks=de.getAttribute("r"))!=null?ks:"",10)||0,Re=parseInt((Rs=de.getAttribute("t"))!=null?Rs:"",10);ee=Number.isFinite(Re)?Re:ee;let Xe=Ke/dt*1e3,Le=ee/dt*1e3;for(let me=0;me<ne+1;me++){let Me=vi(pt,{...Lt,segmentNumber:Mt.toString(10),segmentTime:(ee+me*Ke).toString(10)}),ft=(Le!=null?Le:0)+me*Xe,Bt=ft+Xe;Mt++,ui.push({time:{from:ft,to:Bt},url:Me})}ee+=(ne+1)*Ke,li+=(ne+1)*Xe}ht=ee/dt*1e3,ci=vi(pt,{...Lt,segmentNumber:Mt.toString(10),segmentTime:ee.toString(10)});let $t={time:{from:ht,to:1/0},url:ci},xe={type:"template",baseUrl:We,segmentTemplateUrl:pt,initUrl:"",totalSegmentsDurationMs:li,segments:ui,nextSegmentBeyondManifest:$t,timescale:dt};si={id:ke,kind:"text",segmentReference:xe,profiles:[],duration:S,bitrate:ni,mime:"",codecs:"",width:0,height:0,isAuto:ai}}else si={id:ke,isAuto:ai,kind:"text",url:We}}else{let ke=(Ms=(Ls=V.getAttribute("contentType"))!=null?Ls:Ae==null?void 0:Ae.split("/")[0])!=null?Ms:zi,ai=(Bs=($s=_.getAttribute("profiles"))==null?void 0:$s.split(","))!=null?Bs:[],Ye=parseInt((Ds=V.getAttribute("width"))!=null?Ds:"",10),Lt=parseInt((Cs=V.getAttribute("height"))!=null?Cs:"",10),ni=parseInt((Vs=V.getAttribute("bandwidth"))!=null?Vs:"",10)/1e3,oi=(Os=V.getAttribute("frameRate"))!=null?Os:"",dt=(_s=V.getAttribute("quality"))!=null?_s:void 0,Qi=oi?Cu(oi):void 0,pt=(Fs=V.getAttribute("id"))!=null?Fs:"id"+(E++).toString(10),ui=ke==="video"?`${Lt}p`:ke==="audio"?`${ni}Kbps`:ri,li=`${pt}@${ui}`,ci=[...O,...Cl,...ai],ht,Mt=V.querySelector("SegmentBase"),ee=(Ns=V.querySelector("SegmentTemplate"))!=null?Ns:Ol;if(Mt){let xe=(qs=(Us=V.querySelector("SegmentBase Initialization"))==null?void 0:Us.getAttribute("range"))!=null?qs:"",[de,Ke]=xe.split("-").map(Me=>parseInt(Me,10)),ne={from:de,to:Ke},Re=(js=V.querySelector("SegmentBase"))==null?void 0:js.getAttribute("indexRange"),[Xe,Le]=Re?Re.split("-").map(Me=>parseInt(Me,10)):[],me=Re?{from:Xe,to:Le}:void 0;ht={type:"byteRange",url:We,initRange:ne,indexRange:me}}else if(ee){let xe={representationId:(Hs=V.getAttribute("id"))!=null?Hs:void 0,bandwidth:(Gs=V.getAttribute("bandwidth"))!=null?Gs:void 0},de=parseInt((zs=ee.getAttribute("timescale"))!=null?zs:"",10),Ke=(Qs=ee.getAttribute("initialization"))!=null?Qs:"",ne=ee.getAttribute("media"),Re=(Ys=parseInt((Ws=ee.getAttribute("startNumber"))!=null?Ws:"",10))!=null?Ys:1,Xe=vi(Ke,xe);if(!ne)throw new ReferenceError("No media attribute in SegmentTemplate");let Le=(Ks=ee.querySelectorAll("SegmentTimeline S"))!=null?Ks:[],me=[],Me=0,ft="",Bt=0;if(Le.length){let di=Re,pe=0;for(let mt of Le){let be=parseInt((Xs=mt.getAttribute("d"))!=null?Xs:"",10),Je=parseInt((Js=mt.getAttribute("r"))!=null?Js:"",10)||0,pi=parseInt((Zs=mt.getAttribute("t"))!=null?Zs:"",10);pe=Number.isFinite(pi)?pi:pe;let Wi=be/de*1e3,Yi=pe/de*1e3;for(let hi=0;hi<Je+1;hi++){let Nl=vi(ne,{...xe,segmentNumber:di.toString(10),segmentTime:(pe+hi*be).toString(10)}),ia=(Yi!=null?Yi:0)+hi*Wi,Ul=ia+Wi;di++,me.push({time:{from:ia,to:Ul},url:Nl})}pe+=(Je+1)*be,Me+=(Je+1)*Wi}Bt=pe/de*1e3,ft=vi(ne,{...xe,segmentNumber:di.toString(10),segmentTime:pe.toString(10)})}else if(tC(S)){let pe=parseInt((ea=ee.getAttribute("duration"))!=null?ea:"",10)/de*1e3,mt=Math.ceil(S/pe),be=0;for(let Je=1;Je<mt;Je++){let pi=vi(ne,{...xe,segmentNumber:Je.toString(10),segmentTime:be.toString(10)});me.push({time:{from:be,to:be+pe},url:pi}),be+=pe}Bt=be,ft=vi(ne,{...xe,segmentNumber:mt.toString(10),segmentTime:be.toString(10)})}let Fl={time:{from:Bt,to:1/0},url:ft};ht={type:"template",baseUrl:We,segmentTemplateUrl:ne,initUrl:Xe,totalSegmentsDurationMs:Me,segments:me,nextSegmentBeyondManifest:Fl,timescale:de}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!ke||!Ae)continue;let $t={video:"video",audio:"audio",text:"text"}[ke];if(!$t)continue;ct||(ct=$t),si={id:li,kind:$t,segmentReference:ht,profiles:ci,duration:S,bitrate:ni,mime:Ae,codecs:ri,width:Ye,height:Lt,fps:Qi,quality:dt}}G.language||(G.language=Pe),G.label||(G.label=Rt),G.mime||(G.mime=Ae),G.codecs||(G.codecs=ri),G.hdr||(G.hdr=ct==="video"&&ts(ri)),G.representations.push(si)}if(ct){let V=r[ct].find(Pe=>Pe.id===G.id);if(V&&G.representations.every(Pe=>it(Pe.segmentReference)))for(let Pe of V.representations){let Rt=G.representations.find(Ae=>Ae.id===Pe.id),ii=Rt==null?void 0:Rt.segmentReference,We=Pe.segmentReference;We.segments.push(...ii.segments),We.nextSegmentBeyondManifest=ii.nextSegmentBeyondManifest}else r[ct].push(G)}}return{duration:S,streams:r,baseUrls:n,live:g}};import{isNonNullable as NI}from"@vkontakte/videoplayer-shared/es2018";var j=(s,e)=>NI(s)&&NI(e)&&s.readyState==="open"&&iC(s,e);function iC(s,e){for(let t=0;t<s.activeSourceBuffers.length;++t)if(s.activeSourceBuffers[t]===e)return!0;return!1}var vn=class{constructor(e,t,i,{fetcher:r,tuning:a,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new hr(0);this.currentLowLatencySegmentLength$=new hr(0);this.currentSegmentLength$=new hr(0);this.onLastSegment$=new hr(!1);this.fullyBuffered$=new hr(!1);this.playingRepresentation$=new hr(void 0);this.playingRepresentationInit$=new hr(void 0);this.error$=new sC;this.gaps=[];this.subscription=new aC;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=Oi(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);ut(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new NT(this.sourceBuffer),this.subscription.add(Pp(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:yi.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o!=null||(o={id:"SegmentEjection",category:yi.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),this.error$.next(o)})),this.subscription.add(Pp(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:yi.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o||!j(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,Jr(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);ut(i,"No init buffer for starting representation"),ut(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=Oi(this.destroyAbortController.signal,async function*(e,t=!1){if(!j(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);ut(i,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if(Ge(a)||Ge(r)?yield this.loadInit(i,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),ut(r,"No segments for starting representation"),a=this.initData.get(e),!(!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer||!j(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();is(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=Oi(this.destroyAbortController.signal,async function*(e,t=!1){if(!j(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);ut(i,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if(Ge(a)||Ge(r)?yield this.loadInit(i,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),ut(r,"No segments for starting representation"),a=this.initData.get(e),!(!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer||!j(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();is(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=Oi(this.destroyAbortController.signal,async function*(e){var u,l;let t=(u=(0,_u.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||!it(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);ut(r);let a=this.segments.get(i);ut(a,"No segments for starting representation");let n=this.initData.get(i);if(ut(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){!j(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new ae,Oi(this.switchAbortController.signal,async function*(i,r=!1){this.switchingToRepresentationId=i;let a=this.representations.get(i);ut(a,`No such representation ${i}`);let n=this.segments.get(i),o=this.initData.get(i);if(Ge(o)||Ge(n)?yield this.loadInit(a,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(i),ut(n,"No segments for starting representation"),o=this.initData.get(i),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer||!j(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();is(u)&&!this.isLive&&(this.bufferLimit=this.forwardBufferTarget,yield this.pruneBuffer(u,1/0,!0)),this.downloadingRepresentationId=i,this.switchingToRepresentationId=void 0}this.maintain()}}.bind(this))(e,t))}warmUpMediaSource(){!Ge(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}async abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);return this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new ae,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(Ge(e)||Ge(this.downloadingRepresentationId)||Ge(this.playingRepresentationId)||Ge(this.sourceBuffer)||!j(this.mediaSource,this.sourceBuffer)||is(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(ut(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;let r=i.find(d=>e>=d.time.from&&e<d.time.to);is(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)&&Jr(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,Ou.default)(u,r))d="high";else{let c=(0,rs.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,rs.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;is(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,_u.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,_u.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||!it(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,rs.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;ut(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(!it(a))return;let n=(i=this.segments.get(r.id))!=null?i:[],o=n.find(l=>Math.floor(l.time.from)===Math.floor(e.time.from));if(o&&!isFinite(o.time.to)&&(o.time.to=e.time.to,t=o.time.to-o.time.from),!!!n.find(l=>Math.floor(l.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let l=Math.round(e.time.to*a.timescale/1e3).toString(10),d=vi(a.segmentTemplateUrl,{segmentTime:l});n.push({status:"none",time:{from:e.time.to,to:1/0},url:d})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){var a,n,o;let t=(n=(a=this.switchingToRepresentationId)!=null?a:this.downloadingRepresentationId)!=null?n:this.playingRepresentationId;if(!t)return;let i=this.segments.get(t);if(!i)return;let r=i.find(u=>u.time.from<=e&&u.time.to>=e);return(o=r==null?void 0:r.time.from)!=null?o:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)==null||e.destroy(),this.gapDetectionIdleCallback&&Jt&&Jt(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&Jt&&Jt(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&&j(this.mediaSource,this.sourceBuffer)&&!(He(this.sourceBuffer.buffered,h)&&He(this.sourceBuffer.buffered,p)))&&g&&v});if(r===-1)return[];if(t!=="byteRange")return e.slice(r,r+1);let a=e,n=0,o=0,u=[],l=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,d=this.preloadOnly?this.forwardBufferTarget:0;for(let c=r;c<a.length&&(n<=l||o<=d);c++){let h=a[c];if(n+=h.byte.to+1-h.byte.from,o+=h.time.to+1-h.time.from,h.status==="none"||h.status==="partially_ejected")u.push(h);else break}return u}async loadSegments(e,t,i="auto"){it(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 Oi(o,async function*(){let d=Ap(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,d))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let d=await this.fetcher.fetch(n,{range:a,signal:o,onProgress:u,priority:i,isLowLatency:this.isActiveLowLatency()});if(this.lastDataObtainedTimestampMs=Vu(),!d)return;let c=new DataView(d),h=gn(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]),Sn(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())it(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 Oi(n,async function*(){let u=Ap(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),Pp(window,"online").pipe(rC()).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=Vu(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),Sn(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(it(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:(0,rs.default)(e,0).byte.from,to:(0,rs.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=Vu(),await this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:a,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:yi.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!it(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=Vu();let c=this.onSomeTemplateDataLoaded({dataView:l,loaded:d,signal:a,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(c)}catch(c){this.error$.next({id:"SegmentFeeding",category:yi.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}}:void 0;return{url:r,signal:a,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,Ou.default)(e,t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:a}){if(!this.activeSegments.size||!j(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=gn(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||!j(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=gn(o.mime);if(l.status==="downloading"&&f){l.status="downloaded";let g=new DataView(e.buffer,e.byteOffset+d,h);await this.sourceBufferTaskQueue.append(g,a)&&!a.aborted?this.onSegmentFullyAppended(u,t):await n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(l.status==="downloading"||l.status==="partially_fed")&&(u.loadedBytes=Math.min(h,r-d),u.loadedBytes>u.feedingBytes)){let g=new DataView(e.buffer,e.byteOffset+d+u.feedingBytes,u.loadedBytes-u.feedingBytes),S=u.loadedBytes===h?g:m.parseFeedableSegmentChunk(g);S!=null&&S.byteLength&&(l.status="partially_fed",u.feedingBytes+=S.byteLength,await this.sourceBufferTaskQueue.append(S,a)&&!a.aborted?(u.fedBytes+=S.byteLength,u.fedBytes===h&&this.onSegmentFullyAppended(u,t)):await n())}}}onSegmentFullyAppended(e,t){var i;if(!(Ge(this.sourceBuffer)||!j(this.mediaSource,this.sourceBuffer))){!this.isLive&&q.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(He(this.sourceBuffer.buffered,e.segment.time.from,100)&&He(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:yi.VIDEO_PIPELINE,message:"Browser stuck on empty result of adding segment to source buffer"})),this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",Ip(e.segment)&&(e.segment.size=e.fedBytes);for(let r of this.representations.values())if(r.id!==t)for(let a of(i=this.segments.get(r.id))!=null?i:[])a.status==="fed"&&Math.round(a.time.from)===Math.round(e.segment.time.from)&&Math.round(a.time.to)===Math.round(e.segment.time.to)&&(a.status="none");this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}}abortSegment(e){e.status==="partially_fed"?e.status="partially_ejected":e.status!=="partially_ejected"&&(e.status="none");for(let t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[r,a]of this.initData.entries()){let n=a instanceof Promise;t||(t=n),a===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let i=this.representations.get(e);i&&(this.initLoadIdleCallback=Xr(()=>(0,UI.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?Oi(this.destroyAbortController.signal,async function*(){let o=Ap(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,gn(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&&it(e.segmentReference)&&(h=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,h),u&&this.parsedInitData.set(e.id,u)}).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:yi.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n}async dropBuffer(){for(let e of this.segments.values())for(let t of e)t.status="none";await this.pruneBuffer(0,1/0,!0)}async pruneBuffer(e,t,i=!1){if(!this.sourceBuffer||!j(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||Ge(e))return!1;let r=[],a=0,n=u=>{u.sort((d,c)=>d.from-c.from);let l=[u[0]];for(let d=1;d<u.length;d++){let{from:c,to:h}=u[d],p=l[l.length-1];p.to>=c?p.to=Math.max(p.to,h):l.push(u[d])}return l},o=u=>{var d;if(a>=t)return r;r.push({...u.time}),r=n(r);let l=Ip(u)?(d=u.size)!=null?d:0:u.byte.to-u.byte.from;a+=l};for(let u of this.segments.values())for(let l of u){let d=l.time.to<=e-this.tuning.dash.bufferPruningSafeZone,c=l.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(d||c)&&l.status==="fed"&&o(l)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let l=this.sourceBuffer.buffered.start(u)*1e3,d=this.sourceBuffer.buffered.end(u)*1e3,c=0;for(let h of this.segments.values())for(let p of h)(0,Ou.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||!j(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||!j(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||!j(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||Ge(e)?0:It(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!(!this.sourceBuffer||!j(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||!j(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=Xr(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:yi.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if(Ge(this.sourceBuffer)||!j(this.mediaSource,this.sourceBuffer)||Ge(this.playingRepresentationId))return;let e=[];for(let i=0;i<this.sourceBuffer.buffered.length;i++){let r=Math.floor(this.sourceBuffer.buffered.start(i)*1e3),a=Math.ceil(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:r,to:a})}let t=100;for(let i of this.segments.values())for(let r of i){let{status:a}=r;if(a!=="fed"&&a!=="partially_ejected")continue;let n=Math.floor(r.time.from),o=Math.ceil(r.time.to),u=e.some(d=>d.from-t<=n&&d.to+t>=o),l=e.filter(d=>n>=d.from&&n<d.to-t||o>d.from+t&&o<=d.to);u||(l.length===1?r.status="partially_ejected":this.gaps.some(d=>d.from===r.time.from||d.to===r.time.to)?r.status="partially_ejected":r.status="none")}}handleAsyncError(e,t){this.error$.next({id:t,category:yi.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}};var _i=s=>{let e=new URL(s);return e.searchParams.set("quic","1"),e.toString()};var Fu=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 yn,assertNever as qI,fromEvent as jI,merge as nC,now as Tn,Subscription as oC,Subject as HI,ValueSubject as kp,flattenObject as ss,ErrorCategory as In}from"@vkontakte/videoplayer-shared/es2018";var Nu=s=>{let e=new URL(s);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var qu=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:a=!1}){this.lastConnectionType$=new kp(void 0);this.lastConnectionReused$=new kp(void 0);this.lastRequestFirstBytes$=new kp(void 0);this.recoverableError$=new HI;this.error$=new HI;this.abortAllController=new ae;this.subscription=new oC;this.fetchManifest=yn(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=_i(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=Nu(i));let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(Uu);return r?(t.log("success",ss({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(r.headers),r.text()):(t.error("error",ss({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=yn(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 L=new URL(l,location.href);L.searchParams.append("bytes",`${i.from}-${i.to}`),l=L.toString();break}default:qI(t)}this.requestQuic&&(l=_i(l));let h=this.abortAllController.signal,p;if(n){let L=new ae;if(p=nC(jI(this.abortAllController.signal,"abort"),jI(n,"abort")).subscribe(()=>{try{L.abort()}catch(Q){Uu(Q)}}),this.subscription.add(p),this.abortAllController.signal.aborted||n.aborted)try{L.abort()}catch(Q){Uu(Q)}h=L.signal}let f=Tn();c.log("startRequest",ss({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=Tn();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 L=`Fetch error ${m.status}: ${m.statusText}`;return c.error("error",{message:L}),c.end(),Promise.reject(new Error(`Fetch error ${m.status}: ${m.statusText}`))}if(this.onHeadersReceived(m.headers),!r&&!o){p==null||p.unsubscribe();let L=Tn(),Q={requestStartedAt:f,requestEndedAt:L,duration:L-f};return c.log("endRequest",ss(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=L=>{p==null||p.unsubscribe(),E=!0,Uu(L)},$=yn(h,async function*({done:L,value:Q}){if(I===0&&this.lastRequestFirstBytes$.next(Tn()-f),h.aborted){p==null||p.unsubscribe();return}if(!L&&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($,O)}}.bind(this));yield y==null?void 0:y.read().then($,O),p==null||p.unsubscribe();let w=Tn(),A={failed:E,requestStartedAt:f,requestEndedAt:w,duration:w-f};return E?(c.error("endRequest",ss(A)),c.end(),null):(c.log("endRequest",ss(A)),c.end(),T.buffer)}.bind(this));this.fetchByteRangeRepresentation=yn(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=yn(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}=Fu(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:qI(r)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}async doFetch(e,t){let i=await Pt(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:In.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:In.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:In.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:In.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${a})`,category:In.FATAL})}}},Uu=s=>{if(!Sn(s))throw s};var Ti=(s,e,t)=>t*e+(1-t)*s,Rp=(s,e)=>s.reduce((t,i)=>t+i,0)/e,GI=(s,e,t,i)=>{let r=0,a=t,n=Rp(s,e),o=e<i?e:i;for(let u=0;u<o;u++)s[a]>n?r++:r--,a=(s.length+a-1)%s.length;return Math.abs(r)===o};import{isNullable as uC,ValueSubject as zI}from"@vkontakte/videoplayer-shared/es2018";var Fi=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 zI(e.initial),this.debounced$=new zI(e.initial);let t=(i=e.label)!=null?i:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new et(`raw_${t}`),this.smoothedSeries$=new et(`smoothed_${t}`),this.reportedSeries$=new et(`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)&&(uC(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 ju=class extends Fi{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=Ti(this.slow,e,this.params.emaAlphaSlow),this.fast=Ti(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var Hu=class extends Fi{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=Rp(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Ti(this.emaSmoothed,e,this.params.emaAlpha);let i=GI(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}};var Gu=class extends Fi{constructor(t){super(t);this.furtherValues=[];this.currentTopExtremumValue=0;this.extremumInterval=t.extremumInterval}next(t){this.currentTopExtremumValue<=t?(this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.length===this.extremumInterval?(super.next(this.currentTopExtremumValue),this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.push(t)}updateSmoothedValue(t){this.smoothed=this.smoothed?Ti(this.smoothed,t,this.params.emaAlpha):t}};var Ii=class{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new ju({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new Hu({initial:e,emaAlpha:i.emaAlpha,basisTrendChangeCount:i.basisTrendChangeCount,changeThreshold:i.changeThreshold,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"})}static getLiveBufferSmoothedValue(e,t){return new Gu({initial:e,label:"liveEdgeDelay",...t})}};var as=(s,e)=>{s&&s.playbackRate!==e&&(s.playbackRate=e)};import{isNullable as lC,ValueSubject as cC}from"@vkontakte/videoplayer-shared/es2018";var xn=class s{constructor(e,t){this.currentRepresentation$=new cC(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(!lC(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&&it(t.segmentReference))}};var Qu=N(_t(),1);import{assertNever as Wu}from"@vkontakte/videoplayer-shared/es2018";var QI=(s,{useHlsJs:e,useManagedMediaSource:t,useOldMSEDetection:i})=>{let{containers:r,protocols:a,codecs:n,nativeHlsSupported:o}=q.video,u=(n.h264||n.h265)&&n.aac,l=a.mse&&(!i||!!window.MediaStreamTrack)||a.mms&&t;return s.filter(d=>{switch(d){case"DASH_SEP":return l&&r.mp4&&u;case"DASH_WEBM":return l&&r.webm&&n.vp9&&n.opus;case"DASH_WEBM_AV1":return l&&r.webm&&n.av1&&n.opus;case"DASH_STREAMS":return l&&(r.mp4&&u||r.webm&&(n.vp9||n.av1)&&(n.opus||n.aac));case"DASH_LIVE":return l&&r.mp4&&u;case"DASH_LIVE_CMAF":return l&&r.mp4&&u&&r.cmaf;case"DASH_ONDEMAND":return l&&r.mp4&&u;case"HLS":case"HLS_ONDEMAND":return o||e&&l&&r.mp4&&u;case"HLS_LIVE":case"HLS_LIVE_CMAF":return o;case"MPEG":return r.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return a.webrtc&&a.ws&&n.h264&&(r.mp4||r.webm);default:return Wu(d)}})},zu=s=>{let{webmDecodingInfo:e}=q.video,t="DASH_WEBM",i="DASH_WEBM_AV1";switch(s){case"vp9":return[t,i];case"av1":return[i,t];case"none":return[];case"smooth":return e?e[i].smooth?[i,t]:e[t].smooth?[t,i]:[i,t]:[t,i];case"power_efficient":return e?e[i].powerEfficient?[i,t]:e[t].powerEfficient?[t,i]:[i,t]:[t,i];default:Wu(s)}return[t,i]},WI=({webmCodec:s,androidPreferredFormat:e,preferMultiStream:t})=>{let i=[...t?["DASH_STREAMS"]:[],...zu(s),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],r=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(q.device.isAndroid)switch(e){case"mpeg":return["MPEG",...i,"HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...i,"MPEG"];case"dash":return[...i,"HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return[...r,"MPEG",...zu(s),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...zu(s),"MPEG",...r,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...zu(s),...r,"HLS","HLS_ONDEMAND"];default:Wu(e)}return q.video.nativeHlsSupported?[...i,"HLS","HLS_ONDEMAND","MPEG"]:[...i,"HLS","HLS_ONDEMAND","MPEG"]},YI=({androidPreferredFormat:s,preferCMAF:e,preferWebRTC:t})=>{let i=e?["DASH_LIVE_CMAF","DASH_LIVE"]:["DASH_LIVE","DASH_LIVE_CMAF"],r=e?["HLS_LIVE_CMAF","HLS_LIVE"]:["HLS_LIVE","HLS_LIVE_CMAF"],a=[...i,...r],n=[...r,...i],o,u=q.device.isMac&&q.browser.isSafari;if(q.device.isAndroid)switch(s){case"dash":case"dash_any_mpeg":case"dash_any_webm":case"dash_sep":{o=a;break}case"hls":case"mpeg":{o=n;break}default:Wu(s)}else q.video.nativeHlsSupported&&!u?o=n:u?o=e?["DASH_LIVE_CMAF","HLS_LIVE_CMAF","HLS_LIVE","DASH_LIVE"]:["HLS_LIVE","DASH_LIVE","DASH_LIVE_CMAF","HLS_LIVE_CMAF"]:o=a;return t?["WEB_RTC_LIVE",...o]:[...o,"WEB_RTC_LIVE"]},Lp=s=>s?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],Yu=s=>{if(s.size===0)return;if(s.size===1){let t=s.values().next();return(0,Qu.default)(t.value.split("."),0)}for(let t of s){let i=(0,Qu.default)(t.split("."),0);if(i==="opus"||i==="vp09"||i==="av01")return i}let e=s.values().next();return(0,Qu.default)(e.value.split("."),0)};var SC=["timeupdate","progress","play","seeked","stalled","waiting"],vC=["timeupdate","progress","loadeddata","playing","seeked"];var Ju=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new JI;this.representationSubscription=new JI;this.state$=new H("none");this.currentVideoRepresentation$=new he(void 0);this.currentVideoRepresentationInit$=new he(void 0);this.currentAudioRepresentation$=new he(void 0);this.currentVideoSegmentLength$=new he(0);this.currentAudioSegmentLength$=new he(0);this.error$=new Xu;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 Xu;this.fetcherError$=new Xu;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new Xu;this.gapWatchdogActive=!1;this.destroyController=new ae;this.initManifest=$p(this.destroyController.signal,async function*(e,t,i){var r;this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=Se(t,i,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),(r=this.manifest)!=null&&r.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:Nt.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=$p(this.destroyController.signal,async function*(){var n,o;this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(u=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:Nt.NETWORK,message:"Failed to load manifest",thrown:u})});if(!e)return null;let t=null;try{t=FI(e!=null?e:"",this.manifestUrlString)}catch(u){let l=(n=Du(e))!=null?n:{id:"ManifestParsing",category:Nt.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=Tt())==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=Yu(c);if(h&&(r[u]=d.filter(({codecs:p})=>p.startsWith(h))),u==="video"){let p=this.tuning.preferHDR,f=r.video.some(g=>g.hdr),m=r.video.some(g=>!g.hdr);q.display.isHDR&&p&&f?r.video=r.video.filter(g=>g.hdr):m&&(r.video=r.video.filter(g=>!g.hdr))}}let a={...t,streams:r};return this.tracer.log("updateManifestEnd",wn(a)),a}.bind(this));this.initRepresentations=$p(this.destroyController.signal,async function*(e,t,i){var h;this.tracer.log("initRepresentationsStart",wn({initialVideo:e,initialAudio:t,sourceHls:i})),ns(this.manifest),ns(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let r=p=>{this.representationSubscription.add(xi(p,"error").pipe(Ku(f=>{var m;return!!((m=this.element)!=null&&m.played.length)})).subscribe(f=>{this.error$.next({id:"VideoSource",category:Nt.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:f})}))};this.source=this.tuning.useManagedMediaSource?cu():new MediaSource;let a=document.createElement("source");if(r(a),a.src=URL.createObjectURL(this.source),this.element.appendChild(a),this.tuning.useManagedMediaSource&&jr())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 vn("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],Pn(t)){let p=this.manifest.streams.audio.reduce((f,m)=>[...f,...m.representations],[]);this.audioBufferManager=new vn("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}xn.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new xn(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(fr(...vC.map(p=>xi(this.element,p))).pipe(us(p=>this.element?It(this.element.buffered,this.element.currentTime*1e3):0),En(),bC(p=>{p>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add(fr(xi(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe(En()).subscribe(f=>this.liveStreamEndTimestamp=Dp())),this.subscription.add(xi(this.element,"pause").subscribe(()=>{this.livePauseWatchdogSubscription=Bp(1e3).subscribe(f=>{let m=$i(this.manifestUrlString,2);this.manifestUrlString=Se(this.manifestUrlString,m+1e3,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add(xi(this.element,"play").subscribe(f=>{var m;return(m=this.livePauseWatchdogSubscription)==null?void 0:m.unsubscribe()})),this.representationSubscription.add(os({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(us(({isActiveLive:f,isLowLatency:m})=>f&&m),En()).subscribe(f=>{this.isManualDecreasePlaybackInLive()||as(this.element,1)})),this.representationSubscription.add(os({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(Ku(({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(os({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(Ku(({isLive:f})=>f),En((f,m)=>m.bufferLength<f.bufferLength),us(({rtt:f,bufferLength:m,segmentServerLatency:g})=>{let S=$i(this.manifestUrlString,2);return(f/2+m+g+S)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(os({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),as(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(os({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(gC(1e3)).subscribe(async({liveLoadBufferLength:f,bufferLength:m})=>{if(!this.element||this.isUpdatingLive)return;let g=this.element.playbackRate,S=$i(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(),$=v<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next($);let w="none";if(O?w="active_low_latency":this.isLowLatency$.getValue()&&$?(this.bufferManagers.forEach(A=>A.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 A=p-(y+I),C=this.normolizeLiveOffset(Math.trunc(S+A/g)),M=Math.abs(C-S),L=0;!f||M<=this.tuning.dashCmafLive.offsetCalculationError?L=S:C>0&&M>this.tuning.dashCmafLive.offsetCalculationError&&(L=C),this.manifestUrlString=Se(this.manifestUrlString,L,2)}(w==="live_with_target_offset"||w==="live_forward_buffering")&&(p=0,await this.updateLive())},f=>{this.error$.next({id:"updateLive",category:Nt.VIDEO_PIPELINE,thrown:f,message:"Failed to update live with subscription"})}))}let l=fr(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe(us(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),d=fr(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe(us(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue()))),c=os({allBuffersFull:l,someBufferEnded:d}).pipe(En(),us(({allBuffersFull:p,someBufferEnded:f})=>p&&f),Ku(p=>p));if(this.representationSubscription.add(fr(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:Nt.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:f})}})),this.representationSubscription.add(fr(...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:Nt.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,Cp.default)((0,Cp.default)([...this.manifest.streams.audio,...this.manifest.streams.video],f=>f.representations),f=>{let m=[];return f.duration&&m.push(f.duration),it(f.segmentReference)&&f.segmentReference.totalSegmentsDurationMs&&m.push(f.segmentReference.totalSegmentsDurationMs),m})];this.source.duration=Math.max(...p)/1e3}this.audioBufferManager&&Pn(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=Bp(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),n=>{this.error$.next({id:"GapWatchdog",category:Nt.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 qu({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.subscription.add(this.fetcher.recoverableError$.subscribe(this.fetcherRecoverableError$)),this.subscription.add(this.fetcher.error$.subscribe(this.fetcherError$)),this.liveBuffer=Ii.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator}),this.initTracerSubscription()}async seekLive(e){var r,a,n;ns(this.element);let t=this.liveStreamStatus$.getValue()!=="active"?Dp()-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(){ns(this.element),this.state$.setState("running"),this.subscription.add(fr(...SC.map(e=>xi(this.element,e)),xi(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:Nt.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(xi(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(xi(this.element,"waiting").subscribe(()=>{var t;this.element&&this.element.readyState===2&&!this.element.seeking&&He(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=Dp(),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 $=this.normolizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive($).catch(w=>{this.error$.next({id:"stallIntervalCallback",category:Nt.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:w})}),r.liveLastOffset=$}else{let $=this.element.currentTime*1e3;(E=this.videoBufferManager)==null||E.maintain($),(O=this.audioBufferManager)==null||O.maintain($),r.position=$}this.tracer.log("stallIntervalCallback",wn(r))};(t=this.stallWatchdogSubscription)==null||t.unsubscribe(),this.stallWatchdogSubscription=Bp(50).subscribe(e,i=>{this.error$.next({id:"StallWatchdogCallback",category:Nt.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;ns(this.element),ns(this.videoBufferManager);let i;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?i=e:i=Math.max((r=this.videoBufferManager.findSegmentStartTime(e))!=null?r:e,(n=(a=this.audioBufferManager)==null?void 0:a.findSegmentStartTime(e))!=null?n:e),this.warmUpMediaSourceIfNeeded(i),He(this.element.buffered,i)||await Promise.all([this.videoBufferManager.abort(),(o=this.audioBufferManager)==null?void 0:o.abort()]),!(XI(this.element)||XI(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),(u=this.audioBufferManager)==null||u.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",wn({requestedPosition:e,forcePrecise:t,position:i})))}warmUpMediaSourceIfNeeded(e=(t=>(t=this.element)==null?void 0:t.currentTime)()){var i;Pn(this.element)&&Pn(this.source)&&Pn(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=mC(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",wn(i)))}}};var Zu=class{constructor(e,t){this.fov=e,this.orientation=t}};var el=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 ex=`attribute vec2 a_vertex;
125
125
  attribute vec2 a_texel;
126
126
 
127
127
  varying vec2 v_texel;
@@ -132,7 +132,7 @@ void main(void) {
132
132
  // save texel vector to pass to fragment shader
133
133
  v_texel = a_texel;
134
134
  }
135
- `;var ex=`#ifdef GL_ES
135
+ `;var tx=`#ifdef GL_ES
136
136
  precision highp float;
137
137
  precision highp int;
138
138
  #else
@@ -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 cs=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 Zu(this.params.fov,this.params.orientation),this.cameraRotationManager=new el(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(ZI,this.gl.VERTEX_SHADER),i=this.createShader(ex,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 IC,now as kn,once as xC,Subscription as EC,ValueSubject as Cp,isNonNullable as wC,safeStorage as Vp,filterChanged as PC}from"@vkontakte/videoplayer-shared/es2018";var tl="stalls_manager_metrics",Op="stalls_manager_abr_params",tx="stalls_manager_default_tuning_abr_params",_p=class{constructor(){this.isSeeked$=new Cp(!1);this.isBuffering$=new Cp(!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 EC;this.severeStallOccurred$=new Cp(!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(Op):{};return{...this.abrParams,...e}}set lastVideoTrackSelected(e){var t;((t=this.lastUniqueVideoTrackSelected)==null?void 0:t.id)!==e.id&&(this.lastUniqueVideoTrackSelected=e,this.lastUniqueVideoTrackSelectedTimestamp=kn(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe(),this.currentStallDuration$.getValue()!==0&&this.updateStallData();let e=(kn()-this.providerStartWatchingTimestamp-this.sumStallsDuration)/1e3,t=this.sumStallsDuration;this.addStallInfoToHistory(e,t),this.updateStoredAbrParams()}resetStoredAbrParamsIfNeeded(){let{bitrateFactorAtEmptyBuffer:e,bitrateFactorAtFullBuffer:t,containerSizeFactor:i}={...this.getStoredData(tx)},{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:a,containerSizeFactor:n}={...this.abrParams};this.tuning.enabled&&e===r&&t===a&&i===n||(this.removeStoredData(Op),this.setStoredData(tx,{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:a,containerSizeFactor:n}))}updateStoredAbrParams(){let e=[],t=this.getStoredData(tl,"[]");if(!this.tuning.enabled||t.length<this.tuning.stallsMetricsHistoryLength)return;if(this.tuning.useTotalStallsDurationPerTvt){let r=t.reduce((o,u)=>o+u.tvt,0),n=t.reduce((o,u)=>o+u.stallsDuration,0)/r;e.push(this.calculateOptimalAbrParams(n))}if(this.tuning.useAverageStallsDurationPerTvt){let r=t.reduce((a,n)=>a+n.stallsDurationPerTvt,0)/t.length;e.push(this.calculateOptimalAbrParams(r))}this.tuning.useEmaStallsDurationPerTvt&&e.push(this.calculateOptimalAbrParams(t[t.length-1].stallsDurationPerTvtSmoothed));let i={bitrateFactorAtEmptyBuffer:Math.max(...e.map(r=>r.bitrateFactorAtEmptyBuffer)),bitrateFactorAtFullBuffer:Math.max(...e.map(r=>r.bitrateFactorAtFullBuffer)),containerSizeFactor:Math.min(...e.map(r=>r.containerSizeFactor))};this.setStoredData(tl,[]),this.setStoredData(Op,i)}calculateOptimalAbrParams(e){let{targetStallsDurationPerTvt:t,deviationStallsDurationPerTvt:i,criticalStallsDurationPerTvt:r,abrAdjustingSpeed:a}=this.tuning,n=this.abrTuningParams;return e<t-i?n={bitrateFactorAtEmptyBuffer:Math.max(n.bitrateFactorAtEmptyBuffer-a,this.abrParams.minBitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.max(n.bitrateFactorAtFullBuffer-a,this.abrParams.minBitrateFactorAtFullBuffer),containerSizeFactor:Math.min(n.containerSizeFactor+a,this.abrParams.maxContainerSizeFactor)}:e>t+i&&(n={bitrateFactorAtEmptyBuffer:Math.min(n.bitrateFactorAtEmptyBuffer+a,this.abrParams.maxBitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.min(n.bitrateFactorAtFullBuffer+a,this.abrParams.maxBitrateFactorAtFullBuffer),containerSizeFactor:Math.max(n.containerSizeFactor-a,this.abrParams.minContainerSizeFactor)}),e>r&&(n={bitrateFactorAtEmptyBuffer:Math.max(n.bitrateFactorAtEmptyBuffer,this.abrParams.bitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.max(n.bitrateFactorAtFullBuffer,this.abrParams.bitrateFactorAtFullBuffer),containerSizeFactor:Math.min(n.containerSizeFactor,this.abrParams.containerSizeFactor)}),n}getStoredData(e,t="{}"){var i;return JSON.parse((i=Vp.get(e))!=null?i:t)}setStoredData(e,t){Vp.set(e,JSON.stringify(t))}removeStoredData(e){Vp.remove(e)}addStallInfoToHistory(e,t){if(e<this.tuning.minTvtToBeCounted||e>this.tuning.maxTvtToBeCounted||e*1e3<t)return;let i=this.getStoredData(tl,"[]"),r=t/e,a=i.length?Ti(i[i.length-1].stallsDurationPerTvtSmoothed,t/e,this.tuning.emaAlpha):r,n={tvt:e,stallsDuration:t,stallsDurationPerTvt:r,stallsDurationPerTvtSmoothed:a};i.push(n),i.length>this.tuning.stallsMetricsHistoryLength&&i.shift(),this.setStoredData(tl,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(xC()).subscribe(t=>this.providerStartWatchingTimestamp=kn())),this.subscription.add(this.currentStallDuration$.pipe(PC()).subscribe(t=>{let{stallDurationNoDataBeforeQualityDecrease:i,stallCountBeforeQualityDecrease:r,resetQualityRestrictionTimeout:a,ignoreStallsOnSeek:n}=this.tuning;if(IC(this.lastUniqueVideoTrackSelected)||n&&this.isSeeked$.getValue())return;let o=this.rtt$.getValue(),u=this.throughput$.getValue(),l=this.videoLastDataObtainedTimestamp$.getValue(),d=kn(),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,wC(this.lastUniqueVideoTrackSelected.bitrate)&&u>this.lastUniqueVideoTrackSelected.bitrate&&(this.predictedThroughputWithoutData=this.lastUniqueVideoTrackSelected.bitrate)),!t&&kn()-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}))}},il=_p;import{combine as AC,map as kC,observeElementSize as RC,Subscription as LC,ValueSubject as Fp,noop as MC}from"@vkontakte/videoplayer-shared/es2018";var rl=class{constructor(){this.subscription=new LC;this.pipSize$=new Fp(void 0);this.videoSize$=new Fp(void 0);this.elementSize$=new Fp(void 0);this.pictureInPictureWindowRemoveEventListener=MC}connect({observableVideo:e,video:t}){let i=r=>{let a=r.target;this.pipSize$.next({width:a.width,height:a.height})};this.subscription.add(RC(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(AC({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(kC(({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 mr=class{constructor(e){this.subscription=new OC;this.videoState=new H("stopped");this.droppedFramesManager=new Yr;this.stallsManager=new il;this.elementSizeManager=new rl;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Ci;this.audioTrackSwitchHistory=new Ci;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(r.state==="requested"&&(i==null?void 0:i.to)!=="paused"&&e!=="stopped"&&t!=="stopped"&&this.seek(r.position,r.forcePrecise),t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),R(this.params.desiredState.playbackState,"stopped",!0));return}switch(e){case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();return;case"ready":t==="paused"?(this.videoState.setState("paused"),R(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="ready"&&R(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):t==="playing"&&this.video.paused?this.playIfAllowed():(i==null?void 0:i.to)==="playing"&&R(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&R(this.params.desiredState.playbackState,"paused");return;default:return BC(e)}}};this.init3DScene=e=>{var i,r,a;if(this.scene3D)return;this.scene3D=new cs(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((i=e.projectionData)==null?void 0:i.pose.yaw)||0,y:((r=e.projectionData)==null?void 0:r.pose.pitch)||0,z:((a=e.projectionData)==null?void 0:a.pose.roll)||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSizeManager.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.textTracksManager=new ot(e.source.url),this.params=e,this.video=Ne(e.container,e.tuning),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(we(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.player=new Ju({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=je(this.video);this.subscription.add(()=>i.destroy());let r=this.constructor.name,a=o=>{e.error$.next({id:r,category:ix.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(Np(l=>!!l.length),sx()).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(Up(l=>l.to.state!=="none"),sl());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(Np(rx),sx()),e.firstBytesEvent$),a(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),a(this.videoState.stateChangeEnded$.pipe(Up(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(wt(this.video,t.isLooped,r)),this.subscription.add(qe(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(nt(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),a(ut(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),R(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),R(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:l})=>{if(l==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let d=this.player.getStreams();if(DC(d,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let h=[];for(let p of d.audio){h.push(vp(p));let f=[];for(let m of p.representations){let g=LI(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(yp(h));let p=[];for(let f of h.representations){let m=RI({...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=MI(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(al(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$,VC(this.video,"progress")).pipe(Np(()=>this.videoTracksMap.size>0)).subscribe(async()=>{let l=this.player.state$.getState(),d=this.player.state$.getTransition();if(!(0,ax.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});rx(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(sl()).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(yp(h))},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(sl()).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(vp(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(Up(({to:l})=>l==="ready"),sl());this.subscription.add(al(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,qp(["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(al(o,this.player.state$.stateChangeEnded$,qp(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let u=al(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,qp(["init"])).pipe(CC(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){var A,C,M,L,Q,U,P,F,k,x,B,oe,Ve;if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?Da:Ba,t=this.params.tuning.useNewAutoSelectVideoTrack?ku:Au,i=this.params.tuning.useNewAutoSelectVideoTrack?Xt:Pu,{desiredState:r,output:a}=this.params,n=r.autoVideoTrackSwitching.getState(),o=(A=r.videoTrack.getState())==null?void 0:A.id,l=[...this.videoTracksMap.keys()].find(({id:se})=>se===o),d=a.currentVideoTrack$.getValue(),c=((L=(M=r.videoStream.getState())!=null?M:l&&((C=this.videoTracksMap.get(l))==null?void 0:C.stream))!=null?L: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=De(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,(P=this.audioStreamsMap.get(y))!=null?P:[],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,(B=this.audioStreamsMap.get(y))!=null?B:[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.stallsManager.abrTuningParams,forwardBufferHealth:S,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),$=(oe=this.videoTracksMap.get(E))==null?void 0:oe.representation,w=O&&((Ve=this.audioTracksMap.get(O))==null?void 0:Ve.representation);if($&&w)return[$,w];if($&&!w&&this.audioTracksMap.size===0)return[$,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){He(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),R(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:ix.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),Ue(this.video),this.tracer.end()}};var Rn=class extends mr{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 jp,merge as nx,filter as ox,filterChanged as _C,isNullable as Hp,map as ux,ValueSubject as Gp,isNonNullable as FC}from"@vkontakte/videoplayer-shared/es2018";var Ln=class extends mr{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 Gp(1);a(i.playbackRateState$,n),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(r.isLowLatency.stateChangeEnded$.pipe(ux(o=>o.to)).subscribe(this.player.isLowLatency$)).add(jp({liveBufferTime:t.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(ux(({liveBufferTime:o,liveAvailabilityStartTime:u})=>o&&u?o+u:void 0)).subscribe(t.liveTime$)).add(this.player.liveStreamStatus$.pipe(ox(o=>FC(o))).subscribe(o=>t.isLiveEnded$.next(o!=="active"&&t.position$.getValue()===0))).add(jp({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:nx(i.playbackRateState$,new Gp(1))}).pipe(ox(({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||Hp(l)||(e=o-l)})).add(jp({time:t.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:nx(i.playbackRateState$,new Gp(1))}).pipe(_C((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||Hp(o)||Hp(u))return;let h=-1*(u-o-e);t.position$.next(Math.min(h,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(o=>{if(o){let u=$I(o);this.params.output.availableTextTracks$.next([u])}}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=Math.trunc(t/1e3<=Math.abs(this.params.output.duration$.getValue())?t:0);this.player.seekLive(i).then(()=>{this.params.output.position$.next(e/1e3)})}};import{assertNever as MV,assertNonNullable as $V,debounce as BV,ErrorCategory as Ux,filter as ph,filterChanged as gl,fromEvent as DV,isNonNullable as qx,map as hh,merge as Sl,observableFrom as fh,once as jx,Subscription as CV}from"@vkontakte/videoplayer-shared/es2018";var ch=N(ja(),1);import{abortable as nh,assertNonNullable as ms,combine as bs,ErrorCategory as qt,filter as hl,filterChanged as lo,flattenObject as co,fromEvent as Zt,getTraceSubscriptionMethod as TV,interval as oh,isNonNullable as po,isNullable as Fx,map as gs,merge as Tr,now as uh,Subject as fl,Subscription as lh,tap as IV,throttle as Nx,ValueSubject as fe}from"@vkontakte/videoplayer-shared/es2018";var ll=N(yt(),1),hs=N(_t(),1),cl=N(ja(),1);var Dx=N(Aa(),1);import{assertNever as NC,ErrorCategory as lx,Subject as cx}from"@vkontakte/videoplayer-shared/es2018";var UC=18,dx=!1;try{dx=q.browser.isSafari&&!!q.browser.safariVersion&&q.browser.safariVersion<=UC}catch(s){console.error(s)}var zp=class{constructor(e){this.bufferFull$=new cx;this.error$=new cx;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:lx.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)};dx&&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:lx.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:NC(t)}}},px=zp;import{abortable as Ui,assertNonNullable as ct,ErrorCategory as vr,fromEvent as Bx,getExponentialDelay as rh,isNonNullable as ps,isNullable as Qe,now as ul,once as pV,Subject as hV,Subscription as fV,ValueSubject as yr}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 ds=class extends J{};var Mn=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 $n=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 Bn=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 Dn=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 Cn=class extends J{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Vn=class extends J{constructor(e,t){super(e,t),this.data=this.content}};var br=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 On=class extends J{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};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){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 Nn=class extends le{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var Un=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 qn=class extends J{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var jn=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 Hn=class extends J{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Gn=class extends J{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var zn=class extends le{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var Qn=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.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 Yn=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 Kn=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 Xn=class extends J{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Jn=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 Zn=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 jC={ftyp:$n,moov:Bn,mvhd:Dn,moof:Cn,mdat:Vn,sidx:br,trak:On,mdia:qn,mfhd:zn,tkhd:jn,traf:Qn,tfhd:Wn,tfdt:Yn,trun:Kn,minf:Hn,sv3d:_n,st3d:Fn,prhd:Nn,proj:Gn,equi:Un,uuid:Mn,stbl:Xn,stsd:Jn,avc1:Zn,unknown:ds},Ei=class s{constructor(e={}){this.options={offset:0,...e}}parse(e){let t=[],i=this.options.offset;for(;i<e.byteLength;)try{let a=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+i+4,4)),n=this.createBox(a,new DataView(e.buffer,e.byteOffset+i,e.byteLength-i));if(!n.size)break;t.push(n),i+=n.size}catch(r){break}return t}createBox(e,t){let i=jC[e];return i?new i(t,new s):new ds(t,new s)}};var Ni=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 GC=new TextDecoder("ascii"),zC=s=>GC.decode(new DataView(s.buffer,s.byteOffset+4,4))==="ftyp",QC=s=>{let e=new br(s,new Ei),t=e.earliestPresentationTime/e.timescale*1e3,i=s.byteOffset+s.byteLength+e.firstOffset;return e.segments.map(a=>{if(a.referenceType!==0)throw new Error("Unsupported multilevel sidx");let n=a.subsegmentDuration/e.timescale*1e3,o={status:"none",time:{from:t,to:t+n},byte:{from:i,to:i+a.referencedSize-1}};return t+=n,i+=a.referencedSize,o})},WC=(s,e)=>{let i=new Ei().parse(s),r=new Ni(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)},YC=s=>{let t=new Ei().parse(s),i=new Ni(t),r={},a=i.findAll("uuid");return a.length?a[a.length-1]:r},KC=s=>{var r;let t=new Ei().parse(s);return(r=new Ni(t).find("sidx"))==null?void 0:r.timescale},XC=(s,e)=>{let i=new Ei().parse(s),a=new Ni(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},JC=s=>{let e={is3dVideo:!1,stereoMode:0,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}},i=new Ei().parse(s),r=new Ni(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},hx={validateData:zC,parseInit:JC,getIndexRange:()=>{},parseSegments:QC,parseFeedableSegmentChunk:WC,getChunkEndTime:XC,getServerLatencyTimestamps:YC,getTimescaleFromIndex:KC};var to=N(yt(),1);import{assertNonNullable as Wp,isNonNullable as gx,isNullable as eV}from"@vkontakte/videoplayer-shared/es2018";import{assertNever as ZC}from"@vkontakte/videoplayer-shared/es2018";var fx={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"}},mx=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=eo(s,t),r=i in fx,a=r?fx[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=eo(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}},eo=(s,e=s.byteLength)=>{switch(e){case 1:return s.getUint8(0);case 2:return s.getUint16(0);case 3:return s.getUint8(0)*2**16+s.getUint16(1);case 4:return s.getUint32(0);case 5:return s.getUint8(0)*2**32+s.getUint32(1);case 6:return s.getUint16(0)*2**32+s.getUint32(2);case 7:{let t=s.getUint8(0)*281474976710656+s.getUint16(1)*4294967296+s.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},Ut=(s,e)=>{switch(e){case"int":return s.getInt8(0);case"uint":return eo(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)}},gr=(s,e)=>{let t=0;for(;t<s.byteLength;){let i=new DataView(s.buffer,s.byteOffset+t),r=mx(i);if(!e(r))return;r.type==="master"&&gr(r.value,e),t=r.value.byteOffset-s.byteOffset+r.valueSize}},bx=s=>{if(s.getUint32(0)!==440786851)return!1;let e,t,i,r=mx(s);return gr(r.value,({tag:a,type:n,value:o})=>(a===17143?e=Ut(o,n):a===17026?t=Ut(o,n):a===17029&&(i=Ut(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)};var Sx=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],tV=[231,22612,22743,167,171,163,160,175],iV=s=>{let e,t,i,r,a=!1,n=!1,o=!1,u,l,d=!1,c=0;return gr(s,({tag:h,type:p,value:f,valueSize:m})=>{if(h===21419){let g=Ut(f,p);l=eo(g)}else h!==21420&&(l=void 0);return h===408125543?(e=f.byteOffset,t=f.byteOffset+m):h===357149030?a=!0:h===290298740?n=!0:h===2807729?i=Ut(f,p):h===17545?r=Ut(f,p):h===21420&&l===475249515?u=Ut(f,p):h===374648427?gr(f,({tag:g,type:S,value:v})=>g===30321?(d=Ut(v,S)===1,!1):!0):a&&n&&(0,to.default)(Sx,h)&&(o=!0),!o}),Wp(e,"Failed to parse webm Segment start"),Wp(t,"Failed to parse webm Segment end"),Wp(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}}}},rV=s=>{if(eV(s.cuesSeekPosition))return;let e=s.segmentStart+s.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},sV=(s,e)=>{let t=!1,i=!1,r=o=>gx(o.time)&&gx(o.position),a=[],n;return gr(s,({tag:o,type:u,value:l})=>{switch(o){case 475249515:t=!0;break;case 187:n&&r(n)&&a.push(n),n={};break;case 179:n&&(n.time=Ut(l,u));break;case 183:break;case 241:n&&(n.position=Ut(l,u));break;default:t&&(0,to.default)(Sx,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}}})},aV=s=>{let e=0,t=!1;try{gr(s,i=>i.tag===524531317?i.tagSize<=s.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):(0,to.default)(tV,i.tag)?(e+i.tagSize<=s.byteLength&&(e+=i.tagSize,t||(t=(0,to.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},vx={validateData:bx,parseInit:iV,getIndexRange:rV,parseSegments:sV,parseFeedableSegmentChunk:aV};var io=s=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(s);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return vx;case"mp4":return hx}}throw new ReferenceError(`Unsupported mime type ${s}`)};var eh=N(mp(),1),Rx=N(er(),1),Lx=N(bp(),1),Mx=N(_t(),1),th=N(ur(),1);import{isNonNullable as lV,isNullable as Ax}from"@vkontakte/videoplayer-shared/es2018";var yx=s=>{var e;try{let t=nV(),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 nV(){let s="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",d=`^(?:(?<langtag>${`
178
+ `;var ls=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 Zu(this.params.fov,this.params.orientation),this.cameraRotationManager=new el(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(ex,this.gl.VERTEX_SHADER),i=this.createShader(tx,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 IC,now as An,once as xC,Subscription as EC,ValueSubject as Vp,isNonNullable as wC,safeStorage as Op,filterChanged as PC}from"@vkontakte/videoplayer-shared/es2018";var tl="stalls_manager_metrics",_p="stalls_manager_abr_params",ix="stalls_manager_default_tuning_abr_params",Fp=class{constructor(){this.isSeeked$=new Vp(!1);this.isBuffering$=new Vp(!1);this.maxQualityLimit=void 0;this.currentStallsCount=0;this.sumStallsDuration=0;this.lastStallDuration=0;this.providerStartWatchingTimestamp=0;this.lastUniqueVideoTrackSelectedTimestamp=0;this.predictedThroughputWithoutData=0;this.subscription=new EC;this.severeStallOccurred$=new Vp(!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(_p):{};return{...this.abrParams,...e}}set lastVideoTrackSelected(e){var t;((t=this.lastUniqueVideoTrackSelected)==null?void 0:t.id)!==e.id&&(this.lastUniqueVideoTrackSelected=e,this.lastUniqueVideoTrackSelectedTimestamp=An(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe(),this.currentStallDuration$.getValue()!==0&&this.updateStallData();let e=(An()-this.providerStartWatchingTimestamp-this.sumStallsDuration)/1e3,t=this.sumStallsDuration;this.addStallInfoToHistory(e,t),this.updateStoredAbrParams()}resetStoredAbrParamsIfNeeded(){let{bitrateFactorAtEmptyBuffer:e,bitrateFactorAtFullBuffer:t,containerSizeFactor:i}={...this.getStoredData(ix)},{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:a,containerSizeFactor:n}={...this.abrParams};this.tuning.enabled&&e===r&&t===a&&i===n||(this.removeStoredData(_p),this.setStoredData(ix,{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:a,containerSizeFactor:n}))}updateStoredAbrParams(){let e=[],t=this.getStoredData(tl,"[]");if(!this.tuning.enabled||t.length<this.tuning.stallsMetricsHistoryLength)return;if(this.tuning.useTotalStallsDurationPerTvt){let r=t.reduce((o,u)=>o+u.tvt,0),n=t.reduce((o,u)=>o+u.stallsDuration,0)/r;e.push(this.calculateOptimalAbrParams(n))}if(this.tuning.useAverageStallsDurationPerTvt){let r=t.reduce((a,n)=>a+n.stallsDurationPerTvt,0)/t.length;e.push(this.calculateOptimalAbrParams(r))}this.tuning.useEmaStallsDurationPerTvt&&e.push(this.calculateOptimalAbrParams(t[t.length-1].stallsDurationPerTvtSmoothed));let i={bitrateFactorAtEmptyBuffer:Math.max(...e.map(r=>r.bitrateFactorAtEmptyBuffer)),bitrateFactorAtFullBuffer:Math.max(...e.map(r=>r.bitrateFactorAtFullBuffer)),containerSizeFactor:Math.min(...e.map(r=>r.containerSizeFactor))};this.setStoredData(tl,[]),this.setStoredData(_p,i)}calculateOptimalAbrParams(e){let{targetStallsDurationPerTvt:t,deviationStallsDurationPerTvt:i,criticalStallsDurationPerTvt:r,abrAdjustingSpeed:a}=this.tuning,n=this.abrTuningParams;return e<t-i?n={bitrateFactorAtEmptyBuffer:Math.max(n.bitrateFactorAtEmptyBuffer-a,this.abrParams.minBitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.max(n.bitrateFactorAtFullBuffer-a,this.abrParams.minBitrateFactorAtFullBuffer),containerSizeFactor:Math.min(n.containerSizeFactor+a,this.abrParams.maxContainerSizeFactor)}:e>t+i&&(n={bitrateFactorAtEmptyBuffer:Math.min(n.bitrateFactorAtEmptyBuffer+a,this.abrParams.maxBitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.min(n.bitrateFactorAtFullBuffer+a,this.abrParams.maxBitrateFactorAtFullBuffer),containerSizeFactor:Math.max(n.containerSizeFactor-a,this.abrParams.minContainerSizeFactor)}),e>r&&(n={bitrateFactorAtEmptyBuffer:Math.max(n.bitrateFactorAtEmptyBuffer,this.abrParams.bitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.max(n.bitrateFactorAtFullBuffer,this.abrParams.bitrateFactorAtFullBuffer),containerSizeFactor:Math.min(n.containerSizeFactor,this.abrParams.containerSizeFactor)}),n}getStoredData(e,t="{}"){var i;return JSON.parse((i=Op.get(e))!=null?i:t)}setStoredData(e,t){Op.set(e,JSON.stringify(t))}removeStoredData(e){Op.remove(e)}addStallInfoToHistory(e,t){if(e<this.tuning.minTvtToBeCounted||e>this.tuning.maxTvtToBeCounted||e*1e3<t)return;let i=this.getStoredData(tl,"[]"),r=t/e,a=i.length?Ti(i[i.length-1].stallsDurationPerTvtSmoothed,t/e,this.tuning.emaAlpha):r,n={tvt:e,stallsDuration:t,stallsDurationPerTvt:r,stallsDurationPerTvtSmoothed:a};i.push(n),i.length>this.tuning.stallsMetricsHistoryLength&&i.shift(),this.setStoredData(tl,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(xC()).subscribe(t=>this.providerStartWatchingTimestamp=An())),this.subscription.add(this.currentStallDuration$.pipe(PC()).subscribe(t=>{let{stallDurationNoDataBeforeQualityDecrease:i,stallCountBeforeQualityDecrease:r,resetQualityRestrictionTimeout:a,ignoreStallsOnSeek:n}=this.tuning;if(IC(this.lastUniqueVideoTrackSelected)||n&&this.isSeeked$.getValue())return;let o=this.rtt$.getValue(),u=this.throughput$.getValue(),l=this.videoLastDataObtainedTimestamp$.getValue(),d=An(),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,wC(this.lastUniqueVideoTrackSelected.bitrate)&&u>this.lastUniqueVideoTrackSelected.bitrate&&(this.predictedThroughputWithoutData=this.lastUniqueVideoTrackSelected.bitrate)),!t&&An()-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}))}},il=Fp;import{combine as AC,map as kC,observeElementSize as RC,Subscription as LC,ValueSubject as Np,noop as MC}from"@vkontakte/videoplayer-shared/es2018";var rl=class{constructor(){this.subscription=new LC;this.pipSize$=new Np(void 0);this.videoSize$=new Np(void 0);this.elementSize$=new Np(void 0);this.pictureInPictureWindowRemoveEventListener=MC}connect({observableVideo:e,video:t}){let i=r=>{let a=r.target;this.pipSize$.next({width:a.width,height:a.height})};this.subscription.add(RC(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(AC({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(kC(({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 mr=class{constructor(e){this.subscription=new OC;this.videoState=new H("stopped");this.droppedFramesManager=new Yr;this.stallsManager=new il;this.elementSizeManager=new rl;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Ci;this.audioTrackSwitchHistory=new Ci;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(r.state==="requested"&&(i==null?void 0:i.to)!=="paused"&&e!=="stopped"&&t!=="stopped"&&this.seek(r.position,r.forcePrecise),t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),R(this.params.desiredState.playbackState,"stopped",!0));return}switch(e){case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();return;case"ready":t==="paused"?(this.videoState.setState("paused"),R(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="ready"&&R(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):t==="playing"&&this.video.paused?this.playIfAllowed():(i==null?void 0:i.to)==="playing"&&R(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&R(this.params.desiredState.playbackState,"paused");return;default:return BC(e)}}};this.init3DScene=e=>{var i,r,a;if(this.scene3D)return;this.scene3D=new ls(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 nt(e.source.url),this.params=e,this.video=Fe(e.container,e.tuning),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(we(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.player=new Ju({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=qe(this.video);this.subscription.add(()=>i.destroy());let r=this.constructor.name,a=o=>{e.error$.next({id:r,category:rx.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(Up(l=>!!l.length),ax()).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(qp(l=>l.to.state!=="none"),sl());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(Up(sx),ax()),e.firstBytesEvent$),a(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),a(this.videoState.stateChangeEnded$.pipe(qp(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(wt(this.video,t.isLooped,r)),this.subscription.add(Ue(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(at(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),a(ot(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),R(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),R(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:l})=>{if(l==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let d=this.player.getStreams();if(DC(d,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let h=[];for(let p of d.audio){h.push(yp(p));let f=[];for(let m of p.representations){let g=MI(m);f.push(g),this.audioTracksMap.set(g,{stream:p,representation:m})}this.audioStreamsMap.set(p,f)}this.params.output.availableAudioStreams$.next(h)}let c=[];for(let h of d.video){c.push(Tp(h));let p=[];for(let f of h.representations){let m=LI({...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=$I(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(al(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$,VC(this.video,"progress")).pipe(Up(()=>this.videoTracksMap.size>0)).subscribe(async()=>{let l=this.player.state$.getState(),d=this.player.state$.getTransition();if(!(0,nx.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});sx(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(sl()).subscribe(l=>{let d=[...this.videoTracksMap.entries()].find(([,{representation:f}])=>f.id===l);if(!d){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[c,{stream:h}]=d,p=this.params.desiredState.videoStream.getTransition();p&&p.to&&p.to.id===h.id&&this.params.desiredState.videoStream.setState(p.to),e.currentVideoTrack$.next(c),e.currentVideoStream$.next(Tp(h))},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(sl()).subscribe(l=>{let d=[...this.audioTracksMap.entries()].find(([,{representation:f}])=>f.id===l);if(!d){e.currentAudioStream$.next(void 0);return}let[c,{stream:h}]=d,p=this.params.desiredState.audioStream.getTransition();p&&p.to&&p.to.id===h.id&&this.params.desiredState.audioStream.setState(p.to),e.currentAudioStream$.next(yp(h))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(l=>{var d,c;if(l!=null&&l.is3dVideo&&((d=this.params.tuning.spherical)!=null&&d.enabled))try{this.init3DScene(l),e.is3DVideo$.next(!0)}catch(h){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${h}`})}else this.destroy3DScene(),(c=this.params.tuning.spherical)!=null&&c.enabled&&e.is3DVideo$.next(!1)},r)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,r)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,r)),this.textTracksManager.connect(this.video,t,e);let o=t.playbackState.stateChangeStarted$.pipe(qp(({to:l})=>l==="ready"),sl());this.subscription.add(al(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,jp(["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(al(o,this.player.state$.stateChangeEnded$,jp(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let u=al(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,jp(["init"])).pipe(CC(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){var A,C,M,L,Q,U,P,F,k,x,B,oe,Ce;if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?Ba:$a,t=this.params.tuning.useNewAutoSelectVideoTrack?Au:Pu,i=this.params.tuning.useNewAutoSelectVideoTrack?Xt:wu,{desiredState:r,output:a}=this.params,n=r.autoVideoTrackSwitching.getState(),o=(A=r.videoTrack.getState())==null?void 0:A.id,l=[...this.videoTracksMap.keys()].find(({id:se})=>se===o),d=a.currentVideoTrack$.getValue(),c=((L=(M=r.videoStream.getState())!=null?M:l&&((C=this.videoTracksMap.get(l))==null?void 0:C.stream))!=null?L: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=It(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,(P=this.audioStreamsMap.get(y))!=null?P:[],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,(B=this.audioStreamsMap.get(y))!=null?B:[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.stallsManager.abrTuningParams,forwardBufferHealth:S,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),$=(oe=this.videoTracksMap.get(E))==null?void 0:oe.representation,w=O&&((Ce=this.audioTracksMap.get(O))==null?void 0:Ce.representation);if($&&w)return[$,w];if($&&!w&&this.audioTracksMap.size===0)return[$,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){je(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),R(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:rx.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),Ne(this.video),this.tracer.end()}};var kn=class extends mr{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 Hp,merge as ox,filter as ux,filterChanged as _C,isNullable as Gp,map as lx,ValueSubject as zp,isNonNullable as FC}from"@vkontakte/videoplayer-shared/es2018";var Rn=class extends mr{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 zp(1);a(i.playbackRateState$,n),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(r.isLowLatency.stateChangeEnded$.pipe(lx(o=>o.to)).subscribe(this.player.isLowLatency$)).add(Hp({liveBufferTime:t.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(lx(({liveBufferTime:o,liveAvailabilityStartTime:u})=>o&&u?o+u:void 0)).subscribe(t.liveTime$)).add(this.player.liveStreamStatus$.pipe(ux(o=>FC(o))).subscribe(o=>t.isLiveEnded$.next(o!=="active"&&t.position$.getValue()===0))).add(Hp({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:ox(i.playbackRateState$,new zp(1))}).pipe(ux(({liveStreamStatus:o,liveDuration:u})=>o==="active"&&!!u)).subscribe(({liveDuration:o,playbackRate:u})=>{let l=t.liveBufferTime$.getValue(),d=t.position$.getValue(),{playbackCatchupSpeedup:c}=this.params.tuning.dashCmafLive.lowLatency;d||u<1-c||this.video.paused||Gp(l)||(e=o-l)})).add(Hp({time:t.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:ox(i.playbackRateState$,new zp(1))}).pipe(_C((o,u)=>this.player.liveStreamStatus$.getValue()==="active"?o.liveDuration===u.liveDuration:o.time===u.time)).subscribe(({time:o,liveDuration:u,playbackRate:l})=>{let d=t.position$.getValue(),{playbackCatchupSpeedup:c}=this.params.tuning.dashCmafLive.lowLatency;if(!d&&!this.video.paused&&l>=1-c||Gp(o)||Gp(u))return;let h=-1*(u-o-e);t.position$.next(Math.min(h,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(o=>{if(o){let u=BI(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 MV,assertNonNullable as $V,debounce as BV,ErrorCategory as Ux,filter as hh,filterChanged as Sl,fromEvent as DV,isNonNullable as qx,map as fh,merge as vl,observableFrom as mh,once as jx,Subscription as CV}from"@vkontakte/videoplayer-shared/es2018";var dh=N(qa(),1);import{abortable as oh,assertNonNullable as fs,combine as ms,ErrorCategory as qt,filter as fl,filterChanged as uo,flattenObject as lo,fromEvent as Zt,getTraceSubscriptionMethod as TV,interval as uh,isNonNullable as co,isNullable as Fx,map as bs,merge as Tr,now as lh,Subject as ml,Subscription as ch,tap as IV,throttle as Nx,ValueSubject as fe}from"@vkontakte/videoplayer-shared/es2018";var cl=N(vt(),1),ps=N(_t(),1),dl=N(qa(),1);var Dx=N(Pa(),1);import{assertNever as NC,ErrorCategory as cx,Subject as dx}from"@vkontakte/videoplayer-shared/es2018";var UC=18,px=!1;try{px=q.browser.isSafari&&!!q.browser.safariVersion&&q.browser.safariVersion<=UC}catch(s){console.error(s)}var Qp=class{constructor(e){this.bufferFull$=new dx;this.error$=new dx;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:cx.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)};px&&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:cx.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:NC(t)}}},hx=Qp;import{abortable as Ui,assertNonNullable as lt,ErrorCategory as vr,fromEvent as ul,getExponentialDelay as sh,isNonNullable as ds,isNullable as ze,now as ll,once as pV,Subject as hV,Subscription as fV,ValueSubject as yr}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 cs=class extends J{};var Ln=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 Mn=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 $n=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 Bn=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 Dn=class extends J{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Cn=class extends J{constructor(e,t){super(e,t),this.data=this.content}};var br=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 Vn=class extends J{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var On=class extends J{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var _n=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 Fn=class extends le{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var Nn=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 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.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 jn=class extends J{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Hn=class extends J{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Gn=class extends le{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var zn=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.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 Wn=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 Yn=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 Kn=class extends J{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Xn=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 Jn=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 jC={ftyp:Mn,moov:$n,mvhd:Bn,moof:Dn,mdat:Cn,sidx:br,trak:Vn,mdia:Un,mfhd:Gn,tkhd:qn,traf:zn,tfhd:Qn,tfdt:Wn,trun:Yn,minf:jn,sv3d:On,st3d:_n,prhd:Fn,proj:Hn,equi:Nn,uuid:Ln,stbl:Kn,stsd:Xn,avc1:Jn,unknown:cs},Ei=class s{constructor(e={}){this.options={offset:0,...e}}parse(e){let t=[],i=this.options.offset;for(;i<e.byteLength;)try{let a=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+i+4,4)),n=this.createBox(a,new DataView(e.buffer,e.byteOffset+i,e.byteLength-i));if(!n.size)break;t.push(n),i+=n.size}catch(r){break}return t}createBox(e,t){let i=jC[e];return i?new i(t,new s):new cs(t,new s)}};var Ni=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 GC=new TextDecoder("ascii"),zC=s=>GC.decode(new DataView(s.buffer,s.byteOffset+4,4))==="ftyp",QC=s=>{let e=new br(s,new Ei),t=e.earliestPresentationTime/e.timescale*1e3,i=s.byteOffset+s.byteLength+e.firstOffset;return e.segments.map(a=>{if(a.referenceType!==0)throw new Error("Unsupported multilevel sidx");let n=a.subsegmentDuration/e.timescale*1e3,o={status:"none",time:{from:t,to:t+n},byte:{from:i,to:i+a.referencedSize-1}};return t+=n,i+=a.referencedSize,o})},WC=(s,e)=>{let i=new Ei().parse(s),r=new Ni(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)},YC=s=>{let t=new Ei().parse(s),i=new Ni(t),r={},a=i.findAll("uuid");return a.length?a[a.length-1]:r},KC=s=>{var r;let t=new Ei().parse(s);return(r=new Ni(t).find("sidx"))==null?void 0:r.timescale},XC=(s,e)=>{let i=new Ei().parse(s),a=new Ni(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},JC=s=>{let e={is3dVideo:!1,stereoMode:0,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}},i=new Ei().parse(s),r=new Ni(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},fx={validateData:zC,parseInit:JC,getIndexRange:()=>{},parseSegments:QC,parseFeedableSegmentChunk:WC,getChunkEndTime:XC,getServerLatencyTimestamps:YC,getTimescaleFromIndex:KC};var eo=N(vt(),1);import{assertNonNullable as Yp,isNonNullable as Sx,isNullable as eV}from"@vkontakte/videoplayer-shared/es2018";import{assertNever as ZC}from"@vkontakte/videoplayer-shared/es2018";var mx={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"}},bx=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=Zn(s,t),r=i in mx,a=r?mx[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=Zn(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}},Zn=(s,e=s.byteLength)=>{switch(e){case 1:return s.getUint8(0);case 2:return s.getUint16(0);case 3:return s.getUint8(0)*2**16+s.getUint16(1);case 4:return s.getUint32(0);case 5:return s.getUint8(0)*2**32+s.getUint32(1);case 6:return s.getUint16(0)*2**32+s.getUint32(2);case 7:{let t=s.getUint8(0)*281474976710656+s.getUint16(1)*4294967296+s.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},Ut=(s,e)=>{switch(e){case"int":return s.getInt8(0);case"uint":return Zn(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)}},gr=(s,e)=>{let t=0;for(;t<s.byteLength;){let i=new DataView(s.buffer,s.byteOffset+t),r=bx(i);if(!e(r))return;r.type==="master"&&gr(r.value,e),t=r.value.byteOffset-s.byteOffset+r.valueSize}},gx=s=>{if(s.getUint32(0)!==440786851)return!1;let e,t,i,r=bx(s);return gr(r.value,({tag:a,type:n,value:o})=>(a===17143?e=Ut(o,n):a===17026?t=Ut(o,n):a===17029&&(i=Ut(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)};var vx=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],tV=[231,22612,22743,167,171,163,160,175],iV=s=>{let e,t,i,r,a=!1,n=!1,o=!1,u,l,d=!1,c=0;return gr(s,({tag:h,type:p,value:f,valueSize:m})=>{if(h===21419){let g=Ut(f,p);l=Zn(g)}else h!==21420&&(l=void 0);return h===408125543?(e=f.byteOffset,t=f.byteOffset+m):h===357149030?a=!0:h===290298740?n=!0:h===2807729?i=Ut(f,p):h===17545?r=Ut(f,p):h===21420&&l===475249515?u=Ut(f,p):h===374648427?gr(f,({tag:g,type:S,value:v})=>g===30321?(d=Ut(v,S)===1,!1):!0):a&&n&&(0,eo.default)(vx,h)&&(o=!0),!o}),Yp(e,"Failed to parse webm Segment start"),Yp(t,"Failed to parse webm Segment end"),Yp(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}}}},rV=s=>{if(eV(s.cuesSeekPosition))return;let e=s.segmentStart+s.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},sV=(s,e)=>{let t=!1,i=!1,r=o=>Sx(o.time)&&Sx(o.position),a=[],n;return gr(s,({tag:o,type:u,value:l})=>{switch(o){case 475249515:t=!0;break;case 187:n&&r(n)&&a.push(n),n={};break;case 179:n&&(n.time=Ut(l,u));break;case 183:break;case 241:n&&(n.position=Ut(l,u));break;default:t&&(0,eo.default)(vx,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}}})},aV=s=>{let e=0,t=!1;try{gr(s,i=>i.tag===524531317?i.tagSize<=s.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):(0,eo.default)(tV,i.tag)?(e+i.tagSize<=s.byteLength&&(e+=i.tagSize,t||(t=(0,eo.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},yx={validateData:gx,parseInit:iV,getIndexRange:rV,parseSegments:sV,parseFeedableSegmentChunk:aV};var to=s=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(s);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return yx;case"mp4":return fx}}throw new ReferenceError(`Unsupported mime type ${s}`)};var th=N(bp(),1),Lx=N(er(),1),Mx=N(gp(),1),$x=N(_t(),1),ih=N(ur(),1);import{isNonNullable as lV,isNullable as kx}from"@vkontakte/videoplayer-shared/es2018";var Tx=s=>{var e;try{let t=nV(),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 nV(){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 Kp=N(_t(),1);import{videoSizeToQuality as oV,throttleFn as uV}from"@vkontakte/videoplayer-shared/es2018";var Tx=({id:s,width:e,height:t,bitrate:i,fps:r,quality:a,streamId:n})=>{var u;let o=(u=a?Kt(a):void 0)!=null?u:oV({width:e,height:t});return o&&{id:s,quality:o,bitrate:i,size:{width:e,height:t},fps:r,streamId:n}},Ix=({id:s,bitrate:e})=>({id:s,bitrate:e}),xx=({language:s,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:s,label:e}),Ex=({language:s,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:s,label:e}),Xp=({id:s,language:e,label:t,codecs:i,isDefault:r})=>({id:s,language:e,label:t,codec:(0,Kp.default)(i.split("."),0),isDefault:r}),Jp=({id:s,language:e,label:t,hdr:i,codecs:r})=>({id:s,language:e,hdr:i,label:t,codec:(0,Kp.default)(r.split("."),0)}),Zp=s=>"url"in s,st=s=>s.type==="template",ro=s=>s instanceof DOMException&&(s.name==="AbortError"||s.code===20);var wx=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},Sr=(s,e)=>{for(let t of s)if(e(t))return t;return null},Px=s=>{let e=!1,t=uV(()=>{e=!0},s);return()=>{try{return t(),e}finally{e=!1}}};var kx=s=>{if(!(s!=null&&s.startsWith("P")))return;let e=(n,o)=>{let u=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(u)?0:u)*o},i=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(s),r=(i==null?void 0:i[1])==="-"?-1:1,a={days:e(i==null?void 0:i[5],r),hours:e(i==null?void 0:i[6],r),minutes:e(i==null?void 0:i[7],r),seconds:e(i==null?void 0:i[8],r)};return a.days*24*60*60*1e3+a.hours*60*60*1e3+a.minutes*60*1e3+a.seconds*1e3},wi=(s,e)=>{let t=s;t=(0,eh.default)(t,"$$","$");let i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[r,a]of(0,Rx.default)(i)){let n=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=(0,eh.default)(t,n,(o,u)=>Ax(a)?o:Ax(u)?a:(0,Lx.default)(a,parseInt(u,10),"0"))}return t},$x=(s,e)=>{var w,A,C,M,L,Q,U,P,F,k,x,B,oe,Ve,se,K,ye,Te,Ie,Oe,Et,At,Ht,ei,ki,ys,Ts,Is,xs,Es,ws,Ps,As,ks,Rs,Ls,Ms,$s,Bs,Ds,Cs,Vs,Os,_s,Fs,Ns,Us,qs,js,Hs,Gs,zs,Qs,Ws,Ys,Ks,Xs,Js,Zs,ea,ta;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 _,We;return(We=(_=ce.textContent)==null?void 0:_.trim())!=null?We:""}),o=(w=(0,Mx.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=kx(v):(0,th.default)(T).filter(ce=>ce).length&&!u?S=(0,th.default)(T).reduce((ce,_)=>{var We;return ce+((We=kx(_))!=null?We:0)},0):m&&(S=parseInt(m,10));let E=0,O=(C=(A=a.getAttribute("profiles"))==null?void 0:A.split(","))!=null?C:[];for(let ce of y.map(_=>_.id))for(let _ of I[ce]){let We=(M=_.getAttribute("id"))!=null?M:"id"+(E++).toString(10),kt=(L=_.getAttribute("mimeType"))!=null?L:"",Gi=(Q=_.getAttribute("codecs"))!=null?Q:"",zi=(U=_.getAttribute("contentType"))!=null?U:kt==null?void 0:kt.split("/")[0],Dl=(F=(P=_.getAttribute("profiles"))==null?void 0:P.split(","))!=null?F:[],ia=(x=yx((k=_.getAttribute("lang"))!=null?k:""))!=null?x:{},ti=(Ve=(oe=(B=_.querySelector("Label"))==null?void 0:B.textContent)==null?void 0:oe.trim())!=null?Ve:void 0,Cl=_.querySelectorAll("Representation"),Vl=_.querySelector("SegmentTemplate"),Ol=(K=(se=_.querySelector("Role"))==null?void 0:se.getAttribute("value"))!=null?K:void 0,dt=zi,G={id:We,language:ia.language,isDefault:Ol==="main",label:ti,codecs:Gi,hdr:dt==="video"&&ts(Gi),mime:kt,representations:[]};for(let V of Cl){let Pe=(ye=V.getAttribute("lang"))!=null?ye:void 0,Rt=(Ie=(Te=ti!=null?ti:_.getAttribute("label"))!=null?Te:V.getAttribute("label"))!=null?Ie:void 0,ii=(At=(Et=(Oe=V.querySelector("BaseURL"))==null?void 0:Oe.textContent)==null?void 0:Et.trim())!=null?At:"",Ye=new URL(ii||o,e).toString(),Ae=(Ht=V.getAttribute("mimeType"))!=null?Ht:kt,ri=(ki=(ei=V.getAttribute("codecs"))!=null?ei:Gi)!=null?ki:"",si;if(zi==="text"){let ke=V.getAttribute("id")||"",ai=((ys=ia.privateuse)==null?void 0:ys.includes("x-auto"))||ke.includes("_auto"),Ke=V.querySelector("SegmentTemplate");if(Ke){let Lt={representationId:(Ts=V.getAttribute("id"))!=null?Ts:void 0,bandwidth:(Is=V.getAttribute("bandwidth"))!=null?Is:void 0},ni=parseInt((xs=V.getAttribute("bandwidth"))!=null?xs:"",10)/1e3,oi=(ws=parseInt((Es=Ke.getAttribute("startNumber"))!=null?Es:"",10))!=null?ws:1,pt=parseInt((Ps=Ke.getAttribute("timescale"))!=null?Ps:"",10),Qi=(As=Ke.querySelectorAll("SegmentTimeline S"))!=null?As:[],ht=Ke.getAttribute("media");if(!ht)continue;let ui=[],li=0,ci="",ft=0,Mt=oi,ee=0;for(let de of Qi){let Xe=parseInt((ks=de.getAttribute("d"))!=null?ks:"",10),ne=parseInt((Rs=de.getAttribute("r"))!=null?Rs:"",10)||0,Re=parseInt((Ls=de.getAttribute("t"))!=null?Ls:"",10);ee=Number.isFinite(Re)?Re:ee;let Je=Xe/pt*1e3,Le=ee/pt*1e3;for(let me=0;me<ne+1;me++){let Me=wi(ht,{...Lt,segmentNumber:Mt.toString(10),segmentTime:(ee+me*Xe).toString(10)}),mt=(Le!=null?Le:0)+me*Je,Bt=mt+Je;Mt++,ui.push({time:{from:mt,to:Bt},url:Me})}ee+=(ne+1)*Xe,li+=(ne+1)*Je}ft=ee/pt*1e3,ci=wi(ht,{...Lt,segmentNumber:Mt.toString(10),segmentTime:ee.toString(10)});let $t={time:{from:ft,to:1/0},url:ci},xe={type:"template",baseUrl:Ye,segmentTemplateUrl:ht,initUrl:"",totalSegmentsDurationMs:li,segments:ui,nextSegmentBeyondManifest:$t,timescale:pt};si={id:ke,kind:"text",segmentReference:xe,profiles:[],duration:S,bitrate:ni,mime:"",codecs:"",width:0,height:0,isAuto:ai}}else si={id:ke,isAuto:ai,kind:"text",url:Ye}}else{let ke=($s=(Ms=V.getAttribute("contentType"))!=null?Ms:Ae==null?void 0:Ae.split("/")[0])!=null?$s:zi,ai=(Ds=(Bs=_.getAttribute("profiles"))==null?void 0:Bs.split(","))!=null?Ds:[],Ke=parseInt((Cs=V.getAttribute("width"))!=null?Cs:"",10),Lt=parseInt((Vs=V.getAttribute("height"))!=null?Vs:"",10),ni=parseInt((Os=V.getAttribute("bandwidth"))!=null?Os:"",10)/1e3,oi=(_s=V.getAttribute("frameRate"))!=null?_s:"",pt=(Fs=V.getAttribute("quality"))!=null?Fs:void 0,Qi=oi?Vu(oi):void 0,ht=(Ns=V.getAttribute("id"))!=null?Ns:"id"+(E++).toString(10),ui=ke==="video"?`${Lt}p`:ke==="audio"?`${ni}Kbps`:ri,li=`${ht}@${ui}`,ci=[...O,...Dl,...ai],ft,Mt=V.querySelector("SegmentBase"),ee=(Us=V.querySelector("SegmentTemplate"))!=null?Us:Vl;if(Mt){let xe=(js=(qs=V.querySelector("SegmentBase Initialization"))==null?void 0:qs.getAttribute("range"))!=null?js:"",[de,Xe]=xe.split("-").map(Me=>parseInt(Me,10)),ne={from:de,to:Xe},Re=(Hs=V.querySelector("SegmentBase"))==null?void 0:Hs.getAttribute("indexRange"),[Je,Le]=Re?Re.split("-").map(Me=>parseInt(Me,10)):[],me=Re?{from:Je,to:Le}:void 0;ft={type:"byteRange",url:Ye,initRange:ne,indexRange:me}}else if(ee){let xe={representationId:(Gs=V.getAttribute("id"))!=null?Gs:void 0,bandwidth:(zs=V.getAttribute("bandwidth"))!=null?zs:void 0},de=parseInt((Qs=ee.getAttribute("timescale"))!=null?Qs:"",10),Xe=(Ws=ee.getAttribute("initialization"))!=null?Ws:"",ne=ee.getAttribute("media"),Re=(Ks=parseInt((Ys=ee.getAttribute("startNumber"))!=null?Ys:"",10))!=null?Ks:1,Je=wi(Xe,xe);if(!ne)throw new ReferenceError("No media attribute in SegmentTemplate");let Le=(Xs=ee.querySelectorAll("SegmentTimeline S"))!=null?Xs:[],me=[],Me=0,mt="",Bt=0;if(Le.length){let di=Re,pe=0;for(let bt of Le){let be=parseInt((Js=bt.getAttribute("d"))!=null?Js:"",10),Ze=parseInt((Zs=bt.getAttribute("r"))!=null?Zs:"",10)||0,pi=parseInt((ea=bt.getAttribute("t"))!=null?ea:"",10);pe=Number.isFinite(pi)?pi:pe;let Wi=be/de*1e3,Yi=pe/de*1e3;for(let hi=0;hi<Ze+1;hi++){let Fl=wi(ne,{...xe,segmentNumber:di.toString(10),segmentTime:(pe+hi*be).toString(10)}),ra=(Yi!=null?Yi:0)+hi*Wi,Nl=ra+Wi;di++,me.push({time:{from:ra,to:Nl},url:Fl})}pe+=(Ze+1)*be,Me+=(Ze+1)*Wi}Bt=pe/de*1e3,mt=wi(ne,{...xe,segmentNumber:di.toString(10),segmentTime:pe.toString(10)})}else if(lV(S)){let pe=parseInt((ta=ee.getAttribute("duration"))!=null?ta:"",10)/de*1e3,bt=Math.ceil(S/pe),be=0;for(let Ze=1;Ze<bt;Ze++){let pi=wi(ne,{...xe,segmentNumber:Ze.toString(10),segmentTime:be.toString(10)});me.push({time:{from:be,to:be+pe},url:pi}),be+=pe}Bt=be,mt=wi(ne,{...xe,segmentNumber:bt.toString(10),segmentTime:be.toString(10)})}let _l={time:{from:Bt,to:1/0},url:mt};ft={type:"template",baseUrl:Ye,segmentTemplateUrl:ne,initUrl:Je,totalSegmentsDurationMs:Me,segments:me,nextSegmentBeyondManifest:_l,timescale:de}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!ke||!Ae)continue;let $t={video:"video",audio:"audio",text:"text"}[ke];if(!$t)continue;dt||(dt=$t),si={id:li,kind:$t,segmentReference:ft,profiles:ci,duration:S,bitrate:ni,mime:Ae,codecs:ri,width:Ke,height:Lt,fps:Qi,quality:pt}}G.language||(G.language=Pe),G.label||(G.label=Rt),G.mime||(G.mime=Ae),G.codecs||(G.codecs=ri),G.hdr||(G.hdr=dt==="video"&&ts(ri)),G.representations.push(si)}if(dt){let V=r[dt].find(Pe=>Pe.id===G.id);if(V&&G.representations.every(Pe=>st(Pe.segmentReference)))for(let Pe of V.representations){let Rt=G.representations.find(Ae=>Ae.id===Pe.id),ii=Rt==null?void 0:Rt.segmentReference,Ye=Pe.segmentReference;Ye.segments.push(...ii.segments),Ye.nextSegmentBeyondManifest=ii.nextSegmentBeyondManifest}else r[dt].push(G)}}return{duration:S,streams:r,baseUrls:n,live:g}};import{fromEvent as cV,Subscription as dV}from"@vkontakte/videoplayer-shared/es2018";var nl=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 ol=class{constructor(e,t){this.lastUpdateTs=0;this.lastCallTs=0;this.prevRanges=[];this.subscription=new dV;this.mediaSource=e,this.sourceBuffer=t,this.subscription.add(cV(this.sourceBuffer,"updateend").subscribe(()=>this.updateend()))}updateend(){if(!j(this.mediaSource,this.sourceBuffer))return;let{prevRanges:e}=this,t=nl(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 so=class{constructor(e,t,i,{fetcher:r,tuning:a,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new yr(0);this.currentLowLatencySegmentLength$=new yr(0);this.currentSegmentLength$=new yr(0);this.onLastSegment$=new yr(!1);this.fullyBuffered$=new yr(!1);this.playingRepresentation$=new yr(void 0);this.playingRepresentationInit$=new yr(void 0);this.error$=new hV;this.gaps=[];this.subscription=new fV;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=Ui(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);ct(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new px(this.sourceBuffer),this.sourceBufferBufferedDiff=new ol(this.mediaSource,this.sourceBuffer),this.subscription.add(Bx(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:vr.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o||!j(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,Jr(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=De(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);ct(i,"No init buffer for starting representation"),ct(r,"No segments for starting representation"),i instanceof ArrayBuffer&&(this.searchGaps(r,t),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(a))}.bind(this));this.switchTo=Ui(this.destroyAbortController.signal,async function*(e,t=!1){if(!j(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);ct(i,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if(Qe(a)||Qe(r)?yield this.loadInit(i,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),ct(r,"No segments for starting representation"),a=this.initData.get(e),!(!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer||!j(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();ps(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=Ui(this.destroyAbortController.signal,async function*(e,t=!1){if(!j(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);ct(i,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if(Qe(a)||Qe(r)?yield this.loadInit(i,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),ct(r,"No segments for starting representation"),a=this.initData.get(e),!(!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer||!j(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();ps(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=Ui(this.destroyAbortController.signal,async function*(e){var u,l;let t=(u=(0,cl.default)(e,d=>d.representations))!=null?u:[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let d of this.representations.keys()){let c=t.find(f=>f.id===d);c&&this.representations.set(d,c);let h=this.representations.get(d);if(!h||!st(h.segmentReference))return;let p=this.getActualLiveStartingSegments(h.segmentReference);this.segments.set(h.id,p)}let i=(l=this.switchingToRepresentationId)!=null?l:this.downloadingRepresentationId,r=this.representations.get(i);ct(r);let a=this.segments.get(i);ct(a,"No segments for starting representation");let n=this.initData.get(i);if(ct(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer))return;let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(a,r),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));var d;this.fetcher=r,this.tuning=a,this.compatibilityMode=u,this.forwardBufferTarget=a.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!(l!=null&&l.live),this.baseUrls=(d=l==null?void 0:l.baseUrls)!=null?d:[],this.initData=new Map(i.map(c=>[c.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(c=>[c.id,c])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchToWithPreviousAbort(e,t=!1){!j(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new ae,Ui(this.switchAbortController.signal,async function*(i,r=!1){this.switchingToRepresentationId=i;let a=this.representations.get(i);ct(a,`No such representation ${i}`);let n=this.segments.get(i),o=this.initData.get(i);if(Qe(o)||Qe(n)?yield this.loadInit(a,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(i),ct(n,"No segments for starting representation"),o=this.initData.get(i),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer||!j(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();ps(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)||!j(this.mediaSource,this.sourceBuffer)||ps(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(ct(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;let r=i.find(d=>e>=d.time.from&&e<d.time.to);ps(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=De(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)&&Jr(this.sourceBuffer.buffered)>=this.bufferLimit){let d=De(this.sourceBuffer.buffered,e),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,d<c).catch(h=>{this.handleAsyncError(h,"pruneBuffer")});return}let u=null;if(!this.activeSegments.size&&(u=this.selectForwardBufferSegments(i,t.segmentReference.type,a),u!=null&&u.length)){let d="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if((0,ll.default)(u,r))d="high";else{let c=(0,hs.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)&&De(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let l=(0,hs.default)(i,-1);!this.isLive&&l&&(this.fullyBuffered$.next(l.time.to-e-De(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;ps(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,cl.default)(e==null?void 0:e.streams[this.kind],r=>r.representations).find(r=>r.id===this.downloadingRepresentationId);if(!t)return;let i=this.segments.get(t.id);if(i!=null&&i.length)return{from:i[0].time.from,to:i[i.length-1].time.to}}updateLive(e){var i,r,a,n;let t=(i=(0,cl.default)(e==null?void 0:e.streams[this.kind],o=>o.representations))!=null?i:[];if(![...this.segments.values()].every(o=>!o.length))for(let o of t){if(!o||!st(o.segmentReference))return;let u=o.segmentReference.segments.map(p=>({...p,status:"none",size:void 0})),l=100,d=(r=this.segments.get(o.id))!=null?r:[],c=(n=(a=(0,hs.default)(d,-1))==null?void 0:a.time.to)!=null?n:0,h=u==null?void 0:u.findIndex(p=>c>=p.time.from+l&&c<=p.time.to+l);if(h===-1){this.liveUpdateSegmentIndex=0;let p=this.getActualLiveStartingSegments(o.segmentReference);this.segments.set(o.id,p)}else{let p=u.slice(h+1);this.segments.set(o.id,[...d,...p])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;ct(e);let t=this.segments.get(e);if(t!=null&&t.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}updateLowLatencyLiveIfNeeded(e){let t=0;for(let i of this.representations.values()){let r=i.segmentReference;if(!st(r))return;let a=this.segments.get(i.id);if(!a)continue;let n=a.find(u=>Math.floor(u.time.from)===Math.floor(e.time.from));if(n&&!isFinite(n.time.to)&&(n.time.to=e.time.to,t=n.time.to-n.time.from),!!!a.find(u=>Math.floor(u.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let u=Math.round(e.time.to*r.timescale/1e3).toString(10),l=wi(r.segmentTemplateUrl,{segmentTime:u});a.push({status:"none",time:{from:e.time.to,to:1/0},url:l})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){var a,n,o;let t=(n=(a=this.switchingToRepresentationId)!=null?a:this.downloadingRepresentationId)!=null?n:this.playingRepresentationId;if(!t)return;let i=this.segments.get(t);if(!i)return;let r=i.find(u=>u.time.from<=e&&u.time.to>=e);return(o=r==null?void 0:r.time.from)!=null?o:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e,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&&Jt&&Jt(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&Jt&&Jt(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&&j(this.mediaSource,this.sourceBuffer)&&!(Ge(this.sourceBuffer.buffered,h)&&Ge(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"){st(t.segmentReference)?await this.loadTemplateSegment(e[0],t,i):await this.loadByteRangeSegments(e,t,i)}async loadTemplateSegment(e,t,i="auto"){e.status="downloading";let r={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(r);let{range:a,url:n,signal:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await Ui(o,async function*(){let d=rh(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,d))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let d=await this.fetcher.fetch(n,{range:a,signal:o,onProgress:u,priority:i,isLowLatency:this.isActiveLowLatency()});if(this.lastDataObtainedTimestampMs=ul(),!d)return;let c=new DataView(d),h=io(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]),ro(d)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}updateRepresentationsBaseUrlIfNeeded(){if(!this.tuning.dash.enableBaseUrlSupport||!this.baseUrls.length||this.failedDownloads<=this.tuning.dash.maxSegmentRetryCount)return;this.baseUrlsIndex=(this.baseUrlsIndex+1)%this.baseUrls.length;let e=this.baseUrls[this.baseUrlsIndex];for(let t of this.representations.values())st(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}async loadByteRangeSegments(e,t,i="auto"){if(!e.length)return;for(let u of e)u.status="downloading",this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:r,url:a,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(await Ui(n,async function*(){let u=rh(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),Bx(window,"online").pipe(pV()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(a,{range:r,onProgress:o,signal:n,priority:i}),this.lastDataObtainedTimestampMs=ul(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),ro(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(st(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:(0,hs.default)(e,0).byte.from,to:(0,hs.default)(e,-1).byte.to},{signal:a}=this.downloadAbortController;return{url:i,range:r,signal:a,onProgress:async(o,u)=>{if(!a.aborted)try{this.lastDataObtainedTimestampMs=ul(),await this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:a,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:vr.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!st(t.segmentReference))throw new Error("Representation is not template type");let i=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&i.searchParams.set("low-latency","yes");let r=i.toString(),{signal:a}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,d)=>{if(!a.aborted)try{this.lastDataObtainedTimestampMs=ul();let c=this.onSomeTemplateDataLoaded({dataView:l,loaded:d,signal:a,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(c)}catch(c){this.error$.next({id:"SegmentFeeding",category:vr.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}}:void 0;return{url:r,signal:a,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,ll.default)(e,t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:a}){if(!this.activeSegments.size||!j(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=io(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||!j(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:io(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)||!j(this.mediaSource,this.sourceBuffer))){!this.isLive&&q.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(Ge(this.sourceBuffer.buffered,e.segment.time.from,100)&&Ge(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:vr.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",Zp(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=Xr(()=>(0,Dx.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?Ui(this.destroyAbortController.signal,async function*(){let o=rh(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,io(e.mime),r)).then(o=>{if(!o)return;let{init:u,dataView:l,segments:d}=o,c=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,c);let h=d;this.isLive&&st(e.segmentReference)&&(h=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,h),u&&this.parsedInitData.set(e.id,u)}).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:vr.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||!j(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=Zp(o)?(l=o.size)!=null?l:0:o.byte.to-o.byte.from;a+=u};for(let o of this.segments.values())for(let u of o){let l=u.time.to<=e-this.tuning.dash.bufferPruningSafeZone,d=u.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(l||d)&&u.status==="fed"&&n(u)}for(let o=0;o<this.sourceBuffer.buffered.length;o++){let u=this.sourceBuffer.buffered.start(o)*1e3,l=this.sourceBuffer.buffered.end(o)*1e3,d=0;for(let c of this.segments.values())for(let h of c)(0,ll.default)(["none","partially_ejected"],h.status)&&Math.round(h.time.from)<=Math.round(u)&&Math.round(h.time.to)>=Math.round(l)&&d++;if(d===this.segments.size){let c={time:{from:u,to:l},url:"",status:"none"};n(c)}}if(r.length&&i){let o=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let u of this.segments.values())for(let l of u)l.time.from>=e+o&&l.status==="fed"&&n(l)}return r.length?(r=wx(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||!j(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||!j(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||!j(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||!j(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||Qe(e)?0:De(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!this.sourceBuffer||!j(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||!j(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=Xr(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:vr.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if(Qe(this.sourceBuffer)||!j(this.mediaSource,this.sourceBuffer)||Qe(this.playingRepresentationId)||this.sourceBufferBufferedDiff&&!this.sourceBufferBufferedDiff.wasUpdated())return;let e=nl(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:vr.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}};import{abortable as ao,assertNever as Cx,fromEvent as Vx,merge as mV,now as no,Subject as Ox,ValueSubject as sh,flattenObject as fs,ErrorCategory as oo,SubscriptionRemovable as bV}from"@vkontakte/videoplayer-shared/es2018";var pl=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:a=!1}){this.lastConnectionType$=new sh(void 0);this.lastConnectionReused$=new sh(void 0);this.lastRequestFirstBytes$=new sh(void 0);this.recoverableError$=new Ox;this.error$=new Ox;this.abortAllController=new ae;this.subscription=new bV;this.fetchManifest=ao(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=_i(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=Uu(i));let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(dl);return r?(t.log("success",fs({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(r.headers),r.text()):(t.error("error",fs({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=ao(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,L,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:Cx(t)}this.requestQuic&&(l=_i(l));let h=this.abortAllController.signal,p;if(n){let U=new ae;if(p=mV(Vx(this.abortAllController.signal,"abort"),Vx(n,"abort")).subscribe(()=>{try{U.abort()}catch(P){dl(P)}}),this.subscription.add(p),this.abortAllController.signal.aborted||n.aborted)try{U.abort()}catch(P){dl(P)}h=U.signal}let f=no();c.log("startRequest",fs({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=no();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=no(),P={requestStartedAt:f,requestEndedAt:U,duration:U-f};return c.log("endRequest",fs(P)),c.end(),m.arrayBuffer()}let S=m.body;if(o){let U;[S,U]=m.body.tee(),(L=this.throughputEstimator)==null||L.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,$=U=>{this.unsubscribeAbortSubscription(p),O=!0,dl(U)},w=ao(h,async function*({done:U,value:P}){if(T===0&&this.lastRequestFirstBytes$.next(no()-f),h.aborted){this.unsubscribeAbortSubscription(p);return}if(!U&&P){if(y)E.set(P,T),T+=P.byteLength;else{let F=new Uint8Array(E.length+P.length);F.set(E),F.set(P,E.length),E=F,T+=P.byteLength}r==null||r(new DataView(E.buffer),T),yield v==null?void 0:v.read().then(w,$)}}.bind(this));yield v==null?void 0:v.read().then(w,$),this.unsubscribeAbortSubscription(p);let A=no(),C={failed:O,requestStartedAt:f,requestEndedAt:A,duration:A-f};return O?(c.error("endRequest",fs(C)),c.end(),null):(c.log("endRequest",fs(C)),c.end(),E.buffer)}.bind(this));this.fetchByteRangeRepresentation=ao(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=ao(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}=Nu(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:Cx(r)}}destroy(){this.abortAllController.abort(),this.tracer.end(),this.subscription.unsubscribe()}async doFetch(e,t){let i=await Pt(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:oo.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:oo.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:oo.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:oo.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${a})`,category:oo.FATAL})}}unsubscribeAbortSubscription(e){e&&(e.unsubscribe(),this.subscription.remove(e))}},dl=s=>{if(!ro(s))throw s};import{isNullable as gV,ValueSubject as SV}from"@vkontakte/videoplayer-shared/es2018";var uo=class s{constructor(e,t){this.currentRepresentation$=new SV(null);this.maxRepresentations=4;this.representationsCursor=0;this.representations=[];this.currentSegment=null;this.getCurrentPosition=t.getCurrentPosition,this.processStreams(e)}updateLive(e){this.processStreams(e==null?void 0:e.streams.text)}seekLive(e){this.processStreams(e)}maintain(e=this.getCurrentPosition()){var t;if(!gV(e))for(let i of this.representations)for(let r of i){let a=r.segmentReference,n=a.segments.length,o=a.segments[0].time.from,u=a.segments[n-1].time.to;if(e<o||e>u)continue;let l=a.segments.find(d=>d.time.from<=e&&d.time.to>=e);!l||((t=this.currentSegment)==null?void 0:t.time.from)===l.time.from&&this.currentSegment.time.to===l.time.to||(this.currentSegment=l,this.currentRepresentation$.next({...r,label:"Live Text",language:"ru",isAuto:!0,url:new URL(l.url,a.baseUrl).toString()}))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e!=null?e:[]){let i=s.filterRepresentations(t.representations);if(i){this.representations[this.representationsCursor]=i,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!(e!=null&&e.some(t=>s.filterRepresentations(t.representations)))}static filterRepresentations(e){return e==null?void 0:e.filter(t=>t.kind==="text"&&"segmentReference"in t&&st(t.segmentReference))}};var xV=["progress","play","seeked","stalled","waiting"],EV=["timeupdate","progress","loadeddata","playing","seeked"];var ml=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new lh;this.representationSubscription=new lh;this.state$=new H("none");this.currentVideoRepresentation$=new fe(void 0);this.currentVideoRepresentationInit$=new fe(void 0);this.currentAudioRepresentation$=new fe(void 0);this.currentVideoSegmentLength$=new fe(0);this.currentAudioSegmentLength$=new fe(0);this.error$=new fl;this.lastConnectionType$=new fe(void 0);this.lastConnectionReused$=new fe(void 0);this.lastRequestFirstBytes$=new fe(void 0);this.currentLiveTextRepresentation$=new fe(null);this.isLive$=new fe(!1);this.isActiveLive$=new fe(!1);this.isLowLatency$=new fe(!1);this.liveDuration$=new fe(0);this.liveSeekableDuration$=new fe(0);this.liveAvailabilityStartTime$=new fe(0);this.liveStreamStatus$=new fe(void 0);this.bufferLength$=new fe(0);this.liveLatency$=new fe(void 0);this.liveLoadBufferLength$=new fe(0);this.livePositionFromPlayer$=new fe(0);this.currentStallDuration$=new fe(0);this.videoLastDataObtainedTimestamp$=new fe(0);this.fetcherRecoverableError$=new fl;this.fetcherError$=new fl;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new fl;this.gapWatchdogActive=!1;this.destroyController=new ae;this.initManifest=nh(this.destroyController.signal,async function*(e,t,i){var r;this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=Se(t,i,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),(r=this.manifest)!=null&&r.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:qt.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=nh(this.destroyController.signal,async function*(){var n,o;this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(u=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:qt.NETWORK,message:"Failed to load manifest",thrown:u})});if(!e)return null;let t=null;try{t=$x(e!=null?e:"",this.manifestUrlString)}catch(u){let l=(n=Cu(e))!=null?n:{id:"ManifestParsing",category:qt.PARSER,message:"Failed to parse MPD manifest",thrown:u};this.error$.next(l)}if(!t)return null;let i=(u,l,d)=>{var c,h,p,f;return!!((h=(c=this.element)==null?void 0:c.canPlayType)!=null&&h.call(c,l)&&((f=(p=It())==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=Yu(c);if(h&&(r[u]=d.filter(({codecs:p})=>p.startsWith(h))),u==="video"){let p=this.tuning.preferHDR,f=r.video.some(g=>g.hdr),m=r.video.some(g=>!g.hdr);q.display.isHDR&&p&&f?r.video=r.video.filter(g=>g.hdr):m&&(r.video=r.video.filter(g=>!g.hdr))}}let a={...t,streams:r};return this.tracer.log("updateManifestEnd",co(a)),a}.bind(this));this.initRepresentations=nh(this.destroyController.signal,async function*(e,t,i){var h;this.tracer.log("initRepresentationsStart",co({initialVideo:e,initialAudio:t,sourceHls:i})),ms(this.manifest),ms(this.element),this.representationSubscription.unsubscribe(),this.representationSubscription=new lh,this.state$.startTransitionTo("representations_ready");let r=p=>{this.representationSubscription.add(Zt(p,"error").pipe(hl(f=>{var m;return!!((m=this.element)!=null&&m.played.length)})).subscribe(f=>{this.error$.next({id:"VideoSource",category:qt.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:f})}))};this.source=this.tuning.useManagedMediaSource?du():new MediaSource;let a=document.createElement("source");if(r(a),a.src=URL.createObjectURL(this.source),this.element.appendChild(a),this.tuning.useManagedMediaSource&&jr())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 so("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],po(t)){let p=this.manifest.streams.audio.reduce((f,m)=>[...f,...m.representations],[]);this.audioBufferManager=new so("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}uo.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new uo(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(Tr(...EV.map(p=>Zt(this.element,p))).pipe(gs(p=>this.element?De(this.element.buffered,this.element.currentTime*1e3):0),lo(),IV(p=>{p>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add(Tr(Zt(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe(lo()).subscribe(f=>this.liveStreamEndTimestamp=uh())),this.subscription.add(Zt(this.element,"pause").subscribe(()=>{this.livePauseWatchdogSubscription=oh(1e3).subscribe(f=>{let m=$i(this.manifestUrlString,2);this.manifestUrlString=Se(this.manifestUrlString,m+1e3,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add(Zt(this.element,"play").subscribe(f=>{var m;return(m=this.livePauseWatchdogSubscription)==null?void 0:m.unsubscribe()})),this.representationSubscription.add(bs({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(gs(({isActiveLive:f,isLowLatency:m})=>f&&m),lo()).subscribe(f=>{this.isManualDecreasePlaybackInLive()||ns(this.element,1)})),this.representationSubscription.add(bs({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(hl(({bufferLength:f,isActiveLive:m,isLowLatency:g})=>m&&g&&!!f)).subscribe(({bufferLength:f})=>this.liveBuffer.next(f))),this.representationSubscription.add(this.videoBufferManager.currentLowLatencySegmentLength$.subscribe(f=>{if(!this.isActiveLive$.getValue()&&!this.isLowLatency$.getValue()&&!f)return;let m=this.liveSeekableDuration$.getValue()-f/1e3;this.liveSeekableDuration$.next(Math.max(m,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+f/1e3)})),this.representationSubscription.add(bs({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(hl(({isLive:f})=>f),lo((f,m)=>m.bufferLength<f.bufferLength),gs(({rtt:f,bufferLength:m,segmentServerLatency:g})=>{let S=$i(this.manifestUrlString,2);return(f/2+m+g+S)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(bs({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),ns(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(bs({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(Nx(1e3)).subscribe(async({liveLoadBufferLength:f,bufferLength:m})=>{if(!this.element||this.isUpdatingLive)return;let g=this.element.playbackRate,S=$i(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(),$=v<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next($);let w="none";if(O?w="active_low_latency":this.isLowLatency$.getValue()&&$?(this.bufferManagers.forEach(A=>A.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 A=p-(y+I),C=this.normolizeLiveOffset(Math.trunc(S+A/g)),M=Math.abs(C-S),L=0;!f||M<=this.tuning.dashCmafLive.offsetCalculationError?L=S:C>0&&M>this.tuning.dashCmafLive.offsetCalculationError&&(L=C),this.manifestUrlString=Se(this.manifestUrlString,L,2)}(w==="live_with_target_offset"||w==="live_forward_buffering")&&(p=0,await this.updateLive())},f=>{this.error$.next({id:"updateLive",category:qt.VIDEO_PIPELINE,thrown:f,message:"Failed to update live with subscription"})}))}let l=Tr(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe(gs(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),d=Tr(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe(gs(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue()))),c=bs({allBuffersFull:l,someBufferEnded:d}).pipe(lo(),gs(({allBuffersFull:p,someBufferEnded:f})=>p&&f),hl(p=>p));if(this.representationSubscription.add(Tr(this.forceEnded$,c).subscribe(()=>{var p;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(f=>!f.updating))try{(p=this.source)==null||p.endOfStream()}catch(f){this.error$.next({id:"EndOfStream",category:qt.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:f})}})),this.representationSubscription.add(Tr(...this.bufferManagers.map(p=>p.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.representationSubscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.representationSubscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.liveTextManager&&this.representationSubscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$)),this.source.readyState!=="open"){let p=this.tuning.dash.sourceOpenTimeout>=0;yield new Promise(f=>{var m;p&&(this.timeoutSourceOpenId=setTimeout(()=>{var g;if(((g=this.source)==null?void 0:g.readyState)==="open"){f();return}this.error$.next({id:"OpenOfStream",category:qt.VIDEO_PIPELINE,message:"Failed to open MediaSource",thrown:new Error("Timeout reject when wait sourceopen event"),traceAsLog:!0})},this.tuning.dash.sourceOpenTimeout)),(m=this.source)==null||m.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),f()},{once:!0})})}if(!this.isLive$.getValue()){let p=[(h=this.manifest.duration)!=null?h:0,...(0,ch.default)((0,ch.default)([...this.manifest.streams.audio,...this.manifest.streams.video],f=>f.representations),f=>{let m=[];return f.duration&&m.push(f.duration),st(f.segmentReference)&&f.segmentReference.totalSegmentsDurationMs&&m.push(f.segmentReference.totalSegmentsDurationMs),m})];this.source.duration=Math.max(...p)/1e3}this.audioBufferManager&&po(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")}.bind(this));this.tick=()=>{var t,i,r,a;if(!this.element||!this.videoBufferManager||((t=this.source)==null?void 0:t.readyState)!=="open")return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),(i=this.audioBufferManager)==null||i.maintain(e),(r=this.liveTextManager)==null||r.maintain(e),(this.videoBufferManager.gaps.length||(a=this.audioBufferManager)!=null&&a.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=oh(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),n=>{this.error$.next({id:"GapWatchdog",category:qt.WTF,message:"Error handling gaps",thrown:n})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name);let t=e.tuning.dash.useOldFetherInNewDashProvider?as:pl;this.fetcher=new t({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.subscription.add(this.fetcher.recoverableError$.subscribe(this.fetcherRecoverableError$)),this.subscription.add(this.fetcher.error$.subscribe(this.fetcherError$)),this.liveBuffer=Ii.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator}),this.initTracerSubscription()}async seekLive(e){var r,a,n;ms(this.element);let t=this.liveStreamStatus$.getValue()!=="active"?uh()-this.liveStreamEndTimestamp:0,i=this.normolizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=Se(this.manifestUrlString,i,2),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await((r=this.videoBufferManager)==null?void 0:r.seekLive(this.manifest.streams.video)),await((a=this.audioBufferManager)==null?void 0:a.seekLive(this.manifest.streams.audio)),(n=this.liveTextManager)==null||n.seekLive(this.manifest.streams.text))}initBuffer(){ms(this.element),this.state$.setState("running");let e=Zt(this.element,"timeupdate");this.tuning.dash.timeupdateEventTickThrottle&&(e=e.pipe(Nx(this.tuning.dash.timeupdateEventTickThrottle))),this.subscription.add(Tr(...xV.map(t=>Zt(this.element,t)),Zt(window,"online"),e).subscribe(()=>this.tick(),t=>{this.error$.next({id:"DashVKPlayer",category:qt.WTF,message:"Internal logic error",thrown:t})})),this.subscription.add(Zt(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(Zt(this.element,"waiting").subscribe(()=>{var i;this.element&&this.element.readyState===HTMLMediaElement.HAVE_CURRENT_DATA&&!this.element.seeking&&Ge(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,$;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=uh(),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(A=>{this.error$.next({id:"stallIntervalCallback",category:qt.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:A})}),a.liveLastOffset=w}else{let w=this.element.currentTime*1e3;(O=this.videoBufferManager)==null||O.maintain(w),($=this.audioBufferManager)==null||$.maintain(w),a.position=w}this.tracer.log("stallIntervalCallback",co(a))};(i=this.stallWatchdogSubscription)==null||i.unsubscribe(),this.stallWatchdogSubscription=oh(50).subscribe(t,r=>{this.error$.next({id:"StallWatchdogCallback",category:qt.NETWORK,message:"Can't restore DASH after stall.",thrown:r})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}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;ms(this.element),ms(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),Ge(this.element.buffered,i)||await Promise.all([this.videoBufferManager.abort(),(o=this.audioBufferManager)==null?void 0:o.abort()]),!(Fx(this.element)||Fx(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),(u=this.audioBufferManager)==null||u.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",co({requestedPosition:e,forcePrecise:t,position:i})))}warmUpMediaSourceIfNeeded(e=(t=>(t=this.element)==null?void 0:t.currentTime)()){var i;po(this.element)&&po(this.source)&&po(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=TV(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",co({isJumpGapAfterSeekLive:i,isActiveLowLatency:t,initialCurrentTime:r,jumpTo:u,resultCurrentTime:this.element.currentTime})))}}};import{combine as wV,map as PV,observeElementSize as AV,Subscription as kV,ValueSubject as dh,noop as RV}from"@vkontakte/videoplayer-shared/es2018";var bl=class{constructor(){this.subscription=new kV;this.pipSize$=new dh(void 0);this.videoSize$=new dh(void 0);this.elementSize$=new dh(void 0);this.pictureInPictureWindowRemoveEventListener=RV}connect({observableVideo:e,video:t}){let i=r=>{let a=r.target;this.pipSize$.next({width:a.width,height:a.height})};this.subscription.add(AV(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(wV({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(PV(({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 Ir=class{constructor(e){this.subscription=new CV;this.videoState=new H("stopped");this.droppedFramesManager=new Yr;this.stallsManager=new il;this.elementSizeManager=new bl;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Ci;this.audioTrackSwitchHistory=new Ci;this.selectedRepresentations={audio:null,video:null};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(r.state==="requested"&&(i==null?void 0:i.to)!=="paused"&&e!=="stopped"&&t!=="stopped"&&this.seek(r.position,r.forcePrecise),t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),R(this.params.desiredState.playbackState,"stopped",!0));return}switch(e){case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();return;case"ready":t==="paused"?(this.videoState.setState("paused"),R(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="ready"&&R(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):t==="playing"&&this.video.paused?this.playIfAllowed():(i==null?void 0:i.to)==="playing"&&R(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&R(this.params.desiredState.playbackState,"paused");return;default:return MV(e)}}};this.init3DScene=e=>{var i,r,a;if(this.scene3D)return;this.scene3D=new cs(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((i=e.projectionData)==null?void 0:i.pose.yaw)||0,y:((r=e.projectionData)==null?void 0:r.pose.pitch)||0,z:((a=e.projectionData)==null?void 0:a.pose.roll)||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSizeManager.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.textTracksManager=new ot(e.source.url),this.params=e,this.video=Ne(e.container,e.tuning),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(we(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.player=new ml({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params,i=je(this.video);this.subscription.add(()=>i.destroy());let r=this.constructor.name,a=o=>{e.error$.next({id:r,category:Ux.WTF,message:`${r} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:i,genericErrorListener:a,connect:(o,u)=>this.subscription.add(o.subscribe(u,a))}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:a}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(ph(c=>!!c.length),jx()).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(hh(c=>c.to.state!=="none"),gl());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(ph(qx),jx()),e.firstBytesEvent$),a(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),a(this.videoState.stateChangeEnded$.pipe(hh(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(wt(this.video,t.isLooped,r)),this.subscription.add(qe(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(nt(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),a(ut(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),R(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),R(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:c})=>{if(c==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let h=this.player.getStreams();if($V(h,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let f=[];for(let m of h.audio){f.push(Xp(m));let g=[];for(let S of m.representations){let v=Ix(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(Jp(f));let m=[];for(let g of f.representations){let S=Tx({...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=xx(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&&Px(o)||null;this.subscription.add(Sl(this.player.currentStallDuration$,this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,this.elementSizeManager.getObservable(),this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,DV(this.video,"progress")).pipe(ph(()=>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=Sr(this.videoTracksMap.keys(),S=>{var v;return((v=this.videoTracksMap.get(S))==null?void 0:v.representation.id)===p.id});qx(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(gl()).subscribe(c=>{let h=Sr(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(Jp(f))},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(gl()).subscribe(c=>{let h=Sr(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(Xp(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(hh(({to:c})=>c==="ready"),gl());this.subscription.add(Sl(l,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,fh(["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(Sl(l,this.player.state$.stateChangeEnded$,fh(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let d=Sl(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,fh(["init"])).pipe(BV(0));this.subscription.add(d.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){var $,w,A,C,M,L,Q,U,P,F,k,x;if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?Da:Ba,t=this.params.tuning.useNewAutoSelectVideoTrack?ku:Au,i=this.params.tuning.useNewAutoSelectVideoTrack?Xt:Pu,{desiredState:r,output:a}=this.params,n=r.autoVideoTrackSwitching.getState(),o=($=r.videoTrack.getState())==null?void 0:$.id,u=Sr(this.videoTracksMap.keys(),B=>B.id===o),l=a.currentVideoTrack$.getValue(),d=((C=(A=r.videoStream.getState())!=null?A: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=Sr(this.videoStreamsMap.keys(),B=>B.id===d.id),h=c&&this.videoStreamsMap.get(c);if(!h)return;let p=De(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)&&Sr(this.audioStreamsMap.keys(),B=>B.id===S.id)||this.audioStreamsMap.keys().next().value,y=0;if(v){if(u&&!n){let B=e(u,h,(L=this.audioStreamsMap.get(v))!=null?L:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);y=Math.max(y,(Q=B==null?void 0:B.bitrate)!=null?Q:-1/0)}if(l){let B=e(l,h,(U=this.audioStreamsMap.get(v))!=null?U:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);y=Math.max(y,(P=B==null?void 0:B.bitrate)!=null?P:-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(){He(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),R(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Ux.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.stallsManager.destroy(),this.elementSizeManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),this.params.output.currentVideoStream$.next(void 0),Ue(this.video),this.tracer.end()}};var ho=class extends Ir{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 mh,merge as Hx,filter as Gx,filterChanged as VV,isNullable as bh,map as zx,ValueSubject as gh,isNonNullable as OV}from"@vkontakte/videoplayer-shared/es2018";var fo=class extends Ir{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 gh(1);a(i.playbackRateState$,n),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(r.isLowLatency.stateChangeEnded$.pipe(zx(o=>o.to)).subscribe(this.player.isLowLatency$)).add(mh({liveBufferTime:t.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(zx(({liveBufferTime:o,liveAvailabilityStartTime:u})=>o&&u?o+u:void 0)).subscribe(t.liveTime$)).add(this.player.liveStreamStatus$.pipe(Gx(o=>OV(o))).subscribe(o=>t.isLiveEnded$.next(o!=="active"&&t.position$.getValue()===0))).add(mh({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:Hx(i.playbackRateState$,new gh(1))}).pipe(Gx(({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||bh(l)||(e=o-l)})).add(mh({time:t.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:Hx(i.playbackRateState$,new gh(1))}).pipe(VV((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||bh(o)||bh(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=Ex(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 Wx=N(Aa(),1);import{assertNever as mo,assertNonNullable as Qx,debounce as _V,ErrorCategory as vl,filter as FV,isNonNullable as NV,isNullable as UV,map as yl,merge as qV,Observable as jV,observableFrom as HV,Subscription as GV,videoSizeToQuality as zV}from"@vkontakte/videoplayer-shared/es2018";var jt={};var Ss=(s,e)=>new jV(t=>{let i=(r,a)=>t.next(a);return s.on(e,i),()=>s.off(e,i)}),bo=class{constructor(e){this.subscription=new GV;this.videoState=new H("initializing");this.trackLevels=new Map;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(e!=="initializing")switch((i==null?void 0:i.to)!=="paused"&&r.state==="requested"&&this.seek(r.position),t){case"stopped":switch(e){case"stopped":break;case"ready":case"playing":case"paused":this.stop();break;default:mo(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:mo(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:mo(e)}break;case"paused":switch(e){case"paused":break;case"stopped":this.prepare();break;case"ready":this.videoState.setState("paused"),R(this.params.desiredState.playbackState,"paused");break;case"playing":this.pause();break;default:mo(e)}break;default:mo(t)}};this.textTracksManager=new ot(e.source.url),this.video=Ne(e.container,e.tuning),this.params=e,this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(we(this.params.source.url)),this.loadHlsJs()}destroy(){var e,t;this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),(e=this.hls)==null||e.detachMedia(),(t=this.hls)==null||t.destroy(),this.params.output.element$.next(void 0),Ue(this.video)}loadHlsJs(){let e=!1,t=r=>{e||this.params.output.error$.next({id:r==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:vl.NETWORK,message:"Failed to load Hls.js",thrown:r}),e=!0},i=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);(0,Wx.default)(import("hls.js").then(r=>{e||(jt.Hls=r.default,jt.Events=r.default.Events,this.init())},t),()=>{window.clearTimeout(i),e=!0})}init(){Qx(jt.Hls,"hls.js not loaded"),this.hls=new jt.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){Qx(jt.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,i=l=>{t.error$.next({id:"HlsJsProvider",category:vl.WTF,message:"HlsJsProvider internal logic error",thrown:l})},r=je(this.video);this.subscription.add(()=>r.destroy());let a=(l,d)=>this.subscription.add(l.subscribe(d,i));a(r.timeUpdate$,t.position$),a(r.durationChange$,t.duration$),a(r.ended$,t.endedEvent$),a(r.looped$,t.loopedEvent$),a(r.error$,t.error$),a(r.isBuffering$,t.isBuffering$),a(r.currentBuffer$,t.currentBuffer$),a(r.loadStart$,t.firstBytesEvent$),a(r.loadedMetadata$,t.loadedMetadataEvent$),a(r.playing$,t.firstFrameEvent$),a(r.canplay$,t.canplay$),a(r.seeked$,t.seekedEvent$),a(r.inPiP$,t.inPiP$),a(r.inFullscreen$,t.inFullscreen$),this.subscription.add(wt(this.video,e.isLooped,i)),this.subscription.add(qe(this.video,e.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(nt(this.video,e.playbackRate,r.playbackRateState$,i)),a(ut(this.video),t.elementVisible$),a(this.videoState.stateChangeEnded$.pipe(yl(l=>l.to)),this.params.output.playbackState$),this.subscription.add(Ss(this.hls,jt.Events.ERROR).subscribe(l=>{var d;l.fatal&&t.error$.next({id:["HlsJsFatal",l.type,l.details].join("_"),category:vl.WTF,message:`HlsJs fatal ${l.type} ${l.details}, ${(d=l.err)==null?void 0:d.message} ${l.reason}`,thrown:l.error})})),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),R(e.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),R(e.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())==null?void 0:l.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),a(Ss(this.hls,jt.Events.MANIFEST_PARSED).pipe(yl(({levels:l})=>l.reduce((d,c)=>{var v,y;let h=c.name||c.height.toString(10),{width:p,height:f}=c,m=(y=Kt((v=c.attrs.QUALITY)!=null?v:""))!=null?y:zV({width:p,height:f});if(!m)return d;let g=c.attrs["FRAME-RATE"]?parseFloat(c.attrs["FRAME-RATE"]):void 0,S={id:h.toString(),quality:m,bitrate:c.bitrate/1e3,size:{width:p,height:f},fps:g};return this.trackLevels.set(h,{track:S,level:c}),d.push(S),d},[]))),t.availableVideoTracks$),a(Ss(this.hls,jt.Events.MANIFEST_PARSED),l=>{if(l.subtitleTracks.length>0){let d=[];for(let c of l.subtitleTracks){let h=c.name,p=c.attrs.URI||"",f=c.lang;d.push({id:h,url:p,language:f,type:"internal"})}e.internalTextTracks.startTransitionTo(d)}}),a(Ss(this.hls,jt.Events.LEVEL_LOADING).pipe(yl(({url:l})=>we(l))),t.hostname$),a(Ss(this.hls,jt.Events.FRAG_CHANGED),l=>{var h,p,f,m;let{video:d,audio:c}=l.frag.elementaryStreams;t.currentVideoSegmentLength$.next((((h=d==null?void 0:d.endPTS)!=null?h:0)-((p=d==null?void 0:d.startPTS)!=null?p:0))*1e3),t.currentAudioSegmentLength$.next((((f=c==null?void 0:c.endPTS)!=null?f:0)-((m=c==null?void 0:c.startPTS)!=null?m:0))*1e3)}),this.subscription.add(Bi(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,l=>{this.hls.nextLevel=l?-1:this.hls.currentLevel,this.hls.loadLevel=l?-1:this.hls.loadLevel},{onError:i}));let n=l=>{var d;return(d=Array.from(this.trackLevels.values()).find(({level:c})=>c===l))==null?void 0:d.track},o=Ss(this.hls,jt.Events.LEVEL_SWITCHED).pipe(yl(({level:l})=>n(this.hls.levels[l])));o.pipe(FV(NV)).subscribe(t.currentVideoTrack$,i),this.subscription.add(Bi(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),l=>{var f;if(UV(l))return;let d=(f=this.trackLevels.get(l.id))==null?void 0:f.level;if(!d)return;let c=this.hls.levels.indexOf(d),h=this.hls.currentLevel,p=this.hls.levels[h];!p||d.bitrate>p.bitrate?this.hls.nextLevel=c:(this.hls.loadLevel=c,this.hls.loadLevel=c)},{changed$:o,onError:i})),a(r.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);let u=qV(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,HV(["init"])).pipe(_V(0));this.subscription.add(u.subscribe(this.syncPlayback,i))}prepare(){this.videoState.startTransitionTo("ready"),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}async playIfAllowed(){this.videoState.startTransitionTo("playing"),await He(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:vl.DOM,thrown:t}))||(this.videoState.setState("paused"),R(this.params.desiredState.playbackState,"paused",!0))}pause(){this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.hls.stopLoad(),this.hls.detachMedia(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"),R(this.params.desiredState.playbackState,"stopped",!0)}};var Yx="X-Playback-Duration",Sh=async s=>{var r;let e=await Pt(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(Yx)?parseInt(e.headers.get(Yx),10):void 0};import{assertNever as rO,combine as sO,debounce as aO,ErrorCategory as xl,filter as nO,filterChanged as oO,isNonNullable as Jx,isNullable as El,map as Zx,merge as uO,observableFrom as lO,Subscription as cO,ValueSubject as Th,VideoQuality as dO}from"@vkontakte/videoplayer-shared/es2018";var yh=N(Wc(),1);import{videoSizeToQuality as QV,getExponentialDelay as WV}from"@vkontakte/videoplayer-shared/es2018";var YV=s=>{let e=null;if(s.QUALITY&&(e=Kt(s.QUALITY)),!e&&s.RESOLUTION){let[t,i]=s.RESOLUTION.split("x").map(r=>parseInt(r,10));e=QV({width:t,height:i})}return e!=null?e:null},KV=(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,yh.default)(l[1].split(",").map(v=>v.split("="))),h=(a=c.QUALITY)!=null?a:`stream-${c.BANDWIDTH}`,p=YV(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,yh.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}},XV=s=>new Promise(e=>{setTimeout(()=>{e()},s)}),vh=0,Kx=async(s,e=s,t,i)=>{let a=await(await Pt(s,i)).text();vh+=1;try{let{qualityManifests:n,textTracks:o}=KV(a,e);return{qualityManifests:n,textTracks:o}}catch(n){if(vh<=t.manifestRetryMaxCount)return await XV(WV(vh-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),Kx(s,e,t)}return{qualityManifests:[],textTracks:[]}},Tl=Kx;import{isNonNullable as JV,Subscription as ZV,throttle as eO,ValueSubject as Xx,Subject as tO,ErrorCategory as iO}from"@vkontakte/videoplayer-shared/es2018";var Il=class{constructor(e,t,i,r,a){this.subscription=new ZV;this.abortControllers={destroy:new ae,nextManifest:null};this.prepareUrl=void 0;this.currentTextTrackData=null;this.availableTextTracks$=new Xx(null);this.getCurrentTime$=new Xx(null);this.error$=new tO;this.params={fetchManifestData:i,sourceUrl:r,downloadThreshold:a},this.subscription.add(e.pipe(eO(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 Pt(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(JV(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:iO.WTF,thrown:t,message:e})}};var go=class{constructor(e){this.subscription=new cO;this.videoState=new H("stopped");this.textTracksManager=null;this.liveTextManager=null;this.manifests$=new Th([]);this.liveOffset=new lr;this.manifestStartTime$=new Th(void 0);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),R(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(a||n||o){let d=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(d),this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((r==null?void 0:r.to)!=="paused"&&l.state==="requested"){this.videoState.startTransitionTo("ready"),this.seek(l.position&&l.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":i==="ready"?R(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),R(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&R(this.params.desiredState.playbackState,"playing");return;case"paused":if(i==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let d=this.liveOffset.getTotalOffset();d>=this.maxSeekBackTime$.getValue()&&(d=0,this.liveOffset.resetTo(d)),this.liveOffset.resume(),this.params.output.position$.next(-d/1e3),this.prepare()}else(r==null?void 0:r.to)==="paused"&&(R(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return rO(t)}};var i;this.params=e,this.video=Ne(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:dO.INVARIANT,url:this.params.source.url};let t=(r,a)=>Tl(r,this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},a);this.params.tuning.useHlsLiveNewTextManager?this.liveTextManager=new Il(this.params.output.liveTime$,this.video,t,this.params.source.url,this.params.tuning.hlsLiveNewTextManagerDownloadThreshold):this.textTracksManager=new ot(e.source.url),t(this.generateLiveUrl()).then(({qualityManifests:r,textTracks:a})=>{var n;r.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:xl.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),(n=this.liveTextManager)==null||n.processTextTracks(a,this.params.source.url),this.manifests$.next([this.masterManifest,...r])}).catch(r=>{this.params.output.error$.next({id:"ExtractHlsQualities",category:xl.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:r})}),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(we(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new Th((i=e.source.maxSeekBackTime)!=null?i:1/0),this.subscribe()}selectManifest(){var u,l,d,c;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),a=(c=(d=(u=r==null?void 0:r.to)==null?void 0:u.id)!=null?d:(l=t.getState())==null?void 0:l.id)!=null?c:"master",n=this.manifests$.getValue();if(!n.length)return;let o=i?"master":a;return i&&!r&&t.startTransitionTo(this.masterManifest),n.find(h=>h.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsLiveProvider",category:xl.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},r=je(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(qe(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(nt(this.video,t.playbackRate,r.playbackRateState$,i)),a(ut(this.video),e.elementVisible$),this.liveTextManager?(a(this.liveTextManager.getCurrentTime$,this.params.output.getCurrentTime$),a(this.liveTextManager.error$,this.params.output.error$)):this.textTracksManager&&this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),R(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),R(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.liveTextManager&&this.subscription.add(this.liveTextManager.availableTextTracks$.subscribe(o=>{o&&this.params.output.availableTextTracks$.next(o)})),this.subscription.add(this.maxSeekBackTime$.pipe(oO(),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&&Jx(l.to)){let c=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let h=this.manifests$.getValue().find(p=>p.id===c);h&&(this.params.output.currentVideoTrack$.next(h),this.params.output.hostname$.next(we(h.url)))}d&&this.params.desiredState.autoVideoTrackSwitching.setState(d.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o&&o.state==="requested"&&this.seek(o.position)},i)),this.subscription.add(r.loadedData$.subscribe(()=>{var u,l,d;let o=(d=(l=(u=this.video)==null?void 0:u.getStartDate)==null?void 0:l.call(u))==null?void 0:d.getTime();this.manifestStartTime$.next(o||void 0)},i)),this.subscription.add(sO({startTime:this.manifestStartTime$.pipe(nO(Jx)),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=uO(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,lO(["init"])).pipe(aO(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),Ue(this.video)}prepare(){var o,u,l;let e=this.selectManifest();if(El(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:d,min:c}=(u=(o=t==null?void 0:t.to)!=null?o:i)!=null?u:{};for(let[h,p]of[[d,"mq"],[c,"lq"]]){let f=String(parseFloat(h||""));p&&h&&r.searchParams.set(p,f)}}let a=this.params.format==="HLS_LIVE_CMAF"?2:0,n=Se(r.toString(),this.liveOffset.getTotalOffset(),a);(l=this.liveTextManager)==null||l.prepare(n),this.video.setAttribute("src",n),this.video.load(),Sh(n).then(d=>{var c;if(!El(d))this.maxSeekBackTime$.next(d);else{let h=(c=this.params.source.maxSeekBackTime)!=null?c:this.maxSeekBackTime$.getValue();(El(h)||!isFinite(h))&&Pt(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();Sh(g).then(S=>{El(S)||this.maxSeekBackTime$.next(S)})}}).catch(()=>{})}})}playIfAllowed(){He(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),R(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:xl.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3),this.params.output.seekedEvent$.next()}generateLiveUrl(){let e=Se(this.params.source.url);if(this.params.tuning.useHlsLiveNewTextManager){let t=new URL(e);t.searchParams.set("enable-subtitles","yes"),e=t.toString()}return e}};import{assertNever as pO,debounce as hO,ErrorCategory as Ih,fromEvent as xh,isNonNullable as fO,isNullable as mO,map as eE,merge as tE,observableFrom as iE,Subscription as bO,ValueSubject as gO,VideoQuality as SO}from"@vkontakte/videoplayer-shared/es2018";var So=class{constructor(e){this.subscription=new bO;this.videoState=new H("stopped");this.manifests$=new gO([]);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),R(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(a||n||o){let d=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(d);let{currentTime:c}=this.video;this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:c*1e3,forcePrecise:!0});return}switch((r==null?void 0:r.to)!=="paused"&&l.state==="requested"&&this.seek(l.position),t){case"ready":i==="ready"?R(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),R(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&R(this.params.desiredState.playbackState,"playing");return;case"paused":i==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&R(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return pO(t)}};this.textTracksManager=new ot(e.source.url),this.params=e,this.video=Ne(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:SO.INVARIANT,url:this.params.source.url},this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(we(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),Tl(Se(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:t,textTracks:i})=>{this.manifests$.next([this.masterManifest,...t]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(i)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:Ih.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:Ih.WTF,message:"HlsProvider internal logic error",thrown:o})},r=je(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(eE(o=>o.to)),this.params.output.playbackState$),this.subscription.add(wt(this.video,t.isLooped,i)),this.subscription.add(qe(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(nt(this.video,t.playbackRate,r.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),R(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),R(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i).add(r.loadedMetadata$.subscribe(()=>{var p;let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&fO(l.to)){let f=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let m=this.manifests$.getValue().find(g=>g.id===f);m&&(this.params.output.currentVideoTrack$.next(m),this.params.output.hostname$.next(we(m.url)))}let c=this.params.desiredState.playbackRate.getState(),h=(p=this.params.output.element$.getValue())==null?void 0:p.playbackRate;if(c!==h){let f=this.params.output.element$.getValue();f&&(this.params.desiredState.playbackRate.setState(c),f.playbackRate=c)}d&&this.params.desiredState.autoVideoTrackSwitching.setState(d.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o.state==="requested"&&this.seek(o.position)},i))),this.subscription.add(this.manifests$.pipe(eE(o=>o.map(({id:u,quality:l,size:d,bandwidth:c,fps:h})=>({id:u,quality:l,size:d,fps:h,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,i)),!q.device.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(tE(xh(o,"addtrack"),xh(o,"removetrack"),xh(o,"change"),iE(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},i))}let n=tE(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,iE(["init"])).pipe(hO(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Ue(this.video)}prepare(){var a,n;let e=this.selectManifest();if(mO(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(){He(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),R(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Ih.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var aE=N(er(),1),Eh=N(ur(),1),nE=N(_t(),1);import{assertNever as vO,assertNonNullable as rE,debounce as yO,ErrorCategory as sE,isHigherOrEqual as TO,isLowerOrEqual as IO,isNonNullable as xO,merge as EO,observableFrom as wO,Subscription as PO,map as AO}from"@vkontakte/videoplayer-shared/es2018";var vo=class{constructor(e){this.subscription=new PO;this.videoState=new H("stopped");this.trackUrls={};this.textTracksManager=new ot;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),R(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let a=this.params.desiredState.autoVideoTrackLimits.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.seekState.getState();if(a&&e!=="ready"&&!n){this.handleQualityLimitTransition(a.to);return}if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(n){let{currentTime:u}=this.video;this.prepare(),o.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:u*1e3,forcePrecise:!0});return}switch((i==null?void 0:i.to)!=="paused"&&o.state==="requested"&&this.seek(o.position),e){case"ready":t==="ready"?R(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),R(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(i==null?void 0:i.to)==="playing"&&R(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&R(this.params.desiredState.playbackState,"paused");return;default:return vO(e)}};this.params=e,this.video=Ne(e.container,e.tuning),this.params.output.element$.next(this.video),(0,aE.default)(this.params.source).reverse().forEach(([t,i],r)=>{let a=r.toString(10);this.trackUrls[a]={track:{quality:t,id:a},url:i}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next((0,Eh.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:sE.WTF,message:"MpegProvider internal logic error",thrown:o})},r=je(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(AO(o=>o.to)),this.params.output.playbackState$),this.subscription.add(wt(this.video,t.isLooped,i)),this.subscription.add(qe(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(nt(this.video,t.playbackRate,r.playbackRateState$,i)),a(ut(this.video),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),R(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),R(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var u,l;((u=this.videoState.getTransition())==null?void 0:u.to)==="ready"&&this.videoState.setState("ready");let o=this.params.desiredState.videoTrack.getTransition();if(o&&xO(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=EO(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,wO(["init"])).pipe(yO(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),Ue(this.video)}prepare(){var i;let e=(i=this.params.desiredState.videoTrack.getState())==null?void 0:i.id;rE(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];rE(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=_i(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(we(t))}playIfAllowed(){He(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),R(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:sE.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=Xt(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,Eh.default)(this.trackUrls).map(c=>c.track);if(!r||!a||Hr(e,n[0].quality,(d=(0,nE.default)(n,-1))==null?void 0:d.quality)){i();return}let o=e.max?IO(r,e.max):!0,u=e.min?TO(r,e.min):!0;o&&u||i(e)}};import{assertNever as uE,debounce as MO,merge as lE,observableFrom as $O,Subscription as BO,map as cE,ValueSubject as DO,ErrorCategory as Ph,VideoQuality as CO}from"@vkontakte/videoplayer-shared/es2018";import{ErrorCategory as kO}from"@vkontakte/videoplayer-shared/es2018";var oE=["stun:videostun.mycdn.me:80"],RO=1e3,LO=3,wh=()=>null,wl=class{constructor(e,t){this.ws=null;this.peerConnection=null;this.serverUrl="";this.streamKey="";this.stream=null;this.signalingType="JOIN";this.retryCount=0;this.externalStartCallback=wh;this.externalStopCallback=wh;this.externalErrorCallback=wh;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:oE}]};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:kO.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),RO)}normalizeOptions(e={}){let t={stunServerList:oE,maxRetryNumber:LO,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var yo=class{constructor(e){this.videoState=new H("stopped");this.maxSeekBackTime$=new DO(0);this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.pause(),this.video.srcObject=null,this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),R(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let a=this.params.desiredState.videoTrack.getTransition();if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(a){this.prepare();return}switch(e){case"ready":t==="paused"?(this.videoState.setState("paused"),R(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(i==null?void 0:i.to)==="playing"&&R(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&R(this.params.desiredState.playbackState,"paused");return;default:return uE(e)}};this.subscription=new BO,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=Ne(e.container,e.tuning),this.liveStreamClient=new wl(this.params.source.url,{maxRetryNumber:this.params.tuning.webrtc.connectionRetryMaxNumber,errorChanel:this.params.output.error$}),this.liveStreamClient.onStart(this.onLiveStreamStart.bind(this)),this.liveStreamClient.onStop(this.onLiveStreamStop.bind(this)),this.liveStreamClient.onError(this.onLiveStreamError.bind(this)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),Ue(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,i=n=>{e.error$.next({id:"WebRTCLiveProvider",category:Ph.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};this.subscription.add(lE(this.videoState.stateChangeStarted$.pipe(cE(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(cE(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})}));let r=je(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(ut(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(qe(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 uE(n.to)}},i)).add(lE(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,$O(["init"])).pipe(MO(0)).subscribe(this.syncPlayback.bind(this),i)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),i))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(we(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.currentVideoTrack$.next({id:"webrtc",quality:CO.INVARIANT}),this.video.srcObject=e,R(this.params.desiredState.playbackState,"playing")}onLiveStreamStop(){this.videoState.startTransitionTo("stopped"),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.params.output.endedEvent$.next()}onLiveStreamError(e){this.onLiveStreamStop(),this.params.output.error$.next({id:"WebRTC stream runtime error",category:Ph.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){He(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),R(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Ph.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var To=class{constructor(e){this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next()}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return!!this.current.done}};import{assertNever as xo,assertNonNullable as qi,ErrorCategory as Pl,filter as bE,isNonNullable as gE,isNullable as qO,map as jO,merge as HO,once as GO,Subject as Ce,Subscription as SE,ValueSubject as W,flattenObject as Ah}from"@vkontakte/videoplayer-shared/es2018";import{Observable as VO,map as dE,Subscription as OO,Subject as _O}from"@vkontakte/videoplayer-shared/es2018";var pE=s=>new VO(e=>{let t=new OO,i=s.desiredPlaybackState$.stateChangeStarted$.pipe(dE(({from:l,to:d})=>`${l}-${d}`)),r=s.desiredPlaybackState$.stateChangeEnded$,a=s.providerChanged$.pipe(dE(({type:l})=>l!==void 0)),n=new _O,o=0,u="unknown";return t.add(i.subscribe(l=>{o&&window.clearTimeout(o),u=l,o=window.setTimeout(()=>n.next(l),s.maxTransitionInterval)})),t.add(r.subscribe(()=>{window.clearTimeout(o),u="unknown",o=0})),t.add(a.subscribe(l=>{o&&(window.clearTimeout(o),o=0,l&&(o=window.setTimeout(()=>n.next(u),s.maxTransitionInterval)))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});import{ErrorCategory as FO,Subscription as NO,combine as UO,filter as fE,once as mE}from"@vkontakte/videoplayer-shared/es2018";function hE(){return new(window.AudioContext||window.webkitAudioContext)}var Io=class Io{constructor(e,t,i,r){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=i;this.volumeMultiplier=r;this.destroyController=new ae;this.subscriptions=new NO;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe(fE(a=>!!a.type),mE()).subscribe(({type:a})=>this.subscribe(a)))}subscribe(e){q.browser.isSafari&&e!=="MPEG"||this.subscriptions.add(UO({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(fE(({playbackState:t,video:i,volume:{muted:r,volume:a}})=>t==="playing"&&!!i&&!r&&!!a),mE()).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=hE();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:Io.errorId,category:FO.VIDEO_PIPELINE,message:(t=e==null?void 0:e.message)!=null?t:`${Io.errorId} exception`,thrown:e})}};Io.errorId="VolumeMultiplierManager";var vs=Io;var zO={chunkDuration:5e3,maxParallelRequests:5},Eo=class{constructor(e){this.current$=new W({type:void 0});this.providerError$=new Ce;this.noAvailableProvidersError$=new Ce;this.volumeMultiplierError$=new Ce;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 Ce,fetcherError$:new Ce,fetcherRecoverableError$:new Ce,warning$:new Ce,willSeekEvent$:new Ce,soundProhibitedEvent$:new Ce,seekedEvent$:new Ce,loopedEvent$:new Ce,endedEvent$:new Ce,firstBytesEvent$:new Ce,loadedMetadataEvent$:new Ce,firstFrameEvent$:new Ce,canplay$:new Ce,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 Ce,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 SE;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=zI([...WI(this.params.tuning),...QI(this.params.tuning)],this.params.tuning).filter(l=>gE(e.sources[l])),{forceFormat:i,formatsToAvoid:r}=this.params.tuning,a=[];i?a=[i]:r.length?a=[...t.filter(l=>!(0,kh.default)(r,l)),...t.filter(l=>(0,kh.default)(r,l))]:a=t,this.log({message:`Selected formats: ${a.join(" > ")}`}),this.tracer.log("Selected formats",Ah(a)),this.screenFormatsIterator=new To(a);let n=[...Rp(!0),...Rp(!1)];this.chromecastFormatsIterator=new To(n.filter(l=>gE(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:o=1,tuning:{useVolumeMultiplier:u}}=this.params;u&&o!==1&&vs.isSupported()&&(this.volumeMultiplierManager=new vs(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(qO(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:Pl.WTF,message:"Failed to create provider",thrown:r})}i?this.current$.next({type:t,provider:i,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.tracer.log("reinitProvider"),this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.tracer.log("switchToNextProvider",{destination:e}),this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}destroyProvider(){let e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"}),this.tracer.log("destroyProvider"),e.destroy();let t=this.providerOutput.position$.getValue()*1e3,i=this.params.desiredState.seekState.getState(),r=i.state!=="none";if(this.params.desiredState.seekState.setState({state:"requested",position:r?i.position:t,forcePrecise:r?i.forcePrecise:!1}),e.scene3D){let n=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:n.x,y:n.y})}let a=this.providerOutput.isBuffering$;a.getValue()||a.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),this.tracer.log("createProvider",{destination:e,format:t}),e){case"SCREEN":return this.createScreenProvider(t);case"CHROMECAST":return this.createChromecastProvider(t);default:return xo(e)}}createScreenProvider(e){let{sources:t,container:i,desiredState:r,panelSize:a}=this.params,n=this.providerOutput,o={container:i,source:null,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning,panelSize:a};switch(e){case"DASH_SEP":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_ONDEMAND":case"DASH_STREAMS":{let u=this.applyFailoverHost(t[e]),l=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return qi(u),this.params.tuning.useNewDashProvider?new ho({...o,source:u,sourceHls:l}):new Rn({...o,source:u,sourceHls:l})}case"DASH_LIVE_CMAF":{let u=this.applyFailoverHost(t[e]);return qi(u),this.params.tuning.useNewDashProvider?new fo({...o,source:u}):new Ln({...o,source:u})}case"HLS":case"HLS_ONDEMAND":{let u=this.applyFailoverHost(t[e]);return qi(u),q.video.nativeHlsSupported||!this.params.tuning.useHlsJs?new So({...o,source:u}):new bo({...o,source:u})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let u=this.applyFailoverHost(t[e]);return qi(u),new go({...o,source:u,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let u=this.applyFailoverHost(t[e]);return qi(u),new vo({...o,source:u})}case"DASH_LIVE":{let u=this.applyFailoverHost(t[e]);return qi(u),new zy({...o,source:u,config:{...zO,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let u=this.applyFailoverHost(t[e]);return qi(u),new yo({container:i,source:u,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return xo(e)}}createChromecastProvider(e){let{sources:t,container:i,desiredState:r,meta:a}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return qi(o),new ka({connection:o,meta:a,container:i,source:t,format:e,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?"CHROMECAST":"SCREEN"}chooseFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case"CHROMECAST":return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return xo(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return xo(e)}}handleNoFormatsError(e){switch(e){case"SCREEN":this.noAvailableProvidersError$.next(this.params.tuning.forceFormat),this.current$.next({type:void 0});return;case"CHROMECAST":this.params.dependencies.chromecastInitializer.disconnect();return;default:return xo(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;let t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;let i=r=>{let a=new URL(r);return a.host=t,a.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return{...e,url:i(e.url)}}return(0,yE.default)((0,vE.default)(e).map(([r,a])=>[r,i(a)]))}initProviderErrorHandling(){let e=new SE,t=!1,i=0;return e.add(HO(this.providerOutput.error$.pipe(bE(r=>!this.params.tuning.ignoreAudioRendererError||!r.message||!/AUDIO_RENDERER_ERROR/ig.test(r.message))),pE({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(jO(r=>({id:`ProviderHangup:${r}`,category:Pl.WTF,message:`A ${r} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.providerOutput.fetcherError$.subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;let r=this.params.desiredState.playbackState.transitionEnded$.pipe(bE(({to:a})=>a==="playing"),GO()).subscribe(()=>t=!0);e.add(r)})),e.add(this.providerError$.subscribe(r=>{let a=this.current$.getValue().destination,n={error:r,currentDestination:a};if(a==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("SCREEN"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let o=r.category===Pl.NETWORK,u=r.category===Pl.FATAL,l=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),d=i<this.params.tuning.providerErrorLimit&&!u,c=l&&!u&&(o&&t||!d);n={...n,isNetworkError:o,isFatalError:u,haveFailoverHost:l,tryFailover:c,canReinitProvider:d},d?(i++,this.reinitProvider()):c?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):(i=0,this.switchToNextProvider(a!=null?a:"SCREEN"))}r.traceAsLog?this.tracer.log("providerInfo",Ah(n)):this.tracer.error("providerError",Ah(n))})),e}};import{fromEvent as Al,once as QO,combine as WO,Subscription as TE,ValueSubject as Rh,map as YO,filter as KO,isNonNullable as kl,now as xt,safeStorage as Lh}from"@vkontakte/videoplayer-shared/es2018";var XO=5e3,IE="one_video_throughput",xE="one_video_rtt",Pi=window.navigator.connection,EE=()=>{let s=Pi==null?void 0:Pi.downlink;if(kl(s)&&s!==10)return s*1e3},wE=()=>{let s=Pi==null?void 0:Pi.rtt;if(kl(s)&&s!==3e3)return s},PE=(s,e,t)=>{let i=t*8,r=i/s;return i/(r+e)},Mh=class s{constructor(e){this.subscription=new TE;this.concurrentDownloads=new Set;var r,a;this.tuningConfig=e;let t=s.load(IE)||(e.useBrowserEstimation?EE():void 0)||XO,i=(a=(r=s.load(xE))!=null?r:e.useBrowserEstimation?wE():void 0)!=null?a:0;if(this.throughput$=new Rh(t),this.rtt$=new Rh(i),this.rttAdjustedThroughput$=new Rh(PE(t,i,e.rttPenaltyRequestSize)),this.throughput=Ii.getSmoothedValue(t,-1,e),this.rtt=Ii.getSmoothedValue(i,1,e),e.useBrowserEstimation){let n=()=>{let u=EE();u&&this.throughput.next(u);let l=wE();kl(l)&&this.rtt.next(l)};Pi&&"onchange"in Pi&&this.subscription.add(Al(Pi,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{Lh.set(IE,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{Lh.set(xE,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(WO({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(YO(({throughput:n,rtt:o})=>PE(n,o,e.rttPenaltyRequestSize)),KO(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=xt(),r=new TE;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add(Al(e,"progress").pipe(QO()).subscribe(a=>{t=a.loaded,i=xt()}));break;case 1:case 0:r.add(Al(e,"loadstart").subscribe(()=>{t=0,i=xt()}));break}r.add(Al(e,"loadend").subscribe(a=>{if(e.status===200){let n=a.loaded,o=xt(),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=xt(),n=0,o=xt(),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,xt()-a,1),this.concurrentDownloads.delete(e);else if(c){if(t){let h=xt();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=xt()}else n+=c.byteLength;o=xt()}else r+=c.byteLength,n+=c.byteLength,n>=this.tuningConfig.streamMinSampleSize&&xt()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,xt()-o,this.concurrentDownloads.size),n=0,o=xt());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=Lh.get(e);if(kl(t))return(i=parseInt(t,10))!=null?i:void 0}},AE=Mh;import{fillWithDefault as JO,VideoQuality as Rl}from"@vkontakte/videoplayer-shared/es2018";var kE={configName:["core"],throughputEstimator:{type:"EmaAndMa",emaAlphaSlow:.2,emaAlphaFast:.7,emaAlpha:.45,basisTrendChangeCount:10,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1*1024*1024,streamMinSampleSize:10*1024,streamMinSampleTime:300,deviationDepth:20,deviationFactor:.5,lowLatency:{continuesByteSequenceInterval:50,maxLastEvaluationTimeout:300}},autoTrackSelection:{maxBitrateFactorAtEmptyBuffer:4,bitrateFactorAtEmptyBuffer:2.8,minBitrateFactorAtEmptyBuffer:1.5,bitrateAudioFactorAtEmptyBuffer:10,maxBitrateFactorAtFullBuffer:3,bitrateFactorAtFullBuffer:2,minBitrateFactorAtFullBuffer:1,bitrateAudioFactorAtFullBuffer:7,minVideoAudioRatio:5,minAvailableThroughputAudioRatio:5,usePixelRatio:!0,pixelRatioMultiplier:void 0,pixelRatioLogBase:3,pixelRatioLogCoefficients:[1,0,1],limitByContainer:!0,maxContainerSizeFactor:2,containerSizeFactor:1.3,minContainerSizeFactor:1,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldownIncreaseQuality:15e3,trackCooldownDecreaseQuality:3e3,backgroundVideoQualityLimit:Rl.Q_4320P,activeVideoAreaThreshold:.1,highQualityLimit:Rl.Q_720P,trafficSavingLimit:Rl.Q_480P},stallsManager:{enabled:!1,stallDurationNoDataBeforeQualityDecrease:500,stallDurationToBeCount:100,stallCountBeforeQualityDecrease:3,resetQualityRestrictionTimeout:1e4,ignoreStallsOnSeek:!1,stallsMetricsHistoryLength:5,maxPossibleStallDuration:3e4,minTvtToBeCounted:5,maxTvtToBeCounted:10800,targetStallsDurationPerTvt:1,deviationStallsDurationPerTvt:.5,criticalStallsDurationPerTvt:6,abrAdjustingSpeed:.1,emaAlpha:.6,useTotalStallsDurationPerTvt:!0,useAverageStallsDurationPerTvt:!0,useEmaStallsDurationPerTvt:!0},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:Rl.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,seekBiasInTheEnd:2e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,crashOnStallTimeout:25e3,crashOnStallTWithoutDataTimeout:5e3,enableSubSegmentBufferFeeding:!0,bufferEmptinessTolerance:100,useFetchPriorityHints:!0,enableBaseUrlSupport:!0,maxSegmentRetryCount:5,sourceOpenTimeout:1e3,vktvAbrThrottle:0,timeupdateEventTickThrottle:300,useOldFetherInNewDashProvider:!1},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,maxLiveDuration:7200,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:250,playbackCatchupSpeedup:.05,isActiveOnDefault:!1,bufferEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:"07A4434E",useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"dash",preferCMAF:!1,preferWebRTC:!1,preferMultiStream:!1,preferHDR:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,seekNearDurationBias:1,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useHlsJs:!1,useNativeHLSTextTracks:!1,useManagedMediaSource:!0,useNewSwitchTo:!1,useNewDashProvider:!1,useNewAutoSelectVideoTrack:!1,useSafariEndlessRequestBugfix:!0,useRefactoredSearchGap:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,audioVideoSyncRate:20,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50},useVolumeMultiplier:!1,ignoreAudioRendererError:!1,useEnableSubtitlesParam:!1,useOldMSEDetection:!1,useHlsLiveNewTextManager:!1,exposeInternalsToGlobal:!1,hlsLiveNewTextManagerDownloadThreshold:4e3,disableYandexPiP:!1,asyncResolveClientChecker:!1,autostartOnlyIfVisible:!1},RE=s=>{var e;return{...JO(s,kE),configName:[...(e=s.configName)!=null?e:[],...kE.configName]}};import{assertNonNullable as Ll,combine as Ai,ErrorCategory as Ml,filter as z,filterChanged as te,fromEvent as Bh,isNonNullable as BE,isNullable as a_,Logger as n_,map as Z,mapTo as DE,merge as ji,now as $l,once as Y,Subject as re,Subscription as CE,tap as Dh,ValueSubject as D,isHigher as o_,isInvariantQuality as VE,flattenObject as Hi,throttle as Ch,getTraceSubscriptionMethod as OE,Tracer as u_,InternalsExposure as l_}from"@vkontakte/videoplayer-shared/es2018";import{merge as ZO,map as e_,filter as LE,isNonNullable as t_}from"@vkontakte/videoplayer-shared/es2018";var $h=({seekState:s,position$:e})=>ZO(s.stateChangeEnded$.pipe(e_(({to:t})=>{var i;return t.state==="none"?void 0:((i=t.position)!=null?i:NaN)/1e3}),LE(t_)),e.pipe(LE(()=>s.getState().state==="none")));import{assertNonNullable as i_}from"@vkontakte/videoplayer-shared/es2018";var ME=s=>{let e=typeof s.container=="string"?document.getElementById(s.container):s.container;return i_(e,`Wrong container or containerId {${s.container}}`),e};import{filter as r_,once as s_}from"@vkontakte/videoplayer-shared/es2018";var $E=(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(r_(r=>r.length>0),s_()).subscribe(r=>{r.find(i)&&e.startTransitionTo(s)}):(s===void 0||t!=null&&t.getValue().find(i))&&e.startTransitionTo(s)};var Bl=class{constructor(e={configName:[]},t=u_.createRootTracer(!1)){this.subscription=new CE;this.logger=new n_;this.abrLogger=this.logger.createComponentLog("ABR");this.internalsExposure=null;this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new D(!1);this.hasLiveOffsetByPausedTimer=0;this.playerInitRequest=0;this.playerInited=new D(!1);this.wasSetStartedQuality=!1;this.desiredState={playbackState:new H("stopped"),seekState:new H({state:"none"}),volume:new H({volume:1,muted:!1}),videoTrack:new H(void 0),videoStream:new H(void 0),audioStream:new H(void 0),autoVideoTrackSwitching:new H(!0),autoVideoTrackLimits:new H({}),isLooped:new H(!1),isLowLatency:new H(!1),playbackRate:new H(1),externalTextTracks:new H([]),internalTextTracks:new H([]),currentTextTrack:new H(void 0),textTrackCuesSettings:new H({}),cameraOrientation:new H({x:0,y:0})};this.info={playbackState$:new D(void 0),position$:new D(0),duration$:new D(1/0),muted$:new D(!1),volume$:new D(1),availableVideoStreams$:new D([]),currentVideoStream$:new D(void 0),availableQualities$:new D([]),availableQualitiesFps$:new D({}),currentQuality$:new D(void 0),isAutoQualityEnabled$:new D(!0),autoQualityLimitingAvailable$:new D(!1),autoQualityLimits$:new D({}),predefinedQualityLimitType$:new D("unknown"),availableAudioStreams$:new D([]),currentAudioStream$:new D(void 0),availableAudioTracks$:new D([]),isAudioAvailable$:new D(!0),currentPlaybackRate$:new D(1),currentBuffer$:new D({start:0,end:0}),isBuffering$:new D(!0),isStalled$:new D(!1),isEnded$:new D(!1),isLooped$:new D(!1),isLive$:new D(void 0),isLiveEnded$:new D(null),canChangePlaybackSpeed$:new D(void 0),atLiveEdge$:new D(void 0),atLiveDurationEdge$:new D(void 0),liveTime$:new D(void 0),liveBufferTime$:new D(void 0),liveLatency$:new D(void 0),currentFormat$:new D(void 0),availableTextTracks$:new D([]),currentTextTrack$:new D(void 0),throughputEstimation$:new D(void 0),rttEstimation$:new D(void 0),videoBitrate$:new D(void 0),hostname$:new D(void 0),httpConnectionType$:new D(void 0),httpConnectionReused$:new D(void 0),surface$:new D("none"),chromecastState$:new D("NOT_AVAILABLE"),chromecastDeviceName$:new D(void 0),intrinsicVideoSize$:new D(void 0),availableSources$:new D(void 0),is3DVideo$:new D(!1),currentVideoSegmentLength$:new D(0),currentAudioSegmentLength$:new D(0)};this.events={inited$:new re,ready$:new re,started$:new re,playing$:new re,paused$:new re,stopped$:new re,willStart$:new re,willResume$:new re,willPause$:new re,willStop$:new re,willDestruct$:new re,watchCoverageRecord$:new re,watchCoverageLive$:new re,managedError$:new re,fatalError$:new re,fetcherRecoverableError$:new re,ended$:new re,looped$:new re,seeked$:new re,willSeek$:new re,autoplaySoundProhibited$:new re,firstBytes$:new re,loadedMetadata$:new re,firstFrame$:new re,canplay$:new re,log$:new re,fetcherError$:new re,severeStallOccured$:new re};this.experimental={element$:new D(void 0),tuningConfigName$:new D([]),enableDebugTelemetry$:new D(!1),dumpTelemetry:Sy,getCurrentTime$:new D(null)};if(this.initLogs(),this.tuning=RE(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new $o({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new AE(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new l_("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,_E.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:Ml.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",Hi(o)),this.domContainer=ME(e),this.chromecastInitializer.contentId=(u=e.meta)==null?void 0:u.videoId,this.providerContainer=new Eo({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?q.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"),Bh(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){return this.subscription.add(this.playerInited.pipe(z(t=>!!t),Y()).subscribe(()=>{var n;let t=this.desiredState.volume,i=this.tuning.isAudioDisabled||e,r=t.getTransition(),a=(n=r==null?void 0:r.to.volume)!=null?n:this.info.volume$.getValue();this.tracer.log("setMuted",{isMuted:e,nextMuted:i,volume:a,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue()}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setMuted(i):t.startTransitionTo({volume:a,muted:i})})),this}setVideoStream(e){return this.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(()=>{Ll(this.providerContainer);let t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();this.tracer.log("setQuality",{isDelayed:t.length===0,quality:e}),this.desiredState.videoTrack.getState()===void 0&&this.desiredState.videoTrack.getPrevState()===void 0&&t.length===0?this.wasSetStartedQuality?this.providerContainer.providerOutput.availableVideoTracks$.pipe(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",Hi(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;Ll(this.providerContainer);let t=(i=this.providerContainer)==null?void 0:i.providerOutput.element$.getValue();this.tracer.log("setPlaybackRate",{playbackRate:e,isVideoElementAvailable:!!t}),t&&(this.desiredState.playbackRate.setState(e),t.playbackRate=e)})),this}setExternalTextTracks(e){return this.subscription.add(this.playerInited.pipe(z(t=>!!t),Y()).subscribe(()=>{e.length&&this.tracer.log("setExternalTextTracks",Hi(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;$E(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(a_(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),i=t.state==="none"?void 0:t.position;return BE(i)?i/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){var t,i;let e=(t=this.providerContainer)==null?void 0:t.current$.getValue();if((i=e==null?void 0:e.provider)!=null&&i.scene3D)return e.provider.scene3D}setIntrinsicVideoSize(...e){let t={width:e.reduce((i,{width:r})=>i||r||0,0),height:e.reduce((i,{height:r})=>i||r||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(ji(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(zd(e,t,i))})),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(z(({from:e})=>e==="stopped"),Y()).subscribe(()=>{this.initedAt=$l(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case"ready":this.events.ready$.next();break;case"playing":this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case"paused":this.events.paused$.next();break;case"stopped":this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case"paused":this.events.willPause$.next();break;case"playing":this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case"stopped":this.events.willStop$.next();break;default:}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("willSeekEvent",Hi(n)),n.state==="requested"?this.desiredState.seekState.setState({...n,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:Ml.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe(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",Hi(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(Ai({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)=>VE(u)?1:VE(l)?-1:o_(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=>BE(n))).subscribe(n=>{this.info.currentQuality$.next(n==null?void 0:n.quality),this.info.videoBitrate$.next(n==null?void 0:n.bitrate)})).add(e.providerOutput.currentVideoSegmentLength$.pipe(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(Dh(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(Ai({hasLiveOffsetByPaused:ji(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(Ai({atLiveEdge:Ai({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:$h({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(),Dh(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(Z(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add(Ai({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(),Dh(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($h({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(ji(e.providerOutput.endedEvent$.pipe(DE(!0)),e.providerOutput.seekedEvent$.pipe(DE(!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:Ml.VIDEO_PIPELINE,message:n?`${n} was forced but failed or not available`:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.getCurrentTime$.subscribe(this.experimental.getCurrentTime$)).add(e.providerOutput.firstBytesEvent$.pipe(Y(),Z(n=>n!=null?n:$l()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(Y(),Z(()=>$l()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(Y(),Z(()=>$l()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$)).add(e.providerOutput.availableSources$.subscribe(this.info.availableSources$));let t=new 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=ji(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(ji(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(ji(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 CE;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=Xt(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(ji(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;Ll(this.providerContainer),Ll(e),gy(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(i=>by(i)),this.providerContainer.current$.subscribe(({type:i})=>$a("provider",i)),e.duration$.subscribe(i=>$a("duration",i)),e.availableVideoTracks$.pipe(z(i=>!!i.length),Y()).subscribe(i=>$a("tracks",i)),this.events.fatalError$.subscribe(new tt("fatalError")),this.events.managedError$.subscribe(new tt("managedError")),e.position$.subscribe(new tt("position")),e.currentVideoTrack$.pipe(Z(i=>i==null?void 0:i.quality)).subscribe(new tt("quality")),this.info.currentBuffer$.subscribe(new tt("buffer")),e.isBuffering$.subscribe(new tt("isBuffering"))].forEach(i=>this.subscription.add(i)),$a("codecs",q.video.supportedCodecs)}initTracerSubscription(){let e=OE(this.tracer.log.bind(this.tracer)),t=OE(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(Ai({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(Ai({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(Ch(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(Ai({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(z(({liveTime:i,liveBufferTime:r})=>!!i&&!!r),Ch(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(Ai({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(z(({throughputEstimation:i,rtt:r})=>!!i&&!!r),Ch(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:Ml.DOM,message:String(r)})})};this.subscription.add(ji(Bh(document,"visibilitychange"),Bh(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",Hi({quality:t,availableTracks:Hi(e),track:Hi(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&&!Fa()}};import{Subscription as rte,Observable as ste,Subject as ate,ValueSubject as nte,VideoQuality as ote}from"@vkontakte/videoplayer-shared/es2018";var ute=`@vkontakte/videoplayer-core@${Oh}`;export{wo as ChromecastState,Ul as HttpConnectionType,ste as Observable,at as PlaybackState,Bl as Player,Po as PredefinedQualityLimits,ute as SDK_VERSION,ate as Subject,rte as Subscription,ql as Surface,Oh as VERSION,nte as ValueSubject,fi as VideoFormat,ote as VideoQuality,q as clientChecker,Ma as isMobile};
185
+ `})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(d,"i")}var Xp=N(_t(),1);import{videoSizeToQuality as oV,throttleFn as uV}from"@vkontakte/videoplayer-shared/es2018";var Ix=({id:s,width:e,height:t,bitrate:i,fps:r,quality:a,streamId:n})=>{var u;let o=(u=a?Kt(a):void 0)!=null?u:oV({width:e,height:t});return o&&{id:s,quality:o,bitrate:i,size:{width:e,height:t},fps:r,streamId:n}},xx=({id:s,bitrate:e})=>({id:s,bitrate:e}),Ex=({language:s,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:s,label:e}),wx=({language:s,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:s,label:e}),Jp=({id:s,language:e,label:t,codecs:i,isDefault:r})=>({id:s,language:e,label:t,codec:(0,Xp.default)(i.split("."),0),isDefault:r}),Zp=({id:s,language:e,label:t,hdr:i,codecs:r})=>({id:s,language:e,hdr:i,label:t,codec:(0,Xp.default)(r.split("."),0)}),eh=s=>"url"in s,rt=s=>s.type==="template",io=s=>s instanceof DOMException&&(s.name==="AbortError"||s.code===20);var Px=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},Sr=(s,e)=>{for(let t of s)if(e(t))return t;return null},Ax=s=>{let e=!1,t=uV(()=>{e=!0},s);return()=>{try{return t(),e}finally{e=!1}}};var Rx=s=>{if(!(s!=null&&s.startsWith("P")))return;let e=(n,o)=>{let u=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(u)?0:u)*o},i=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(s),r=(i==null?void 0:i[1])==="-"?-1:1,a={days:e(i==null?void 0:i[5],r),hours:e(i==null?void 0:i[6],r),minutes:e(i==null?void 0:i[7],r),seconds:e(i==null?void 0:i[8],r)};return a.days*24*60*60*1e3+a.hours*60*60*1e3+a.minutes*60*1e3+a.seconds*1e3},wi=(s,e)=>{let t=s;t=(0,th.default)(t,"$$","$");let i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[r,a]of(0,Lx.default)(i)){let n=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=(0,th.default)(t,n,(o,u)=>kx(a)?o:kx(u)?a:(0,Mx.default)(a,parseInt(u,10),"0"))}return t},Bx=(s,e)=>{var w,A,C,M,L,Q,U,P,F,k,x,B,oe,Ce,se,K,ye,Te,Ie,Ve,Et,At,Ht,ei,ki,vs,ys,Ts,Is,xs,Es,ws,Ps,As,ks,Rs,Ls,Ms,$s,Bs,Ds,Cs,Vs,Os,_s,Fs,Ns,Us,qs,js,Hs,Gs,zs,Qs,Ws,Ys,Ks,Xs,Js,Zs,ea;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 _,Qe;return(Qe=(_=ce.textContent)==null?void 0:_.trim())!=null?Qe:""}),o=(w=(0,$x.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=Rx(v):(0,ih.default)(T).filter(ce=>ce).length&&!u?S=(0,ih.default)(T).reduce((ce,_)=>{var Qe;return ce+((Qe=Rx(_))!=null?Qe:0)},0):m&&(S=parseInt(m,10));let E=0,O=(C=(A=a.getAttribute("profiles"))==null?void 0:A.split(","))!=null?C:[];for(let ce of y.map(_=>_.id))for(let _ of I[ce]){let Qe=(M=_.getAttribute("id"))!=null?M:"id"+(E++).toString(10),kt=(L=_.getAttribute("mimeType"))!=null?L:"",Gi=(Q=_.getAttribute("codecs"))!=null?Q:"",zi=(U=_.getAttribute("contentType"))!=null?U:kt==null?void 0:kt.split("/")[0],Cl=(F=(P=_.getAttribute("profiles"))==null?void 0:P.split(","))!=null?F:[],ta=(x=Tx((k=_.getAttribute("lang"))!=null?k:""))!=null?x:{},ti=(Ce=(oe=(B=_.querySelector("Label"))==null?void 0:B.textContent)==null?void 0:oe.trim())!=null?Ce:void 0,Vl=_.querySelectorAll("Representation"),Ol=_.querySelector("SegmentTemplate"),_l=(K=(se=_.querySelector("Role"))==null?void 0:se.getAttribute("value"))!=null?K:void 0,ct=zi,G={id:Qe,language:ta.language,isDefault:_l==="main",label:ti,codecs:Gi,hdr:ct==="video"&&ts(Gi),mime:kt,representations:[]};for(let V of Vl){let Pe=(ye=V.getAttribute("lang"))!=null?ye:void 0,Rt=(Ie=(Te=ti!=null?ti:_.getAttribute("label"))!=null?Te:V.getAttribute("label"))!=null?Ie:void 0,ii=(At=(Et=(Ve=V.querySelector("BaseURL"))==null?void 0:Ve.textContent)==null?void 0:Et.trim())!=null?At:"",We=new URL(ii||o,e).toString(),Ae=(Ht=V.getAttribute("mimeType"))!=null?Ht:kt,ri=(ki=(ei=V.getAttribute("codecs"))!=null?ei:Gi)!=null?ki:"",si;if(zi==="text"){let ke=V.getAttribute("id")||"",ai=((vs=ta.privateuse)==null?void 0:vs.includes("x-auto"))||ke.includes("_auto"),Ye=V.querySelector("SegmentTemplate");if(Ye){let Lt={representationId:(ys=V.getAttribute("id"))!=null?ys:void 0,bandwidth:(Ts=V.getAttribute("bandwidth"))!=null?Ts:void 0},ni=parseInt((Is=V.getAttribute("bandwidth"))!=null?Is:"",10)/1e3,oi=(Es=parseInt((xs=Ye.getAttribute("startNumber"))!=null?xs:"",10))!=null?Es:1,dt=parseInt((ws=Ye.getAttribute("timescale"))!=null?ws:"",10),Qi=(Ps=Ye.querySelectorAll("SegmentTimeline S"))!=null?Ps:[],pt=Ye.getAttribute("media");if(!pt)continue;let ui=[],li=0,ci="",ht=0,Mt=oi,ee=0;for(let de of Qi){let Ke=parseInt((As=de.getAttribute("d"))!=null?As:"",10),ne=parseInt((ks=de.getAttribute("r"))!=null?ks:"",10)||0,Re=parseInt((Rs=de.getAttribute("t"))!=null?Rs:"",10);ee=Number.isFinite(Re)?Re:ee;let Xe=Ke/dt*1e3,Le=ee/dt*1e3;for(let me=0;me<ne+1;me++){let Me=wi(pt,{...Lt,segmentNumber:Mt.toString(10),segmentTime:(ee+me*Ke).toString(10)}),ft=(Le!=null?Le:0)+me*Xe,Bt=ft+Xe;Mt++,ui.push({time:{from:ft,to:Bt},url:Me})}ee+=(ne+1)*Ke,li+=(ne+1)*Xe}ht=ee/dt*1e3,ci=wi(pt,{...Lt,segmentNumber:Mt.toString(10),segmentTime:ee.toString(10)});let $t={time:{from:ht,to:1/0},url:ci},xe={type:"template",baseUrl:We,segmentTemplateUrl:pt,initUrl:"",totalSegmentsDurationMs:li,segments:ui,nextSegmentBeyondManifest:$t,timescale:dt};si={id:ke,kind:"text",segmentReference:xe,profiles:[],duration:S,bitrate:ni,mime:"",codecs:"",width:0,height:0,isAuto:ai}}else si={id:ke,isAuto:ai,kind:"text",url:We}}else{let ke=(Ms=(Ls=V.getAttribute("contentType"))!=null?Ls:Ae==null?void 0:Ae.split("/")[0])!=null?Ms:zi,ai=(Bs=($s=_.getAttribute("profiles"))==null?void 0:$s.split(","))!=null?Bs:[],Ye=parseInt((Ds=V.getAttribute("width"))!=null?Ds:"",10),Lt=parseInt((Cs=V.getAttribute("height"))!=null?Cs:"",10),ni=parseInt((Vs=V.getAttribute("bandwidth"))!=null?Vs:"",10)/1e3,oi=(Os=V.getAttribute("frameRate"))!=null?Os:"",dt=(_s=V.getAttribute("quality"))!=null?_s:void 0,Qi=oi?Cu(oi):void 0,pt=(Fs=V.getAttribute("id"))!=null?Fs:"id"+(E++).toString(10),ui=ke==="video"?`${Lt}p`:ke==="audio"?`${ni}Kbps`:ri,li=`${pt}@${ui}`,ci=[...O,...Cl,...ai],ht,Mt=V.querySelector("SegmentBase"),ee=(Ns=V.querySelector("SegmentTemplate"))!=null?Ns:Ol;if(Mt){let xe=(qs=(Us=V.querySelector("SegmentBase Initialization"))==null?void 0:Us.getAttribute("range"))!=null?qs:"",[de,Ke]=xe.split("-").map(Me=>parseInt(Me,10)),ne={from:de,to:Ke},Re=(js=V.querySelector("SegmentBase"))==null?void 0:js.getAttribute("indexRange"),[Xe,Le]=Re?Re.split("-").map(Me=>parseInt(Me,10)):[],me=Re?{from:Xe,to:Le}:void 0;ht={type:"byteRange",url:We,initRange:ne,indexRange:me}}else if(ee){let xe={representationId:(Hs=V.getAttribute("id"))!=null?Hs:void 0,bandwidth:(Gs=V.getAttribute("bandwidth"))!=null?Gs:void 0},de=parseInt((zs=ee.getAttribute("timescale"))!=null?zs:"",10),Ke=(Qs=ee.getAttribute("initialization"))!=null?Qs:"",ne=ee.getAttribute("media"),Re=(Ys=parseInt((Ws=ee.getAttribute("startNumber"))!=null?Ws:"",10))!=null?Ys:1,Xe=wi(Ke,xe);if(!ne)throw new ReferenceError("No media attribute in SegmentTemplate");let Le=(Ks=ee.querySelectorAll("SegmentTimeline S"))!=null?Ks:[],me=[],Me=0,ft="",Bt=0;if(Le.length){let di=Re,pe=0;for(let mt of Le){let be=parseInt((Xs=mt.getAttribute("d"))!=null?Xs:"",10),Je=parseInt((Js=mt.getAttribute("r"))!=null?Js:"",10)||0,pi=parseInt((Zs=mt.getAttribute("t"))!=null?Zs:"",10);pe=Number.isFinite(pi)?pi:pe;let Wi=be/de*1e3,Yi=pe/de*1e3;for(let hi=0;hi<Je+1;hi++){let Nl=wi(ne,{...xe,segmentNumber:di.toString(10),segmentTime:(pe+hi*be).toString(10)}),ia=(Yi!=null?Yi:0)+hi*Wi,Ul=ia+Wi;di++,me.push({time:{from:ia,to:Ul},url:Nl})}pe+=(Je+1)*be,Me+=(Je+1)*Wi}Bt=pe/de*1e3,ft=wi(ne,{...xe,segmentNumber:di.toString(10),segmentTime:pe.toString(10)})}else if(lV(S)){let pe=parseInt((ea=ee.getAttribute("duration"))!=null?ea:"",10)/de*1e3,mt=Math.ceil(S/pe),be=0;for(let Je=1;Je<mt;Je++){let pi=wi(ne,{...xe,segmentNumber:Je.toString(10),segmentTime:be.toString(10)});me.push({time:{from:be,to:be+pe},url:pi}),be+=pe}Bt=be,ft=wi(ne,{...xe,segmentNumber:mt.toString(10),segmentTime:be.toString(10)})}let Fl={time:{from:Bt,to:1/0},url:ft};ht={type:"template",baseUrl:We,segmentTemplateUrl:ne,initUrl:Xe,totalSegmentsDurationMs:Me,segments:me,nextSegmentBeyondManifest:Fl,timescale:de}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!ke||!Ae)continue;let $t={video:"video",audio:"audio",text:"text"}[ke];if(!$t)continue;ct||(ct=$t),si={id:li,kind:$t,segmentReference:ht,profiles:ci,duration:S,bitrate:ni,mime:Ae,codecs:ri,width:Ye,height:Lt,fps:Qi,quality:dt}}G.language||(G.language=Pe),G.label||(G.label=Rt),G.mime||(G.mime=Ae),G.codecs||(G.codecs=ri),G.hdr||(G.hdr=ct==="video"&&ts(ri)),G.representations.push(si)}if(ct){let V=r[ct].find(Pe=>Pe.id===G.id);if(V&&G.representations.every(Pe=>rt(Pe.segmentReference)))for(let Pe of V.representations){let Rt=G.representations.find(Ae=>Ae.id===Pe.id),ii=Rt==null?void 0:Rt.segmentReference,We=Pe.segmentReference;We.segments.push(...ii.segments),We.nextSegmentBeyondManifest=ii.nextSegmentBeyondManifest}else r[ct].push(G)}}return{duration:S,streams:r,baseUrls:n,live:g}};import{fromEvent as cV,Subscription as dV}from"@vkontakte/videoplayer-shared/es2018";var nl=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 ol=class{constructor(e,t){this.lastUpdateTs=0;this.lastCallTs=0;this.prevRanges=[];this.subscription=new dV;this.mediaSource=e,this.sourceBuffer=t,this.subscription.add(cV(this.sourceBuffer,"updateend").subscribe(()=>this.updateend()))}updateend(){if(!j(this.mediaSource,this.sourceBuffer))return;let{prevRanges:e}=this,t=nl(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 ro=class{constructor(e,t,i,{fetcher:r,tuning:a,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new yr(0);this.currentLowLatencySegmentLength$=new yr(0);this.currentSegmentLength$=new yr(0);this.onLastSegment$=new yr(!1);this.fullyBuffered$=new yr(!1);this.playingRepresentation$=new yr(void 0);this.playingRepresentationInit$=new yr(void 0);this.error$=new hV;this.gaps=[];this.subscription=new fV;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=Ui(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);lt(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new hx(this.sourceBuffer),this.tuning.dash.useSourceBufferBufferedDiff?this.sourceBufferBufferedDiff=new ol(this.mediaSource,this.sourceBuffer):this.subscription.add(ul(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments()})),this.tuning.dash.useSourceBufferUpdateendMaintain&&this.subscription.add(ul(this.sourceBuffer,"updateend").subscribe(()=>{this.maintain()})),this.subscription.add(ul(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:vr.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o||!j(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,Jr(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=It(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);lt(i,"No init buffer for starting representation"),lt(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=Ui(this.destroyAbortController.signal,async function*(e,t=!1){if(!j(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);lt(i,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if(ze(a)||ze(r)?yield this.loadInit(i,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),lt(r,"No segments for starting representation"),a=this.initData.get(e),!(!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer||!j(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();ds(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=Ui(this.destroyAbortController.signal,async function*(e,t=!1){if(!j(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);lt(i,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if(ze(a)||ze(r)?yield this.loadInit(i,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),lt(r,"No segments for starting representation"),a=this.initData.get(e),!(!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer||!j(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();ds(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=Ui(this.destroyAbortController.signal,async function*(e){var u,l;let t=(u=(0,dl.default)(e,d=>d.representations))!=null?u:[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let d of this.representations.keys()){let c=t.find(f=>f.id===d);c&&this.representations.set(d,c);let h=this.representations.get(d);if(!h||!rt(h.segmentReference))return;let p=this.getActualLiveStartingSegments(h.segmentReference);this.segments.set(h.id,p)}let i=(l=this.switchingToRepresentationId)!=null?l:this.downloadingRepresentationId,r=this.representations.get(i);lt(r);let a=this.segments.get(i);lt(a,"No segments for starting representation");let n=this.initData.get(i);if(lt(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){!j(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new ae,Ui(this.switchAbortController.signal,async function*(i,r=!1){this.switchingToRepresentationId=i;let a=this.representations.get(i);lt(a,`No such representation ${i}`);let n=this.segments.get(i),o=this.initData.get(i);if(ze(o)||ze(n)?yield this.loadInit(a,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(i),lt(n,"No segments for starting representation"),o=this.initData.get(i),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer||!j(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();ds(u)&&!this.isLive&&(this.bufferLimit=this.forwardBufferTarget,yield this.pruneBuffer(u,1/0,!0)),this.downloadingRepresentationId=i,this.switchingToRepresentationId=void 0}this.maintain()}}.bind(this))(e,t))}warmUpMediaSource(){!ze(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}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(ze(e)||ze(this.downloadingRepresentationId)||ze(this.playingRepresentationId)||ze(this.sourceBuffer)||!j(this.mediaSource,this.sourceBuffer)||ds(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(lt(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;let r=i.find(d=>e>=d.time.from&&e<d.time.to);ds(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)&&Jr(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=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,cl.default)(u,r))d="high";else{let c=(0,ps.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)&&this.getForwardBufferDuration(e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let l=(0,ps.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,persistent:!0}),i=a.time.to;ds(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,dl.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,dl.default)(e==null?void 0:e.streams[this.kind],o=>o.representations))!=null?i:[];if(![...this.segments.values()].every(o=>!o.length))for(let o of t){if(!o||!rt(o.segmentReference))return;let u=o.segmentReference.segments.map(p=>({...p,status:"none",size:void 0})),l=100,d=(r=this.segments.get(o.id))!=null?r:[],c=(n=(a=(0,ps.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;lt(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(!rt(r))return;let a=this.segments.get(i.id);if(!a)continue;let n=a.find(u=>Math.floor(u.time.from)===Math.floor(e.time.from));if(n&&!isFinite(n.time.to)&&(n.time.to=e.time.to,t=n.time.to-n.time.from),!!!a.find(u=>Math.floor(u.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let u=Math.round(e.time.to*r.timescale/1e3).toString(10),l=wi(r.segmentTemplateUrl,{segmentTime:u});a.push({status:"none",time:{from:e.time.to,to:1/0},url:l})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){var a,n,o;let t=(n=(a=this.switchingToRepresentationId)!=null?a:this.downloadingRepresentationId)!=null?n:this.playingRepresentationId;if(!t)return;let i=this.segments.get(t);if(!i)return;let r=i.find(u=>u.time.from<=e&&u.time.to>=e);return(o=r==null?void 0:r.time.from)!=null?o:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e,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&&Jt&&Jt(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&Jt&&Jt(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&&j(this.mediaSource,this.sourceBuffer)&&!(He(this.sourceBuffer.buffered,h)&&He(this.sourceBuffer.buffered,p)))&&g&&v});if(r===-1)return null;if(t!=="byteRange")return e.slice(r,r+1);let a=e,n=0,o=0,u=[],l=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,d=this.preloadOnly?this.forwardBufferTarget:0;for(let c=r;c<a.length&&(n<=l||o<=d);c++){let h=a[c];if(n+=h.byte.to+1-h.byte.from,o+=h.time.to+1-h.time.from,h.status==="none"||h.status==="partially_ejected")u.push(h);else break}return u}async loadSegments(e,t,i="auto"){rt(t.segmentReference)?await this.loadTemplateSegment(e[0],t,i):await this.loadByteRangeSegments(e,t,i)}async loadTemplateSegment(e,t,i="auto"){e.status="downloading";let r={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(r);let{range:a,url:n,signal:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await Ui(o,async function*(){let d=sh(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=ll(),!d)return;let c=new DataView(d),h=to(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]),io(d)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}updateRepresentationsBaseUrlIfNeeded(){if(!this.tuning.dash.enableBaseUrlSupport||!this.baseUrls.length||this.failedDownloads<=this.tuning.dash.maxSegmentRetryCount)return;this.baseUrlsIndex=(this.baseUrlsIndex+1)%this.baseUrls.length;let e=this.baseUrls[this.baseUrlsIndex];for(let t of this.representations.values())rt(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}async loadByteRangeSegments(e,t,i="auto"){if(!e.length)return;for(let u of e)u.status="downloading",this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:r,url:a,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(await Ui(n,async function*(){let u=sh(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),ul(window,"online").pipe(pV()).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=ll(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),io(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(rt(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:(0,ps.default)(e,0).byte.from,to:(0,ps.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=ll(),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:vr.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!rt(t.segmentReference))throw new Error("Representation is not template type");let i=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&i.searchParams.set("low-latency","yes");let r=i.toString(),{signal:a}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,d)=>{if(!a.aborted)try{this.lastDataObtainedTimestampMs=ll();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:vr.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,cl.default)(e,t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:a}){if(!this.activeSegments.size||!j(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=to(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||!j(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:to(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(!(ze(this.sourceBuffer)||!j(this.mediaSource,this.sourceBuffer))){!this.isLive&&q.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(He(this.sourceBuffer.buffered,e.segment.time.from,100)&&He(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:vr.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",eh(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=Xr(()=>(0,Dx.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?Ui(this.destroyAbortController.signal,async function*(){let o=sh(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,to(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&&rt(e.segmentReference)&&(h=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,h),u&&this.parsedInitData.set(e.id,u)}).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:vr.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||!j(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||ze(e))return!1;this.checkEjectedSegments();let r=[],a=0,n=o=>{var l;if(a>=t)return;r.push({...o.time});let u=eh(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,cl.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=Px(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||!j(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||!j(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||!j(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||!j(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||ze(e)?0:It(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!this.sourceBuffer||!j(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||!j(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=Xr(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:vr.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if(ze(this.sourceBuffer)||!j(this.mediaSource,this.sourceBuffer)||ze(this.playingRepresentationId)||this.sourceBufferBufferedDiff&&!this.sourceBufferBufferedDiff.wasUpdated())return;let e=nl(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:vr.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}};import{abortable as so,assertNever as Cx,fromEvent as Vx,merge as mV,now as ao,Subject as Ox,ValueSubject as ah,flattenObject as hs,ErrorCategory as no,SubscriptionRemovable as bV}from"@vkontakte/videoplayer-shared/es2018";var hl=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:a=!1}){this.lastConnectionType$=new ah(void 0);this.lastConnectionReused$=new ah(void 0);this.lastRequestFirstBytes$=new ah(void 0);this.recoverableError$=new Ox;this.error$=new Ox;this.abortAllController=new ae;this.subscription=new bV;this.fetchManifest=so(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=_i(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=Nu(i));let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(pl);return r?(t.log("success",hs({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(r.headers),r.text()):(t.error("error",hs({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=so(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,L,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:Cx(t)}this.requestQuic&&(l=_i(l));let h=this.abortAllController.signal,p;if(n){let U=new ae;if(p=mV(Vx(this.abortAllController.signal,"abort"),Vx(n,"abort")).subscribe(()=>{try{U.abort()}catch(P){pl(P)}}),this.subscription.add(p),this.abortAllController.signal.aborted||n.aborted)try{U.abort()}catch(P){pl(P)}h=U.signal}let f=ao();c.log("startRequest",hs({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=ao();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=ao(),P={requestStartedAt:f,requestEndedAt:U,duration:U-f};return c.log("endRequest",hs(P)),c.end(),m.arrayBuffer()}let S=m.body;if(o){let U;[S,U]=m.body.tee(),(L=this.throughputEstimator)==null||L.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,$=U=>{this.unsubscribeAbortSubscription(p),O=!0,pl(U)},w=so(h,async function*({done:U,value:P}){if(T===0&&this.lastRequestFirstBytes$.next(ao()-f),h.aborted){this.unsubscribeAbortSubscription(p);return}if(!U&&P){if(y)E.set(P,T),T+=P.byteLength;else{let F=new Uint8Array(E.length+P.length);F.set(E),F.set(P,E.length),E=F,T+=P.byteLength}r==null||r(new DataView(E.buffer),T),yield v==null?void 0:v.read().then(w,$)}}.bind(this));yield v==null?void 0:v.read().then(w,$),this.unsubscribeAbortSubscription(p);let A=ao(),C={failed:O,requestStartedAt:f,requestEndedAt:A,duration:A-f};return O?(c.error("endRequest",hs(C)),c.end(),null):(c.log("endRequest",hs(C)),c.end(),E.buffer)}.bind(this));this.fetchByteRangeRepresentation=so(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=so(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}=Fu(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:Cx(r)}}destroy(){this.abortAllController.abort(),this.tracer.end(),this.subscription.unsubscribe()}async doFetch(e,t){let i=await Pt(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:no.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:no.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:no.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:no.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${a})`,category:no.FATAL})}}unsubscribeAbortSubscription(e){e&&(e.unsubscribe(),this.subscription.remove(e))}},pl=s=>{if(!io(s))throw s};import{isNullable as gV,ValueSubject as SV}from"@vkontakte/videoplayer-shared/es2018";var oo=class s{constructor(e,t){this.currentRepresentation$=new SV(null);this.maxRepresentations=4;this.representationsCursor=0;this.representations=[];this.currentSegment=null;this.getCurrentPosition=t.getCurrentPosition,this.processStreams(e)}updateLive(e){this.processStreams(e==null?void 0:e.streams.text)}seekLive(e){this.processStreams(e)}maintain(e=this.getCurrentPosition()){var t;if(!gV(e))for(let i of this.representations)for(let r of i){let a=r.segmentReference,n=a.segments.length,o=a.segments[0].time.from,u=a.segments[n-1].time.to;if(e<o||e>u)continue;let l=a.segments.find(d=>d.time.from<=e&&d.time.to>=e);!l||((t=this.currentSegment)==null?void 0:t.time.from)===l.time.from&&this.currentSegment.time.to===l.time.to||(this.currentSegment=l,this.currentRepresentation$.next({...r,label:"Live Text",language:"ru",isAuto:!0,url:new URL(l.url,a.baseUrl).toString()}))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e!=null?e:[]){let i=s.filterRepresentations(t.representations);if(i){this.representations[this.representationsCursor]=i,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!(e!=null&&e.some(t=>s.filterRepresentations(t.representations)))}static filterRepresentations(e){return e==null?void 0:e.filter(t=>t.kind==="text"&&"segmentReference"in t&&rt(t.segmentReference))}};var xV=["progress","play","seeked","stalled","waiting"],EV=["timeupdate","progress","loadeddata","playing","seeked"];var bl=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new ch;this.representationSubscription=new ch;this.state$=new H("none");this.currentVideoRepresentation$=new fe(void 0);this.currentVideoRepresentationInit$=new fe(void 0);this.currentAudioRepresentation$=new fe(void 0);this.currentVideoSegmentLength$=new fe(0);this.currentAudioSegmentLength$=new fe(0);this.error$=new ml;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 ml;this.fetcherError$=new ml;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new ml;this.gapWatchdogActive=!1;this.destroyController=new ae;this.initManifest=oh(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:qt.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=oh(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:qt.NETWORK,message:"Failed to load manifest",thrown:u})});if(!e)return null;let t=null;try{t=Bx(e!=null?e:"",this.manifestUrlString)}catch(u){let l=(n=Du(e))!=null?n:{id:"ManifestParsing",category:qt.PARSER,message:"Failed to parse MPD manifest",thrown:u};this.error$.next(l)}if(!t)return null;let i=(u,l,d)=>{var c,h,p,f;return!!((h=(c=this.element)==null?void 0:c.canPlayType)!=null&&h.call(c,l)&&((f=(p=Tt())==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=Yu(c);if(h&&(r[u]=d.filter(({codecs:p})=>p.startsWith(h))),u==="video"){let p=this.tuning.preferHDR,f=r.video.some(g=>g.hdr),m=r.video.some(g=>!g.hdr);q.display.isHDR&&p&&f?r.video=r.video.filter(g=>g.hdr):m&&(r.video=r.video.filter(g=>!g.hdr))}}let a={...t,streams:r};return this.tracer.log("updateManifestEnd",lo(a)),a}.bind(this));this.initRepresentations=oh(this.destroyController.signal,async function*(e,t,i){var h;this.tracer.log("initRepresentationsStart",lo({initialVideo:e,initialAudio:t,sourceHls:i})),fs(this.manifest),fs(this.element),this.representationSubscription.unsubscribe(),this.representationSubscription=new ch,this.state$.startTransitionTo("representations_ready");let r=p=>{this.representationSubscription.add(Zt(p,"error").pipe(fl(f=>{var m;return!!((m=this.element)!=null&&m.played.length)})).subscribe(f=>{this.error$.next({id:"VideoSource",category:qt.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:f})}))};this.source=this.tuning.useManagedMediaSource?cu():new MediaSource;let a=document.createElement("source");if(r(a),a.src=URL.createObjectURL(this.source),this.element.appendChild(a),this.tuning.useManagedMediaSource&&jr())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 ro("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],co(t)){let p=this.manifest.streams.audio.reduce((f,m)=>[...f,...m.representations],[]);this.audioBufferManager=new ro("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}oo.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new oo(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(Tr(...EV.map(p=>Zt(this.element,p))).pipe(bs(p=>this.element?It(this.element.buffered,this.element.currentTime*1e3):0),uo(),IV(p=>{p>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add(Tr(Zt(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe(uo()).subscribe(f=>this.liveStreamEndTimestamp=lh())),this.subscription.add(Zt(this.element,"pause").subscribe(()=>{this.livePauseWatchdogSubscription=uh(1e3).subscribe(f=>{let m=$i(this.manifestUrlString,2);this.manifestUrlString=Se(this.manifestUrlString,m+1e3,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add(Zt(this.element,"play").subscribe(f=>{var m;return(m=this.livePauseWatchdogSubscription)==null?void 0:m.unsubscribe()})),this.representationSubscription.add(ms({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(bs(({isActiveLive:f,isLowLatency:m})=>f&&m),uo()).subscribe(f=>{this.isManualDecreasePlaybackInLive()||as(this.element,1)})),this.representationSubscription.add(ms({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(fl(({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(ms({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(fl(({isLive:f})=>f),uo((f,m)=>m.bufferLength<f.bufferLength),bs(({rtt:f,bufferLength:m,segmentServerLatency:g})=>{let S=$i(this.manifestUrlString,2);return(f/2+m+g+S)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(ms({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),as(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(ms({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(Nx(1e3)).subscribe(async({liveLoadBufferLength:f,bufferLength:m})=>{if(!this.element||this.isUpdatingLive)return;let g=this.element.playbackRate,S=$i(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(),$=v<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next($);let w="none";if(O?w="active_low_latency":this.isLowLatency$.getValue()&&$?(this.bufferManagers.forEach(A=>A.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 A=p-(y+I),C=this.normolizeLiveOffset(Math.trunc(S+A/g)),M=Math.abs(C-S),L=0;!f||M<=this.tuning.dashCmafLive.offsetCalculationError?L=S:C>0&&M>this.tuning.dashCmafLive.offsetCalculationError&&(L=C),this.manifestUrlString=Se(this.manifestUrlString,L,2)}(w==="live_with_target_offset"||w==="live_forward_buffering")&&(p=0,await this.updateLive())},f=>{this.error$.next({id:"updateLive",category:qt.VIDEO_PIPELINE,thrown:f,message:"Failed to update live with subscription"})}))}let l=Tr(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe(bs(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),d=Tr(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe(bs(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue()))),c=ms({allBuffersFull:l,someBufferEnded:d}).pipe(uo(),bs(({allBuffersFull:p,someBufferEnded:f})=>p&&f),fl(p=>p));if(this.representationSubscription.add(Tr(this.forceEnded$,c).subscribe(()=>{var p;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(f=>!f.updating))try{(p=this.source)==null||p.endOfStream()}catch(f){this.error$.next({id:"EndOfStream",category:qt.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:f})}})),this.representationSubscription.add(Tr(...this.bufferManagers.map(p=>p.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.representationSubscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.representationSubscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.liveTextManager&&this.representationSubscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$)),this.source.readyState!=="open"){let p=this.tuning.dash.sourceOpenTimeout>=0;yield new Promise(f=>{var m;p&&(this.timeoutSourceOpenId=setTimeout(()=>{var g;if(((g=this.source)==null?void 0:g.readyState)==="open"){f();return}this.error$.next({id:"OpenOfStream",category:qt.VIDEO_PIPELINE,message:"Failed to open MediaSource",thrown:new Error("Timeout reject when wait sourceopen event"),traceAsLog:!0})},this.tuning.dash.sourceOpenTimeout)),(m=this.source)==null||m.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),f()},{once:!0})})}if(!this.isLive$.getValue()){let p=[(h=this.manifest.duration)!=null?h:0,...(0,dh.default)((0,dh.default)([...this.manifest.streams.audio,...this.manifest.streams.video],f=>f.representations),f=>{let m=[];return f.duration&&m.push(f.duration),rt(f.segmentReference)&&f.segmentReference.totalSegmentsDurationMs&&m.push(f.segmentReference.totalSegmentsDurationMs),m})];this.source.duration=Math.max(...p)/1e3}this.audioBufferManager&&co(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=uh(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),n=>{this.error$.next({id:"GapWatchdog",category:qt.WTF,message:"Error handling gaps",thrown:n})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.fetcher=new hl({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.subscription.add(this.fetcher.recoverableError$.subscribe(this.fetcherRecoverableError$)),this.subscription.add(this.fetcher.error$.subscribe(this.fetcherError$)),this.liveBuffer=Ii.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator}),this.initTracerSubscription()}async seekLive(e){var r,a,n;fs(this.element);let t=this.liveStreamStatus$.getValue()!=="active"?lh()-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(){fs(this.element),this.state$.setState("running");let e=Zt(this.element,"timeupdate");this.tuning.dash.timeupdateEventTickThrottle&&(e=e.pipe(Nx(this.tuning.dash.timeupdateEventTickThrottle))),this.subscription.add(Tr(...xV.map(t=>Zt(this.element,t)),Zt(window,"online"),e).subscribe(()=>this.tick(),t=>{this.error$.next({id:"DashVKPlayer",category:qt.WTF,message:"Internal logic error",thrown:t})})),this.subscription.add(Zt(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(Zt(this.element,"waiting").subscribe(()=>{var i;this.element&&this.element.readyState===HTMLMediaElement.HAVE_CURRENT_DATA&&!this.element.seeking&&He(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let t=()=>{var f,m,g,S,v,y,I,T,E,O,$;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=lh(),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(A=>{this.error$.next({id:"stallIntervalCallback",category:qt.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:A})}),a.liveLastOffset=w}else{let w=this.element.currentTime*1e3;(O=this.videoBufferManager)==null||O.maintain(w),($=this.audioBufferManager)==null||$.maintain(w),a.position=w}this.tracer.log("stallIntervalCallback",lo(a))};(i=this.stallWatchdogSubscription)==null||i.unsubscribe(),this.stallWatchdogSubscription=uh(50).subscribe(t,r=>{this.error$.next({id:"StallWatchdogCallback",category:qt.NETWORK,message:"Can't restore DASH after stall.",thrown:r})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}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;fs(this.element),fs(this.videoBufferManager);let i;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?i=e:i=Math.max((r=this.videoBufferManager.findSegmentStartTime(e))!=null?r:e,(n=(a=this.audioBufferManager)==null?void 0:a.findSegmentStartTime(e))!=null?n:e),this.warmUpMediaSourceIfNeeded(i),He(this.element.buffered,i)||await Promise.all([this.videoBufferManager.abort(),(o=this.audioBufferManager)==null?void 0:o.abort()]),!(Fx(this.element)||Fx(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),(u=this.audioBufferManager)==null||u.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",lo({requestedPosition:e,forcePrecise:t,position:i})))}warmUpMediaSourceIfNeeded(e=(t=>(t=this.element)==null?void 0:t.currentTime)()){var i;co(this.element)&&co(this.source)&&co(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=TV(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",lo({isJumpGapAfterSeekLive:i,isActiveLowLatency:t,initialCurrentTime:r,jumpTo:u,resultCurrentTime:this.element.currentTime})))}}};import{combine as wV,map as PV,observeElementSize as AV,Subscription as kV,ValueSubject as ph,noop as RV}from"@vkontakte/videoplayer-shared/es2018";var gl=class{constructor(){this.subscription=new kV;this.pipSize$=new ph(void 0);this.videoSize$=new ph(void 0);this.elementSize$=new ph(void 0);this.pictureInPictureWindowRemoveEventListener=RV}connect({observableVideo:e,video:t}){let i=r=>{let a=r.target;this.pipSize$.next({width:a.width,height:a.height})};this.subscription.add(AV(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(wV({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(PV(({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 Ir=class{constructor(e){this.subscription=new CV;this.videoState=new H("stopped");this.droppedFramesManager=new Yr;this.stallsManager=new il;this.elementSizeManager=new gl;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Ci;this.audioTrackSwitchHistory=new Ci;this.selectedRepresentations={audio:null,video:null};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(r.state==="requested"&&(i==null?void 0:i.to)!=="paused"&&e!=="stopped"&&t!=="stopped"&&this.seek(r.position,r.forcePrecise),t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),R(this.params.desiredState.playbackState,"stopped",!0));return}switch(e){case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();return;case"ready":t==="paused"?(this.videoState.setState("paused"),R(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="ready"&&R(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):t==="playing"&&this.video.paused?this.playIfAllowed():(i==null?void 0:i.to)==="playing"&&R(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&R(this.params.desiredState.playbackState,"paused");return;default:return MV(e)}}};this.init3DScene=e=>{var i,r,a;if(this.scene3D)return;this.scene3D=new ls(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 nt(e.source.url),this.params=e,this.video=Fe(e.container,e.tuning),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(we(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.player=new bl({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=qe(this.video);this.subscription.add(()=>i.destroy());let r=this.constructor.name,a=o=>{e.error$.next({id:r,category:Ux.WTF,message:`${r} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:i,genericErrorListener:a,connect:(o,u)=>this.subscription.add(o.subscribe(u,a))}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:a}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(hh(c=>!!c.length),jx()).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(fh(c=>c.to.state!=="none"),Sl());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(hh(qx),jx()),e.firstBytesEvent$),a(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),a(this.videoState.stateChangeEnded$.pipe(fh(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(wt(this.video,t.isLooped,r)),this.subscription.add(Ue(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(at(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),a(ot(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),R(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),R(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:c})=>{if(c==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let h=this.player.getStreams();if($V(h,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let f=[];for(let m of h.audio){f.push(Jp(m));let g=[];for(let S of m.representations){let v=xx(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(Zp(f));let m=[];for(let g of f.representations){let S=Ix({...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=Ex(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&&Ax(o)||null;this.subscription.add(vl(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$,DV(this.video,"progress")).pipe(hh(()=>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=Sr(this.videoTracksMap.keys(),S=>{var v;return((v=this.videoTracksMap.get(S))==null?void 0:v.representation.id)===p.id});qx(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(Sl()).subscribe(c=>{let h=Sr(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(Zp(f))},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(Sl()).subscribe(c=>{let h=Sr(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(Jp(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(fh(({to:c})=>c==="ready"),Sl());this.subscription.add(vl(l,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,mh(["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(vl(l,this.player.state$.stateChangeEnded$,mh(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let d=vl(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,mh(["init"])).pipe(BV(0));this.subscription.add(d.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){var $,w,A,C,M,L,Q,U,P,F,k,x;if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?Ba:$a,t=this.params.tuning.useNewAutoSelectVideoTrack?Au:Pu,i=this.params.tuning.useNewAutoSelectVideoTrack?Xt:wu,{desiredState:r,output:a}=this.params,n=r.autoVideoTrackSwitching.getState(),o=($=r.videoTrack.getState())==null?void 0:$.id,u=Sr(this.videoTracksMap.keys(),B=>B.id===o),l=a.currentVideoTrack$.getValue(),d=((C=(A=r.videoStream.getState())!=null?A: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=Sr(this.videoStreamsMap.keys(),B=>B.id===d.id),h=c&&this.videoStreamsMap.get(c);if(!h)return;let p=It(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)&&Sr(this.audioStreamsMap.keys(),B=>B.id===S.id)||this.audioStreamsMap.keys().next().value,y=0;if(v){if(u&&!n){let B=e(u,h,(L=this.audioStreamsMap.get(v))!=null?L:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);y=Math.max(y,(Q=B==null?void 0:B.bitrate)!=null?Q:-1/0)}if(l){let B=e(l,h,(U=this.audioStreamsMap.get(v))!=null?U:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);y=Math.max(y,(P=B==null?void 0:B.bitrate)!=null?P:-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(){je(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),R(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Ux.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.stallsManager.destroy(),this.elementSizeManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),this.params.output.currentVideoStream$.next(void 0),Ne(this.video),this.tracer.end()}};var po=class extends Ir{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 bh,merge as Hx,filter as Gx,filterChanged as VV,isNullable as gh,map as zx,ValueSubject as Sh,isNonNullable as OV}from"@vkontakte/videoplayer-shared/es2018";var ho=class extends Ir{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 Sh(1);a(i.playbackRateState$,n),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(r.isLowLatency.stateChangeEnded$.pipe(zx(o=>o.to)).subscribe(this.player.isLowLatency$)).add(bh({liveBufferTime:t.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(zx(({liveBufferTime:o,liveAvailabilityStartTime:u})=>o&&u?o+u:void 0)).subscribe(t.liveTime$)).add(this.player.liveStreamStatus$.pipe(Gx(o=>OV(o))).subscribe(o=>t.isLiveEnded$.next(o!=="active"&&t.position$.getValue()===0))).add(bh({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:Hx(i.playbackRateState$,new Sh(1))}).pipe(Gx(({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||gh(l)||(e=o-l)})).add(bh({time:t.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:Hx(i.playbackRateState$,new Sh(1))}).pipe(VV((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||gh(o)||gh(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=wx(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 Wx=N(Pa(),1);import{assertNever as fo,assertNonNullable as Qx,debounce as _V,ErrorCategory as yl,filter as FV,isNonNullable as NV,isNullable as UV,map as Tl,merge as qV,Observable as jV,observableFrom as HV,Subscription as GV,videoSizeToQuality as zV}from"@vkontakte/videoplayer-shared/es2018";var jt={};var gs=(s,e)=>new jV(t=>{let i=(r,a)=>t.next(a);return s.on(e,i),()=>s.off(e,i)}),mo=class{constructor(e){this.subscription=new GV;this.videoState=new H("initializing");this.trackLevels=new Map;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(e!=="initializing")switch((i==null?void 0:i.to)!=="paused"&&r.state==="requested"&&this.seek(r.position),t){case"stopped":switch(e){case"stopped":break;case"ready":case"playing":case"paused":this.stop();break;default:fo(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:fo(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:fo(e)}break;case"paused":switch(e){case"paused":break;case"stopped":this.prepare();break;case"ready":this.videoState.setState("paused"),R(this.params.desiredState.playbackState,"paused");break;case"playing":this.pause();break;default:fo(e)}break;default:fo(t)}};this.textTracksManager=new nt(e.source.url),this.video=Fe(e.container,e.tuning),this.params=e,this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(we(this.params.source.url)),this.loadHlsJs()}destroy(){var e,t;this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),(e=this.hls)==null||e.detachMedia(),(t=this.hls)==null||t.destroy(),this.params.output.element$.next(void 0),Ne(this.video)}loadHlsJs(){let e=!1,t=r=>{e||this.params.output.error$.next({id:r==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:yl.NETWORK,message:"Failed to load Hls.js",thrown:r}),e=!0},i=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);(0,Wx.default)(import("hls.js").then(r=>{e||(jt.Hls=r.default,jt.Events=r.default.Events,this.init())},t),()=>{window.clearTimeout(i),e=!0})}init(){Qx(jt.Hls,"hls.js not loaded"),this.hls=new jt.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){Qx(jt.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,i=l=>{t.error$.next({id:"HlsJsProvider",category:yl.WTF,message:"HlsJsProvider internal logic error",thrown:l})},r=qe(this.video);this.subscription.add(()=>r.destroy());let a=(l,d)=>this.subscription.add(l.subscribe(d,i));a(r.timeUpdate$,t.position$),a(r.durationChange$,t.duration$),a(r.ended$,t.endedEvent$),a(r.looped$,t.loopedEvent$),a(r.error$,t.error$),a(r.isBuffering$,t.isBuffering$),a(r.currentBuffer$,t.currentBuffer$),a(r.loadStart$,t.firstBytesEvent$),a(r.loadedMetadata$,t.loadedMetadataEvent$),a(r.playing$,t.firstFrameEvent$),a(r.canplay$,t.canplay$),a(r.seeked$,t.seekedEvent$),a(r.inPiP$,t.inPiP$),a(r.inFullscreen$,t.inFullscreen$),this.subscription.add(wt(this.video,e.isLooped,i)),this.subscription.add(Ue(this.video,e.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(at(this.video,e.playbackRate,r.playbackRateState$,i)),a(ot(this.video),t.elementVisible$),a(this.videoState.stateChangeEnded$.pipe(Tl(l=>l.to)),this.params.output.playbackState$),this.subscription.add(gs(this.hls,jt.Events.ERROR).subscribe(l=>{var d;l.fatal&&t.error$.next({id:["HlsJsFatal",l.type,l.details].join("_"),category:yl.WTF,message:`HlsJs fatal ${l.type} ${l.details}, ${(d=l.err)==null?void 0:d.message} ${l.reason}`,thrown:l.error})})),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),R(e.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),R(e.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())==null?void 0:l.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),a(gs(this.hls,jt.Events.MANIFEST_PARSED).pipe(Tl(({levels:l})=>l.reduce((d,c)=>{var v,y;let h=c.name||c.height.toString(10),{width:p,height:f}=c,m=(y=Kt((v=c.attrs.QUALITY)!=null?v:""))!=null?y:zV({width:p,height:f});if(!m)return d;let g=c.attrs["FRAME-RATE"]?parseFloat(c.attrs["FRAME-RATE"]):void 0,S={id:h.toString(),quality:m,bitrate:c.bitrate/1e3,size:{width:p,height:f},fps:g};return this.trackLevels.set(h,{track:S,level:c}),d.push(S),d},[]))),t.availableVideoTracks$),a(gs(this.hls,jt.Events.MANIFEST_PARSED),l=>{if(l.subtitleTracks.length>0){let d=[];for(let c of l.subtitleTracks){let h=c.name,p=c.attrs.URI||"",f=c.lang;d.push({id:h,url:p,language:f,type:"internal"})}e.internalTextTracks.startTransitionTo(d)}}),a(gs(this.hls,jt.Events.LEVEL_LOADING).pipe(Tl(({url:l})=>we(l))),t.hostname$),a(gs(this.hls,jt.Events.FRAG_CHANGED),l=>{var h,p,f,m;let{video:d,audio:c}=l.frag.elementaryStreams;t.currentVideoSegmentLength$.next((((h=d==null?void 0:d.endPTS)!=null?h:0)-((p=d==null?void 0:d.startPTS)!=null?p:0))*1e3),t.currentAudioSegmentLength$.next((((f=c==null?void 0:c.endPTS)!=null?f:0)-((m=c==null?void 0:c.startPTS)!=null?m:0))*1e3)}),this.subscription.add(Bi(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,l=>{this.hls.nextLevel=l?-1:this.hls.currentLevel,this.hls.loadLevel=l?-1:this.hls.loadLevel},{onError:i}));let n=l=>{var d;return(d=Array.from(this.trackLevels.values()).find(({level:c})=>c===l))==null?void 0:d.track},o=gs(this.hls,jt.Events.LEVEL_SWITCHED).pipe(Tl(({level:l})=>n(this.hls.levels[l])));o.pipe(FV(NV)).subscribe(t.currentVideoTrack$,i),this.subscription.add(Bi(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),l=>{var f;if(UV(l))return;let d=(f=this.trackLevels.get(l.id))==null?void 0:f.level;if(!d)return;let c=this.hls.levels.indexOf(d),h=this.hls.currentLevel,p=this.hls.levels[h];!p||d.bitrate>p.bitrate?this.hls.nextLevel=c:(this.hls.loadLevel=c,this.hls.loadLevel=c)},{changed$:o,onError:i})),a(r.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);let u=qV(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,HV(["init"])).pipe(_V(0));this.subscription.add(u.subscribe(this.syncPlayback,i))}prepare(){this.videoState.startTransitionTo("ready"),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}async playIfAllowed(){this.videoState.startTransitionTo("playing"),await je(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:yl.DOM,thrown:t}))||(this.videoState.setState("paused"),R(this.params.desiredState.playbackState,"paused",!0))}pause(){this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.hls.stopLoad(),this.hls.detachMedia(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"),R(this.params.desiredState.playbackState,"stopped",!0)}};var Yx="X-Playback-Duration",vh=async s=>{var r;let e=await Pt(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(Yx)?parseInt(e.headers.get(Yx),10):void 0};import{assertNever as rO,combine as sO,debounce as aO,ErrorCategory as El,filter as nO,filterChanged as oO,isNonNullable as Jx,isNullable as wl,map as Zx,merge as uO,observableFrom as lO,Subscription as cO,ValueSubject as Ih,VideoQuality as dO}from"@vkontakte/videoplayer-shared/es2018";var Th=N(Yc(),1);import{videoSizeToQuality as QV,getExponentialDelay as WV}from"@vkontakte/videoplayer-shared/es2018";var YV=s=>{let e=null;if(s.QUALITY&&(e=Kt(s.QUALITY)),!e&&s.RESOLUTION){let[t,i]=s.RESOLUTION.split("x").map(r=>parseInt(r,10));e=QV({width:t,height:i})}return e!=null?e:null},KV=(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,Th.default)(l[1].split(",").map(v=>v.split("="))),h=(a=c.QUALITY)!=null?a:`stream-${c.BANDWIDTH}`,p=YV(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,Th.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}},XV=s=>new Promise(e=>{setTimeout(()=>{e()},s)}),yh=0,Kx=async(s,e=s,t,i)=>{let a=await(await Pt(s,i)).text();yh+=1;try{let{qualityManifests:n,textTracks:o}=KV(a,e);return{qualityManifests:n,textTracks:o}}catch(n){if(yh<=t.manifestRetryMaxCount)return await XV(WV(yh-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),Kx(s,e,t)}return{qualityManifests:[],textTracks:[]}},Il=Kx;import{isNonNullable as JV,Subscription as ZV,throttle as eO,ValueSubject as Xx,Subject as tO,ErrorCategory as iO}from"@vkontakte/videoplayer-shared/es2018";var xl=class{constructor(e,t,i,r,a){this.subscription=new ZV;this.abortControllers={destroy:new ae,nextManifest:null};this.prepareUrl=void 0;this.currentTextTrackData=null;this.availableTextTracks$=new Xx(null);this.getCurrentTime$=new Xx(null);this.error$=new tO;this.params={fetchManifestData:i,sourceUrl:r,downloadThreshold:a},this.subscription.add(e.pipe(eO(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 Pt(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(JV(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:iO.WTF,thrown:t,message:e})}};var bo=class{constructor(e){this.subscription=new cO;this.videoState=new H("stopped");this.textTracksManager=null;this.liveTextManager=null;this.manifests$=new Ih([]);this.liveOffset=new lr;this.manifestStartTime$=new Ih(void 0);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),R(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(a||n||o){let d=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(d),this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((r==null?void 0:r.to)!=="paused"&&l.state==="requested"){this.videoState.startTransitionTo("ready"),this.seek(l.position&&l.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":i==="ready"?R(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),R(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&R(this.params.desiredState.playbackState,"playing");return;case"paused":if(i==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let d=this.liveOffset.getTotalOffset();d>=this.maxSeekBackTime$.getValue()&&(d=0,this.liveOffset.resetTo(d)),this.liveOffset.resume(),this.params.output.position$.next(-d/1e3),this.prepare()}else(r==null?void 0:r.to)==="paused"&&(R(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return rO(t)}};var i;this.params=e,this.video=Fe(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:dO.INVARIANT,url:this.params.source.url};let t=(r,a)=>Il(r,this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},a);this.params.tuning.useHlsLiveNewTextManager?this.liveTextManager=new xl(this.params.output.liveTime$,this.video,t,this.params.source.url,this.params.tuning.hlsLiveNewTextManagerDownloadThreshold):this.textTracksManager=new nt(e.source.url),t(this.generateLiveUrl()).then(({qualityManifests:r,textTracks:a})=>{var n;r.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:El.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),(n=this.liveTextManager)==null||n.processTextTracks(a,this.params.source.url),this.manifests$.next([this.masterManifest,...r])}).catch(r=>{this.params.output.error$.next({id:"ExtractHlsQualities",category:El.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:r})}),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(we(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new Ih((i=e.source.maxSeekBackTime)!=null?i:1/0),this.subscribe()}selectManifest(){var u,l,d,c;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),a=(c=(d=(u=r==null?void 0:r.to)==null?void 0:u.id)!=null?d:(l=t.getState())==null?void 0:l.id)!=null?c:"master",n=this.manifests$.getValue();if(!n.length)return;let o=i?"master":a;return i&&!r&&t.startTransitionTo(this.masterManifest),n.find(h=>h.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsLiveProvider",category:El.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},r=qe(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(Ue(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(at(this.video,t.playbackRate,r.playbackRateState$,i)),a(ot(this.video),e.elementVisible$),this.liveTextManager?(a(this.liveTextManager.getCurrentTime$,this.params.output.getCurrentTime$),a(this.liveTextManager.error$,this.params.output.error$)):this.textTracksManager&&this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),R(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),R(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.liveTextManager&&this.subscription.add(this.liveTextManager.availableTextTracks$.subscribe(o=>{o&&this.params.output.availableTextTracks$.next(o)})),this.subscription.add(this.maxSeekBackTime$.pipe(oO(),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&&Jx(l.to)){let c=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let h=this.manifests$.getValue().find(p=>p.id===c);h&&(this.params.output.currentVideoTrack$.next(h),this.params.output.hostname$.next(we(h.url)))}d&&this.params.desiredState.autoVideoTrackSwitching.setState(d.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o&&o.state==="requested"&&this.seek(o.position)},i)),this.subscription.add(r.loadedData$.subscribe(()=>{var u,l,d;let o=(d=(l=(u=this.video)==null?void 0:u.getStartDate)==null?void 0:l.call(u))==null?void 0:d.getTime();this.manifestStartTime$.next(o||void 0)},i)),this.subscription.add(sO({startTime:this.manifestStartTime$.pipe(nO(Jx)),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=uO(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,lO(["init"])).pipe(aO(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),Ne(this.video)}prepare(){var o,u,l;let e=this.selectManifest();if(wl(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:d,min:c}=(u=(o=t==null?void 0:t.to)!=null?o:i)!=null?u:{};for(let[h,p]of[[d,"mq"],[c,"lq"]]){let f=String(parseFloat(h||""));p&&h&&r.searchParams.set(p,f)}}let a=this.params.format==="HLS_LIVE_CMAF"?2:0,n=Se(r.toString(),this.liveOffset.getTotalOffset(),a);(l=this.liveTextManager)==null||l.prepare(n),this.video.setAttribute("src",n),this.video.load(),vh(n).then(d=>{var c;if(!wl(d))this.maxSeekBackTime$.next(d);else{let h=(c=this.params.source.maxSeekBackTime)!=null?c:this.maxSeekBackTime$.getValue();(wl(h)||!isFinite(h))&&Pt(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();vh(g).then(S=>{wl(S)||this.maxSeekBackTime$.next(S)})}}).catch(()=>{})}})}playIfAllowed(){je(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),R(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:El.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3),this.params.output.seekedEvent$.next()}generateLiveUrl(){let e=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 pO,debounce as hO,ErrorCategory as xh,fromEvent as Eh,isNonNullable as fO,isNullable as mO,map as eE,merge as tE,observableFrom as iE,Subscription as bO,ValueSubject as gO,VideoQuality as SO}from"@vkontakte/videoplayer-shared/es2018";var go=class{constructor(e){this.subscription=new bO;this.videoState=new H("stopped");this.manifests$=new gO([]);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),R(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(a||n||o){let d=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(d);let{currentTime:c}=this.video;this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:c*1e3,forcePrecise:!0});return}switch((r==null?void 0:r.to)!=="paused"&&l.state==="requested"&&this.seek(l.position),t){case"ready":i==="ready"?R(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),R(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&R(this.params.desiredState.playbackState,"playing");return;case"paused":i==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&R(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return pO(t)}};this.textTracksManager=new nt(e.source.url),this.params=e,this.video=Fe(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:SO.INVARIANT,url:this.params.source.url},this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(we(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),Il(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:xh.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:xh.WTF,message:"HlsProvider internal logic error",thrown:o})},r=qe(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(eE(o=>o.to)),this.params.output.playbackState$),this.subscription.add(wt(this.video,t.isLooped,i)),this.subscription.add(Ue(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(at(this.video,t.playbackRate,r.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),R(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),R(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i).add(r.loadedMetadata$.subscribe(()=>{var p;let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&fO(l.to)){let f=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let m=this.manifests$.getValue().find(g=>g.id===f);m&&(this.params.output.currentVideoTrack$.next(m),this.params.output.hostname$.next(we(m.url)))}let c=this.params.desiredState.playbackRate.getState(),h=(p=this.params.output.element$.getValue())==null?void 0:p.playbackRate;if(c!==h){let f=this.params.output.element$.getValue();f&&(this.params.desiredState.playbackRate.setState(c),f.playbackRate=c)}d&&this.params.desiredState.autoVideoTrackSwitching.setState(d.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o.state==="requested"&&this.seek(o.position)},i))),this.subscription.add(this.manifests$.pipe(eE(o=>o.map(({id:u,quality:l,size:d,bandwidth:c,fps:h})=>({id:u,quality:l,size:d,fps:h,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,i)),!q.device.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(tE(Eh(o,"addtrack"),Eh(o,"removetrack"),Eh(o,"change"),iE(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},i))}let n=tE(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,iE(["init"])).pipe(hO(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Ne(this.video)}prepare(){var a,n;let e=this.selectManifest();if(mO(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(){je(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),R(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:xh.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var aE=N(er(),1),wh=N(ur(),1),nE=N(_t(),1);import{assertNever as vO,assertNonNullable as rE,debounce as yO,ErrorCategory as sE,isHigherOrEqual as TO,isLowerOrEqual as IO,isNonNullable as xO,merge as EO,observableFrom as wO,Subscription as PO,map as AO}from"@vkontakte/videoplayer-shared/es2018";var So=class{constructor(e){this.subscription=new PO;this.videoState=new H("stopped");this.trackUrls={};this.textTracksManager=new nt;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),R(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let a=this.params.desiredState.autoVideoTrackLimits.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.seekState.getState();if(a&&e!=="ready"&&!n){this.handleQualityLimitTransition(a.to);return}if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(n){let{currentTime:u}=this.video;this.prepare(),o.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:u*1e3,forcePrecise:!0});return}switch((i==null?void 0:i.to)!=="paused"&&o.state==="requested"&&this.seek(o.position),e){case"ready":t==="ready"?R(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),R(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(i==null?void 0:i.to)==="playing"&&R(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&R(this.params.desiredState.playbackState,"paused");return;default:return vO(e)}};this.params=e,this.video=Fe(e.container,e.tuning),this.params.output.element$.next(this.video),(0,aE.default)(this.params.source).reverse().forEach(([t,i],r)=>{let a=r.toString(10);this.trackUrls[a]={track:{quality:t,id:a},url:i}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next((0,wh.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:sE.WTF,message:"MpegProvider internal logic error",thrown:o})},r=qe(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(AO(o=>o.to)),this.params.output.playbackState$),this.subscription.add(wt(this.video,t.isLooped,i)),this.subscription.add(Ue(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(at(this.video,t.playbackRate,r.playbackRateState$,i)),a(ot(this.video),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),R(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),R(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var u,l;((u=this.videoState.getTransition())==null?void 0:u.to)==="ready"&&this.videoState.setState("ready");let o=this.params.desiredState.videoTrack.getTransition();if(o&&xO(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=EO(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,wO(["init"])).pipe(yO(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),Ne(this.video)}prepare(){var i;let e=(i=this.params.desiredState.videoTrack.getState())==null?void 0:i.id;rE(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];rE(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=_i(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(we(t))}playIfAllowed(){je(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),R(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:sE.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=Xt(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,wh.default)(this.trackUrls).map(c=>c.track);if(!r||!a||Hr(e,n[0].quality,(d=(0,nE.default)(n,-1))==null?void 0:d.quality)){i();return}let o=e.max?IO(r,e.max):!0,u=e.min?TO(r,e.min):!0;o&&u||i(e)}};import{assertNever as uE,debounce as MO,merge as lE,observableFrom as $O,Subscription as BO,map as cE,ValueSubject as DO,ErrorCategory as Ah,VideoQuality as CO}from"@vkontakte/videoplayer-shared/es2018";import{ErrorCategory as kO}from"@vkontakte/videoplayer-shared/es2018";var oE=["stun:videostun.mycdn.me:80"],RO=1e3,LO=3,Ph=()=>null,Pl=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=Ph;this.externalStopCallback=Ph;this.externalErrorCallback=Ph;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:oE}]};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:kO.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),RO)}normalizeOptions(e={}){let t={stunServerList:oE,maxRetryNumber:LO,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var vo=class{constructor(e){this.videoState=new H("stopped");this.maxSeekBackTime$=new DO(0);this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.pause(),this.video.srcObject=null,this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),R(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let a=this.params.desiredState.videoTrack.getTransition();if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(a){this.prepare();return}switch(e){case"ready":t==="paused"?(this.videoState.setState("paused"),R(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(i==null?void 0:i.to)==="playing"&&R(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&R(this.params.desiredState.playbackState,"paused");return;default:return uE(e)}};this.subscription=new BO,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=Fe(e.container,e.tuning),this.liveStreamClient=new Pl(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),Ne(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,i=n=>{e.error$.next({id:"WebRTCLiveProvider",category:Ah.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};this.subscription.add(lE(this.videoState.stateChangeStarted$.pipe(cE(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(cE(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})}));let r=qe(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(ot(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(Ue(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 uE(n.to)}},i)).add(lE(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,$O(["init"])).pipe(MO(0)).subscribe(this.syncPlayback.bind(this),i)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),i))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(we(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.currentVideoTrack$.next({id:"webrtc",quality:CO.INVARIANT}),this.video.srcObject=e,R(this.params.desiredState.playbackState,"playing")}onLiveStreamStop(){this.videoState.startTransitionTo("stopped"),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.params.output.endedEvent$.next()}onLiveStreamError(e){this.onLiveStreamStop(),this.params.output.error$.next({id:"WebRTC stream runtime error",category:Ah.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){je(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),R(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Ah.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var yo=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 Io,assertNonNullable as qi,ErrorCategory as Al,filter as bE,isNonNullable as gE,isNullable as qO,map as jO,merge as HO,once as GO,Subject as De,Subscription as SE,ValueSubject as W,flattenObject as kh}from"@vkontakte/videoplayer-shared/es2018";import{Observable as VO,map as dE,Subscription as OO,Subject as _O}from"@vkontakte/videoplayer-shared/es2018";var pE=s=>new VO(e=>{let t=new OO,i=s.desiredPlaybackState$.stateChangeStarted$.pipe(dE(({from:l,to:d})=>`${l}-${d}`)),r=s.desiredPlaybackState$.stateChangeEnded$,a=s.providerChanged$.pipe(dE(({type:l})=>l!==void 0)),n=new _O,o=0,u="unknown";return t.add(i.subscribe(l=>{o&&window.clearTimeout(o),u=l,o=window.setTimeout(()=>n.next(l),s.maxTransitionInterval)})),t.add(r.subscribe(()=>{window.clearTimeout(o),u="unknown",o=0})),t.add(a.subscribe(l=>{o&&(window.clearTimeout(o),o=0,l&&(o=window.setTimeout(()=>n.next(u),s.maxTransitionInterval)))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});import{ErrorCategory as FO,Subscription as NO,combine as UO,filter as fE,once as mE}from"@vkontakte/videoplayer-shared/es2018";function hE(){return new(window.AudioContext||window.webkitAudioContext)}var To=class To{constructor(e,t,i,r){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=i;this.volumeMultiplier=r;this.destroyController=new ae;this.subscriptions=new NO;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe(fE(a=>!!a.type),mE()).subscribe(({type:a})=>this.subscribe(a)))}subscribe(e){q.browser.isSafari&&e!=="MPEG"||this.subscriptions.add(UO({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(fE(({playbackState:t,video:i,volume:{muted:r,volume:a}})=>t==="playing"&&!!i&&!r&&!!a),mE()).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=hE();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:To.errorId,category:FO.VIDEO_PIPELINE,message:(t=e==null?void 0:e.message)!=null?t:`${To.errorId} exception`,thrown:e})}};To.errorId="VolumeMultiplierManager";var Ss=To;var zO={chunkDuration:5e3,maxParallelRequests:5},xo=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 SE;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=QI([...YI(this.params.tuning),...WI(this.params.tuning)],this.params.tuning).filter(l=>gE(e.sources[l])),{forceFormat:i,formatsToAvoid:r}=this.params.tuning,a=[];i?a=[i]:r.length?a=[...t.filter(l=>!(0,Rh.default)(r,l)),...t.filter(l=>(0,Rh.default)(r,l))]:a=t,this.log({message:`Selected formats: ${a.join(" > ")}`}),this.tracer.log("Selected formats",kh(a)),this.screenFormatsIterator=new yo(a);let n=[...Lp(!0),...Lp(!1)];this.chromecastFormatsIterator=new yo(n.filter(l=>gE(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:o=1,tuning:{useVolumeMultiplier:u}}=this.params;u&&o!==1&&Ss.isSupported()&&(this.volumeMultiplierManager=new Ss(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(qO(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:Al.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 Io(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 qi(u),this.params.tuning.useNewDashProvider?new po({...o,source:u,sourceHls:l}):new kn({...o,source:u,sourceHls:l})}case"DASH_LIVE_CMAF":{let u=this.applyFailoverHost(t[e]);return qi(u),this.params.tuning.useNewDashProvider?new ho({...o,source:u}):new Rn({...o,source:u})}case"HLS":case"HLS_ONDEMAND":{let u=this.applyFailoverHost(t[e]);return qi(u),q.video.nativeHlsSupported||!this.params.tuning.useHlsJs?new go({...o,source:u}):new mo({...o,source:u})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let u=this.applyFailoverHost(t[e]);return qi(u),new bo({...o,source:u,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let u=this.applyFailoverHost(t[e]);return qi(u),new So({...o,source:u})}case"DASH_LIVE":{let u=this.applyFailoverHost(t[e]);return qi(u),new Qy({...o,source:u,config:{...zO,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let u=this.applyFailoverHost(t[e]);return qi(u),new vo({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 Io(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 qi(o),new Aa({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 Io(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return Io(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 Io(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,yE.default)((0,vE.default)(e).map(([r,a])=>[r,i(a)]))}initProviderErrorHandling(){let e=new SE,t=!1,i=0;return e.add(HO(this.providerOutput.error$.pipe(bE(r=>!this.params.tuning.ignoreAudioRendererError||!r.message||!/AUDIO_RENDERER_ERROR/ig.test(r.message))),pE({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(jO(r=>({id:`ProviderHangup:${r}`,category:Al.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(bE(({to:a})=>a==="playing"),GO()).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===Al.NETWORK,u=r.category===Al.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",kh(n)):this.tracer.error("providerError",kh(n))})),e}};import{fromEvent as kl,once as QO,combine as WO,Subscription as TE,ValueSubject as Lh,map as YO,filter as KO,isNonNullable as Rl,now as xt,safeStorage as Mh}from"@vkontakte/videoplayer-shared/es2018";var XO=5e3,IE="one_video_throughput",xE="one_video_rtt",Pi=window.navigator.connection,EE=()=>{let s=Pi==null?void 0:Pi.downlink;if(Rl(s)&&s!==10)return s*1e3},wE=()=>{let s=Pi==null?void 0:Pi.rtt;if(Rl(s)&&s!==3e3)return s},PE=(s,e,t)=>{let i=t*8,r=i/s;return i/(r+e)},$h=class s{constructor(e){this.subscription=new TE;this.concurrentDownloads=new Set;var r,a;this.tuningConfig=e;let t=s.load(IE)||(e.useBrowserEstimation?EE():void 0)||XO,i=(a=(r=s.load(xE))!=null?r:e.useBrowserEstimation?wE():void 0)!=null?a:0;if(this.throughput$=new Lh(t),this.rtt$=new Lh(i),this.rttAdjustedThroughput$=new Lh(PE(t,i,e.rttPenaltyRequestSize)),this.throughput=Ii.getSmoothedValue(t,-1,e),this.rtt=Ii.getSmoothedValue(i,1,e),e.useBrowserEstimation){let n=()=>{let u=EE();u&&this.throughput.next(u);let l=wE();Rl(l)&&this.rtt.next(l)};Pi&&"onchange"in Pi&&this.subscription.add(kl(Pi,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{Mh.set(IE,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{Mh.set(xE,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(WO({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(YO(({throughput:n,rtt:o})=>PE(n,o,e.rttPenaltyRequestSize)),KO(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=xt(),r=new TE;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add(kl(e,"progress").pipe(QO()).subscribe(a=>{t=a.loaded,i=xt()}));break;case 1:case 0:r.add(kl(e,"loadstart").subscribe(()=>{t=0,i=xt()}));break}r.add(kl(e,"loadend").subscribe(a=>{if(e.status===200){let n=a.loaded,o=xt(),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=xt(),n=0,o=xt(),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,xt()-a,1),this.concurrentDownloads.delete(e);else if(c){if(t){let h=xt();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=xt()}else n+=c.byteLength;o=xt()}else r+=c.byteLength,n+=c.byteLength,n>=this.tuningConfig.streamMinSampleSize&&xt()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,xt()-o,this.concurrentDownloads.size),n=0,o=xt());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=Mh.get(e);if(Rl(t))return(i=parseInt(t,10))!=null?i:void 0}},AE=$h;import{fillWithDefault as JO,VideoQuality as Ll}from"@vkontakte/videoplayer-shared/es2018";var kE={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:Ll.Q_4320P,activeVideoAreaThreshold:.1,highQualityLimit:Ll.Q_720P,trafficSavingLimit:Ll.Q_480P},stallsManager:{enabled:!1,stallDurationNoDataBeforeQualityDecrease:500,stallDurationToBeCount:100,stallCountBeforeQualityDecrease:3,resetQualityRestrictionTimeout:1e4,ignoreStallsOnSeek:!1,stallsMetricsHistoryLength:5,maxPossibleStallDuration:3e4,minTvtToBeCounted:5,maxTvtToBeCounted:10800,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:Ll.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,useSourceBufferUpdateendMaintain:!1,useSourceBufferBufferedDiff:!1},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,maxLiveDuration:7200,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:250,playbackCatchupSpeedup:.05,isActiveOnDefault:!1,bufferEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:"07A4434E",useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"dash",preferCMAF:!1,preferWebRTC:!1,preferMultiStream:!1,preferHDR:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,seekNearDurationBias:1,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useHlsJs:!1,useNativeHLSTextTracks:!1,useManagedMediaSource:!0,useNewSwitchTo:!1,useNewDashProvider:!1,useNewAutoSelectVideoTrack:!1,useSafariEndlessRequestBugfix:!0,useRefactoredSearchGap:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,audioVideoSyncRate:20,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50},useVolumeMultiplier:!1,ignoreAudioRendererError:!1,useEnableSubtitlesParam:!1,useOldMSEDetection:!1,useHlsLiveNewTextManager:!1,exposeInternalsToGlobal:!1,hlsLiveNewTextManagerDownloadThreshold:4e3,disableYandexPiP:!1,asyncResolveClientChecker:!1,autostartOnlyIfVisible:!1},RE=s=>{var e;return{...JO(s,kE),configName:[...(e=s.configName)!=null?e:[],...kE.configName]}};import{assertNonNullable as Ml,combine as Ai,ErrorCategory as $l,filter as z,filterChanged as te,fromEvent as Dh,isNonNullable as BE,isNullable as a_,Logger as n_,map as Z,mapTo as DE,merge as ji,now as Bl,once as Y,Subject as re,Subscription as CE,tap as Ch,ValueSubject as D,isHigher as o_,isInvariantQuality as VE,flattenObject as Hi,throttle as Vh,getTraceSubscriptionMethod as OE,Tracer as u_,InternalsExposure as l_}from"@vkontakte/videoplayer-shared/es2018";import{merge as ZO,map as e_,filter as LE,isNonNullable as t_}from"@vkontakte/videoplayer-shared/es2018";var Bh=({seekState:s,position$:e})=>ZO(s.stateChangeEnded$.pipe(e_(({to:t})=>{var i;return t.state==="none"?void 0:((i=t.position)!=null?i:NaN)/1e3}),LE(t_)),e.pipe(LE(()=>s.getState().state==="none")));import{assertNonNullable as i_}from"@vkontakte/videoplayer-shared/es2018";var ME=s=>{let e=typeof s.container=="string"?document.getElementById(s.container):s.container;return i_(e,`Wrong container or containerId {${s.container}}`),e};import{filter as r_,once as s_}from"@vkontakte/videoplayer-shared/es2018";var $E=(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(r_(r=>r.length>0),s_()).subscribe(r=>{r.find(i)&&e.startTransitionTo(s)}):(s===void 0||t!=null&&t.getValue().find(i))&&e.startTransitionTo(s)};var Dl=class{constructor(e={configName:[]},t=u_.createRootTracer(!1)){this.subscription=new CE;this.logger=new n_;this.abrLogger=this.logger.createComponentLog("ABR");this.internalsExposure=null;this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new D(!1);this.hasLiveOffsetByPausedTimer=0;this.playerInitRequest=0;this.playerInited=new D(!1);this.wasSetStartedQuality=!1;this.desiredState={playbackState:new H("stopped"),seekState:new H({state:"none"}),volume:new H({volume:1,muted:!1}),videoTrack:new H(void 0),videoStream:new H(void 0),audioStream:new H(void 0),autoVideoTrackSwitching:new H(!0),autoVideoTrackLimits:new H({}),isLooped:new H(!1),isLowLatency:new H(!1),playbackRate:new H(1),externalTextTracks:new H([]),internalTextTracks:new H([]),currentTextTrack:new H(void 0),textTrackCuesSettings:new H({}),cameraOrientation:new H({x:0,y:0})};this.info={playbackState$:new D(void 0),position$:new D(0),duration$:new D(1/0),muted$:new D(!1),volume$:new D(1),availableVideoStreams$:new D([]),currentVideoStream$:new D(void 0),availableQualities$:new D([]),availableQualitiesFps$:new D({}),currentQuality$:new D(void 0),isAutoQualityEnabled$:new D(!0),autoQualityLimitingAvailable$:new D(!1),autoQualityLimits$:new D({}),predefinedQualityLimitType$:new D("unknown"),availableAudioStreams$:new D([]),currentAudioStream$:new D(void 0),availableAudioTracks$:new D([]),isAudioAvailable$:new D(!0),currentPlaybackRate$:new D(1),currentBuffer$:new D({start:0,end:0}),isBuffering$:new D(!0),isStalled$:new D(!1),isEnded$:new D(!1),isLooped$:new D(!1),isLive$:new D(void 0),isLiveEnded$:new D(null),canChangePlaybackSpeed$:new D(void 0),atLiveEdge$:new D(void 0),atLiveDurationEdge$:new D(void 0),liveTime$:new D(void 0),liveBufferTime$:new D(void 0),liveLatency$:new D(void 0),currentFormat$:new D(void 0),availableTextTracks$:new D([]),currentTextTrack$:new D(void 0),throughputEstimation$:new D(void 0),rttEstimation$:new D(void 0),videoBitrate$:new D(void 0),hostname$:new D(void 0),httpConnectionType$:new D(void 0),httpConnectionReused$:new D(void 0),surface$:new D("none"),chromecastState$:new D("NOT_AVAILABLE"),chromecastDeviceName$:new D(void 0),intrinsicVideoSize$:new D(void 0),availableSources$:new D(void 0),is3DVideo$:new D(!1),currentVideoSegmentLength$:new D(0),currentAudioSegmentLength$:new D(0)};this.events={inited$:new re,ready$:new re,started$:new re,playing$:new re,paused$:new re,stopped$:new re,willStart$:new re,willResume$:new re,willPause$:new re,willStop$:new re,willDestruct$:new re,watchCoverageRecord$:new re,watchCoverageLive$:new re,managedError$:new re,fatalError$:new re,fetcherRecoverableError$:new re,ended$:new re,looped$:new re,seeked$:new re,willSeek$:new re,autoplaySoundProhibited$:new re,firstBytes$:new re,loadedMetadata$:new re,firstFrame$:new re,canplay$:new re,log$:new re,fetcherError$:new re,severeStallOccured$:new re};this.experimental={element$:new D(void 0),tuningConfigName$:new D([]),enableDebugTelemetry$:new D(!1),dumpTelemetry:vy,getCurrentTime$:new D(null)};if(this.initLogs(),this.tuning=RE(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new Mo({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new AE(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new l_("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,_E.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:$l.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",Hi(o)),this.domContainer=ME(e),this.chromecastInitializer.contentId=(u=e.meta)==null?void 0:u.videoId,this.providerContainer=new xo({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?q.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"),Dh(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){return this.subscription.add(this.playerInited.pipe(z(t=>!!t),Y()).subscribe(()=>{var n;let t=this.desiredState.volume,i=this.tuning.isAudioDisabled||e,r=t.getTransition(),a=(n=r==null?void 0:r.to.volume)!=null?n:this.info.volume$.getValue();this.tracer.log("setMuted",{isMuted:e,nextMuted:i,volume:a,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue()}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setMuted(i):t.startTransitionTo({volume:a,muted:i})})),this}setVideoStream(e){return this.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(()=>{Ml(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",Hi(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;Ml(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",Hi(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;$E(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(a_(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),i=t.state==="none"?void 0:t.position;return BE(i)?i/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){var t,i;let e=(t=this.providerContainer)==null?void 0:t.current$.getValue();if((i=e==null?void 0:e.provider)!=null&&i.scene3D)return e.provider.scene3D}setIntrinsicVideoSize(...e){let t={width:e.reduce((i,{width:r})=>i||r||0,0),height:e.reduce((i,{height:r})=>i||r||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(ji(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(Qd(e,t,i))})),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(z(({from:e})=>e==="stopped"),Y()).subscribe(()=>{this.initedAt=Bl(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case"ready":this.events.ready$.next();break;case"playing":this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case"paused":this.events.paused$.next();break;case"stopped":this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case"paused":this.events.willPause$.next();break;case"playing":this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case"stopped":this.events.willStop$.next();break;default:}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("willSeekEvent",Hi(n)),n.state==="requested"?this.desiredState.seekState.setState({...n,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:$l.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",Hi(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(Ai({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)=>VE(u)?1:VE(l)?-1:o_(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=>BE(n))).subscribe(n=>{this.info.currentQuality$.next(n==null?void 0:n.quality),this.info.videoBitrate$.next(n==null?void 0:n.bitrate)})).add(e.providerOutput.currentVideoSegmentLength$.pipe(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(Ch(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(Ai({hasLiveOffsetByPaused:ji(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(Ai({atLiveEdge:Ai({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Bh({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(),Ch(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(Z(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add(Ai({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(),Ch(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(Bh({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(ji(e.providerOutput.endedEvent$.pipe(DE(!0)),e.providerOutput.seekedEvent$.pipe(DE(!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:$l.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:Bl()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(Y(),Z(()=>Bl()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(Y(),Z(()=>Bl()-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=ji(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(ji(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(ji(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 CE;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=Xt(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(ji(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;Ml(this.providerContainer),Ml(e),Sy(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(i=>gy(i)),this.providerContainer.current$.subscribe(({type:i})=>Ma("provider",i)),e.duration$.subscribe(i=>Ma("duration",i)),e.availableVideoTracks$.pipe(z(i=>!!i.length),Y()).subscribe(i=>Ma("tracks",i)),this.events.fatalError$.subscribe(new et("fatalError")),this.events.managedError$.subscribe(new et("managedError")),e.position$.subscribe(new et("position")),e.currentVideoTrack$.pipe(Z(i=>i==null?void 0:i.quality)).subscribe(new et("quality")),this.info.currentBuffer$.subscribe(new et("buffer")),e.isBuffering$.subscribe(new et("isBuffering"))].forEach(i=>this.subscription.add(i)),Ma("codecs",q.video.supportedCodecs)}initTracerSubscription(){let e=OE(this.tracer.log.bind(this.tracer)),t=OE(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(Ai({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(Ai({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(Vh(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(Ai({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(z(({liveTime:i,liveBufferTime:r})=>!!i&&!!r),Vh(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(Ai({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(z(({throughputEstimation:i,rtt:r})=>!!i&&!!r),Vh(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:$l.DOM,message:String(r)})})};this.subscription.add(ji(Dh(document,"visibilitychange"),Dh(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",Hi({quality:t,availableTracks:Hi(e),track:Hi(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&&!_a()}};import{Subscription as ite,Observable as rte,Subject as ste,ValueSubject as ate,VideoQuality as nte}from"@vkontakte/videoplayer-shared/es2018";var ote=`@vkontakte/videoplayer-core@${_h}`;export{Eo as ChromecastState,ql as HttpConnectionType,rte as Observable,st as PlaybackState,Dl as Player,wo as PredefinedQualityLimits,ote as SDK_VERSION,ste as Subject,ite as Subscription,jl as Surface,_h as VERSION,ate as ValueSubject,fi as VideoFormat,nte as VideoQuality,q as clientChecker,La as isMobile};